language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__hadoop | hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-infra/src/main/java/org/apache/hadoop/tools/dynamometer/SimulatedDataNodes.java | {
"start": 2863,
"end": 3498
} | class ____ extends Configured implements Tool {
// Set this arbitrarily large (100TB) since we don't care about storage
// capacity
private static final long STORAGE_CAPACITY = 100 * 2L << 40;
private static final String USAGE = "Usage: "
+ "org.apache.hadoop.tools.dynamometer.SimulatedDataNodes "
+ "bpid blockListFile1 [ blockListFileN ... ]\n"
+ " bpid should be the ID of the block pool to which these DataNodes "
+ "belong.\n"
+ " Each blockListFile specified should contain a list of blocks to "
+ "be served by one DataNode.\n"
+ " See the Javadoc of this | SimulatedDataNodes |
java | spring-projects__spring-boot | module/spring-boot-rsocket/src/test/java/org/springframework/boot/rsocket/autoconfigure/RSocketMessagingAutoConfigurationTests.java | {
"start": 5474,
"end": 5707
} | class ____ {
@Bean
RSocketMessageHandlerCustomizer customizer() {
return (messageHandler) -> messageHandler.setDefaultDataMimeType(MimeType.valueOf("application/json"));
}
}
@Controller
static final | CustomizerConfiguration |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java | {
"start": 87578,
"end": 88146
} | class ____ extends
BaseTransition {
RMAppAttemptEvent amUnregisteredEvent;
public AMFinishedAfterFinalSavingTransition(
RMAppAttemptEvent amUnregisteredEvent) {
this.amUnregisteredEvent = amUnregisteredEvent;
}
@Override
public void
transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) {
appAttempt.updateInfoOnAMUnregister(amUnregisteredEvent);
new FinalTransition(RMAppAttemptState.FINISHED).transition(appAttempt,
event);
}
}
private static | AMFinishedAfterFinalSavingTransition |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/typeutils/SortedMapTypeInfo.java | {
"start": 4221,
"end": 4774
} | class ____<K> implements Comparator<K>, Serializable {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
public int compare(K obj1, K obj2) {
return ((Comparable<K>) obj1).compareTo(obj2);
}
@Override
public boolean equals(Object o) {
return (o == this) || (o != null && o.getClass() == getClass());
}
@Override
public int hashCode() {
return "ComparableComparator".hashCode();
}
}
}
| ComparableComparator |
java | apache__flink | flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/handlers/JarRequestBody.java | {
"start": 1813,
"end": 1945
} | class ____ {@link RequestBody} for running a jar or querying the plan. */
@JsonInclude(JsonInclude.Include.NON_NULL)
public abstract | for |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/dialect/HANADialectTestCase.java | {
"start": 1293,
"end": 2149
} | class ____ {
@Test
public void testIdentityInsertNoColumns(DomainModelScope modelScope) {
final MetadataImplementor domainModel = modelScope.getDomainModel();
try ( SessionFactoryImplementor sessionFactory = domainModel.buildSessionFactory() ) {
fail( "Expecting a MappingException" );
}
catch (MappingException expected) {
assertThat( expected.getMessage() )
.matches( "The INSERT statement for table \\[EntityWithIdentity\\] contains no column, and this is not supported by \\[" + HANADialect.class.getName() + ", version: [\\d\\.]+\\]" );
}
}
/**
* Intentionally one of those silly cases where a table has only an id column.
* Here especially, since it is an IDENTITY the insert will have no columns at all.
*/
@Entity( name = "EntityWithIdentity" )
@Table( name = "EntityWithIdentity" )
public static | HANADialectTestCase |
java | grpc__grpc-java | xds/src/test/java/io/grpc/xds/FakeControlPlaneXdsIntegrationTest.java | {
"start": 11921,
"end": 15166
} | class ____ implements ClientInterceptor {
Metadata reponseHeaders;
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method,
CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(ClientCall.Listener<RespT> responseListener, Metadata headers) {
super.start(new ForwardingClientCallListener<RespT>() {
@Override
protected ClientCall.Listener<RespT> delegate() {
return responseListener;
}
@Override
public void onHeaders(Metadata headers) {
reponseHeaders = headers;
}
}, headers);
}
};
}
}
/**
* Basic test to make sure RING_HASH configuration works.
*/
@Test
public void pingPong_ringHash() {
controlPlane.setCdsConfig(
ControlPlaneRule.buildCluster().toBuilder()
.setLbPolicy(LbPolicy.RING_HASH).build());
ManagedChannel channel = dataPlane.getManagedChannel();
SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub = SimpleServiceGrpc.newBlockingStub(
channel);
SimpleRequest request = SimpleRequest.getDefaultInstance();
SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setResponseMessage("Hi, xDS! Authority= test-server")
.build();
assertEquals(goldenResponse, blockingStub.unaryRpc(request));
}
@Test
public void pingPong_logicalDns_authorityOverride() {
System.setProperty("GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE", "true");
try {
InetSocketAddress serverAddress =
(InetSocketAddress) dataPlane.getServer().getListenSockets().get(0);
controlPlane.setCdsConfig(
ControlPlaneRule.buildCluster().toBuilder()
.setType(Cluster.DiscoveryType.LOGICAL_DNS)
.setLoadAssignment(
ClusterLoadAssignment.newBuilder().addEndpoints(
LocalityLbEndpoints.newBuilder().addLbEndpoints(
LbEndpoint.newBuilder().setEndpoint(
Endpoint.newBuilder().setAddress(
Address.newBuilder().setSocketAddress(
SocketAddress.newBuilder()
.setAddress("localhost")
.setPortValue(serverAddress.getPort()))))))
.build())
.build());
ManagedChannel channel = dataPlane.getManagedChannel();
SimpleServiceGrpc.SimpleServiceBlockingStub blockingStub = SimpleServiceGrpc.newBlockingStub(
channel);
SimpleRequest request = SimpleRequest.getDefaultInstance();
SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setResponseMessage("Hi, xDS! Authority= localhost:" + serverAddress.getPort())
.build();
assertEquals(goldenResponse, blockingStub.unaryRpc(request));
} finally {
System.clearProperty("GRPC_EXPERIMENTAL_XDS_AUTHORITY_REWRITE");
}
}
}
| ResponseHeaderClientInterceptor |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/ComponentSetTestEntity.java | {
"start": 559,
"end": 1863
} | class ____ {
@Id
@GeneratedValue
private Integer id;
@ElementCollection
@CollectionTable(name = "CompTestEntityComps", joinColumns = @JoinColumn(name = "entity_id"))
private Set<Component1> comps = new HashSet<Component1>();
public ComponentSetTestEntity() {
}
public ComponentSetTestEntity(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set<Component1> getComps() {
return comps;
}
public void setComps(Set<Component1> comps) {
this.comps = comps;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof ComponentSetTestEntity) ) {
return false;
}
ComponentSetTestEntity that = (ComponentSetTestEntity) o;
if ( comps != null ? !comps.equals( that.comps ) : that.comps != null ) {
return false;
}
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (comps != null ? comps.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ComponentSetTestEntity{" +
"id=" + id +
", comps=" + comps +
'}';
}
}
| ComponentSetTestEntity |
java | junit-team__junit5 | junit-vintage-engine/src/testFixtures/java/org/junit/vintage/engine/samples/junit4/MalformedJUnit4TestCase.java | {
"start": 457,
"end": 649
} | class ____ {
@Test
@SuppressWarnings("TestMethodWithIncorrectSignature") // intentionally not public
void nonPublicTest() {
fail("this should never be called");
}
}
| MalformedJUnit4TestCase |
java | apache__camel | components/camel-ssh/src/generated/java/org/apache/camel/component/ssh/SshComponentConfigurer.java | {
"start": 730,
"end": 10807
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private org.apache.camel.component.ssh.SshConfiguration getOrCreateConfiguration(SshComponent target) {
if (target.getConfiguration() == null) {
target.setConfiguration(new org.apache.camel.component.ssh.SshConfiguration());
}
return target.getConfiguration();
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
SshComponent target = (SshComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "certresource":
case "certResource": getOrCreateConfiguration(target).setCertResource(property(camelContext, java.lang.String.class, value)); return true;
case "certresourcepassword":
case "certResourcePassword": getOrCreateConfiguration(target).setCertResourcePassword(property(camelContext, java.lang.String.class, value)); return true;
case "channeltype":
case "channelType": getOrCreateConfiguration(target).setChannelType(property(camelContext, java.lang.String.class, value)); return true;
case "ciphers": getOrCreateConfiguration(target).setCiphers(property(camelContext, java.lang.String.class, value)); return true;
case "clientbuilder":
case "clientBuilder": getOrCreateConfiguration(target).setClientBuilder(property(camelContext, org.apache.sshd.client.ClientBuilder.class, value)); return true;
case "compressions": getOrCreateConfiguration(target).setCompressions(property(camelContext, java.lang.String.class, value)); return true;
case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.ssh.SshConfiguration.class, value)); return true;
case "failonunknownhost":
case "failOnUnknownHost": getOrCreateConfiguration(target).setFailOnUnknownHost(property(camelContext, boolean.class, value)); return true;
case "healthcheckconsumerenabled":
case "healthCheckConsumerEnabled": target.setHealthCheckConsumerEnabled(property(camelContext, boolean.class, value)); return true;
case "healthcheckproducerenabled":
case "healthCheckProducerEnabled": target.setHealthCheckProducerEnabled(property(camelContext, boolean.class, value)); return true;
case "kex": getOrCreateConfiguration(target).setKex(property(camelContext, java.lang.String.class, value)); return true;
case "keypairprovider":
case "keyPairProvider": getOrCreateConfiguration(target).setKeyPairProvider(property(camelContext, org.apache.sshd.common.keyprovider.KeyPairProvider.class, value)); return true;
case "keytype":
case "keyType": getOrCreateConfiguration(target).setKeyType(property(camelContext, java.lang.String.class, value)); return true;
case "knownhostsresource":
case "knownHostsResource": getOrCreateConfiguration(target).setKnownHostsResource(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "macs": getOrCreateConfiguration(target).setMacs(property(camelContext, java.lang.String.class, value)); return true;
case "password": getOrCreateConfiguration(target).setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "pollcommand":
case "pollCommand": getOrCreateConfiguration(target).setPollCommand(property(camelContext, java.lang.String.class, value)); return true;
case "shellprompt":
case "shellPrompt": getOrCreateConfiguration(target).setShellPrompt(property(camelContext, java.lang.String.class, value)); return true;
case "signatures": getOrCreateConfiguration(target).setSignatures(property(camelContext, java.lang.String.class, value)); return true;
case "sleepforshellprompt":
case "sleepForShellPrompt": getOrCreateConfiguration(target).setSleepForShellPrompt(property(camelContext, long.class, value)); return true;
case "timeout": getOrCreateConfiguration(target).setTimeout(property(camelContext, long.class, value)); return true;
case "username": getOrCreateConfiguration(target).setUsername(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public String[] getAutowiredNames() {
return new String[]{"clientBuilder"};
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "certresource":
case "certResource": return java.lang.String.class;
case "certresourcepassword":
case "certResourcePassword": return java.lang.String.class;
case "channeltype":
case "channelType": return java.lang.String.class;
case "ciphers": return java.lang.String.class;
case "clientbuilder":
case "clientBuilder": return org.apache.sshd.client.ClientBuilder.class;
case "compressions": return java.lang.String.class;
case "configuration": return org.apache.camel.component.ssh.SshConfiguration.class;
case "failonunknownhost":
case "failOnUnknownHost": return boolean.class;
case "healthcheckconsumerenabled":
case "healthCheckConsumerEnabled": return boolean.class;
case "healthcheckproducerenabled":
case "healthCheckProducerEnabled": return boolean.class;
case "kex": return java.lang.String.class;
case "keypairprovider":
case "keyPairProvider": return org.apache.sshd.common.keyprovider.KeyPairProvider.class;
case "keytype":
case "keyType": return java.lang.String.class;
case "knownhostsresource":
case "knownHostsResource": return java.lang.String.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "macs": return java.lang.String.class;
case "password": return java.lang.String.class;
case "pollcommand":
case "pollCommand": return java.lang.String.class;
case "shellprompt":
case "shellPrompt": return java.lang.String.class;
case "signatures": return java.lang.String.class;
case "sleepforshellprompt":
case "sleepForShellPrompt": return long.class;
case "timeout": return long.class;
case "username": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
SshComponent target = (SshComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "certresource":
case "certResource": return getOrCreateConfiguration(target).getCertResource();
case "certresourcepassword":
case "certResourcePassword": return getOrCreateConfiguration(target).getCertResourcePassword();
case "channeltype":
case "channelType": return getOrCreateConfiguration(target).getChannelType();
case "ciphers": return getOrCreateConfiguration(target).getCiphers();
case "clientbuilder":
case "clientBuilder": return getOrCreateConfiguration(target).getClientBuilder();
case "compressions": return getOrCreateConfiguration(target).getCompressions();
case "configuration": return target.getConfiguration();
case "failonunknownhost":
case "failOnUnknownHost": return getOrCreateConfiguration(target).isFailOnUnknownHost();
case "healthcheckconsumerenabled":
case "healthCheckConsumerEnabled": return target.isHealthCheckConsumerEnabled();
case "healthcheckproducerenabled":
case "healthCheckProducerEnabled": return target.isHealthCheckProducerEnabled();
case "kex": return getOrCreateConfiguration(target).getKex();
case "keypairprovider":
case "keyPairProvider": return getOrCreateConfiguration(target).getKeyPairProvider();
case "keytype":
case "keyType": return getOrCreateConfiguration(target).getKeyType();
case "knownhostsresource":
case "knownHostsResource": return getOrCreateConfiguration(target).getKnownHostsResource();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "macs": return getOrCreateConfiguration(target).getMacs();
case "password": return getOrCreateConfiguration(target).getPassword();
case "pollcommand":
case "pollCommand": return getOrCreateConfiguration(target).getPollCommand();
case "shellprompt":
case "shellPrompt": return getOrCreateConfiguration(target).getShellPrompt();
case "signatures": return getOrCreateConfiguration(target).getSignatures();
case "sleepforshellprompt":
case "sleepForShellPrompt": return getOrCreateConfiguration(target).getSleepForShellPrompt();
case "timeout": return getOrCreateConfiguration(target).getTimeout();
case "username": return getOrCreateConfiguration(target).getUsername();
default: return null;
}
}
}
| SshComponentConfigurer |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/association/bidirectional/onetomany/BidirectionalOneToManyBagSubclassCollectionEventTest.java | {
"start": 495,
"end": 746
} | class ____ extends BidirectionalOneToManyBagCollectionEventTest {
@Override
public ParentWithCollection createParent(String name) {
return new ParentWithBidirectionalOneToManySubclass( name );
}
}
| BidirectionalOneToManyBagSubclassCollectionEventTest |
java | google__guava | android/guava/src/com/google/common/collect/ImmutableRangeMap.java | {
"start": 4518,
"end": 13519
} | class ____<K extends Comparable<?>, V> {
private final List<Entry<Range<K>, V>> entries;
public Builder() {
this.entries = new ArrayList<>();
}
/**
* Associates the specified range with the specified value.
*
* @throws IllegalArgumentException if {@code range} is empty
*/
@CanIgnoreReturnValue
public Builder<K, V> put(Range<K> range, V value) {
checkNotNull(range);
checkNotNull(value);
checkArgument(!range.isEmpty(), "Range must not be empty, but was %s", range);
entries.add(immutableEntry(range, value));
return this;
}
/** Copies all associations from the specified range map into this builder. */
@CanIgnoreReturnValue
public Builder<K, V> putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
@CanIgnoreReturnValue
Builder<K, V> combine(Builder<K, V> builder) {
entries.addAll(builder.entries);
return this;
}
/**
* Returns an {@code ImmutableRangeMap} containing the associations previously added to this
* builder.
*
* @throws IllegalArgumentException if any two ranges inserted into this builder overlap
*/
public ImmutableRangeMap<K, V> build() {
sort(entries, Range.<K>rangeLexOrdering().onKeys());
ImmutableList.Builder<Range<K>> rangesBuilder = new ImmutableList.Builder<>(entries.size());
ImmutableList.Builder<V> valuesBuilder = new ImmutableList.Builder<>(entries.size());
for (int i = 0; i < entries.size(); i++) {
Range<K> range = entries.get(i).getKey();
if (i > 0) {
Range<K> prevRange = entries.get(i - 1).getKey();
if (range.isConnected(prevRange) && !range.intersection(prevRange).isEmpty()) {
throw new IllegalArgumentException(
"Overlapping ranges: range " + prevRange + " overlaps with entry " + range);
}
}
rangesBuilder.add(range);
valuesBuilder.add(entries.get(i).getValue());
}
return new ImmutableRangeMap<>(rangesBuilder.build(), valuesBuilder.build());
}
}
private final transient ImmutableList<Range<K>> ranges;
private final transient ImmutableList<V> values;
ImmutableRangeMap(ImmutableList<Range<K>> ranges, ImmutableList<V> values) {
this.ranges = ranges;
this.values = values;
}
@Override
public @Nullable V get(K key) {
int index =
SortedLists.binarySearch(
ranges,
Range::lowerBound,
Cut.belowValue(key),
KeyPresentBehavior.ANY_PRESENT,
KeyAbsentBehavior.NEXT_LOWER);
if (index == -1) {
return null;
} else {
Range<K> range = ranges.get(index);
return range.contains(key) ? values.get(index) : null;
}
}
@Override
public @Nullable Entry<Range<K>, V> getEntry(K key) {
int index =
SortedLists.binarySearch(
ranges,
Range::lowerBound,
Cut.belowValue(key),
KeyPresentBehavior.ANY_PRESENT,
KeyAbsentBehavior.NEXT_LOWER);
if (index == -1) {
return null;
} else {
Range<K> range = ranges.get(index);
return range.contains(key) ? immutableEntry(range, values.get(index)) : null;
}
}
@Override
public Range<K> span() {
if (ranges.isEmpty()) {
throw new NoSuchElementException();
}
Range<K> firstRange = ranges.get(0);
Range<K> lastRange = ranges.get(ranges.size() - 1);
return Range.create(firstRange.lowerBound, lastRange.upperBound);
}
/**
* Guaranteed to throw an exception and leave the {@code RangeMap} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void put(Range<K> range, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeMap} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void putCoalescing(Range<K> range, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeMap} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void putAll(RangeMap<K, ? extends V> rangeMap) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeMap} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void clear() {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the {@code RangeMap} unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public final void remove(Range<K> range) {
throw new UnsupportedOperationException();
}
@Override
public ImmutableMap<Range<K>, V> asMapOfRanges() {
if (ranges.isEmpty()) {
return ImmutableMap.of();
}
RegularImmutableSortedSet<Range<K>> rangeSet =
new RegularImmutableSortedSet<>(ranges, rangeLexOrdering());
return new ImmutableSortedMap<>(rangeSet, values);
}
@Override
public ImmutableMap<Range<K>, V> asDescendingMapOfRanges() {
if (ranges.isEmpty()) {
return ImmutableMap.of();
}
RegularImmutableSortedSet<Range<K>> rangeSet =
new RegularImmutableSortedSet<>(ranges.reverse(), Range.<K>rangeLexOrdering().reverse());
return new ImmutableSortedMap<>(rangeSet, values.reverse());
}
@Override
public ImmutableRangeMap<K, V> subRangeMap(Range<K> range) {
if (checkNotNull(range).isEmpty()) {
return ImmutableRangeMap.of();
} else if (ranges.isEmpty() || range.encloses(span())) {
return this;
}
int lowerIndex =
SortedLists.binarySearch(
ranges,
Range::upperBound,
range.lowerBound,
KeyPresentBehavior.FIRST_AFTER,
KeyAbsentBehavior.NEXT_HIGHER);
int upperIndex =
SortedLists.binarySearch(
ranges,
Range::lowerBound,
range.upperBound,
KeyPresentBehavior.ANY_PRESENT,
KeyAbsentBehavior.NEXT_HIGHER);
if (lowerIndex >= upperIndex) {
return ImmutableRangeMap.of();
}
int off = lowerIndex;
int len = upperIndex - lowerIndex;
ImmutableList<Range<K>> subRanges =
new ImmutableList<Range<K>>() {
@Override
public int size() {
return len;
}
@Override
public Range<K> get(int index) {
checkElementIndex(index, len);
if (index == 0 || index == len - 1) {
return ranges.get(index + off).intersection(range);
} else {
return ranges.get(index + off);
}
}
@Override
boolean isPartialView() {
return true;
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
};
ImmutableRangeMap<K, V> outer = this;
return new ImmutableRangeMap<K, V>(subRanges, values.subList(lowerIndex, upperIndex)) {
@Override
public ImmutableRangeMap<K, V> subRangeMap(Range<K> subRange) {
if (range.isConnected(subRange)) {
return outer.subRangeMap(subRange.intersection(range));
} else {
return ImmutableRangeMap.of();
}
}
// redeclare to help optimizers with b/310253115
@SuppressWarnings("RedundantOverride")
@Override
@J2ktIncompatible // serialization
Object writeReplace() {
return super.writeReplace();
}
};
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public boolean equals(@Nullable Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
/**
* This | Builder |
java | grpc__grpc-java | core/src/testFixtures/java/io/grpc/internal/MockServerTransportListener.java | {
"start": 2643,
"end": 3080
} | class ____ {
public final ServerStream stream;
public final String method;
public final Metadata headers;
public final ServerStreamListenerBase listener;
public StreamCreation(
ServerStream stream, String method, Metadata headers, ServerStreamListenerBase listener) {
this.stream = stream;
this.method = method;
this.headers = headers;
this.listener = listener;
}
}
}
| StreamCreation |
java | apache__camel | components/camel-bean/src/main/java/org/apache/camel/component/bean/MethodsFilter.java | {
"start": 1144,
"end": 2568
} | class ____ {
private final List<Method> methods = new ArrayList<>();
private final Class<?> inheritingClass;
/**
* Creates a <code>MethodsFilter</code> for a given {@link java.lang.Class}.
*
* @param clazz The {@link java.lang.Class} whose methods are to be filtered.
*/
public MethodsFilter(Class<?> clazz) {
this.inheritingClass = clazz;
}
/**
* Retains methods, preferring those from public classes in case of overrides.
*
* @param proposedMethod The method proposed to the filter.
*/
void filterMethod(Method proposedMethod) {
if (proposedMethod.isBridge()) {
return;
}
for (int i = 0; i < methods.size(); i++) {
Method alreadyRegistered = methods.get(i);
if (Modifier.isPublic(proposedMethod.getDeclaringClass().getModifiers())) {
boolean overridden = ObjectHelper.isOverridingMethod(inheritingClass, proposedMethod, alreadyRegistered, false);
boolean overridding
= ObjectHelper.isOverridingMethod(inheritingClass, alreadyRegistered, proposedMethod, false);
boolean registeredMethodIsPublic = Modifier.isPublic(alreadyRegistered.getDeclaringClass().getModifiers());
if (overridden && !registeredMethodIsPublic) {
// Retain the overridden method from a public | MethodsFilter |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/exchange/ExchangeServiceTests.java | {
"start": 3433,
"end": 8059
} | class ____ extends ESTestCase {
private TestThreadPool threadPool;
private static final String ESQL_TEST_EXECUTOR = "esql_test_executor";
@Before
public void setThreadPool() {
int numThreads = randomBoolean() ? 1 : between(2, 16);
threadPool = new TestThreadPool(
"test",
new FixedExecutorBuilder(Settings.EMPTY, ESQL_TEST_EXECUTOR, numThreads, 1024, "esql", EsExecutors.TaskTrackingConfig.DEFAULT)
);
}
@After
public void shutdownThreadPool() {
terminate(threadPool);
}
public void testBasic() throws Exception {
BlockFactory blockFactory = blockFactory();
Page[] pages = new Page[7];
for (int i = 0; i < pages.length; i++) {
pages[i] = new Page(blockFactory.newConstantIntBlockWith(i, 2));
}
ExchangeSinkHandler sinkExchanger = new ExchangeSinkHandler(blockFactory, 2, threadPool.relativeTimeInMillisSupplier());
AtomicInteger pagesAddedToSink = new AtomicInteger();
ExchangeSink sink1 = sinkExchanger.createExchangeSink(pagesAddedToSink::incrementAndGet);
ExchangeSink sink2 = sinkExchanger.createExchangeSink(pagesAddedToSink::incrementAndGet);
ExchangeSourceHandler sourceExchanger = new ExchangeSourceHandler(3, threadPool.executor(ESQL_TEST_EXECUTOR));
ExchangeSource source = sourceExchanger.createExchangeSource();
AtomicInteger pagesAddedToSource = new AtomicInteger();
PlainActionFuture<Void> remoteSinkFuture = new PlainActionFuture<>();
sourceExchanger.addRemoteSink(
sinkExchanger::fetchPageAsync,
randomBoolean(),
pagesAddedToSource::incrementAndGet,
1,
remoteSinkFuture
);
SubscribableListener<Void> waitForReading = source.waitForReading().listener();
assertFalse(waitForReading.isDone());
assertNull(source.pollPage());
assertTrue(sink1.waitForWriting().listener().isDone());
randomFrom(sink1, sink2).addPage(pages[0]);
assertThat(pagesAddedToSink.get(), equalTo(1));
randomFrom(sink1, sink2).addPage(pages[1]);
assertThat(pagesAddedToSink.get(), equalTo(2));
assertBusy(() -> assertThat(pagesAddedToSource.get(), equalTo(2)));
// source and sink buffers can store 5 pages
for (Page p : List.of(pages[2], pages[3], pages[4])) {
ExchangeSink sink = randomFrom(sink1, sink2);
assertBusy(() -> assertTrue(sink.waitForWriting().listener().isDone()));
sink.addPage(p);
}
assertThat(pagesAddedToSink.get(), equalTo(5));
assertBusy(() -> assertThat(pagesAddedToSource.get(), equalTo(3)));
// sink buffer is full
assertFalse(randomFrom(sink1, sink2).waitForWriting().listener().isDone());
assertBusy(() -> assertTrue(source.waitForReading().listener().isDone()));
assertEquals(pages[0], source.pollPage());
assertBusy(() -> assertTrue(source.waitForReading().listener().isDone()));
assertEquals(pages[1], source.pollPage());
assertBusy(() -> assertThat(pagesAddedToSource.get(), equalTo(5)));
// sink can write again
assertBusy(() -> assertTrue(randomFrom(sink1, sink2).waitForWriting().listener().isDone()));
randomFrom(sink1, sink2).addPage(pages[5]);
assertBusy(() -> assertTrue(randomFrom(sink1, sink2).waitForWriting().listener().isDone()));
randomFrom(sink1, sink2).addPage(pages[6]);
assertThat(pagesAddedToSink.get(), equalTo(7));
// sink buffer is full
assertFalse(randomFrom(sink1, sink2).waitForWriting().listener().isDone());
sink1.finish();
assertTrue(sink1.isFinished());
for (int i = 0; i < 5; i++) {
assertBusy(() -> assertTrue(source.waitForReading().listener().isDone()));
assertEquals(pages[2 + i], source.pollPage());
}
assertBusy(() -> assertThat(pagesAddedToSource.get(), equalTo(7)));
// source buffer is empty
assertFalse(source.waitForReading().listener().isDone());
assertBusy(() -> assertTrue(sink2.waitForWriting().listener().isDone()));
sink2.finish();
assertTrue(sink2.isFinished());
assertTrue(source.isFinished());
source.finish();
ESTestCase.terminate(threadPool);
for (Page page : pages) {
page.releaseBlocks();
}
safeGet(remoteSinkFuture);
}
/**
* Generates sequence numbers up to the {@code maxInputSeqNo} (exclusive)
*/
static | ExchangeServiceTests |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockAM.java | {
"start": 2902,
"end": 18626
} | class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(MockAM.class);
private volatile int responseId = 0;
private final ApplicationAttemptId attemptId;
private RMContext context;
private ApplicationMasterProtocol amRMProtocol;
private UserGroupInformation ugi;
private volatile AllocateResponse lastResponse;
private Map<Set<String>, PlacementConstraint> placementConstraints =
new HashMap<>();
private List<SchedulingRequest> schedulingRequests = new ArrayList<>();
private final List<ResourceRequest> requests = new ArrayList<ResourceRequest>();
private final List<ContainerId> releases = new ArrayList<ContainerId>();
public MockAM(RMContext context, ApplicationMasterProtocol amRMProtocol,
ApplicationAttemptId attemptId) {
this.context = context;
this.amRMProtocol = amRMProtocol;
this.attemptId = attemptId;
}
public void setAMRMProtocol(ApplicationMasterProtocol amRMProtocol,
RMContext context) {
this.context = context;
this.amRMProtocol = amRMProtocol;
}
/**
* Wait until an attempt has reached a specified state.
* The timeout is 40 seconds.
* @param finalState the attempt state waited
* @throws InterruptedException
* if interrupted while waiting for the state transition
*/
private void waitForState(RMAppAttemptState finalState)
throws InterruptedException {
RMApp app = context.getRMApps().get(attemptId.getApplicationId());
RMAppAttempt attempt = app.getRMAppAttempt(attemptId);
MockRM.waitForState(attempt, finalState);
}
public RegisterApplicationMasterResponse registerAppAttempt()
throws Exception {
return registerAppAttempt(true);
}
public void addPlacementConstraint(Set<String> tags,
PlacementConstraint constraint) {
placementConstraints.put(tags, constraint);
}
public MockAM addSchedulingRequest(List<SchedulingRequest> reqs) {
schedulingRequests.addAll(reqs);
return this;
}
public RegisterApplicationMasterResponse registerAppAttempt(boolean wait)
throws Exception {
if (wait) {
waitForState(RMAppAttemptState.LAUNCHED);
}
responseId = 0;
final RegisterApplicationMasterRequest req =
Records.newRecord(RegisterApplicationMasterRequest.class);
req.setHost("");
req.setRpcPort(1);
req.setTrackingUrl("");
if (!placementConstraints.isEmpty()) {
req.setPlacementConstraints(this.placementConstraints);
}
if (ugi == null) {
ugi = UserGroupInformation.createRemoteUser(
attemptId.toString());
Token<AMRMTokenIdentifier> token =
context.getRMApps().get(attemptId.getApplicationId())
.getRMAppAttempt(attemptId).getAMRMToken();
ugi.addTokenIdentifier(token.decodeIdentifier());
}
try {
return ugi
.doAs(
new PrivilegedExceptionAction<RegisterApplicationMasterResponse>() {
@Override
public RegisterApplicationMasterResponse run() throws Exception {
return amRMProtocol.registerApplicationMaster(req);
}
});
} catch (UndeclaredThrowableException e) {
throw (Exception) e.getCause();
}
}
public boolean setApplicationLastResponseId(int newLastResponseId) {
ApplicationMasterService applicationMasterService =
(ApplicationMasterService) amRMProtocol;
responseId = newLastResponseId;
return applicationMasterService.setAttemptLastResponseId(attemptId,
newLastResponseId);
}
public int getResponseId() {
return responseId;
}
public void addRequests(String[] hosts, int memory, int priority,
int containers) throws Exception {
addRequests(hosts, memory, priority, containers, 0L);
}
public void addRequests(String[] hosts, int memory, int priority,
int containers, long allocationRequestId) throws Exception {
requests.addAll(
createReq(hosts, memory, priority, containers, allocationRequestId));
}
public AllocateResponse schedule() throws Exception {
AllocateResponse response = allocate(requests, releases);
requests.clear();
releases.clear();
return response;
}
public void addContainerToBeReleased(ContainerId containerId) {
releases.add(containerId);
}
public AllocateResponse allocate(
String host, int memory, int numContainers,
List<ContainerId> releases) throws Exception {
return allocate(host, memory, numContainers, releases, null);
}
public AllocateResponse allocate(
String host, int memory, int numContainers,
List<ContainerId> releases, String labelExpression) throws Exception {
return allocate(host, memory, numContainers, 1, releases, labelExpression);
}
public AllocateResponse allocate(
String host, int memory, int numContainers, int priority,
List<ContainerId> releases, String labelExpression) throws Exception {
List<ResourceRequest> reqs =
createReq(new String[] { host }, memory, priority, numContainers,
labelExpression, -1);
return allocate(reqs, releases);
}
public AllocateResponse allocate(
String host, Resource cap, int numContainers,
List<ContainerId> rels, String labelExpression) throws Exception {
List<ResourceRequest> reqs = new ArrayList<>();
ResourceRequest oneReq =
createResourceReq(host, cap, numContainers,
labelExpression);
reqs.add(oneReq);
return allocate(reqs, rels);
}
public List<ResourceRequest> createReq(String[] hosts, int memory,
int priority, int containers, long allocationRequestId) throws Exception {
return createReq(hosts, memory, priority, containers, null,
allocationRequestId);
}
public List<ResourceRequest> createReq(String[] hosts, int memory,
int priority, int containers, String labelExpression,
long allocationRequestId) throws Exception {
List<ResourceRequest> reqs = new ArrayList<ResourceRequest>();
if (hosts != null) {
for (String host : hosts) {
// only add host/rack request when asked host isn't ANY
if (!host.equals(ResourceRequest.ANY)) {
ResourceRequest hostReq =
createResourceReq(host, memory, priority, containers,
labelExpression);
hostReq.setAllocationRequestId(allocationRequestId);
reqs.add(hostReq);
ResourceRequest rackReq =
createResourceReq("/default-rack", memory, priority, containers,
labelExpression);
rackReq.setAllocationRequestId(allocationRequestId);
reqs.add(rackReq);
}
}
}
ResourceRequest offRackReq = createResourceReq(ResourceRequest.ANY, memory,
priority, containers, labelExpression);
offRackReq.setAllocationRequestId(allocationRequestId);
reqs.add(offRackReq);
return reqs;
}
public ResourceRequest createResourceReq(String resource, int memory, int priority,
int containers) throws Exception {
return createResourceReq(resource, memory, priority, containers, null);
}
public ResourceRequest createResourceReq(String resource, int memory,
int priority, int containers, String labelExpression) throws Exception {
return createResourceReq(resource, memory, priority, containers,
labelExpression, ExecutionTypeRequest.newInstance());
}
public ResourceRequest createResourceReq(String resource, int memory,
int priority, int containers, String labelExpression,
ExecutionTypeRequest executionTypeRequest) throws Exception {
ResourceRequest req = Records.newRecord(ResourceRequest.class);
req.setResourceName(resource);
req.setNumContainers(containers);
Priority pri = Records.newRecord(Priority.class);
pri.setPriority(priority);
req.setPriority(pri);
Resource capability = Records.newRecord(Resource.class);
capability.setMemorySize(memory);
req.setCapability(capability);
if (labelExpression != null) {
req.setNodeLabelExpression(labelExpression);
}
req.setExecutionTypeRequest(executionTypeRequest);
return req;
}
public ResourceRequest createResourceReq(String host, Resource cap,
int containers, String labelExpression) throws Exception {
ResourceRequest req = Records.newRecord(ResourceRequest.class);
req.setResourceName(host);
req.setNumContainers(containers);
Priority pri = Records.newRecord(Priority.class);
pri.setPriority(1);
req.setPriority(pri);
req.setCapability(cap);
if (labelExpression != null) {
req.setNodeLabelExpression(labelExpression);
}
req.setExecutionTypeRequest(ExecutionTypeRequest.newInstance());
return req;
}
public AllocateResponse allocate(
List<ResourceRequest> resourceRequest, List<ContainerId> releases)
throws Exception {
final AllocateRequest req =
AllocateRequest.newInstance(0, 0F, resourceRequest,
releases, null);
if (!schedulingRequests.isEmpty()) {
req.setSchedulingRequests(schedulingRequests);
schedulingRequests.clear();
}
return allocate(req);
}
public AllocateResponse allocate(List<ResourceRequest> resourceRequest,
List<SchedulingRequest> newSchedulingRequests, List<ContainerId> releases)
throws Exception {
final AllocateRequest req =
AllocateRequest.newInstance(0, 0F, resourceRequest,
releases, null);
if (newSchedulingRequests != null) {
addSchedulingRequest(newSchedulingRequests);
}
if (!schedulingRequests.isEmpty()) {
req.setSchedulingRequests(schedulingRequests);
schedulingRequests.clear();
}
return allocate(req);
}
public AllocateResponse allocateIntraAppAntiAffinity(
ResourceSizing resourceSizing, Priority priority, long allocationId,
Set<String> allocationTags, String... targetTags) throws Exception {
return allocateAppAntiAffinity(resourceSizing, priority, allocationId,
null, allocationTags, targetTags);
}
public AllocateResponse allocateAppAntiAffinity(
ResourceSizing resourceSizing, Priority priority, long allocationId,
String namespace, Set<String> allocationTags, String... targetTags)
throws Exception {
return this.allocate(null,
Arrays.asList(SchedulingRequest.newBuilder().executionType(
ExecutionTypeRequest.newInstance(ExecutionType.GUARANTEED))
.allocationRequestId(allocationId).priority(priority)
.allocationTags(allocationTags).placementConstraintExpression(
PlacementConstraints
.targetNotIn(PlacementConstraints.NODE,
PlacementConstraints.PlacementTargets
.allocationTagWithNamespace(namespace, targetTags))
.build())
.resourceSizing(resourceSizing).build()), null);
}
public AllocateResponse allocateIntraAppAntiAffinity(
String nodePartition, ResourceSizing resourceSizing, Priority priority,
long allocationId, String... tags) throws Exception {
return this.allocate(null,
Arrays.asList(SchedulingRequest.newBuilder().executionType(
ExecutionTypeRequest.newInstance(ExecutionType.GUARANTEED))
.allocationRequestId(allocationId).priority(priority)
.placementConstraintExpression(PlacementConstraints
.targetNotIn(PlacementConstraints.NODE,
PlacementConstraints.PlacementTargets
.allocationTag(tags),
PlacementConstraints.PlacementTargets
.nodePartition(nodePartition)).build())
.resourceSizing(resourceSizing).build()), null);
}
public AllocateResponse sendContainerResizingRequest(
List<UpdateContainerRequest> updateRequests) throws Exception {
final AllocateRequest req = AllocateRequest.newInstance(0, 0F, null, null,
updateRequests, null);
return allocate(req);
}
public AllocateResponse sendContainerUpdateRequest(
List<UpdateContainerRequest> updateRequests) throws Exception {
final AllocateRequest req = AllocateRequest.newInstance(0, 0F, null, null,
updateRequests, null);
return allocate(req);
}
public AllocateResponse allocate(AllocateRequest allocateRequest)
throws Exception {
UserGroupInformation ugi =
UserGroupInformation.createRemoteUser(attemptId.toString());
Token<AMRMTokenIdentifier> token =
context.getRMApps().get(attemptId.getApplicationId())
.getRMAppAttempt(attemptId).getAMRMToken();
ugi.addTokenIdentifier(token.decodeIdentifier());
lastResponse = doAllocateAs(ugi, allocateRequest);
return lastResponse;
}
public AllocateResponse doAllocateAs(UserGroupInformation ugi,
final AllocateRequest req) throws Exception {
req.setResponseId(responseId);
try {
AllocateResponse response =
ugi.doAs(new PrivilegedExceptionAction<AllocateResponse>() {
@Override
public AllocateResponse run() throws Exception {
return amRMProtocol.allocate(req);
}
});
responseId = response.getResponseId();
return response;
} catch (UndeclaredThrowableException e) {
throw (Exception) e.getCause();
}
}
public AllocateResponse doHeartbeat() throws Exception {
return allocate(null, null);
}
public void unregisterAppAttempt() throws Exception {
waitForState(RMAppAttemptState.RUNNING);
unregisterAppAttempt(true);
}
public void unregisterAppAttempt(boolean waitForStateRunning)
throws Exception {
final FinishApplicationMasterRequest req =
FinishApplicationMasterRequest.newInstance(
FinalApplicationStatus.SUCCEEDED, "", "");
unregisterAppAttempt(req, waitForStateRunning);
}
public void unregisterAppAttempt(final FinishApplicationMasterRequest req,
boolean waitForStateRunning) throws Exception {
if (waitForStateRunning) {
waitForState(RMAppAttemptState.RUNNING);
}
if (ugi == null) {
ugi = UserGroupInformation.createRemoteUser(attemptId.toString());
Token<AMRMTokenIdentifier> token =
context.getRMApps()
.get(attemptId.getApplicationId())
.getRMAppAttempt(attemptId).getAMRMToken();
ugi.addTokenIdentifier(token.decodeIdentifier());
}
try {
ugi.doAs(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
amRMProtocol.finishApplicationMaster(req);
return null;
}
});
} catch (UndeclaredThrowableException e) {
throw (Exception) e.getCause();
}
}
public ApplicationAttemptId getApplicationAttemptId() {
return this.attemptId;
}
public List<Container> allocateAndWaitForContainers(int nContainer,
int memory, MockNM nm) throws Exception {
return allocateAndWaitForContainers("ANY", nContainer, memory, nm);
}
public List<Container> allocateAndWaitForContainers(String host,
int nContainer, int memory, MockNM nm) throws Exception {
// AM request for containers
allocate(host, memory, nContainer, null);
// kick the scheduler
nm.nodeHeartbeat(true);
List<Container> conts = allocate(new ArrayList<ResourceRequest>(), null)
.getAllocatedContainers();
while (conts.size() < nContainer) {
nm.nodeHeartbeat(true);
conts.addAll(allocate(new ArrayList<ResourceRequest>(),
new ArrayList<ContainerId>()).getAllocatedContainers());
Thread.sleep(500);
}
return conts;
}
}
| MockAM |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/StaleObjectStateException.java | {
"start": 366,
"end": 1885
} | class ____ extends StaleStateException {
private final String entityName;
private final Object identifier;
/**
* Constructs a {@code StaleObjectStateException} using the supplied information.
*
* @param entityName The name of the entity
* @param identifier The identifier of the entity
*/
public StaleObjectStateException(String entityName, Object identifier) {
this( entityName, identifier, "Row was already updated or deleted by another transaction" );
}
/**
* Constructs a {@code StaleObjectStateException} using the supplied information.
*
* @param entityName The name of the entity
* @param identifier The identifier of the entity
*/
public StaleObjectStateException(String entityName, Object identifier, String message) {
super( message );
this.entityName = entityName;
this.identifier = identifier;
}
/**
* Constructs a {@code StaleObjectStateException} using the supplied information
* and cause.
*
* @param entityName The name of the entity
* @param identifier The identifier of the entity
*/
public StaleObjectStateException(String entityName, Object identifier, StaleStateException cause) {
super( cause.getMessage(), cause );
this.entityName = entityName;
this.identifier = identifier;
}
public String getEntityName() {
return entityName;
}
public Object getIdentifier() {
return identifier;
}
public String getMessage() {
return super.getMessage() + " for entity " + infoString( entityName, identifier );
}
}
| StaleObjectStateException |
java | netty__netty | microbench/src/main/java/io/netty/microbench/buffer/ByteBufBenchmark.java | {
"start": 1039,
"end": 2577
} | class ____ extends AbstractMicrobenchmark {
static {
System.setProperty("io.netty.buffer.checkAccessible", "false");
}
private static final byte BYTE = '0';
@Param({
"true",
"false",
})
public String checkBounds;
private ByteBuffer byteBuffer;
private ByteBuffer directByteBuffer;
private ByteBuf buffer;
private ByteBuf directBuffer;
private ByteBuf directBufferPooled;
@Setup
public void setup() {
System.setProperty("io.netty.buffer.checkBounds", checkBounds);
byteBuffer = ByteBuffer.allocate(8);
directByteBuffer = ByteBuffer.allocateDirect(8);
buffer = Unpooled.buffer(8);
directBuffer = Unpooled.directBuffer(8);
directBufferPooled = PooledByteBufAllocator.DEFAULT.directBuffer(8);
}
@TearDown
public void tearDown() {
buffer.release();
directBuffer.release();
directBufferPooled.release();
}
@Benchmark
public ByteBuffer setByteBufferHeap() {
return byteBuffer.put(0, BYTE);
}
@Benchmark
public ByteBuffer setByteBufferDirect() {
return directByteBuffer.put(0, BYTE);
}
@Benchmark
public ByteBuf setByteBufHeap() {
return buffer.setByte(0, BYTE);
}
@Benchmark
public ByteBuf setByteBufDirect() {
return directBuffer.setByte(0, BYTE);
}
@Benchmark
public ByteBuf setByteBufDirectPooled() {
return directBufferPooled.setByte(0, BYTE);
}
}
| ByteBufBenchmark |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedMethodTest.java | {
"start": 7412,
"end": 8277
} | class ____ {
private Function<Integer, Integer> usedInLambda() {
return x -> 1;
}
private String print(Object o) {
return o.toString();
}
public List<String> print(List<Object> os) {
return os.stream().map(this::print).collect(Collectors.toList());
}
public static void main(String[] args) {
System.err.println(new UsedInLambda().usedInLambda());
System.err.println(new UsedInLambda().print(Arrays.asList(1, 2, 3)));
}
}
""")
.doTest();
}
@Test
public void onlyForMethodReference() {
helper
.addSourceLines(
"Test.java",
"""
import java.util.function.Predicate;
| UsedInLambda |
java | dropwizard__dropwizard | dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapperTest.java | {
"start": 424,
"end": 1344
} | class ____ {
private final IllegalStateExceptionMapper mapper = new IllegalStateExceptionMapper();
@Test
void delegatesToParentClass() {
@SuppressWarnings("serial")
final Response reponse = mapper.toResponse(new IllegalStateException(getClass().getName()) {
});
assertThat(reponse.getStatusInfo()).isEqualTo(INTERNAL_SERVER_ERROR);
}
@Test
void handlesFormParamContentTypeError() {
final Response reponse = mapper
.toResponse(new IllegalStateException(LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR()));
assertThat(reponse.getStatusInfo()).isEqualTo(UNSUPPORTED_MEDIA_TYPE);
assertThat(reponse.getEntity()).isInstanceOf(ErrorMessage.class);
assertThat(((ErrorMessage) reponse.getEntity()).getMessage())
.isEqualTo(new NotSupportedException().getLocalizedMessage());
}
}
| IllegalStateExceptionMapperTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/LocalPhysicalPlanOptimizerTests.java | {
"start": 123362,
"end": 123815
} | class ____ extends FullTextFunctionTestCase {
MatchOperatorTestCase() {
super(MatchOperator.class);
}
@Override
public QueryBuilder queryBuilder() {
return new MatchQueryBuilder(fieldName(), queryString()).lenient(true);
}
@Override
public String esqlQuery() {
return fieldName() + ": \"" + queryString() + "\"";
}
}
private | MatchOperatorTestCase |
java | google__truth | extensions/liteproto/src/test/java/com/google/common/truth/extensions/proto/LiteProtoSubjectTest.java | {
"start": 1893,
"end": 2454
} | class ____ {
abstract MessageLite nonEmptyMessage();
abstract MessageLite equivalentNonEmptyMessage();
abstract MessageLite nonEmptyMessageOfOtherValue();
abstract MessageLite nonEmptyMessageOfOtherType();
abstract MessageLite defaultInstance();
abstract MessageLite defaultInstanceOfOtherType();
abstract Optional<MessageLite> messageWithoutRequiredFields();
public static Builder newBuilder() {
return new AutoValue_LiteProtoSubjectTest_Config.Builder();
}
@AutoValue.Builder
public abstract static | Config |
java | elastic__elasticsearch | libs/x-content/src/main/java/org/elasticsearch/xcontent/ConstructingObjectParser.java | {
"start": 11178,
"end": 23148
} | interface ____.
public static <Value, FieldT> BiConsumer<Value, FieldT> optionalConstructorArg() {
return (BiConsumer<Value, FieldT>) OPTIONAL_CONSTRUCTOR_ARG_MARKER;
}
@Override
public <T> void declareField(BiConsumer<Value, T> consumer, ContextParser<Context, T> parser, ParseField parseField, ValueType type) {
if (consumer == null) {
throw new IllegalArgumentException("[consumer] is required");
}
if (parser == null) {
throw new IllegalArgumentException("[parser] is required");
}
if (parseField == null) {
throw new IllegalArgumentException("[parseField] is required");
}
if (type == null) {
throw new IllegalArgumentException("[type] is required");
}
if (isConstructorArg(consumer)) {
/*
* Build a new consumer directly against the object parser that
* triggers the "constructor arg just arrived behavior" of the
* parser. Conveniently, we can close over the position of the
* constructor in the argument list so we don't need to do any fancy
* or expensive lookups whenever the constructor args come in.
*/
Map<RestApiVersion, Integer> positions = addConstructorArg(consumer, parseField);
objectParser.declareField((target, v) -> target.constructorArg(positions, v), parser, parseField, type);
} else {
numberOfFields += 1;
objectParser.declareField(queueingConsumer(consumer, parseField), parser, parseField, type);
}
}
/**
* Declare a field that is an array of objects or null. Used to avoid calling the consumer when used with
* {@link #optionalConstructorArg()} or {@link #constructorArg()}.
* @param consumer Consumer that will be passed as is to the {@link #declareField(BiConsumer, ContextParser, ParseField, ValueType)}.
* @param objectParser Parser that will parse the objects in the array, checking for nulls.
* @param field Field to declare.
*/
@Override
public <T> void declareObjectArrayOrNull(
BiConsumer<Value, List<T>> consumer,
ContextParser<Context, T> objectParser,
ParseField field
) {
declareField(
consumer,
(p, c) -> p.currentToken() == XContentParser.Token.VALUE_NULL ? null : parseArray(p, c, objectParser),
field,
ValueType.OBJECT_ARRAY_OR_NULL
);
}
@Override
public <T> void declareNamedObject(
BiConsumer<Value, T> consumer,
NamedObjectParser<T, Context> namedObjectParser,
ParseField parseField
) {
if (consumer == null) {
throw new IllegalArgumentException("[consumer] is required");
}
if (namedObjectParser == null) {
throw new IllegalArgumentException("[parser] is required");
}
if (parseField == null) {
throw new IllegalArgumentException("[parseField] is required");
}
if (isConstructorArg(consumer)) {
/*
* Build a new consumer directly against the object parser that
* triggers the "constructor arg just arrived behavior" of the
* parser. Conveniently, we can close over the position of the
* constructor in the argument list so we don't need to do any fancy
* or expensive lookups whenever the constructor args come in.
*/
Map<RestApiVersion, Integer> positions = addConstructorArg(consumer, parseField);
objectParser.declareNamedObject((target, v) -> target.constructorArg(positions, v), namedObjectParser, parseField);
} else {
numberOfFields += 1;
objectParser.declareNamedObject(queueingConsumer(consumer, parseField), namedObjectParser, parseField);
}
}
@Override
public <T> void declareNamedObjects(
BiConsumer<Value, List<T>> consumer,
NamedObjectParser<T, Context> namedObjectParser,
ParseField parseField
) {
if (consumer == null) {
throw new IllegalArgumentException("[consumer] is required");
}
if (namedObjectParser == null) {
throw new IllegalArgumentException("[parser] is required");
}
if (parseField == null) {
throw new IllegalArgumentException("[parseField] is required");
}
if (isConstructorArg(consumer)) {
/*
* Build a new consumer directly against the object parser that
* triggers the "constructor arg just arrived behavior" of the
* parser. Conveniently, we can close over the position of the
* constructor in the argument list so we don't need to do any fancy
* or expensive lookups whenever the constructor args come in.
*/
Map<RestApiVersion, Integer> positions = addConstructorArg(consumer, parseField);
objectParser.declareNamedObjects((target, v) -> target.constructorArg(positions, v), namedObjectParser, parseField);
} else {
numberOfFields += 1;
objectParser.declareNamedObjects(queueingConsumer(consumer, parseField), namedObjectParser, parseField);
}
}
@Override
public <T> void declareNamedObjects(
BiConsumer<Value, List<T>> consumer,
NamedObjectParser<T, Context> namedObjectParser,
Consumer<Value> orderedModeCallback,
ParseField parseField
) {
if (consumer == null) {
throw new IllegalArgumentException("[consumer] is required");
}
if (namedObjectParser == null) {
throw new IllegalArgumentException("[parser] is required");
}
if (orderedModeCallback == null) {
throw new IllegalArgumentException("[orderedModeCallback] is required");
}
if (parseField == null) {
throw new IllegalArgumentException("[parseField] is required");
}
if (isConstructorArg(consumer)) {
/*
* Build a new consumer directly against the object parser that
* triggers the "constructor arg just arrived behavior" of the
* parser. Conveniently, we can close over the position of the
* constructor in the argument list so we don't need to do any fancy
* or expensive lookups whenever the constructor args come in.
*/
Map<RestApiVersion, Integer> positions = addConstructorArg(consumer, parseField);
objectParser.declareNamedObjects(
(target, v) -> target.constructorArg(positions, v),
namedObjectParser,
wrapOrderedModeCallBack(orderedModeCallback),
parseField
);
} else {
numberOfFields += 1;
objectParser.declareNamedObjects(
queueingConsumer(consumer, parseField),
namedObjectParser,
wrapOrderedModeCallBack(orderedModeCallback),
parseField
);
}
}
int getNumberOfFields() {
assert this.constructorArgInfos.get(RestApiVersion.current()).size() == this.constructorArgInfos.get(
RestApiVersion.minimumSupported()
).size() : "Constructors must have same number of arguments per all compatible versions";
return this.constructorArgInfos.get(RestApiVersion.current()).size();
}
/**
* Constructor arguments are detected by this "marker" consumer. It
* keeps the API looking clean even if it is a bit sleezy.
*/
private static boolean isConstructorArg(BiConsumer<?, ?> consumer) {
return consumer == REQUIRED_CONSTRUCTOR_ARG_MARKER || consumer == OPTIONAL_CONSTRUCTOR_ARG_MARKER;
}
/**
* Add a constructor argument
* @param consumer Either {@link #REQUIRED_CONSTRUCTOR_ARG_MARKER} or {@link #REQUIRED_CONSTRUCTOR_ARG_MARKER}
* @param parseField Parse field
* @return The argument position
*/
private Map<RestApiVersion, Integer> addConstructorArg(BiConsumer<?, ?> consumer, ParseField parseField) {
boolean required = consumer == REQUIRED_CONSTRUCTOR_ARG_MARKER;
if (RestApiVersion.minimumSupported().matches(parseField.getForRestApiVersion())) {
constructorArgInfos.computeIfAbsent(RestApiVersion.minimumSupported(), (v) -> new ArrayList<>())
.add(new ConstructorArgInfo(parseField, required));
}
if (RestApiVersion.current().matches(parseField.getForRestApiVersion())) {
constructorArgInfos.computeIfAbsent(RestApiVersion.current(), (v) -> new ArrayList<>())
.add(new ConstructorArgInfo(parseField, required));
}
// calculate the positions for the arguments
return constructorArgInfos.entrySet().stream().collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, e -> e.getValue().size()));
}
@Override
public String getName() {
return objectParser.getName();
}
@Override
public void declareRequiredFieldSet(String... requiredSet) {
objectParser.declareRequiredFieldSet(requiredSet);
}
@Override
public void declareExclusiveFieldSet(String... exclusiveSet) {
objectParser.declareExclusiveFieldSet(exclusiveSet);
}
private Consumer<Target> wrapOrderedModeCallBack(Consumer<Value> callback) {
return (target) -> {
if (target.targetObject != null) {
// The target has already been built. Call the callback now.
callback.accept(target.targetObject);
return;
}
/*
* The target hasn't been built. Queue the callback.
*/
target.queuedOrderedModeCallback = callback;
};
}
/**
* Creates the consumer that does the "field just arrived" behavior. If the targetObject hasn't been built then it queues the value.
* Otherwise it just applies the value just like {@linkplain ObjectParser} does.
*/
private <T> BiConsumer<Target, T> queueingConsumer(BiConsumer<Value, T> consumer, ParseField parseField) {
return (target, v) -> {
if (target.targetObject != null) {
// The target has already been built. Just apply the consumer now.
consumer.accept(target.targetObject, v);
return;
}
/*
* The target hasn't been built. Queue the consumer. The next two lines are the only allocations that ConstructingObjectParser
* does during parsing other than the boxing the ObjectParser might do. The first one is to preserve a snapshot of the current
* location so we can add it to the error message if parsing fails. The second one (the lambda) is the actual operation being
* queued. Note that we don't do any of this if the target object has already been built.
*/
XContentLocation location = target.parser.getTokenLocation();
target.queue(targetObject -> {
try {
consumer.accept(targetObject, v);
} catch (Exception e) {
throw new XContentParseException(
location,
"[" + objectParser.getName() + "] failed to parse field [" + parseField.getPreferredName() + "]",
e
);
}
});
};
}
/**
* The target of the {@linkplain ConstructingObjectParser}. One of these is built every time you call
* {@linkplain ConstructingObjectParser#apply(XContentParser, Object)} Note that it is not static so it inherits
* {@linkplain ConstructingObjectParser}'s type parameters.
*/
private | pretty |
java | quarkusio__quarkus | extensions/arc/runtime/src/main/java/io/quarkus/arc/lookup/LookupUnlessProperty.java | {
"start": 1102,
"end": 1682
} | class ____ {
*
* {@literal @Inject}
* Instance<Service> service;
*
* void printServiceName() {
* // This would print "bar" if the property of name "service.foo.disabled" is set to true
* // Note that service.get() would normally result in AmbiguousResolutionException
* System.out.println(service.get().name());
* }
* }
* </code>
* </pre>
*
* @see Instance
*/
@Repeatable(LookupUnlessProperty.List.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE, ElementType.FIELD })
public @ | Client |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/constraint/algorithm/TestCircularIterator.java | {
"start": 1219,
"end": 2617
} | class ____ {
@Test
public void testIteration() throws Exception {
List<String> list = Arrays.asList("a", "b", "c", "d");
CircularIterator<String> ci =
new CircularIterator<>(null, list.iterator(), list);
StringBuilder sb = new StringBuilder("");
while (ci.hasNext()) {
sb.append(ci.next());
}
assertEquals("abcd", sb.toString());
Iterator<String> lIter = list.iterator();
lIter.next();
lIter.next();
sb = new StringBuilder("");
ci = new CircularIterator<>(null, lIter, list);
while (ci.hasNext()) {
sb.append(ci.next());
}
assertEquals("cdab", sb.toString());
lIter = list.iterator();
lIter.next();
lIter.next();
lIter.next();
sb = new StringBuilder("");
ci = new CircularIterator<>("x", lIter, list);
while (ci.hasNext()) {
sb.append(ci.next());
}
assertEquals("xdabc", sb.toString());
list = Arrays.asList("a");
lIter = list.iterator();
lIter.next();
sb = new StringBuilder("");
ci = new CircularIterator<>("y", lIter, list);
while (ci.hasNext()) {
sb.append(ci.next());
}
assertEquals("ya", sb.toString());
try {
list = new ArrayList<>();
lIter = list.iterator();
new CircularIterator<>("y", lIter, list);
fail("Should fail..");
} catch (Exception e) {
// foo bar
}
}
}
| TestCircularIterator |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/PostOpParam.java | {
"start": 1026,
"end": 2781
} | enum ____ implements HttpOpParam.Op {
APPEND(true, HttpURLConnection.HTTP_OK),
CONCAT(false, HttpURLConnection.HTTP_OK),
TRUNCATE(false, HttpURLConnection.HTTP_OK),
UNSETECPOLICY(false, HttpURLConnection.HTTP_OK),
UNSETSTORAGEPOLICY(false, HttpURLConnection.HTTP_OK),
NULL(false, HttpURLConnection.HTTP_NOT_IMPLEMENTED);
final boolean doOutputAndRedirect;
final int expectedHttpResponseCode;
Op(final boolean doOutputAndRedirect, final int expectedHttpResponseCode) {
this.doOutputAndRedirect = doOutputAndRedirect;
this.expectedHttpResponseCode = expectedHttpResponseCode;
}
@Override
public Type getType() {
return Type.POST;
}
@Override
public boolean getRequireAuth() {
return false;
}
@Override
public boolean getDoOutput() {
return doOutputAndRedirect;
}
@Override
public boolean getRedirect() {
return doOutputAndRedirect;
}
@Override
public int getExpectedHttpResponseCode() {
return expectedHttpResponseCode;
}
/** @return a URI query string. */
@Override
public String toQueryString() {
return NAME + "=" + this;
}
}
private static final Domain<Op> DOMAIN = new Domain<>(NAME, Op.class);
/**
* Constructor.
* @param str a string representation of the parameter value.
*/
public PostOpParam(final String str) {
super(DOMAIN, getOp(str));
}
private static Op getOp(String str) {
try {
return DOMAIN.parse(str);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(str + " is not a valid " + Type.POST
+ " operation.");
}
}
@Override
public String getName() {
return NAME;
}
}
| Op |
java | google__dagger | javatests/dagger/functional/componentdependency/ComponentDependenciesTest.java | {
"start": 1215,
"end": 1562
} | interface ____ {
Builder dep(Merged dep);
TestComponent build();
}
}
@Test
public void testSameMethodTwice() throws Exception {
TestComponent component =
DaggerComponentDependenciesTest_TestComponent.builder().dep(() -> "test").build();
assertThat(component.getString()).isEqualTo("test");
}
public | Builder |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/SQLDeclareItem.java | {
"start": 824,
"end": 3069
} | class ____ extends SQLObjectImpl implements SQLObjectWithDataType, SQLReplaceable {
protected Type type;
protected SQLName name;
protected SQLDataType dataType;
protected SQLExpr value;
protected List<SQLTableElement> tableElementList = new ArrayList<SQLTableElement>();
protected transient SQLObject resolvedObject;
public SQLDeclareItem() {
}
public SQLDeclareItem(SQLName name, SQLDataType dataType) {
this.setName(name);
this.setDataType(dataType);
}
public SQLDeclareItem(SQLName name, SQLDataType dataType, SQLExpr value) {
this.setName(name);
this.setDataType(dataType);
this.setValue(value);
}
public boolean replace(SQLExpr expr, SQLExpr target) {
if (name == expr) {
setName((SQLName) target);
return true;
}
if (value == expr) {
setValue(target);
return true;
}
return false;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, this.name);
acceptChild(visitor, this.dataType);
acceptChild(visitor, this.value);
acceptChild(visitor, this.tableElementList);
}
visitor.endVisit(this);
}
public SQLName getName() {
return name;
}
public void setName(SQLName name) {
if (name != null) {
name.setParent(this);
}
this.name = name;
}
public SQLDataType getDataType() {
return dataType;
}
public void setDataType(SQLDataType dataType) {
if (dataType != null) {
dataType.setParent(this);
}
this.dataType = dataType;
}
public SQLExpr getValue() {
return value;
}
public void setValue(SQLExpr value) {
if (value != null) {
value.setParent(this);
}
this.value = value;
}
public List<SQLTableElement> getTableElementList() {
return tableElementList;
}
public void setTableElementList(List<SQLTableElement> tableElementList) {
this.tableElementList = tableElementList;
}
public | SQLDeclareItem |
java | spring-projects__spring-boot | module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/autoconfigure/ResourceChainResourceHandlerRegistrationCustomizer.java | {
"start": 1311,
"end": 2833
} | class ____ implements ResourceHandlerRegistrationCustomizer {
private final Resources resourceProperties;
ResourceChainResourceHandlerRegistrationCustomizer(Resources resources) {
this.resourceProperties = resources;
}
@Override
public void customize(ResourceHandlerRegistration registration) {
Resources.Chain properties = this.resourceProperties.getChain();
configureResourceChain(properties, registration.resourceChain(properties.isCache()));
}
private void configureResourceChain(Resources.Chain properties, ResourceChainRegistration chain) {
Resources.Chain.Strategy strategy = properties.getStrategy();
if (properties.isCompressed()) {
chain.addResolver(new EncodedResourceResolver());
}
if (strategy.getFixed().isEnabled() || strategy.getContent().isEnabled()) {
chain.addResolver(getVersionResourceResolver(strategy));
}
}
private ResourceResolver getVersionResourceResolver(Resources.Chain.Strategy properties) {
VersionResourceResolver resolver = new VersionResourceResolver();
if (properties.getFixed().isEnabled()) {
String version = properties.getFixed().getVersion();
String[] paths = properties.getFixed().getPaths();
Assert.state(version != null, "'version' must not be null");
resolver.addFixedVersionStrategy(version, paths);
}
if (properties.getContent().isEnabled()) {
String[] paths = properties.getContent().getPaths();
resolver.addContentVersionStrategy(paths);
}
return resolver;
}
}
| ResourceChainResourceHandlerRegistrationCustomizer |
java | apache__flink | flink-core/src/test/java/org/apache/flink/core/fs/CloseableRegistryTest.java | {
"start": 5234,
"end": 6106
} | class ____ implements Closeable {
private final AtomicInteger callsToClose;
private final String exceptionMessageOnClose;
TestClosable() {
this("");
}
TestClosable(String exceptionMessageOnClose) {
this.exceptionMessageOnClose = exceptionMessageOnClose;
this.callsToClose = new AtomicInteger(0);
}
@Override
public void close() throws IOException {
callsToClose.incrementAndGet();
if (exceptionMessageOnClose != null && exceptionMessageOnClose.length() > 0) {
throw new IOException(exceptionMessageOnClose);
}
}
public int getCallsToClose() {
return callsToClose.get();
}
public void resetCallsToClose() {
this.callsToClose.set(0);
}
}
}
| TestClosable |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableElementCollectionMemberOfTest.java | {
"start": 1386,
"end": 2164
} | class ____ {
private Long id;
private String name;
private Set<Address> addresses = new HashSet<>();
private Address address;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ElementCollection
@JoinTable(
name = "addresses",
joinColumns = @JoinColumn(name = "PERSON_ID"))
public Set<Address> getAddresses() {
return addresses;
}
public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@Embeddable
public static | Person |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/CachedDNSToSwitchMapping.java | {
"start": 1418,
"end": 5007
} | class ____ extends AbstractDNSToSwitchMapping {
private Map<String, String> cache = new ConcurrentHashMap<String, String>();
/**
* The uncached mapping
*/
protected final DNSToSwitchMapping rawMapping;
/**
* cache a raw DNS mapping
* @param rawMapping the raw mapping to cache
*/
public CachedDNSToSwitchMapping(DNSToSwitchMapping rawMapping) {
this.rawMapping = rawMapping;
}
/**
* @param names a list of hostnames to probe for being cached
* @return the hosts from 'names' that have not been cached previously
*/
private List<String> getUncachedHosts(List<String> names) {
// find out all names without cached resolved location
List<String> unCachedHosts = new ArrayList<String>(names.size());
for (String name : names) {
if (cache.get(name) == null) {
unCachedHosts.add(name);
}
}
return unCachedHosts;
}
/**
* Caches the resolved host:rack mappings. The two list
* parameters must be of equal size.
*
* @param uncachedHosts a list of hosts that were uncached
* @param resolvedHosts a list of resolved host entries where the element
* at index(i) is the resolved value for the entry in uncachedHosts[i]
*/
private void cacheResolvedHosts(List<String> uncachedHosts,
List<String> resolvedHosts) {
// Cache the result
if (resolvedHosts != null) {
for (int i=0; i<uncachedHosts.size(); i++) {
cache.put(uncachedHosts.get(i), resolvedHosts.get(i));
}
}
}
/**
* @param names a list of hostnames to look up (can be be empty)
* @return the cached resolution of the list of hostnames/addresses.
* or null if any of the names are not currently in the cache
*/
private List<String> getCachedHosts(List<String> names) {
List<String> result = new ArrayList<String>(names.size());
// Construct the result
for (String name : names) {
String networkLocation = cache.get(name);
if (networkLocation != null) {
result.add(networkLocation);
} else {
return null;
}
}
return result;
}
@Override
public List<String> resolve(List<String> names) {
// normalize all input names to be in the form of IP addresses
names = NetUtils.normalizeHostNames(names);
List <String> result = new ArrayList<String>(names.size());
if (names.isEmpty()) {
return result;
}
List<String> uncachedHosts = getUncachedHosts(names);
// Resolve the uncached hosts
List<String> resolvedHosts = rawMapping.resolve(uncachedHosts);
//cache them
cacheResolvedHosts(uncachedHosts, resolvedHosts);
//now look up the entire list in the cache
return getCachedHosts(names);
}
/**
* Get the (host x switch) map.
* @return a copy of the cached map of hosts to rack
*/
@Override
public Map<String, String> getSwitchMap() {
return new HashMap<>(cache);
}
@Override
public String toString() {
return "cached switch mapping relaying to " + rawMapping;
}
/**
* Delegate the switch topology query to the raw mapping, via
* {@link AbstractDNSToSwitchMapping#isMappingSingleSwitch(DNSToSwitchMapping)}
* @return true iff the raw mapper is considered single-switch.
*/
@Override
public boolean isSingleSwitch() {
return isMappingSingleSwitch(rawMapping);
}
@Override
public void reloadCachedMappings() {
cache.clear();
}
@Override
public void reloadCachedMappings(List<String> names) {
for (String name : names) {
cache.remove(name);
}
}
}
| CachedDNSToSwitchMapping |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/DuplicateDateFormatFieldTest.java | {
"start": 3548,
"end": 4087
} | class ____ {
public void foo() {
SimpleDateFormat format = new SimpleDateFormat();
// BUG: Diagnostic contains: uses the field 'm' more than once
format.applyLocalizedPattern("mm/dd/yyyy hh:mm:ss");
}
}
""")
.doTest();
}
@Test
public void forgotToEscapteSpecialCharacters() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import java.text.SimpleDateFormat;
| Test |
java | apache__camel | core/camel-core-processor/src/main/java/org/apache/camel/processor/errorhandler/DefaultExceptionPolicyStrategy.java | {
"start": 9303,
"end": 9444
} | class ____ testing
* @param exception the thrown exception
* @return <tt>true</tt> if the to current exception | for |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java | {
"start": 78883,
"end": 79136
} | class ____ {
List<TestBean> testBeans;
@Bean(autowireCandidate = false)
public TestBean thing(List<TestBean> testBeans) {
this.testBeans = testBeans;
return new TestBean();
}
}
@Configuration
public static | CollectionArgumentConfiguration |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/reflection/ReflectorTest.java | {
"start": 6440,
"end": 6795
} | class ____ implements BeanInterface<String> {
@Override
public void setId(String id) {
// Do nothing
}
}
ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
Reflector reflector = reflectorFactory.findForClass(BeanClass.class);
assertEquals(String.class, reflector.getSetterType("id"));
}
| BeanClass |
java | apache__camel | test-infra/camel-test-infra-artemis/src/test/java/org/apache/camel/test/infra/artemis/services/ArtemisServiceFactory.java | {
"start": 4519,
"end": 5012
} | class ____ {
static final ArtemisService INSTANCE;
static {
SimpleTestServiceBuilder<ArtemisService> persistentInstanceBuilder = new SimpleTestServiceBuilder<>("artemis");
persistentInstanceBuilder.addLocalMapping(
() -> new SingletonArtemisService(new ArtemisPersistentVMService(), "artemis-persistent"));
INSTANCE = persistentInstanceBuilder.build();
}
}
private static | SingletonPersistentVMServiceHolder |
java | elastic__elasticsearch | x-pack/qa/security-example-spi-extension/src/javaRestTest/java/org/elasticsearch/example/realm/CustomRealmIT.java | {
"start": 898,
"end": 3110
} | class ____ extends ESRestTestCase {
// These are configured in build.gradle
public static final String USERNAME = "test_user";
public static final String PASSWORD = "secret_password";
@Override
protected Settings restClientSettings() {
return Settings.builder()
.put(ThreadContext.PREFIX + "." + CustomRealm.USER_HEADER, USERNAME)
.put(ThreadContext.PREFIX + "." + CustomRealm.PW_HEADER, PASSWORD)
.build();
}
public void testHttpConnectionWithNoAuthentication() {
Request request = new Request("GET", "/");
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
builder.addHeader(CustomRealm.USER_HEADER, "");
builder.addHeader(CustomRealm.PW_HEADER, "");
request.setOptions(builder);
ResponseException e = expectThrows(ResponseException.class, () -> client().performRequest(request));
Response response = e.getResponse();
assertThat(response.getStatusLine().getStatusCode(), is(401));
String value = response.getHeader("WWW-Authenticate");
assertThat(value, is("custom-challenge"));
}
public void testHttpAuthentication() throws Exception {
Request request = new Request("GET", "/");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader(CustomRealm.USER_HEADER, USERNAME);
options.addHeader(CustomRealm.PW_HEADER, PASSWORD);
request.setOptions(options);
Response response = client().performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), is(200));
}
public void testSettingsFiltering() throws Exception {
Request request = new Request("GET", "/_nodes/_all/settings");
request.addParameter("flat_settings", "true");
Response response = client().performRequest(request);
String responseString = EntityUtils.toString(response.getEntity());
assertThat(responseString, not(containsString("xpack.security.authc.realms.custom.my_realm.filtered_setting")));
assertThat(responseString, containsString("xpack.security.authc.realms.custom.my_realm.order"));
}
}
| CustomRealmIT |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/sampler/SamplerAggregationBuilder.java | {
"start": 1313,
"end": 5509
} | class ____ extends AbstractAggregationBuilder<SamplerAggregationBuilder> {
public static final String NAME = "sampler";
public static final int DEFAULT_SHARD_SAMPLE_SIZE = 100;
private int shardSize = DEFAULT_SHARD_SAMPLE_SIZE;
public SamplerAggregationBuilder(String name) {
super(name);
}
protected SamplerAggregationBuilder(SamplerAggregationBuilder clone, Builder factoriesBuilder, Map<String, Object> metadata) {
super(clone, factoriesBuilder, metadata);
this.shardSize = clone.shardSize;
}
@Override
protected AggregationBuilder shallowCopy(Builder factoriesBuilder, Map<String, Object> metadata) {
return new SamplerAggregationBuilder(this, factoriesBuilder, metadata);
}
/**
* Read from a stream.
*/
public SamplerAggregationBuilder(StreamInput in) throws IOException {
super(in);
shardSize = in.readVInt();
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeVInt(shardSize);
}
/**
* Set the max num docs to be returned from each shard.
*/
public SamplerAggregationBuilder shardSize(int shardSize) {
this.shardSize = shardSize;
return this;
}
@Override
public BucketCardinality bucketCardinality() {
return BucketCardinality.ONE;
}
@Override
protected SamplerAggregatorFactory doBuild(AggregationContext context, AggregatorFactory parent, Builder subFactoriesBuilder)
throws IOException {
return new SamplerAggregatorFactory(name, shardSize, context, parent, subFactoriesBuilder, metadata);
}
@Override
protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(SamplerAggregator.SHARD_SIZE_FIELD.getPreferredName(), shardSize);
builder.endObject();
return builder;
}
public static SamplerAggregationBuilder parse(String aggregationName, XContentParser parser) throws IOException {
XContentParser.Token token;
String currentFieldName = null;
Integer shardSize = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.VALUE_NUMBER) {
if (SamplerAggregator.SHARD_SIZE_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
shardSize = parser.intValue();
} else {
throw new ParsingException(
parser.getTokenLocation(),
"Unsupported property \"" + currentFieldName + "\" for aggregation \"" + aggregationName
);
}
} else {
throw new ParsingException(
parser.getTokenLocation(),
"Unsupported property \"" + currentFieldName + "\" for aggregation \"" + aggregationName
);
}
}
SamplerAggregationBuilder factory = new SamplerAggregationBuilder(aggregationName);
if (shardSize != null) {
factory.shardSize(shardSize);
}
return factory;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), shardSize);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
if (super.equals(obj) == false) return false;
SamplerAggregationBuilder other = (SamplerAggregationBuilder) obj;
return Objects.equals(shardSize, other.shardSize);
}
@Override
public String getType() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.zero();
}
@Override
public boolean supportsParallelCollection(ToLongFunction<String> fieldCardinalityResolver) {
return false;
}
}
| SamplerAggregationBuilder |
java | quarkusio__quarkus | independent-projects/qute/core/src/main/java/io/quarkus/qute/ValueResolvers.java | {
"start": 19790,
"end": 20558
} | class ____ extends IntArithmeticResolver {
@Override
protected boolean appliesToName(String name) {
return "mod".equals(name);
}
@Override
protected Object compute(Long op1, Long op2) {
return op1 % op2;
}
@Override
protected Object compute(Integer op1, Long op2) {
return op1 % op2;
}
@Override
protected Object compute(Long op1, Integer op2) {
return op1 % op2;
}
@Override
protected Object compute(Integer op1, Integer op2) {
return op1 % op2;
}
}
public static ValueResolver equalsResolver() {
return new EqualsResolver();
}
public static final | ModResolver |
java | google__guice | core/src/com/google/inject/internal/Initializable.java | {
"start": 782,
"end": 946
} | interface ____<T> {
/** Ensures the reference is initialized, then returns it. */
T get(InternalContext context) throws InternalProvisionException;
}
| Initializable |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/bcextensions/ExtensionsEntryPoint.java | {
"start": 3358,
"end": 3522
} | class ____ well as all other classes
* that implement the BCExtensions API do not guard data against concurrent access, but they
* do ensure visibility.
*/
public | as |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/io/InspectedContent.java | {
"start": 3746,
"end": 4289
} | interface ____ {
/**
* Update inspected information based on the provided bytes.
* @param input the array of bytes.
* @param offset the offset to start from in the array of bytes.
* @param len the number of bytes to use, starting at {@code offset}.
* @throws IOException on IO error
*/
void update(byte[] input, int offset, int len) throws IOException;
}
/**
* Internal {@link OutputStream} used to capture the content either as bytes, or to a
* File if the content is too large.
*/
private static final | Inspector |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/PointTest.java | {
"start": 261,
"end": 1128
} | class ____ extends TestCase {
public void test_color() throws Exception {
JSONSerializer serializer = new JSONSerializer();
Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Point.class).getClass());
Point point = new Point(3, 4);
String text = JSON.toJSONString(point);
Point point2 = JSON.parseObject(text, Point.class);
Assert.assertEquals(point, point2);
}
public void test_color_2() throws Exception {
JSONSerializer serializer = new JSONSerializer();
Assert.assertEquals(AwtCodec.class, serializer.getObjectWriter(Point.class).getClass());
Point point = new Point(5, 6);
String text = JSON.toJSONString(point);
Point point2 = JSON.parseObject(text, Point.class);
Assert.assertEquals(point, point2);
}
}
| PointTest |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/analytics/ingest/AnalyticsEventIngestConfig.java | {
"start": 1198,
"end": 4106
} | class ____ {
private static final String SETTING_ROOT_PATH = "xpack.applications.behavioral_analytics.ingest";
private static final TimeValue DEFAULT_FLUSH_DELAY = TimeValue.timeValueSeconds(10);
private static final TimeValue MIN_FLUSH_DELAY = TimeValue.timeValueSeconds(1);
private static final TimeValue MAX_FLUSH_DELAY = TimeValue.timeValueSeconds(60);
public static final Setting<TimeValue> FLUSH_DELAY_SETTING = Setting.timeSetting(
Strings.format("%s.%s", SETTING_ROOT_PATH, "bulk_processor.flush_delay"),
DEFAULT_FLUSH_DELAY,
MIN_FLUSH_DELAY,
MAX_FLUSH_DELAY,
Setting.Property.NodeScope
);
private static final int DEFAULT_BULK_SIZE = 500;
private static final int MIN_BULK_SIZE = 1;
private static final int MAX_BULK_SIZE = 1000;
public static final Setting<Integer> MAX_NUMBER_OF_EVENTS_PER_BULK_SETTING = Setting.intSetting(
Strings.format("%s.%s", SETTING_ROOT_PATH, "bulk_processor.max_events_per_bulk"),
DEFAULT_BULK_SIZE,
MIN_BULK_SIZE,
MAX_BULK_SIZE,
Setting.Property.NodeScope
);
private static final int DEFAULT_MAX_NUMBER_OF_RETRIES = 1;
private static final int MIN_MAX_NUMBER_OF_RETRIES = 0;
private static final int MAX_MAX_NUMBER_OF_RETRIES = 5;
public static final Setting<Integer> MAX_NUMBER_OF_RETRIES_SETTING = Setting.intSetting(
Strings.format("%s.%s", SETTING_ROOT_PATH, "bulk_processor.max_number_of_retries"),
DEFAULT_MAX_NUMBER_OF_RETRIES,
MIN_MAX_NUMBER_OF_RETRIES,
MAX_MAX_NUMBER_OF_RETRIES,
Setting.Property.NodeScope
);
private static final String DEFAULT_MAX_BYTES_IN_FLIGHT = "5%";
public static final Setting<ByteSizeValue> MAX_BYTES_IN_FLIGHT_SETTING = Setting.memorySizeSetting(
Strings.format("%s.%s", SETTING_ROOT_PATH, "bulk_processor.max_bytes_in_flight"),
DEFAULT_MAX_BYTES_IN_FLIGHT,
Setting.Property.NodeScope
);
private final TimeValue flushDelay;
private final int maxNumberOfRetries;
private final int maxNumberOfEventsPerBulk;
private final ByteSizeValue maxBytesInFlight;
@Inject
public AnalyticsEventIngestConfig(Settings settings) {
this.flushDelay = FLUSH_DELAY_SETTING.get(settings);
this.maxNumberOfRetries = MAX_NUMBER_OF_RETRIES_SETTING.get(settings);
this.maxNumberOfEventsPerBulk = MAX_NUMBER_OF_EVENTS_PER_BULK_SETTING.get(settings);
this.maxBytesInFlight = MAX_BYTES_IN_FLIGHT_SETTING.get(settings);
}
public TimeValue flushDelay() {
return flushDelay;
}
public int maxNumberOfRetries() {
return maxNumberOfRetries;
}
public int maxNumberOfEventsPerBulk() {
return maxNumberOfEventsPerBulk;
}
public ByteSizeValue maxBytesInFlight() {
return maxBytesInFlight;
}
}
| AnalyticsEventIngestConfig |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/OrderByFragmentTranslator.java | {
"start": 1283,
"end": 4171
} | class ____ {
/**
* Perform the translation of the user-supplied fragment, returning the translation.
*
* @return The translation.
*
* @apiNote The important distinction to this split between (1) translating and (2) resolving aliases is that
* both happen at different times. This is performed at boot-time while building the CollectionPersister
* happens at runtime while loading the described collection
*/
public static OrderByFragment translate(
String fragment,
PluralAttributeMapping pluralAttributeMapping,
TranslationContext context) {
final var parseTree = buildParseTree( fragment );
final var visitor = new ParseTreeVisitor( pluralAttributeMapping, context );
return new OrderByFragmentImpl( visitor.visitOrderByFragment( parseTree ) );
}
public static void check(String fragment) {
final var parseTree = buildParseTree( fragment );
// TODO: check against the model (requires the PluralAttributeMapping)
}
private static OrderingParser.OrderByFragmentContext buildParseTree(String fragment) {
final var lexer = new OrderingLexer( CharStreams.fromString( fragment ) );
final var parser = new OrderingParser( new CommonTokenStream( lexer ) );
// try to use SLL(k)-based parsing first - it's faster
parser.getInterpreter().setPredictionMode( PredictionMode.SLL );
parser.removeErrorListeners();
parser.setErrorHandler( new BailErrorStrategy() );
try {
return parser.orderByFragment();
}
catch (ParseCancellationException e) {
// When resetting the parser, its CommonTokenStream will seek(0) i.e. restart emitting buffered tokens.
// This is enough when reusing the lexer and parser, and it would be wrong to also reset the lexer.
// Resetting the lexer causes it to hand out tokens again from the start, which will then append to the
// CommonTokenStream and cause a wrong parse
// lexer.reset();
// reset the input token stream and parser state
parser.reset();
// fall back to LL(k)-based parsing
parser.getInterpreter().setPredictionMode( PredictionMode.LL );
// parser.addErrorListener( ConsoleErrorListener.INSTANCE );
parser.setErrorHandler( new DefaultErrorStrategy() );
final ANTLRErrorListener errorListener = new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
throw new SyntaxException( prettifyAntlrError( offendingSymbol, line, charPositionInLine, msg, e, fragment, true ), fragment );
}
};
parser.addErrorListener( errorListener );
return parser.orderByFragment();
}
catch ( ParsingException ex ) {
// Note that this is supposed to represent a bug in the parser
throw new QueryException( "Failed to interpret syntax [" + ex.getMessage() + "]", fragment, ex );
}
}
}
| OrderByFragmentTranslator |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/executor/loader/ProxyFactory.java | {
"start": 898,
"end": 1192
} | interface ____ {
default void setProperties(Properties properties) {
// NOP
}
Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration,
ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs);
}
| ProxyFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java | {
"start": 67920,
"end": 68227
} | class ____ {}
// BUG: Diagnostic contains: [QualifyTypeLocalClassChecker] InInstanceMethod
return new InInstanceMethod();
}
void lambda() {
Supplier<Object> consumer =
() -> {
| InInstanceMethod |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/MapKeyTest.java | {
"start": 3667,
"end": 4336
} | class ____ {
@Id
private int id;
private String name;
@OneToMany(mappedBy = "school")
@MapKeyClass(Date.class)
@MapKeyColumn(name = "THE_DATE")
@MapKeyTemporal(TemporalType.DATE)
private Map<Date, Person> studentsByDate;
@Temporal( TemporalType.DATE )
private Date aDate;
public School() {
}
public School(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Map getStudentsByDate() {
return studentsByDate;
}
public void setStudentsByDate(Map studentsByDate) {
this.studentsByDate = studentsByDate;
}
}
}
| School |
java | spring-projects__spring-framework | spring-websocket/src/main/java/org/springframework/web/socket/server/support/WebSocketHttpRequestHandler.java | {
"start": 2466,
"end": 6311
} | class ____ implements HttpRequestHandler, Lifecycle, ServletContextAware {
private static final Log logger = LogFactory.getLog(WebSocketHttpRequestHandler.class);
private final WebSocketHandler wsHandler;
private final HandshakeHandler handshakeHandler;
private final List<HandshakeInterceptor> interceptors = new ArrayList<>();
private volatile boolean running;
public WebSocketHttpRequestHandler(WebSocketHandler wsHandler) {
this(wsHandler, new DefaultHandshakeHandler());
}
public WebSocketHttpRequestHandler(WebSocketHandler wsHandler, HandshakeHandler handshakeHandler) {
Assert.notNull(wsHandler, "wsHandler must not be null");
Assert.notNull(handshakeHandler, "handshakeHandler must not be null");
this.wsHandler = decorate(wsHandler);
this.handshakeHandler = handshakeHandler;
}
/**
* Decorate the {@code WebSocketHandler} passed into the constructor.
* <p>By default, {@link LoggingWebSocketHandlerDecorator} and
* {@link ExceptionWebSocketHandlerDecorator} are added.
* @since 5.2.2
*/
protected WebSocketHandler decorate(WebSocketHandler handler) {
return new ExceptionWebSocketHandlerDecorator(new LoggingWebSocketHandlerDecorator(handler));
}
/**
* Return the WebSocketHandler.
*/
public WebSocketHandler getWebSocketHandler() {
return this.wsHandler;
}
/**
* Return the HandshakeHandler.
*/
public HandshakeHandler getHandshakeHandler() {
return this.handshakeHandler;
}
/**
* Configure one or more WebSocket handshake request interceptors.
*/
public void setHandshakeInterceptors(@Nullable List<HandshakeInterceptor> interceptors) {
this.interceptors.clear();
if (interceptors != null) {
this.interceptors.addAll(interceptors);
}
}
/**
* Return the configured WebSocket handshake request interceptors.
*/
public List<HandshakeInterceptor> getHandshakeInterceptors() {
return this.interceptors;
}
@Override
public void setServletContext(ServletContext servletContext) {
if (this.handshakeHandler instanceof ServletContextAware servletContextAware) {
servletContextAware.setServletContext(servletContext);
}
}
@Override
public void start() {
if (!isRunning()) {
this.running = true;
if (this.handshakeHandler instanceof Lifecycle lifecycle) {
lifecycle.start();
}
}
}
@Override
public void stop() {
if (isRunning()) {
this.running = false;
if (this.handshakeHandler instanceof Lifecycle lifecycle) {
lifecycle.stop();
}
}
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws ServletException, IOException {
ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(this.interceptors, this.wsHandler);
HandshakeFailureException failure = null;
try {
if (logger.isDebugEnabled()) {
logger.debug(servletRequest.getMethod() + " " + servletRequest.getRequestURI());
}
Map<String, Object> attributes = new HashMap<>();
if (!chain.applyBeforeHandshake(request, response, attributes)) {
return;
}
this.handshakeHandler.doHandshake(request, response, this.wsHandler, attributes);
chain.applyAfterHandshake(request, response, null);
}
catch (HandshakeFailureException ex) {
failure = ex;
}
catch (Exception ex) {
failure = new HandshakeFailureException(
"Uncaught failure for request " + request.getURI() + " - " + ex.getMessage(), ex);
}
finally {
if (failure != null) {
chain.applyAfterHandshake(request, response, failure);
response.close();
throw failure;
}
response.close();
}
}
}
| WebSocketHttpRequestHandler |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java | {
"start": 1803,
"end": 4742
} | class ____ extends ConfigCenterConfig
implements ApplicationContextAware, DisposableBean, EnvironmentAware {
private transient ApplicationContext applicationContext;
private Boolean includeSpringEnv = false;
public ConfigCenterBean() {}
public ConfigCenterBean(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void destroy() throws Exception {}
@Override
public void setEnvironment(Environment environment) {
if (includeSpringEnv) {
// Get PropertySource mapped to 'dubbo.properties' in Spring Environment.
setExternalConfig(getConfigurations(getConfigFile(), environment));
// Get PropertySource mapped to 'application.dubbo.properties' in Spring Environment.
setAppExternalConfig(getConfigurations(
StringUtils.isNotEmpty(getAppConfigFile())
? getAppConfigFile()
: ("application." + getConfigFile()),
environment));
}
}
private Map<String, String> getConfigurations(String key, Environment environment) {
Object rawProperties = environment.getProperty(key, Object.class);
Map<String, String> externalProperties = new HashMap<>();
try {
if (rawProperties instanceof Map) {
externalProperties.putAll((Map<String, String>) rawProperties);
} else if (rawProperties instanceof String) {
externalProperties.putAll(ConfigurationUtils.parseProperties((String) rawProperties));
}
if (environment instanceof ConfigurableEnvironment && externalProperties.isEmpty()) {
ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment;
PropertySource propertySource =
configurableEnvironment.getPropertySources().get(key);
if (propertySource != null) {
Object source = propertySource.getSource();
if (source instanceof Map) {
((Map<String, Object>) source).forEach((k, v) -> {
externalProperties.put(k, (String) v);
});
}
}
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return externalProperties;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public Boolean getIncludeSpringEnv() {
return includeSpringEnv;
}
public void setIncludeSpringEnv(Boolean includeSpringEnv) {
this.includeSpringEnv = includeSpringEnv;
}
}
| ConfigCenterBean |
java | elastic__elasticsearch | x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/EqlTestUtils.java | {
"start": 1950,
"end": 5710
} | class ____ {
private EqlTestUtils() {}
public static final EqlConfiguration TEST_CFG = new EqlConfiguration(
new String[] { "none" },
org.elasticsearch.xpack.ql.util.DateUtils.UTC,
"nobody",
"cluster",
null,
emptyMap(),
null,
TimeValue.timeValueSeconds(30),
null,
123,
1,
false,
true,
null,
"",
new TaskId("test", 123),
null
);
public static EqlConfiguration randomConfiguration() {
return new EqlConfiguration(
new String[] { randomAlphaOfLength(16) },
randomZone(),
randomAlphaOfLength(16),
randomAlphaOfLength(16),
null,
emptyMap(),
null,
new TimeValue(randomNonNegativeLong()),
randomIndicesOptions(),
randomIntBetween(1, 1000),
randomIntBetween(1, 1000),
randomBoolean(),
randomBoolean(),
null,
randomAlphaOfLength(16),
new TaskId(randomAlphaOfLength(10), randomNonNegativeLong()),
randomTask()
);
}
public static EqlSearchTask randomTask() {
return new EqlSearchTask(
randomLong(),
"transport",
EqlSearchAction.NAME,
"",
null,
emptyMap(),
emptyMap(),
new AsyncExecutionId("", new TaskId(randomAlphaOfLength(10), 1)),
TimeValue.timeValueDays(5)
);
}
public static InsensitiveEquals seq(Expression left, Expression right) {
return new InsensitiveWildcardEquals(EMPTY, left, right, randomZone());
}
public static InsensitiveNotEquals sneq(Expression left, Expression right) {
return new InsensitiveWildcardNotEquals(EMPTY, left, right, randomZone());
}
public static IndicesOptions randomIndicesOptions() {
return IndicesOptions.fromOptions(
randomBoolean(),
randomBoolean(),
randomBoolean(),
randomBoolean(),
randomBoolean(),
randomBoolean(),
randomBoolean(),
randomBoolean(),
randomBoolean()
);
}
public static SearchSortValues randomSearchSortValues(Object[] values) {
DocValueFormat[] sortValueFormats = new DocValueFormat[values.length];
for (int i = 0; i < values.length; i++) {
sortValueFormats[i] = DocValueFormat.RAW;
}
return new SearchSortValues(values, sortValueFormats);
}
public static SearchSortValues randomSearchLongSortValues() {
int size = randomIntBetween(1, 20);
Object[] values = new Object[size];
DocValueFormat[] sortValueFormats = new DocValueFormat[size];
for (int i = 0; i < size; i++) {
values[i] = randomLong();
sortValueFormats[i] = DocValueFormat.RAW;
}
return new SearchSortValues(values, sortValueFormats);
}
public static BreakerSettings circuitBreakerSettings(Settings settings) {
return BreakerSettings.updateFromSettings(
new BreakerSettings(
EqlPlugin.CIRCUIT_BREAKER_NAME,
EqlPlugin.CIRCUIT_BREAKER_LIMIT,
EqlPlugin.CIRCUIT_BREAKER_OVERHEAD,
CircuitBreaker.Type.MEMORY,
CircuitBreaker.Durability.TRANSIENT
),
settings
);
}
public static boolean[] booleanArrayOf(int size, boolean value) {
boolean[] missing = new boolean[size];
for (int i = 0; i < size; i++) {
missing[i] = value;
}
return missing;
}
}
| EqlTestUtils |
java | apache__avro | lang/java/trevni/avro/src/main/java/org/apache/trevni/avro/AvroColumnator.java | {
"start": 1204,
"end": 5563
} | class ____ {
private List<ColumnMetaData> columns = new ArrayList<>();
private List<Integer> arrayWidths = new ArrayList<>();
public AvroColumnator(Schema schema) {
Schema schema1 = schema;
columnize(null, schema, null, false);
}
/** Return columns for the schema. */
public ColumnMetaData[] getColumns() {
return columns.toArray(new ColumnMetaData[0]);
}
/**
* Return array giving the number of columns immediately following each column
* that are descendents of that column.
*/
public int[] getArrayWidths() {
int[] result = new int[arrayWidths.size()];
int i = 0;
for (Integer width : arrayWidths)
result[i++] = width;
return result;
}
private Map<Schema, Schema> seen = new IdentityHashMap<>();
private void columnize(String path, Schema s, ColumnMetaData parent, boolean isArray) {
if (isSimple(s)) {
if (path == null)
path = s.getFullName();
addColumn(path, simpleValueType(s), parent, isArray);
return;
}
if (seen.containsKey(s)) // catch recursion
throw new TrevniRuntimeException("Cannot shred recursive schemas: " + s);
seen.put(s, s);
switch (s.getType()) {
case MAP:
path = path == null ? ">" : path + ">";
int start = columns.size();
ColumnMetaData p = addColumn(path, ValueType.NULL, parent, true);
addColumn(p(path, "key", ""), ValueType.STRING, p, false);
columnize(p(path, "value", ""), s.getValueType(), p, false);
arrayWidths.set(start, columns.size() - start); // fixup with actual width
break;
case RECORD:
for (Field field : s.getFields()) // flatten fields to columns
columnize(p(path, field.name(), "#"), field.schema(), parent, isArray);
break;
case ARRAY:
path = path == null ? "[]" : path + "[]";
addArrayColumn(path, s.getElementType(), parent);
break;
case UNION:
for (Schema branch : s.getTypes()) // array per non-null branch
if (branch.getType() != Schema.Type.NULL)
addArrayColumn(p(path, branch, "/"), branch, parent);
break;
default:
throw new TrevniRuntimeException("Unknown schema: " + s);
}
seen.remove(s);
}
private String p(String parent, Schema child, String sep) {
if (child.getType() == Schema.Type.UNION)
return parent;
return p(parent, child.getFullName(), sep);
}
private String p(String parent, String child, String sep) {
return parent == null ? child : parent + sep + child;
}
private ColumnMetaData addColumn(String path, ValueType type, ColumnMetaData parent, boolean isArray) {
ColumnMetaData column = new ColumnMetaData(path, type);
if (parent != null)
column.setParent(parent);
column.isArray(isArray);
columns.add(column);
arrayWidths.add(1); // placeholder
return column;
}
private void addArrayColumn(String path, Schema element, ColumnMetaData parent) {
if (path == null)
path = element.getFullName();
if (isSimple(element)) { // optimize simple arrays
addColumn(path, simpleValueType(element), parent, true);
return;
}
// complex array: insert a parent column with lengths
int start = columns.size();
ColumnMetaData array = addColumn(path, ValueType.NULL, parent, true);
columnize(path, element, array, false);
arrayWidths.set(start, columns.size() - start); // fixup with actual width
}
static boolean isSimple(Schema s) {
switch (s.getType()) {
case NULL:
case BOOLEAN:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
case BYTES:
case STRING:
case ENUM:
case FIXED:
return true;
default:
return false;
}
}
private ValueType simpleValueType(Schema s) {
switch (s.getType()) {
case NULL:
return ValueType.NULL;
case BOOLEAN:
return ValueType.BOOLEAN;
case INT:
return ValueType.INT;
case LONG:
return ValueType.LONG;
case FLOAT:
return ValueType.FLOAT;
case DOUBLE:
return ValueType.DOUBLE;
case BYTES:
return ValueType.BYTES;
case STRING:
return ValueType.STRING;
case ENUM:
return ValueType.INT;
case FIXED:
return ValueType.BYTES;
default:
throw new TrevniRuntimeException("Unknown schema: " + s);
}
}
}
| AvroColumnator |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/support/opds/udf/ExportSelectListColumns.java | {
"start": 941,
"end": 2016
} | class ____ extends UDF {
public String evaluate(String sql) {
return evaluate(sql, null);
}
public String evaluate(String sql, String dbType) {
try {
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, DbType.valueOf(dbType));
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(DbType.valueOf(dbType));
for (SQLStatement stmt : statementList) {
stmt.accept(visitor);
}
StringBuilder buf = new StringBuilder();
for (TableStat.Column column : visitor.getColumns()) {
if (!column.isSelect()) {
continue;
}
if (buf.length() != 0) {
buf.append(',');
}
buf.append(column.toString());
}
return buf.toString();
} catch (Exception ex) {
System.err.println("error sql : " + sql);
ex.printStackTrace();
return null;
}
}
}
| ExportSelectListColumns |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/optimizer/Optimizer.java | {
"start": 9909,
"end": 11471
} | class ____ extends OptimizerRule<Pivot> {
@Override
protected LogicalPlan rule(Pivot plan) {
// 1. add the IN filter
List<Expression> rawValues = new ArrayList<>(plan.values().size());
for (NamedExpression namedExpression : plan.values()) {
// everything should have resolved to an alias
if (namedExpression instanceof Alias) {
rawValues.add(Literal.of(((Alias) namedExpression).child()));
}
// fallback - should not happen
else {
UnresolvedAttribute attr = new UnresolvedAttribute(
namedExpression.source(),
namedExpression.name(),
null,
"Unexpected alias"
);
return new Pivot(plan.source(), plan.child(), plan.column(), singletonList(attr), plan.aggregates());
}
}
Filter filter = new Filter(plan.source(), plan.child(), new In(plan.source(), plan.column(), rawValues));
// 2. preserve the PIVOT
return new Pivot(plan.source(), filter, plan.column(), plan.values(), plan.aggregates(), plan.groupings());
}
}
//
// Replace any reference attribute with its source, if it does not affect the result.
// This avoid ulterior look-ups between attributes and its source across nodes, which is
// problematic when doing script translation.
//
static | RewritePivot |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/filter/ProblemHandlerTest.java | {
"start": 2949,
"end": 3440
} | class ____
extends DeserializationProblemHandler
{
protected final Object value;
public MissingInstantiationHandler(Object v0) {
value = v0;
}
@Override
public Object handleMissingInstantiator(DeserializationContext ctxt,
Class<?> instClass, ValueInstantiator inst, JsonParser p, String msg)
{
p.skipChildren();
return value;
}
}
static | MissingInstantiationHandler |
java | quarkusio__quarkus | extensions/container-image/container-image-docker-common/deployment/src/main/java/io/quarkus/container/image/docker/common/deployment/CommonConfig.java | {
"start": 318,
"end": 1894
} | interface ____ {
/**
* Path to the JVM Dockerfile.
* If set to an absolute path then the absolute path will be used, otherwise the path
* will be considered relative to the project root.
* If not set src/main/docker/Dockerfile.jvm will be used.
*/
@ConfigDocDefault("src/main/docker/Dockerfile.jvm")
Optional<String> dockerfileJvmPath();
/**
* Path to the native Dockerfile.
* If set to an absolute path then the absolute path will be used, otherwise the path
* will be considered relative to the project root.
* If not set src/main/docker/Dockerfile.native will be used.
*/
@ConfigDocDefault("src/main/docker/Dockerfile.native")
Optional<String> dockerfileNativePath();
/**
* Build args passed to docker via {@code --build-arg}
*/
@ConfigDocMapKey("arg-name")
Map<String, String> buildArgs();
/**
* Images to consider as cache sources. Values are passed to {@code docker build}/{@code podman build} via the
* {@code cache-from} option
*/
Optional<List<String>> cacheFrom();
/**
* The networking mode for the RUN instructions during build
*/
Optional<String> network();
/**
* Name of binary used to execute the docker/podman commands.
* This setting can override the global container runtime detection.
*/
Optional<String> executableName();
/**
* Additional arbitrary arguments passed to the executable when building the container image.
*/
Optional<List<String>> additionalArgs();
}
| CommonConfig |
java | spring-projects__spring-boot | module/spring-boot-data-mongodb/src/test/java/org/springframework/boot/data/mongodb/autoconfigure/domain/city/City.java | {
"start": 811,
"end": 1428
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String state;
private String country;
private String map;
protected City() {
}
public City(String name, String country) {
this.name = name;
this.country = country;
}
public String getName() {
return this.name;
}
public String getState() {
return this.state;
}
public String getCountry() {
return this.country;
}
public String getMap() {
return this.map;
}
@Override
public String toString() {
return getName() + "," + getState() + "," + getCountry();
}
}
| City |
java | apache__kafka | streams/src/test/java/org/apache/kafka/streams/processor/internals/PunctuationQueueTest.java | {
"start": 1295,
"end": 7530
} | class ____ {
private final MockProcessorNode<String, String, ?, ?> node = new MockProcessorNode<>();
private final PunctuationQueue queue = new PunctuationQueue();
private final Punctuator punctuator = timestamp -> node.mockProcessor.punctuatedStreamTime().add(timestamp);
@Test
public void testPunctuationInterval() {
final PunctuationSchedule sched = new PunctuationSchedule(node, 0L, 100L, punctuator);
final long now = sched.timestamp - 100L;
queue.schedule(sched);
assertCanPunctuateAtPrecisely(now + 100L);
final ProcessorNodePunctuator processorNodePunctuator = (node, timestamp, type, punctuator) -> punctuator.punctuate(timestamp);
queue.maybePunctuate(now, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(0, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 100L);
queue.maybePunctuate(now + 99L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(0, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 100L);
queue.maybePunctuate(now + 100L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(1, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 200L);
queue.maybePunctuate(now + 199L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(1, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 200L);
queue.maybePunctuate(now + 200L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(2, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 300L);
queue.maybePunctuate(now + 1001L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(3, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 1100L);
queue.maybePunctuate(now + 1002L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(3, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 1100L);
queue.maybePunctuate(now + 1100L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(4, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 1200L);
}
@Test
public void testPunctuationIntervalCustomAlignment() {
final PunctuationSchedule sched = new PunctuationSchedule(node, 50L, 100L, punctuator);
final long now = sched.timestamp - 50L;
queue.schedule(sched);
assertCanPunctuateAtPrecisely(now + 50L);
final ProcessorNodePunctuator processorNodePunctuator =
(node, timestamp, type, punctuator) -> punctuator.punctuate(timestamp);
queue.maybePunctuate(now, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(0, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 50L);
queue.maybePunctuate(now + 49L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(0, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 50L);
queue.maybePunctuate(now + 50L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(1, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 150L);
queue.maybePunctuate(now + 149L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(1, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 150L);
queue.maybePunctuate(now + 150L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(2, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 250L);
queue.maybePunctuate(now + 1051L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(3, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 1150L);
queue.maybePunctuate(now + 1052L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(3, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 1150L);
queue.maybePunctuate(now + 1150L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(4, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 1250L);
}
@Test
public void testPunctuationIntervalCancelFromPunctuator() {
final PunctuationSchedule sched = new PunctuationSchedule(node, 0L, 100L, punctuator);
final long now = sched.timestamp - 100L;
final Cancellable cancellable = queue.schedule(sched);
assertCanPunctuateAtPrecisely(now + 100L);
final ProcessorNodePunctuator processorNodePunctuator = (node, timestamp, type, punctuator) -> {
punctuator.punctuate(timestamp);
// simulate scheduler cancelled from within punctuator
cancellable.cancel();
};
queue.maybePunctuate(now, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(0, node.mockProcessor.punctuatedStreamTime().size());
assertCanPunctuateAtPrecisely(now + 100L);
queue.maybePunctuate(now + 100L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(1, node.mockProcessor.punctuatedStreamTime().size());
assertFalse(queue.canPunctuate(Long.MAX_VALUE));
queue.maybePunctuate(now + 200L, PunctuationType.STREAM_TIME, processorNodePunctuator);
assertEquals(1, node.mockProcessor.punctuatedStreamTime().size());
assertFalse(queue.canPunctuate(Long.MAX_VALUE));
}
private void assertCanPunctuateAtPrecisely(final long now) {
assertFalse(queue.canPunctuate(now - 1));
assertTrue(queue.canPunctuate(now));
assertTrue(queue.canPunctuate(now + 1));
}
}
| PunctuationQueueTest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/shortcircuit/ShortCircuitShm.java | {
"start": 4557,
"end": 5487
} | class ____ {
private final ShmId shmId;
private final int slotIdx;
public SlotId(ShmId shmId, int slotIdx) {
this.shmId = shmId;
this.slotIdx = slotIdx;
}
public ShmId getShmId() {
return shmId;
}
public int getSlotIdx() {
return slotIdx;
}
@Override
public boolean equals(Object o) {
if ((o == null) || (o.getClass() != this.getClass())) {
return false;
}
SlotId other = (SlotId)o;
return new EqualsBuilder().
append(shmId, other.shmId).
append(slotIdx, other.slotIdx).
isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().
append(this.shmId).
append(this.slotIdx).
toHashCode();
}
@Override
public String toString() {
return String.format("SlotId(%s:%d)", shmId.toString(), slotIdx);
}
}
public | SlotId |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/FieldMissingNullableTest.java | {
"start": 5734,
"end": 7266
} | class ____ {
private String message;
public void reset(FieldMissingNullTest other) {
// BUG: Diagnostic contains: @Nullable
if (other.message != null) {}
}
}
""")
.doTest();
}
@Test
public void recordComponent() {
createAggressiveRefactoringTestHelper()
.addInputLines(
"com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
"""
package com.google.errorprone.bugpatterns.nullness;
record FieldMissingNullTest(String message) {
boolean hasMessage() {
return message != null;
}
}
""")
.addOutputLines(
"com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
"""
package com.google.errorprone.bugpatterns.nullness;
import org.jspecify.annotations.Nullable;
record FieldMissingNullTest(@Nullable String message) {
boolean hasMessage() {
return message != null;
}
}
""")
.doTest();
}
@Test
public void negativeCases_comparisonToNullConservative() {
createCompilationTestHelper()
.addSourceLines(
"com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
"""
package com.google.errorprone.bugpatterns.nullness;
public | FieldMissingNullTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/unmappedtarget/Target.java | {
"start": 202,
"end": 501
} | class ____ {
private Long foo;
private int bar;
public Long getFoo() {
return foo;
}
public void setFoo(Long foo) {
this.foo = foo;
}
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
}
| Target |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java | {
"start": 48243,
"end": 48600
} | class ____ mutable field
private final Object o = null;
}
}
""")
.doTest();
}
@Test
public void mutableEnclosing() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.errorprone.annotations.Immutable;
public | has |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceAmbiguousInjectTest.java | {
"start": 753,
"end": 1942
} | class ____ {
@RegisterExtension
static QuarkusUnitTest testExtension = new QuarkusUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
JavaArchive war = ShrinkWrap.create(JavaArchive.class);
war.addClass(PortProviderUtil.class);
war.addClass(EnglishGreeterResource.class);
war.addClass(SpanishGreeterResource.class);
war.addClass(GreeterResource.class);
war.addClass(LanguageResource.class);
war.addClass(LanguageResourceV2.class);
war.addClass(GreeterResourceV2.class);
war.addClass(EnglishGreeterResource.class);
war.addClass(SpanishGreeterResource.class);
return war;
}
});
@Test
void basicTest() {
given().when().get("/languages/en").then().statusCode(200).body(is("hello"));
given().when().get("/languages/v2/es").then().statusCode(200).body(is("hola"));
}
@RequestScoped
public static | SubResourceAmbiguousInjectTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/listener/TrackingListener.java | {
"start": 873,
"end": 1065
} | interface ____ extends ObjectListener {
/**
* Invoked when a Redisson object was changed
*
* @param name object name
*/
void onChange(String name);
}
| TrackingListener |
java | apache__camel | components/camel-servlet/src/test/java/org/apache/camel/component/servlet/rest/RestServletPostXmlJaxbPojoTest.java | {
"start": 1282,
"end": 3613
} | class ____ extends ServletCamelRouterTestSupport {
@Test
public void testPostJaxbPojo() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:input");
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(UserJaxbPojo.class);
String body = "{\"id\": 123, \"name\": \"Donald Duck\"}";
WebRequest req = new PostMethodWebRequest(
contextUrl + "/services/users/new",
new ByteArrayInputStream(body.getBytes()), "application/json");
WebResponse response = query(req, false);
assertEquals(200, response.getResponseCode());
MockEndpoint.assertIsSatisfied(context);
UserJaxbPojo user = mock.getReceivedExchanges().get(0).getIn().getBody(UserJaxbPojo.class);
assertNotNull(user);
assertEquals(123, user.getId());
assertEquals("Donald Duck", user.getName());
}
@Test
public void testPostJaxbPojoNoContentType() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:input");
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(UserJaxbPojo.class);
String body = "<user name=\"Donald Duck\" id=\"456\"></user>";
WebRequest req = new PostMethodWebRequest(
contextUrl + "/services/users/new",
new ByteArrayInputStream(body.getBytes()), "foo");
WebResponse response = query(req, false);
assertEquals(200, response.getResponseCode());
MockEndpoint.assertIsSatisfied(context);
UserJaxbPojo user = mock.getReceivedExchanges().get(0).getIn().getBody(UserJaxbPojo.class);
assertNotNull(user);
assertEquals(456, user.getId());
assertEquals("Donald Duck", user.getName());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
restConfiguration().component("servlet").bindingMode(RestBindingMode.auto);
// use the rest DSL to define the rest services
rest("/users/")
.post("new").type(UserJaxbPojo.class)
.to("mock:input");
}
};
}
}
| RestServletPostXmlJaxbPojoTest |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndParametersTests.java | {
"start": 1243,
"end": 1523
} | class ____ {
@Test
void test() {
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class, Bar.class);
assertThat(ctx.getBean(Bar.class).foo).isNotNull();
ctx.close();
}
@Configuration
static | ConfigurationWithFactoryBeanAndParametersTests |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/subjects/MaybeSubjectTest.java | {
"start": 998,
"end": 7295
} | class ____ extends RxJavaTest {
@Test
public void success() {
MaybeSubject<Integer> ms = MaybeSubject.create();
assertFalse(ms.hasValue());
assertNull(ms.getValue());
assertFalse(ms.hasComplete());
assertFalse(ms.hasThrowable());
assertNull(ms.getThrowable());
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
TestObserver<Integer> to = ms.test();
to.assertEmpty();
assertTrue(ms.hasObservers());
assertEquals(1, ms.observerCount());
ms.onSuccess(1);
assertTrue(ms.hasValue());
assertEquals(1, ms.getValue().intValue());
assertFalse(ms.hasComplete());
assertFalse(ms.hasThrowable());
assertNull(ms.getThrowable());
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
to.assertResult(1);
ms.test().assertResult(1);
assertTrue(ms.hasValue());
assertEquals(1, ms.getValue().intValue());
assertFalse(ms.hasComplete());
assertFalse(ms.hasThrowable());
assertNull(ms.getThrowable());
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
}
@Test
public void once() {
MaybeSubject<Integer> ms = MaybeSubject.create();
TestObserver<Integer> to = ms.test();
ms.onSuccess(1);
ms.onSuccess(2);
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
ms.onError(new IOException());
TestHelper.assertUndeliverable(errors, 0, IOException.class);
} finally {
RxJavaPlugins.reset();
}
ms.onComplete();
to.assertResult(1);
}
@Test
public void error() {
MaybeSubject<Integer> ms = MaybeSubject.create();
assertFalse(ms.hasValue());
assertNull(ms.getValue());
assertFalse(ms.hasComplete());
assertFalse(ms.hasThrowable());
assertNull(ms.getThrowable());
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
TestObserver<Integer> to = ms.test();
to.assertEmpty();
assertTrue(ms.hasObservers());
assertEquals(1, ms.observerCount());
ms.onError(new IOException());
assertFalse(ms.hasValue());
assertNull(ms.getValue());
assertFalse(ms.hasComplete());
assertTrue(ms.hasThrowable());
assertTrue(ms.getThrowable().toString(), ms.getThrowable() instanceof IOException);
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
to.assertFailure(IOException.class);
ms.test().assertFailure(IOException.class);
assertFalse(ms.hasValue());
assertNull(ms.getValue());
assertFalse(ms.hasComplete());
assertTrue(ms.hasThrowable());
assertTrue(ms.getThrowable().toString(), ms.getThrowable() instanceof IOException);
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
}
@Test
public void complete() {
MaybeSubject<Integer> ms = MaybeSubject.create();
assertFalse(ms.hasValue());
assertNull(ms.getValue());
assertFalse(ms.hasComplete());
assertFalse(ms.hasThrowable());
assertNull(ms.getThrowable());
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
TestObserver<Integer> to = ms.test();
to.assertEmpty();
assertTrue(ms.hasObservers());
assertEquals(1, ms.observerCount());
ms.onComplete();
assertFalse(ms.hasValue());
assertNull(ms.getValue());
assertTrue(ms.hasComplete());
assertFalse(ms.hasThrowable());
assertNull(ms.getThrowable());
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
to.assertResult();
ms.test().assertResult();
assertFalse(ms.hasValue());
assertNull(ms.getValue());
assertTrue(ms.hasComplete());
assertFalse(ms.hasThrowable());
assertNull(ms.getThrowable());
assertFalse(ms.hasObservers());
assertEquals(0, ms.observerCount());
}
@Test
public void cancelOnArrival() {
MaybeSubject.create()
.test(true)
.assertEmpty();
}
@Test
public void cancelOnArrival2() {
MaybeSubject<Integer> ms = MaybeSubject.create();
ms.test();
ms
.test(true)
.assertEmpty();
}
@Test
public void dispose() {
TestHelper.checkDisposed(MaybeSubject.create());
}
@Test
public void disposeTwice() {
MaybeSubject.create()
.subscribe(new MaybeObserver<Object>() {
@Override
public void onSubscribe(Disposable d) {
assertFalse(d.isDisposed());
d.dispose();
d.dispose();
assertTrue(d.isDisposed());
}
@Override
public void onSuccess(Object value) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
@Test
public void onSubscribeDispose() {
MaybeSubject<Integer> ms = MaybeSubject.create();
Disposable d = Disposable.empty();
ms.onSubscribe(d);
assertFalse(d.isDisposed());
ms.onComplete();
d = Disposable.empty();
ms.onSubscribe(d);
assertTrue(d.isDisposed());
}
@Test
public void addRemoveRace() {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
final MaybeSubject<Integer> ms = MaybeSubject.create();
final TestObserver<Integer> to = ms.test();
Runnable r1 = new Runnable() {
@Override
public void run() {
ms.test();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
to.dispose();
}
};
TestHelper.race(r1, r2);
}
}
}
| MaybeSubjectTest |
java | apache__dubbo | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmServiceImpl.java | {
"start": 954,
"end": 1177
} | class ____ implements MultipleRegistryCenterInjvmService {
/**
* {@inheritDoc}
*/
@Override
public String hello(String name) {
return "Hello " + name;
}
}
| MultipleRegistryCenterInjvmServiceImpl |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/node/TreeTraversingParserTest.java | {
"start": 755,
"end": 831
} | class ____ {
public Inner inner;
}
public static | Jackson370Bean |
java | apache__camel | components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/spring/CamelSpringOverridePropertiesTest.java | {
"start": 1738,
"end": 2616
} | class ____ {
@Produce("direct:start")
private ProducerTemplate start;
@EndpointInject("mock:a")
private MockEndpoint mockA;
@EndpointInject("mock:test")
private MockEndpoint mockTest;
@EndpointInject("mock:foo")
private MockEndpoint mockFoo;
@UseOverridePropertiesWithPropertiesComponent
public static Properties override() {
Properties answer = new Properties();
answer.put("cool.end", "mock:foo");
return answer;
}
@Test
public void testOverride() throws Exception {
mockA.expectedBodiesReceived("Camel");
mockTest.expectedMessageCount(0);
mockFoo.expectedBodiesReceived("Hello Camel");
start.sendBody("Camel");
mockA.assertIsSatisfied();
mockTest.assertIsSatisfied();
mockFoo.assertIsSatisfied();
}
}
| CamelSpringOverridePropertiesTest |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.java | {
"start": 6929,
"end": 7008
} | class ____ extends UsernamePasswordAuthenticationFilter {
}
static | CustomFilter |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java | {
"start": 2995,
"end": 3069
} | class ____ {
@Bean
TestBean z2() {
return new TestBean();
}
}
}
| Z2 |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/authentication/SecurityAssertions.java | {
"start": 1614,
"end": 3053
} | class ____ extends AbstractObjectAssert<AuthenticationAssert, Authentication> {
private final Authentication authentication;
private AuthenticationAssert(Authentication authentication) {
super(authentication, AuthenticationAssert.class);
this.authentication = authentication;
}
public AuthenticationAssert name(String name) {
Assertions.assertThat(this.authentication.getName()).isEqualTo(name);
return this;
}
public ObjectAssert<GrantedAuthority> hasAuthority(String authority) {
Collection<? extends GrantedAuthority> actual = this.authentication.getAuthorities();
for (GrantedAuthority element : actual) {
if (element.getAuthority().equals(authority)) {
return new ObjectAssert<>(element);
}
}
throw new AssertionError(actual + " does not contain " + authority + " as expected");
}
public CollectionAssert<GrantedAuthority> hasAuthorities(String... authorities) {
HasAuthoritiesPredicate test = new HasAuthoritiesPredicate(authorities);
return authorities().has(new Condition<>(test, "contains %s", Arrays.toString(authorities)));
}
public CollectionAssert<GrantedAuthority> roles() {
return authorities().filteredOn((authority) -> authority.getAuthority().startsWith("ROLE_"));
}
public CollectionAssert<GrantedAuthority> authorities() {
return new CollectionAssert<>(this.authentication.getAuthorities());
}
}
private static final | AuthenticationAssert |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/http/HttpHeadersValidationException.java | {
"start": 705,
"end": 1014
} | class ____ extends ElasticsearchException implements ElasticsearchWrapperException {
public HttpHeadersValidationException(Exception cause) {
super(cause);
}
public HttpHeadersValidationException(StreamInput in) throws IOException {
super(in);
}
}
| HttpHeadersValidationException |
java | apache__logging-log4j2 | log4j-jpl/src/main/java/org/apache/logging/log4j/jpl/Log4jSystemLogger.java | {
"start": 1407,
"end": 5145
} | class ____ implements Logger {
private final ExtendedLogger logger;
private static final String FQCN = Log4jSystemLogger.class.getName();
public Log4jSystemLogger(final ExtendedLogger logger) {
this.logger = logger;
}
@Override
public String getName() {
return logger.getName();
}
@Override
public boolean isLoggable(final Level level) {
return logger.isEnabled(getLevel(level));
}
@Override
public void log(final Level level, final String msg) {
log(level, (ResourceBundle) null, msg, (Throwable) null);
}
@Override
public void log(final Level level, final Supplier<String> msgSupplier) {
Objects.requireNonNull(msgSupplier);
if (isLoggable(Objects.requireNonNull(level))) {
log(level, (ResourceBundle) null, msgSupplier.get(), (Throwable) null);
}
}
@Override
public void log(final Level level, final Object obj) {
Objects.requireNonNull(obj);
if (isLoggable(Objects.requireNonNull(level))) {
log(level, (ResourceBundle) null, obj.toString(), (Throwable) null);
}
}
@Override
public void log(final Level level, final String msg, final Throwable thrown) {
log(level, null, msg, thrown);
}
@Override
public void log(final Level level, final Supplier<String> msgSupplier, final Throwable thrown) {
Objects.requireNonNull(msgSupplier);
if (isLoggable(Objects.requireNonNull(level))) {
log(level, null, msgSupplier.get(), thrown);
}
}
@Override
public void log(final Level level, final String format, final Object... params) {
log(level, null, format, params);
}
@Override
public void log(final Level level, final ResourceBundle bundle, final String msg, final Throwable thrown) {
logger.logIfEnabled(FQCN, getLevel(level), null, getResource(bundle, msg), thrown);
}
@Override
public void log(final Level level, final ResourceBundle bundle, final String format, final Object... params) {
final Message message = createMessage(getResource(bundle, format), params);
logger.logIfEnabled(FQCN, getLevel(level), null, message, message.getThrowable());
}
private static Message createMessage(final String format, final Object... params) {
if (params == null || params.length == 0) {
return new SimpleMessage(format);
}
return new MessageFormatMessage(format, params);
}
private static org.apache.logging.log4j.Level getLevel(final Level level) {
switch (level) {
case OFF:
return org.apache.logging.log4j.Level.OFF;
case ERROR:
return org.apache.logging.log4j.Level.ERROR;
case WARNING:
return org.apache.logging.log4j.Level.WARN;
case INFO:
return org.apache.logging.log4j.Level.INFO;
case DEBUG:
return org.apache.logging.log4j.Level.DEBUG;
case TRACE:
return org.apache.logging.log4j.Level.TRACE;
case ALL:
return org.apache.logging.log4j.Level.ALL;
}
return org.apache.logging.log4j.Level.ERROR;
}
private static String getResource(final ResourceBundle bundle, final String msg) {
if (bundle == null || msg == null) {
return msg;
}
try {
return bundle.getString(msg);
} catch (MissingResourceException e) {
// ignore
return msg;
} catch (ClassCastException ex) {
return bundle.getObject(msg).toString();
}
}
}
| Log4jSystemLogger |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/aot/AotIntegrationTests.java | {
"start": 3309,
"end": 3685
} | class ____ extends AbstractAotTests {
private static final String CLASSPATH_ROOT = "AotIntegrationTests.classpath_root";
// We have to determine the classpath root and store it in a system property
// since @CompileWithForkedClassLoader uses a custom ClassLoader that does
// not support CodeSource.
//
// The system property will only be set when this | AotIntegrationTests |
java | apache__camel | dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/TransformMessageAction.java | {
"start": 1897,
"end": 14632
} | class ____ extends ActionWatchCommand {
@CommandLine.Option(names = { "--camel-version" },
description = "To run using a different Camel version than the default version.")
String camelVersion;
@CommandLine.Option(names = { "--body" }, required = true,
description = "Message body to send (prefix with file: to refer to loading message body from file)")
String body;
@CommandLine.Option(names = { "--header" },
description = "Message header (key=value)")
List<String> headers;
@CommandLine.Option(names = {
"--source" },
description = "Instead of using external template file then refer to an existing Camel route source with inlined Camel language expression in a route. (use :line-number or :id to refer to the exact location of the EIP to use)")
private String source;
@CommandLine.Option(names = {
"--language" },
description = "The language to use for message transformation")
private String language;
@CommandLine.Option(names = {
"--component" },
description = "The component to use for message transformation")
private String component;
@CommandLine.Option(names = {
"--dataformat" },
description = "The dataformat to use for message transformation")
private String dataformat;
@CommandLine.Option(names = {
"--template" },
description = "The template to use for message transformation (prefix with file: to refer to loading message body from file)")
private String template;
@CommandLine.Option(names = { "--option" },
description = "Option for additional configuration of the used language, component or dataformat (key=value)")
List<String> options;
@CommandLine.Option(names = {
"--output" },
description = "File to store output. If none provide then output is printed to console.")
private String output;
@CommandLine.Option(names = { "--show-exchange-properties" }, defaultValue = "false",
description = "Show exchange properties from the output message")
boolean showExchangeProperties;
@CommandLine.Option(names = { "--show-headers" }, defaultValue = "true",
description = "Show message headers from the output message")
boolean showHeaders = true;
@CommandLine.Option(names = { "--show-body" }, defaultValue = "true",
description = "Show message body from the output message")
boolean showBody = true;
@CommandLine.Option(names = { "--show-exception" }, defaultValue = "true",
description = "Show exception and stacktrace for failed transformation")
boolean showException = true;
@CommandLine.Option(names = { "--timeout" }, defaultValue = "20000",
description = "Timeout in millis waiting for message to be transformed")
long timeout = 20000;
@CommandLine.Option(names = { "--logging-color" }, defaultValue = "true", description = "Use colored logging")
boolean loggingColor = true;
@CommandLine.Option(names = { "--pretty" },
description = "Pretty print message body when using JSon or XML format")
boolean pretty;
@CommandLine.Option(names = { "--repo", "--repos" },
description = "Additional maven repositories (Use commas to separate multiple repositories)")
String repositories;
private volatile long pid;
private MessageTableHelper tableHelper;
public TransformMessageAction(CamelJBangMain main) {
super(main);
}
@Override
public Integer doCall() throws Exception {
if (dataformat == null) {
// either source or language/template is required
if (source == null && template == null && language == null && component == null) {
printer().printErr("Either source or template and one of language/component must be configured");
return -1;
}
if (source == null && (template == null || language == null && component == null)) {
printer().printErr("Both template and one of language/component must be configured");
return -1;
}
}
// does files exists
if (source != null && source.startsWith("file:")) {
String s = source.substring(5);
s = StringHelper.beforeLast(s, ":", s); // remove line number
Path f = Path.of(s);
if (!Files.exists(f)) {
printer().printErr("Source file does not exist: " + f);
return -1;
}
}
if (template != null && template.startsWith("file:")) {
Path f = Path.of(template.substring(5));
if (!Files.exists(f)) {
printer().printErr("Template file does not exist: " + f);
return -1;
}
}
Integer exit;
try {
// start a new empty camel in the background
Run run = new Run(getMain());
// requires camel 4.3 onwards
if (camelVersion != null && VersionHelper.isLE(camelVersion, "4.2.0")) {
printer().printErr("This requires Camel version 4.3 or newer");
return -1;
}
exit = run.runTransformMessage(camelVersion, repositories);
this.pid = run.spawnPid;
if (exit == 0) {
exit = super.doCall();
}
} finally {
if (pid > 0) {
// cleanup output file
Path outputFile = getOutputFile(Long.toString(pid));
PathUtils.deleteFile(outputFile);
// stop running camel as we are done
Path parent = CommandLineHelper.getCamelDir();
Path pidFile = parent.resolve(Long.toString(pid));
if (Files.exists(pidFile)) {
PathUtils.deleteFile(pidFile);
}
}
}
return exit;
}
@Override
protected Integer doWatchCall() throws Exception {
// ensure output file is deleted before executing action
Path outputFile = getOutputFile(Long.toString(pid));
PathUtils.deleteFile(outputFile);
JsonObject root = new JsonObject();
root.put("action", "transform");
if (source != null) {
root.put("source", source);
}
if (language != null) {
root.put("language", language);
}
if (component != null) {
root.put("component", component);
}
if (dataformat != null) {
root.put("dataformat", dataformat);
}
if (template != null) {
root.put("template", Jsoner.escape(template));
}
root.put("body", Jsoner.escape(body));
if (headers != null) {
JsonArray arr = new JsonArray();
for (String h : headers) {
JsonObject jo = new JsonObject();
if (!h.contains("=")) {
printer().println("Header must be in key=value format, was: " + h);
return 0;
}
jo.put("key", StringHelper.before(h, "="));
jo.put("value", StringHelper.after(h, "="));
arr.add(jo);
}
root.put("headers", arr);
}
if (options != null) {
JsonArray arr = new JsonArray();
for (String h : options) {
JsonObject jo = new JsonObject();
if (!h.contains("=")) {
printer().println("Option must be in key=value format, was: " + h);
return 0;
}
jo.put("key", StringHelper.before(h, "="));
jo.put("value", StringHelper.after(h, "="));
arr.add(jo);
}
root.put("options", arr);
}
Path f = getActionFile(Long.toString(pid));
try {
PathUtils.writeTextSafely(root.toJson(), f);
} catch (Exception e) {
// ignore
}
JsonObject jo = waitForOutputFile(outputFile);
if (jo != null) {
printStatusLine(jo);
String exchangeId = jo.getString("exchangeId");
JsonObject message = jo.getMap("message");
JsonObject cause = jo.getMap("exception");
if (message != null || cause != null) {
if (output != null) {
Path target = Path.of(output);
String json = jo.toJson();
if (pretty) {
json = Jsoner.prettyPrint(json, 2);
}
Files.writeString(target, json);
}
if (!showExchangeProperties && message != null) {
message.remove("exchangeProperties");
}
if (!showHeaders && message != null) {
message.remove("headers");
}
if (!showBody && message != null) {
message.remove("body");
}
if (!showException && cause != null) {
cause = null;
}
if (output == null) {
if (watch) {
clearScreen();
}
tableHelper = new MessageTableHelper();
tableHelper.setPretty(pretty);
tableHelper.setLoggingColor(loggingColor);
tableHelper.setShowExchangeProperties(showExchangeProperties);
String table = tableHelper.getDataAsTable(exchangeId, "InOut", null, null, message, cause);
printer().println(table);
}
}
}
// delete output file after use
PathUtils.deleteFile(outputFile);
return 0;
}
private void printStatusLine(JsonObject jo) {
// timstamp
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String ts = sdf.format(new Date(jo.getLong("timestamp")));
if (loggingColor) {
AnsiConsole.out().print(Ansi.ansi().fgBrightDefault().a(Ansi.Attribute.INTENSITY_FAINT).a(ts).reset());
} else {
printer().print(ts);
}
// pid
printer().print(" ");
String p = String.format("%5.5s", this.pid);
if (loggingColor) {
AnsiConsole.out().print(Ansi.ansi().fgMagenta().a(p).reset());
AnsiConsole.out().print(Ansi.ansi().fgBrightDefault().a(Ansi.Attribute.INTENSITY_FAINT).a(" --- ").reset());
} else {
printer().print(p);
printer().print(" --- ");
}
// status
printer().print(getStatus(jo));
// elapsed
String e = TimeUtils.printDuration(jo.getLong("elapsed"), true);
if (loggingColor) {
AnsiConsole.out().print(Ansi.ansi().fgBrightDefault().a(" (" + e + ")").reset());
} else {
printer().print("(" + e + ")");
}
printer().println();
}
private String getStatus(JsonObject r) {
boolean failed = "failed".equals(r.getString("status")) || "error".equals(r.getString("status"));
String status;
if (failed) {
status = "Failed (exception)";
} else if (output != null) {
status = "Output saved to file (success)";
} else {
status = "Message transformed (success)";
}
if (loggingColor) {
return Ansi.ansi().fg(failed ? Ansi.Color.RED : Ansi.Color.GREEN).a(status).reset().toString();
} else {
return status;
}
}
protected JsonObject waitForOutputFile(Path outputFile) {
StopWatch watch = new StopWatch();
while (watch.taken() < timeout) {
try {
// give time for response to be ready
Thread.sleep(20);
if (Files.exists(outputFile)) {
String text = Files.readString(outputFile);
return (JsonObject) Jsoner.deserialize(text);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
// ignore
}
}
return null;
}
}
| TransformMessageAction |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/cache/config/ExpressionCachingIntegrationTests.java | {
"start": 1841,
"end": 2035
} | class ____ {
@Bean
public BaseDao<User> userDao() {
return new UserDaoImpl();
}
@Bean
public BaseDao<Order> orderDao() {
return new OrderDaoImpl();
}
}
private | Spr11692Config |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/elementcollection/EmbeddedElementCollectionWithIdenticallyNamedAssociationTest.java | {
"start": 1255,
"end": 3827
} | class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
EntityA a1 = new EntityA();
a1.setId( 1 );
EntityB b1 = new EntityB();
b1.setId( 1 );
b1.setIdenticallyNamedAssociation( a1 );
a1.setB( b1 );
EntityA a2 = new EntityA();
a2.setId( 2 );
EntityB b2 = new EntityB();
b2.setId( 2 );
b2.setIdenticallyNamedAssociation( a2 );
a2.setB( b2 );
EmbeddableB embeddableB = new EmbeddableB();
embeddableB.setIdenticallyNamedAssociation( a2 );
b1.getElementCollection().add( embeddableB );
scope.inTransaction( session -> {
session.persist( a1 );
session.persist( a2 );
session.persist( b1 );
session.persist( b2 );
} );
assertThat( b1.getIdenticallyNamedAssociation() ).isEqualTo( a1 );
assertThat( b1.getElementCollection() ).hasSize( 1 );
assertThat( b1.getElementCollection().get( 0 ).getIdenticallyNamedAssociation() ).isEqualTo( a2 );
assertThat( a2.getB() ).isEqualTo( b2 );
}
@Test
public void testGetEntityA(SessionFactoryScope scope) {
scope.inTransaction( session -> {
EntityA a1 = session.get( EntityA.class, 1 );
EntityB b1 = a1.getB();
assertThat( b1.getId() ).isEqualTo( 1 );
assertThat( b1.getElementCollection() ).hasSize( 1 );
assertThat( b1.getIdenticallyNamedAssociation()).isEqualTo( a1 );
EntityA identicallyNamedAssociation = b1.getElementCollection().get( 0 ).getIdenticallyNamedAssociation();
assertThat( identicallyNamedAssociation.getId() ).isEqualTo( 2 );
EntityB b = identicallyNamedAssociation.getB();
assertThat( b.getId() ).isEqualTo( 2 );
assertThat( b.getElementCollection().size()).isEqualTo( 0 );
} );
}
@Test
public void testGetEntities(SessionFactoryScope scope) {
scope.inTransaction( session -> {
EntityA a1 = session.get( EntityA.class, 1 );
EntityA a2 = session.get( EntityA.class, 2 );
EntityB b1 = session.get( EntityB.class, 1 );
EntityB b2 = session.get( EntityB.class, 2 );
assertThat( a1 ).isNotNull();
assertThat( a2 ).isNotNull();
assertThat( b1 ).isNotNull();
assertThat( b1.getIdenticallyNamedAssociation() ).isEqualTo( a1 );
assertThat( a1.getB() ).isEqualTo( b1 );
assertThat( b1.getElementCollection() ).hasSize( 1 );
EntityA identicallyNamedAssociation = b1.getElementCollection().get( 0 ).getIdenticallyNamedAssociation();
assertThat( identicallyNamedAssociation ).isEqualTo( a2 );
assertThat( identicallyNamedAssociation.getB() ).isEqualTo( b2 );
} );
}
@Entity(name = "entityA")
public static | EmbeddedElementCollectionWithIdenticallyNamedAssociationTest |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/extensions/MockErrorSASTokenProvider.java | {
"start": 1236,
"end": 2314
} | class ____ implements SASTokenProvider {
Configuration config = null;
@Override
public void initialize(org.apache.hadoop.conf.Configuration configuration, String accountName) {
boolean throwExceptionAtInit = configuration.getBoolean(MOCK_SASTOKENPROVIDER_FAIL_INIT, false);
if (throwExceptionAtInit) {
throw new RuntimeException("MockSASTokenProvider initialize exception");
}
this.config = configuration;
}
/**
* Returns null SAS token query or Empty if returnEmptySASToken is set.
* @param accountName
* @param fileSystem the name of the fileSystem.
* @param path the file or directory path.
* @param operation the operation to be performed on the path.
* @return
*/
@Override
public String getSASToken(String accountName, String fileSystem, String path,
String operation) {
boolean returnEmptySASTokenQuery = this.config.getBoolean(
MOCK_SASTOKENPROVIDER_RETURN_EMPTY_SAS_TOKEN, false);
if (returnEmptySASTokenQuery) {
return "";
} else { return null; }
}
}
| MockErrorSASTokenProvider |
java | quarkusio__quarkus | integration-tests/main/src/main/java/io/quarkus/it/arc/interceptor/SimpleBean.java | {
"start": 120,
"end": 249
} | class ____ {
@Simple(name = "foo")
@Simple(name = "bar")
public String ping() {
return "OK";
}
}
| SimpleBean |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/AbstractSerializationTestCase.java | {
"start": 1298,
"end": 7421
} | class ____<T extends Writeable> extends AbstractWireSerializingTestCase<T> {
/**
* Generic test that creates new instance from the test instance and checks
* both for equality and asserts equality on the two instances.
*/
public final void testFromXContent() throws IOException {
createXContentTester().numberOfTestRuns(NUMBER_OF_TEST_RUNS)
.supportsUnknownFields(supportsUnknownFields())
.shuffleFieldsExceptions(getShuffleFieldsExceptions())
.randomFieldsExcludeFilter(getRandomFieldsExcludeFilter())
.assertEqualsConsumer(this::assertEqualInstances)
.assertToXContentEquivalence(assertToXContentEquivalence())
.dispose(this::dispose)
.test();
}
/**
* Calls xContent serialization on many threads and verifies that
* they produce the same result. Async search sometimes does this to
* aggregation responses and, in general, we think it's reasonable for
* everything that can convert itself to json to be able to do so
* concurrently.
*/
public final void testConcurrentToXContent() throws IOException, InterruptedException, ExecutionException {
XContentType xContentType = randomValueOtherThanMany(
/*
* SMILE will sometimes use the unicode marker for ascii strings
* if the it's internal buffer doeesn't have enough space for the
* whole string. That's fine for SMILE readers, but we're comparing
* bytes here so we can't use it.
*/
type -> type.xContent() == SmileXContent.smileXContent,
() -> randomFrom(XContentType.values())
);
T testInstance = createXContextTestInstance(xContentType);
try {
ToXContent.Params params = new ToXContent.DelegatingMapParams(
singletonMap(RestSearchAction.TYPED_KEYS_PARAM, "true"),
getToXContentParams()
);
boolean humanReadable = randomBoolean();
BytesRef firstTimeBytes = toXContent(asXContent(testInstance), xContentType, params, humanReadable).toBytesRef();
/*
* 500 rounds seems to consistently reproduce the issue on Nik's
* laptop. Larger numbers are going to be slower but more likely
* to reproduce the issue.
*/
int rounds = scaledRandomIntBetween(300, 5000);
concurrentTest(() -> {
try {
for (int r = 0; r < rounds; r++) {
BytesRef thisRoundBytes = toXContent(asXContent(testInstance), xContentType, params, humanReadable).toBytesRef();
if (firstTimeBytes.bytesEquals(thisRoundBytes)) {
continue;
}
StringBuilder error = new StringBuilder("Failed to round trip over ");
if (humanReadable) {
error.append("human readable ");
}
error.append(xContentType);
error.append("\nCanonical is:\n").append(Strings.toString(asXContent(testInstance), true, true));
boolean showBytes = xContentType.xContent() == CborXContent.cborXContent;
error.append("\nWanted : ").append(showBytes ? firstTimeBytes : firstTimeBytes.utf8ToString());
error.append("\nBut got: ").append(showBytes ? thisRoundBytes : thisRoundBytes.utf8ToString());
fail(error.toString());
}
} catch (IOException e) {
throw new AssertionError(e);
}
});
} finally {
dispose(testInstance);
}
}
protected abstract ToXContent asXContent(T instance);
/**
* Creates a random instance to use in the xcontent tests.
* Override this method if the random instance that you build
* should be aware of the {@link XContentType} used in the test.
*/
protected abstract T createXContextTestInstance(XContentType xContentType);
protected abstract AbstractXContentTestCase.XContentTester<T> createXContentTester();
/**
* Indicates whether the parser supports unknown fields or not. In case it does, such behaviour will be tested by
* inserting random fields before parsing and checking that they don't make parsing fail.
*/
protected boolean supportsUnknownFields() {
return false;
}
/**
* Returns a predicate that given the field name indicates whether the field has to be excluded from random fields insertion or not
*/
protected Predicate<String> getRandomFieldsExcludeFilter() {
return Predicates.never();
}
/**
* Fields that have to be ignored when shuffling as part of testFromXContent
*/
protected String[] getShuffleFieldsExceptions() {
return Strings.EMPTY_ARRAY;
}
/**
* Params that have to be provided when calling calling {@link ToXContent#toXContent(XContentBuilder, ToXContent.Params)}
*/
protected ToXContent.Params getToXContentParams() {
return ToXContent.EMPTY_PARAMS;
}
/**
* Whether or not to assert equivalence of the {@link org.elasticsearch.xcontent.XContent} of the test instance and the instance
* parsed from the {@link org.elasticsearch.xcontent.XContent} of the test instance.
*
* @return true if equivalence should be asserted, otherwise false
*/
protected boolean assertToXContentEquivalence() {
return true;
}
/**
* @return a random date between 1970 and ca 2065
*/
protected Date randomDate() {
return new Date(randomLongBetween(0, 3000000000000L));
}
/**
* @return a random instant between 1970 and ca 2065
*/
protected Instant randomInstant() {
return Instant.ofEpochSecond(randomLongBetween(0, 3000000000L), randomLongBetween(0, 999999999));
}
}
| AbstractSerializationTestCase |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/spi/AttributeMarker.java | {
"start": 714,
"end": 823
} | interface ____ extends AttributeMarker {
boolean optional();
void optional(boolean value);
}
| Optionalable |
java | micronaut-projects__micronaut-core | http/src/test/java/io/micronaut/http/cookie/ClientCookieEncoderTest.java | {
"start": 137,
"end": 325
} | class ____ {
@Test
void clientCookieEncoderResolvedViaSpi() {
assertInstanceOf(DefaultClientCookieEncoder.class, ClientCookieEncoder.INSTANCE);
}
}
| ClientCookieEncoderTest |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java | {
"start": 7958,
"end": 9915
} | class ____ extends ServletInvocableHandlerMethod {
private final MethodParameter returnType;
public ConcurrentResultHandlerMethod(@Nullable Object result, ConcurrentResultMethodParameter returnType) {
super((Callable<Object>) () -> {
if (result instanceof Exception exception) {
throw exception;
}
else if (result instanceof Throwable throwable) {
throw new ServletException("Async processing failed: " + result, throwable);
}
return result;
}, CALLABLE_METHOD);
if (ServletInvocableHandlerMethod.this.returnValueHandlers != null) {
setHandlerMethodReturnValueHandlers(ServletInvocableHandlerMethod.this.returnValueHandlers);
}
this.returnType = returnType;
}
/**
* Bridge to actual controller type-level annotations.
*/
@Override
public Class<?> getBeanType() {
return ServletInvocableHandlerMethod.this.getBeanType();
}
/**
* Bridge to actual return value or generic type within the declared
* async return type, for example, Foo instead of {@code DeferredResult<Foo>}.
*/
@Override
public MethodParameter getReturnValueType(@Nullable Object returnValue) {
return this.returnType;
}
/**
* Bridge to controller method-level annotations.
*/
@Override
public <A extends Annotation> @Nullable A getMethodAnnotation(Class<A> annotationType) {
return ServletInvocableHandlerMethod.this.getMethodAnnotation(annotationType);
}
/**
* Bridge to controller method-level annotations.
*/
@Override
public <A extends Annotation> boolean hasMethodAnnotation(Class<A> annotationType) {
return ServletInvocableHandlerMethod.this.hasMethodAnnotation(annotationType);
}
}
/**
* MethodParameter subclass based on the actual return value type or if
* that's null falling back on the generic type within the declared async
* return type, for example, Foo instead of {@code DeferredResult<Foo>}.
*/
private | ConcurrentResultHandlerMethod |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/RollbackReifier.java | {
"start": 1066,
"end": 2133
} | class ____ extends ProcessorReifier<RollbackDefinition> {
public RollbackReifier(Route route, ProcessorDefinition<?> definition) {
super(route, (RollbackDefinition) definition);
}
@Override
public Processor createProcessor() {
boolean isMarkRollbackOnly = parseBoolean(definition.getMarkRollbackOnly(), false);
boolean isMarkRollbackOnlyLast = parseBoolean(definition.getMarkRollbackOnlyLast(), false);
// validate that only either mark rollbacks is chosen and not both
if (isMarkRollbackOnly && isMarkRollbackOnlyLast) {
throw new IllegalArgumentException(
"Only either one of markRollbackOnly and markRollbackOnlyLast is possible to select as true");
}
RollbackProcessor answer = new RollbackProcessor(definition.getMessage());
answer.setDisabled(isDisabled(camelContext, definition));
answer.setMarkRollbackOnly(isMarkRollbackOnly);
answer.setMarkRollbackOnlyLast(isMarkRollbackOnlyLast);
return answer;
}
}
| RollbackReifier |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/includes/IncludeTest.java | {
"start": 1072,
"end": 2364
} | class ____ {
private static SqlSessionFactory sqlSessionFactory;
@BeforeAll
static void setUp() throws Exception {
// create a SqlSessionFactory
try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/includes/MapperConfig.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
// populate in-memory database
BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
"org/apache/ibatis/submitted/includes/CreateDB.sql");
}
@Test
void includes() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
final Integer result = sqlSession.selectOne("org.apache.ibatis.submitted.includes.mapper.selectWithProperty");
Assertions.assertEquals(Integer.valueOf(1), result);
}
}
@Test
void parametrizedIncludes() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
sqlSession.selectOne("org.apache.ibatis.submitted.includes.mapper.select");
}
}
@Test
void shouldNamespaceBeResolvedAfterIncluded() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Assertions.assertNotNull(sqlSession.selectList("org.apache.ibatis.submitted.includes.mapper.selectIds"));
}
}
}
| IncludeTest |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/main/java/io/quarkus/rest/client/reactive/deployment/ClientContextResolverHandler.java | {
"start": 8722,
"end": 8832
} | interface ____
return methodInfo.declaringClass().name().toString().contains("$Companion");
}
}
| method |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/ServerImpl.java | {
"start": 30427,
"end": 31298
} | class ____ extends ContextRunnable {
MessagesAvailable() {
super(context);
}
@Override
public void runInContext() {
try (TaskCloseable ignore =
PerfMark.traceTask("ServerCallListener(app).messagesAvailable")) {
PerfMark.attachTag(tag);
PerfMark.linkIn(link);
getListener().messagesAvailable(producer);
} catch (Throwable t) {
internalClose(t);
throw t;
}
}
}
callExecutor.execute(new MessagesAvailable());
}
}
@Override
public void halfClosed() {
try (TaskCloseable ignore = PerfMark.traceTask("ServerStreamListener.halfClosed")) {
PerfMark.attachTag(tag);
final Link link = PerfMark.linkOut();
final | MessagesAvailable |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java | {
"start": 4891,
"end": 19356
} | class ____ to use.
* @param loggerContext the {@link LoggerContext} to use.
*/
Log4J2LoggingSystem(ClassLoader classLoader, LoggerContext loggerContext) {
super(classLoader);
this.loggerContext = loggerContext;
}
@Override
protected String[] getStandardConfigLocations() {
// With Log4J2 we use the ConfigurationFactory
throw new IllegalStateException("Standard config locations cannot be used with Log4J2");
}
@Override
protected @Nullable String getSelfInitializationConfig() {
return getConfigLocation(getLoggerContext().getConfiguration());
}
@Override
protected @Nullable String getSpringInitializationConfig() {
ConfigurationFactory configurationFactory = ConfigurationFactory.getInstance();
try {
Configuration springConfiguration = configurationFactory.getConfiguration(getLoggerContext(), "-spring",
null, getClassLoader());
String configLocation = getConfigLocation(springConfiguration);
return (configLocation != null && configLocation.contains("-spring")) ? configLocation : null;
}
catch (ConfigurationException ex) {
statusLogger.warn("Could not load Spring-specific Log4j Core configuration", ex);
return null;
}
}
/**
* Return the configuration location. The result may be:
* <ul>
* <li>{@code null}: if DefaultConfiguration is used (no explicit config loaded)</li>
* <li>A file path: if provided explicitly by the user</li>
* <li>A URI: if loaded from the classpath default or a custom location</li>
* </ul>
* @param configuration the source configuration
* @return the config location or {@code null}
*/
private @Nullable String getConfigLocation(Configuration configuration) {
return configuration.getConfigurationSource().getLocation();
}
@Override
public void beforeInitialize() {
LoggerContext loggerContext = getLoggerContext();
if (isAlreadyInitialized(loggerContext)) {
return;
}
if (!configureJdkLoggingBridgeHandler()) {
super.beforeInitialize();
}
loggerContext.getConfiguration().addFilter(FILTER);
}
private boolean configureJdkLoggingBridgeHandler() {
try {
if (isJulUsingASingleConsoleHandlerAtMost() && !isLog4jLogManagerInstalled()
&& isLog4jBridgeHandlerAvailable()) {
removeDefaultRootHandler();
Log4jBridgeHandler.install(false, null, true);
return true;
}
}
catch (Throwable ex) {
// Ignore. No java.util.logging bridge is installed.
}
return false;
}
private boolean isJulUsingASingleConsoleHandlerAtMost() {
java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
Handler[] handlers = rootLogger.getHandlers();
return handlers.length == 0 || (handlers.length == 1 && handlers[0] instanceof ConsoleHandler);
}
private boolean isLog4jLogManagerInstalled() {
final String logManagerClassName = java.util.logging.LogManager.getLogManager().getClass().getName();
return LOG4J_LOG_MANAGER.equals(logManagerClassName);
}
private boolean isLog4jBridgeHandlerAvailable() {
return ClassUtils.isPresent(LOG4J_BRIDGE_HANDLER, getClassLoader());
}
private void removeLog4jBridgeHandler() {
removeDefaultRootHandler();
java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
for (final Handler handler : rootLogger.getHandlers()) {
if (handler instanceof Log4jBridgeHandler) {
handler.close();
rootLogger.removeHandler(handler);
}
}
}
private void removeDefaultRootHandler() {
try {
java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
Handler[] handlers = rootLogger.getHandlers();
if (handlers.length == 1 && handlers[0] instanceof ConsoleHandler) {
rootLogger.removeHandler(handlers[0]);
}
}
catch (Throwable ex) {
// Ignore and continue
}
}
@Override
public void initialize(LoggingInitializationContext initializationContext, @Nullable String configLocation,
@Nullable LogFile logFile) {
LoggerContext loggerContext = getLoggerContext();
if (isAlreadyInitialized(loggerContext)) {
return;
}
StatusConsoleListener listener = new StatusConsoleListener(Level.WARN);
StatusLogger.getLogger().registerListener(listener);
loggerContext.putObject(STATUS_LISTENER_KEY, listener);
Environment environment = initializationContext.getEnvironment();
if (environment != null) {
loggerContext.putObject(ENVIRONMENT_KEY, environment);
Log4J2LoggingSystem.propertySource.setEnvironment(environment);
PropertiesUtil.getProperties().addPropertySource(Log4J2LoggingSystem.propertySource);
}
loggerContext.getConfiguration().removeFilter(FILTER);
super.initialize(initializationContext, configLocation, logFile);
markAsInitialized(loggerContext);
}
@Override
protected void loadDefaults(LoggingInitializationContext initializationContext, @Nullable LogFile logFile) {
String location = getPackagedConfigFile((logFile != null) ? "log4j2-file.xml" : "log4j2.xml");
load(initializationContext, location, logFile);
}
@Override
protected void loadConfiguration(LoggingInitializationContext initializationContext, String location,
@Nullable LogFile logFile) {
load(initializationContext, location, logFile);
}
private void load(LoggingInitializationContext initializationContext, String location, @Nullable LogFile logFile) {
List<String> overrides = getOverrides(initializationContext);
Environment environment = initializationContext.getEnvironment();
Assert.state(environment != null, "'environment' must not be null");
applySystemProperties(environment, logFile);
reconfigure(location, overrides);
}
private List<String> getOverrides(LoggingInitializationContext initializationContext) {
Environment environment = initializationContext.getEnvironment();
Assert.state(environment != null, "'environment' must not be null");
BindResult<List<String>> overrides = Binder.get(environment)
.bind("logging.log4j2.config.override", Bindable.listOf(String.class));
return overrides.orElse(Collections.emptyList());
}
private void reconfigure(String location, List<String> overrides) {
Assert.notNull(location, "'location' must not be null");
try {
List<Configuration> configurations = new ArrayList<>();
ResourceLoader resourceLoader = ApplicationResourceLoader.get(getClassLoader());
configurations.add(load(resourceLoader, location));
for (String override : overrides) {
Configuration overrideConfiguration = loadOverride(resourceLoader, override);
if (overrideConfiguration != null) {
configurations.add(overrideConfiguration);
}
}
this.loggerContext.reconfigure(mergeConfigurations(configurations));
}
catch (Exception ex) {
throw new IllegalStateException("Could not initialize Log4J2 logging from %s%s".formatted(location,
(overrides.isEmpty() ? "" : " with overrides " + overrides)), ex);
}
}
private Configuration load(ResourceLoader resourceLoader, String location) throws IOException {
ConfigurationFactory configurationFactory = ConfigurationFactory.getInstance();
Resource resource = resourceLoader.getResource(location);
Configuration configuration = configurationFactory.getConfiguration(getLoggerContext(), null, resource.getURI(),
getClassLoader());
// The error handling in Log4j Core 2.25.x is not consistent, some loading and
// parsing errors result in a null configuration, others in an exception.
if (configuration == null) {
throw new ConfigurationException("Could not load Log4j Core configuration from " + location);
}
return configuration;
}
private @Nullable Configuration loadOverride(ResourceLoader resourceLoader, String location) throws IOException {
if (location.startsWith(OPTIONAL_PREFIX)) {
String actualLocation = location.substring(OPTIONAL_PREFIX.length());
Resource resource = resourceLoader.getResource(actualLocation);
try {
return (resource.exists()) ? load(resourceLoader, actualLocation) : null;
}
catch (FileNotFoundException ex) {
return null;
}
}
return load(resourceLoader, location);
}
private Configuration mergeConfigurations(List<Configuration> configurations) {
if (configurations.size() == 1) {
return configurations.iterator().next();
}
return new CompositeConfiguration(configurations.stream().map(AbstractConfiguration.class::cast).toList());
}
@Override
protected void reinitialize(LoggingInitializationContext initializationContext) {
String currentLocation = getSelfInitializationConfig();
Assert.notNull(currentLocation, "'currentLocation' must not be null");
load(initializationContext, currentLocation, null);
}
@Override
public Set<LogLevel> getSupportedLogLevels() {
return LEVELS.getSupported();
}
@Override
public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel logLevel) {
setLogLevel(loggerName, LEVELS.convertSystemToNative(logLevel));
}
private void setLogLevel(@Nullable String loggerName, @Nullable Level level) {
LoggerConfig logger = getLogger(loggerName);
if (level == null) {
clearLogLevel(loggerName, logger);
}
else {
setLogLevel(loggerName, logger, level);
}
getLoggerContext().updateLoggers();
}
private void clearLogLevel(@Nullable String loggerName, @Nullable LoggerConfig logger) {
if (logger == null) {
return;
}
if (logger instanceof LevelSetLoggerConfig) {
getLoggerContext().getConfiguration().removeLogger(loggerName);
}
else {
logger.setLevel(null);
}
}
private void setLogLevel(@Nullable String loggerName, @Nullable LoggerConfig logger, Level level) {
if (logger == null) {
getLoggerContext().getConfiguration()
.addLogger(loggerName, new LevelSetLoggerConfig(loggerName, level, true));
}
else {
logger.setLevel(level);
}
}
@Override
public List<LoggerConfiguration> getLoggerConfigurations() {
List<LoggerConfiguration> result = new ArrayList<>();
getAllLoggers().forEach((name, loggerConfig) -> result.add(convertLoggerConfig(name, loggerConfig)));
result.sort(CONFIGURATION_COMPARATOR);
return result;
}
@Override
public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) {
LoggerConfig loggerConfig = getAllLoggers().get(loggerName);
return (loggerConfig != null) ? convertLoggerConfig(loggerName, loggerConfig) : null;
}
private Map<String, LoggerConfig> getAllLoggers() {
Map<String, LoggerConfig> loggers = new LinkedHashMap<>();
for (Logger logger : getLoggerContext().getLoggers()) {
addLogger(loggers, logger.getName());
}
getLoggerContext().getConfiguration().getLoggers().keySet().forEach((name) -> addLogger(loggers, name));
return loggers;
}
private void addLogger(Map<String, LoggerConfig> loggers, String name) {
Configuration configuration = getLoggerContext().getConfiguration();
while (name != null) {
loggers.computeIfAbsent(name, configuration::getLoggerConfig);
name = getSubName(name);
}
}
private @Nullable String getSubName(String name) {
if (!StringUtils.hasLength(name)) {
return null;
}
int nested = name.lastIndexOf('$');
return (nested != -1) ? name.substring(0, nested) : NameUtil.getSubName(name);
}
private @Nullable LoggerConfiguration convertLoggerConfig(String name, @Nullable LoggerConfig loggerConfig) {
if (loggerConfig == null) {
return null;
}
LevelConfiguration effectiveLevelConfiguration = getLevelConfiguration(loggerConfig.getLevel());
if (!StringUtils.hasLength(name) || LogManager.ROOT_LOGGER_NAME.equals(name)) {
name = ROOT_LOGGER_NAME;
}
boolean isAssigned = loggerConfig.getName().equals(name);
LevelConfiguration assignedLevelConfiguration = (!isAssigned) ? null : effectiveLevelConfiguration;
return new LoggerConfiguration(name, assignedLevelConfiguration, effectiveLevelConfiguration);
}
private LevelConfiguration getLevelConfiguration(Level level) {
LogLevel logLevel = LEVELS.convertNativeToSystem(level);
return (logLevel != null) ? LevelConfiguration.of(logLevel) : LevelConfiguration.ofCustom(level.name());
}
@Override
public Runnable getShutdownHandler() {
return () -> getLoggerContext().stop();
}
@Override
public void cleanUp() {
if (isLog4jBridgeHandlerAvailable()) {
removeLog4jBridgeHandler();
}
super.cleanUp();
LoggerContext loggerContext = getLoggerContext();
markAsUninitialized(loggerContext);
StatusConsoleListener listener = (StatusConsoleListener) loggerContext.getObject(STATUS_LISTENER_KEY);
if (listener != null) {
StatusLogger.getLogger().removeListener(listener);
loggerContext.removeObject(STATUS_LISTENER_KEY);
}
loggerContext.getConfiguration().removeFilter(FILTER);
Log4J2LoggingSystem.propertySource.setEnvironment(null);
loggerContext.removeObject(ENVIRONMENT_KEY);
}
private @Nullable LoggerConfig getLogger(@Nullable String name) {
if (!StringUtils.hasLength(name) || ROOT_LOGGER_NAME.equals(name)) {
return findLogger(LogManager.ROOT_LOGGER_NAME);
}
return findLogger(name);
}
private @Nullable LoggerConfig findLogger(String name) {
Configuration configuration = getLoggerContext().getConfiguration();
if (configuration instanceof AbstractConfiguration abstractConfiguration) {
return abstractConfiguration.getLogger(name);
}
return configuration.getLoggers().get(name);
}
LoggerContext getLoggerContext() {
return this.loggerContext;
}
private boolean isAlreadyInitialized(LoggerContext loggerContext) {
return LoggingSystem.class.getName().equals(loggerContext.getExternalContext());
}
private void markAsInitialized(LoggerContext loggerContext) {
loggerContext.setExternalContext(LoggingSystem.class.getName());
}
private void markAsUninitialized(LoggerContext loggerContext) {
loggerContext.setExternalContext(null);
}
@Override
protected String getDefaultLogCorrelationPattern() {
return "%correlationId";
}
/**
* Get the Spring {@link Environment} attached to the given {@link LoggerContext} or
* {@code null} if no environment is available.
* @param loggerContext the logger context
* @return the Spring {@link Environment} or {@code null}
* @since 3.0.0
*/
public static @Nullable Environment getEnvironment(@Nullable LoggerContext loggerContext) {
return (Environment) ((loggerContext != null) ? loggerContext.getObject(ENVIRONMENT_KEY) : null);
}
/**
* {@link LoggingSystemFactory} that returns {@link Log4J2LoggingSystem} if possible.
*/
@Order(0)
public static | loader |
java | quarkusio__quarkus | integration-tests/hibernate-orm-panache/src/main/java/io/quarkus/it/panache/defaultpu/Bug7721EntitySuperClass.java | {
"start": 231,
"end": 582
} | class ____ extends PanacheEntity {
@Column(nullable = false)
public String superField = "default";
public void setSuperField(String superField) {
Objects.requireNonNull(superField);
// should never be null
Objects.requireNonNull(this.superField);
this.superField = superField;
}
}
| Bug7721EntitySuperClass |
java | resilience4j__resilience4j | resilience4j-vavr/src/main/java/io/github/resilience4j/bulkhead/VavrBulkhead.java | {
"start": 893,
"end": 6691
} | interface ____ {
/**
* Returns a supplier which is decorated by a bulkhead.
*
* @param bulkhead the Bulkhead
* @param supplier the original supplier
* @param <T> the type of results supplied by this supplier
* @return a supplier which is decorated by a Bulkhead.
*/
static <T> CheckedFunction0<T> decorateCheckedSupplier(Bulkhead bulkhead,
CheckedFunction0<T> supplier) {
return () -> {
bulkhead.acquirePermission();
try {
return supplier.apply();
} finally {
bulkhead.onComplete();
}
};
}
/**
* Returns a runnable which is decorated by a bulkhead.
*
* @param bulkhead the bulkhead
* @param runnable the original runnable
* @return a runnable which is decorated by a Bulkhead.
*/
static CheckedRunnable decorateCheckedRunnable(Bulkhead bulkhead, CheckedRunnable runnable) {
return () -> {
bulkhead.acquirePermission();
try {
runnable.run();
} finally {
bulkhead.onComplete();
}
};
}
/**
* Returns a supplier which is decorated by a bulkhead.
*
* @param bulkhead the bulkhead
* @param supplier the original supplier
* @param <T> the type of results supplied by this supplier
* @return a supplier which is decorated by a Bulkhead.
*/
static <T> Supplier<Try<T>> decorateTrySupplier(Bulkhead bulkhead, Supplier<Try<T>> supplier) {
return () -> {
if (bulkhead.tryAcquirePermission()) {
try {
return supplier.get();
} finally {
bulkhead.onComplete();
}
} else {
return Try.failure(BulkheadFullException.createBulkheadFullException(bulkhead));
}
};
}
/**
* Returns a supplier which is decorated by a bulkhead.
*
* @param bulkhead the bulkhead
* @param supplier the original supplier
* @param <T> the type of results supplied by this supplier
* @return a supplier which is decorated by a Bulkhead.
*/
static <T> Supplier<Either<Exception, T>> decorateEitherSupplier(Bulkhead bulkhead,
Supplier<Either<? extends Exception, T>> supplier) {
return () -> {
if (bulkhead.tryAcquirePermission()) {
try {
Either<? extends Exception, T> result = supplier.get();
return Either.narrow(result);
} finally {
bulkhead.onComplete();
}
} else {
return Either.left(BulkheadFullException.createBulkheadFullException(bulkhead));
}
};
}
/**
* Returns a consumer which is decorated by a bulkhead.
*
* @param bulkhead the bulkhead
* @param consumer the original consumer
* @param <T> the type of the input to the consumer
* @return a consumer which is decorated by a Bulkhead.
*/
static <T> CheckedConsumer<T> decorateCheckedConsumer(Bulkhead bulkhead,
CheckedConsumer<T> consumer) {
return t -> {
bulkhead.acquirePermission();
try {
consumer.accept(t);
} finally {
bulkhead.onComplete();
}
};
}
/**
* Returns a function which is decorated by a bulkhead.
*
* @param bulkhead the bulkhead
* @param function the original function
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
* @return a function which is decorated by a bulkhead.
*/
static <T, R> CheckedFunction1<T, R> decorateCheckedFunction(Bulkhead bulkhead,
CheckedFunction1<T, R> function) {
return (T t) -> {
bulkhead.acquirePermission();
try {
return function.apply(t);
} finally {
bulkhead.onComplete();
}
};
}
/**
* Decorates and executes the decorated Supplier.
*
* @param supplier the original Supplier
* @param <T> the type of results supplied by this supplier
* @return the result of the decorated Supplier.
*/
static <T> Try<T> executeTrySupplier(Bulkhead bulkhead, Supplier<Try<T>> supplier) {
return decorateTrySupplier(bulkhead, supplier).get();
}
/**
* Decorates and executes the decorated Supplier.
*
* @param supplier the original Supplier
* @param <T> the type of results supplied by this supplier
* @return the result of the decorated Supplier.
*/
static <T> Either<Exception, T> executeEitherSupplier(Bulkhead bulkhead,
Supplier<Either<? extends Exception, T>> supplier) {
return decorateEitherSupplier(bulkhead, supplier).get();
}
/**
* Decorates and executes the decorated Supplier.
*
* @param checkedSupplier the original Supplier
* @param <T> the type of results supplied by this supplier
* @return the result of the decorated Supplier.
* @throws Throwable if something goes wrong applying this function to the given arguments
*/
static <T> T executeCheckedSupplier(Bulkhead bulkhead, CheckedFunction0<T> checkedSupplier) throws Throwable {
return decorateCheckedSupplier(bulkhead, checkedSupplier).apply();
}
}
| VavrBulkhead |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/reflection/BusTripPk.java | {
"start": 194,
"end": 540
} | class ____ {
private String busNumber;
private String busDriver;
public String getBusDriver() {
return busDriver;
}
public void setBusDriver(String busDriver) {
this.busDriver = busDriver;
}
public String getBusNumber() {
return busNumber;
}
public void setBusNumber(String busNumber) {
this.busNumber = busNumber;
}
}
| BusTripPk |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManager.java | {
"start": 7963,
"end": 8788
} | class ____ {
private final LoggerContext loggerContext;
private final String topic;
private final boolean syncSend;
private final boolean sendTimestamp;
private final Property[] properties;
private final String key;
public FactoryData(
final LoggerContext loggerContext,
final String topic,
final boolean syncSend,
final boolean sendTimestamp,
final Property[] properties,
final String key) {
this.loggerContext = loggerContext;
this.topic = topic;
this.syncSend = syncSend;
this.sendTimestamp = sendTimestamp;
this.properties = properties;
this.key = key;
}
}
private static | FactoryData |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/introspect/AnnotatedMethodCollector.java | {
"start": 4330,
"end": 4523
} | class ____
if (mixInCls != null) {
_addMethodMixIns(tc, cls, methods, mixInCls);
}
if (cls == null) { // just so caller need not check when passing super- | methods |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/FilterJoinTableAnnotation.java | {
"start": 937,
"end": 3593
} | class ____ implements FilterJoinTable, FilterDetails {
private String name;
private String condition;
private boolean deduceAliasInjectionPoints;
private org.hibernate.annotations.SqlFragmentAlias[] aliases;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public FilterJoinTableAnnotation(ModelsContext modelContext) {
this.condition = "";
this.deduceAliasInjectionPoints = true;
this.aliases = new org.hibernate.annotations.SqlFragmentAlias[0];
}
/**
* Used in creating annotation instances from JDK variant
*/
public FilterJoinTableAnnotation(FilterJoinTable annotation, ModelsContext modelContext) {
this.name = annotation.name();
this.condition = annotation.condition();
this.deduceAliasInjectionPoints = annotation.deduceAliasInjectionPoints();
this.aliases = extractJdkValue( annotation, FILTER_JOIN_TABLE, "aliases", modelContext );
}
/**
* Used in creating annotation instances from Jandex variant
*/
public FilterJoinTableAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) {
this.name = (String) attributeValues.get( "name" );
this.condition = (String) attributeValues.get( "condition" );
this.deduceAliasInjectionPoints = (boolean) attributeValues.get( "deduceAliasInjectionPoints" );
this.aliases = (org.hibernate.annotations.SqlFragmentAlias[]) attributeValues.get( "aliases" );
}
@Override
public Class<? extends Annotation> annotationType() {
return FilterJoinTable.class;
}
@Override
public String name() {
return name;
}
public void name(String value) {
this.name = value;
}
@Override
public String condition() {
return condition;
}
public void condition(String value) {
this.condition = value;
}
@Override
public boolean deduceAliasInjectionPoints() {
return deduceAliasInjectionPoints;
}
public void deduceAliasInjectionPoints(boolean value) {
this.deduceAliasInjectionPoints = value;
}
@Override
public org.hibernate.annotations.SqlFragmentAlias[] aliases() {
return aliases;
}
public void aliases(org.hibernate.annotations.SqlFragmentAlias[] value) {
this.aliases = value;
}
@Override
public void apply(JaxbFilterImpl jaxbFilter, XmlDocumentContext xmlDocumentContext) {
name( jaxbFilter.getName() );
if ( StringHelper.isNotEmpty( jaxbFilter.getCondition() ) ) {
condition( jaxbFilter.getCondition() );
}
if ( jaxbFilter.isAutoAliasInjection() != null ) {
deduceAliasInjectionPoints( jaxbFilter.isAutoAliasInjection() );
}
aliases( FilterProcessing.collectSqlFragmentAliases(
jaxbFilter.getAliases(),
xmlDocumentContext
) );
}
}
| FilterJoinTableAnnotation |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaCreationToOutputScriptTest.java | {
"start": 1478,
"end": 5307
} | class ____ {
private final String createTableMyEntity = "create table MyEntity";
private final String createTableMySecondEntity = "create table MySecondEntity";
private File output;
private ServiceRegistry serviceRegistry;
private MetadataImplementor metadata;
@BeforeEach
public void setUp() throws Exception {
output = File.createTempFile( "creation_script", ".sql" );
output.deleteOnExit();
List<String> content = Arrays.asList(
"This is the database creation script generated by Hibernate"
, "This is the second line"
, "This is the third line"
, "This is the fourth line"
, "This is the fifth line"
, "This is the sixth line"
, "This is the seventh line"
, "This is the eighth line"
, "This is the ninth line"
);
try (BufferedWriter bw = new BufferedWriter( new FileWriter( output ) )) {
for ( String s : content ) {
bw.write( s );
bw.write( System.lineSeparator() );
}
}
}
private void createServiceRegistryAndMetadata(String append) {
final StandardServiceRegistryBuilder standardServiceRegistryBuilder = ServiceRegistryUtil.serviceRegistryBuilder()
.applySetting( Environment.FORMAT_SQL, "false" )
.applySetting( Environment.JAKARTA_HBM2DDL_SCRIPTS_ACTION, "create" )
.applySetting( AvailableSettings.JAKARTA_HBM2DDL_SCRIPTS_CREATE_TARGET, output.getAbsolutePath() );
if ( append != null ) {
standardServiceRegistryBuilder.applySetting( AvailableSettings.HBM2DDL_SCRIPTS_CREATE_APPEND, append );
}
serviceRegistry = standardServiceRegistryBuilder.build();
metadata = (MetadataImplementor) new MetadataSources( serviceRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClass( MySecondEntity.class )
.buildMetadata();
metadata.orderColumns( false );
metadata.validate();
}
@AfterEach
public void tearDown() {
ServiceRegistryBuilder.destroy( serviceRegistry );
}
@Test
public void testAppendModeFalse() throws Exception {
createServiceRegistryAndMetadata( "false" );
HashMap properties = new HashMap<>();
properties.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );
SchemaManagementToolCoordinator.process(
metadata,
serviceRegistry,
properties,
null
);
List<String> commands = Files.readAllLines( output.toPath() );
assertThat( commands.size(), is( 2 ) );
assertThat( commands.get( 0 ), containsString( createTableMyEntity ) );
assertThat( commands.get( 1 ), containsString( createTableMySecondEntity ) );
}
@Test
public void testAppendModeTrue() throws Exception {
createServiceRegistryAndMetadata( "true" );
HashMap properties = new HashMap<>();
properties.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );
SchemaManagementToolCoordinator.process(
metadata,
serviceRegistry,
properties,
null
);
List<String> commands = Files.readAllLines( output.toPath() );
assertThat( commands.size(), is( 11 ) );
assertThat( commands.get( 9 ), containsString( createTableMyEntity ) );
assertThat( commands.get( 10 ), containsString( createTableMySecondEntity ) );
}
@Test
public void testDefaultAppendMode() throws Exception {
createServiceRegistryAndMetadata( null );
HashMap properties = new HashMap<>();
properties.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );
SchemaManagementToolCoordinator.process(
metadata,
serviceRegistry,
properties,
null
);
List<String> commands = Files.readAllLines( output.toPath() );
assertThat( commands.size(), is( 11 ) );
assertThat( commands.get( 9 ), containsString( createTableMyEntity ) );
assertThat( commands.get( 10 ), containsString( createTableMySecondEntity ) );
}
@Entity(name = "MyEntity")
public static | SchemaCreationToOutputScriptTest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/impl/MembershipStoreImpl.java | {
"start": 11690,
"end": 11966
} | class ____
} else if (records.size() > 0) {
TreeSet<MembershipState> sortedList = new TreeSet<>(records);
LOG.debug("Quorum failed, using most recent: {}", sortedList.first());
return sortedList.first();
} else {
return null;
}
}
}
| comparator |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/EmbeddableWithGenericAndMappedSuperClassTest.java | {
"start": 6400,
"end": 6614
} | class ____<T> {
private T minimum;
private T maximum;
public Range() {
}
public Range(T minimum, T maximum) {
this.minimum = minimum;
this.maximum = maximum;
}
}
@Embeddable
public static | Range |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.