language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | google__guava | android/guava-tests/test/com/google/common/base/FinalizableReferenceQueueClassLoaderUnloadingTest.java | {
"start": 6987,
"end": 7710
} | class ____ specified by the {@code java.class.path} {@linkplain
* System#getProperty system property}.
*/
// TODO(b/65488446): Make this a public API.
private static ImmutableList<URL> parseJavaClassPath() {
ImmutableList.Builder<URL> urls = ImmutableList.builder();
for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) {
try {
try {
urls.add(new File(entry).toURI().toURL());
} catch (SecurityException e) { // File.toURI checks to see if the file is a directory
urls.add(new URL("file", null, new File(entry).getAbsolutePath()));
}
} catch (MalformedURLException e) {
throw new AssertionError("malformed | path |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/io/ParsingDecoder.java | {
"start": 1187,
"end": 2421
} | class ____ extends Decoder implements ActionHandler, SkipHandler {
protected final SkipParser parser;
protected ParsingDecoder(Symbol root) throws IOException {
this.parser = new SkipParser(root, this, this);
}
protected abstract void skipFixed() throws IOException;
@Override
public void skipAction() throws IOException {
parser.popSymbol();
}
@Override
public void skipTopSymbol() throws IOException {
Symbol top = parser.topSymbol();
if (top == Symbol.NULL) {
readNull();
} else if (top == Symbol.BOOLEAN) {
readBoolean();
} else if (top == Symbol.INT) {
readInt();
} else if (top == Symbol.LONG) {
readLong();
} else if (top == Symbol.FLOAT) {
readFloat();
} else if (top == Symbol.DOUBLE) {
readDouble();
} else if (top == Symbol.STRING) {
skipString();
} else if (top == Symbol.BYTES) {
skipBytes();
} else if (top == Symbol.ENUM) {
readEnum();
} else if (top == Symbol.FIXED) {
skipFixed();
} else if (top == Symbol.UNION) {
readIndex();
} else if (top == Symbol.ARRAY_START) {
skipArray();
} else if (top == Symbol.MAP_START) {
skipMap();
}
}
}
| ParsingDecoder |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/co/AsyncKeyedCoProcessOperator.java | {
"start": 7678,
"end": 9649
} | class ____<K, IN1, IN2, OUT>
extends KeyedCoProcessFunction<K, IN1, IN2, OUT>.OnTimerContext {
private final TimerService timerService;
private final DeclaredVariable<String> timeDomain;
private final DeclaredVariable<Long> timestamp;
OnTimerContextImpl(
KeyedCoProcessFunction<K, IN1, IN2, OUT> function,
TimerService timerService,
DeclarationContext declarationContext) {
function.super();
this.timerService = checkNotNull(timerService);
this.timeDomain =
declarationContext.declareVariable(
StringSerializer.INSTANCE, "_OnTimerContextImpl$timeDomain", null);
this.timestamp =
declarationContext.declareVariable(
LongSerializer.INSTANCE, "_OnTimerContextImpl$timestamp", null);
}
public void setTime(long time, TimeDomain one) {
timestamp.set(time);
timeDomain.set(one.name());
}
@Override
public Long timestamp() {
checkState(timestamp.get() != null);
return timestamp.get();
}
@Override
public TimerService timerService() {
return timerService;
}
@Override
public <X> void output(OutputTag<X> outputTag, X value) {
if (outputTag == null) {
throw new IllegalArgumentException("OutputTag must not be null.");
}
output.collect(outputTag, new StreamRecord<>(value, timestamp()));
}
@Override
public TimeDomain timeDomain() {
checkState(timeDomain.get() != null);
return TimeDomain.valueOf(timeDomain.get());
}
@Override
public K getCurrentKey() {
return (K) AsyncKeyedCoProcessOperator.this.getCurrentKey();
}
}
}
| OnTimerContextImpl |
java | google__dagger | javatests/dagger/internal/codegen/AssistedFactoryErrorsTest.java | {
"start": 2331,
"end": 2493
} | class ____ {",
" @AssistedInject",
" Foo(@Assisted int i) {}",
"",
" @AssistedFactory",
" abstract | Foo |
java | quarkusio__quarkus | extensions/quartz/deployment/src/test/java/io/quarkus/quartz/test/programmatic/InterruptableJobTest.java | {
"start": 4290,
"end": 4750
} | class ____ implements Job {
@Override
public void execute(JobExecutionContext context) {
NON_INTERRUPTABLE_EXECUTE_LATCH.countDown();
try {
// halt execution so that we can interrupt it
NON_INTERRUPTABLE_HOLD_LATCH.await(4, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
| MyNonInterruptableJob |
java | micronaut-projects__micronaut-core | http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/ParameterTest.java | {
"start": 1328,
"end": 2015
} | class ____ {
public static final String SPEC_NAME = "ParameterTest";
@Test
void testGetAllMethod() throws IOException {
asserts(SPEC_NAME,
HttpRequest.GET(UriBuilder.of("/parameters-test").path("all")
.queryParam("test", "one", "two", "three+four")
.build()),
(server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.body("[\"one\",\"two\",\"three+four\"]")
.build()));
}
@Controller("/parameters-test")
@Requires(property = "spec.name", value = SPEC_NAME)
static | ParameterTest |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/inject/qualifiers/Qualified.java | {
"start": 898,
"end": 1137
} | interface ____<T> {
/**
* Override the bean qualifier.
*
* @param qualifier The bean qualifier to use
*/
@Internal
@SuppressWarnings("MethodName")
void $withBeanQualifier(Qualifier<T> qualifier);
}
| Qualified |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestFileSystemCaching.java | {
"start": 2348,
"end": 2686
} | class ____ extends HadoopTestBase {
@Test
public void testCacheEnabled() throws Exception {
Configuration conf = newConf();
FileSystem fs1 = FileSystem.get(new URI("cachedfile://a"), conf);
FileSystem fs2 = FileSystem.get(new URI("cachedfile://a"), conf);
assertSame(fs1, fs2);
}
private static | TestFileSystemCaching |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/transformer/TransformerRouteTest.java | {
"start": 14793,
"end": 15091
} | class ____ extends Transformer {
@Override
public void transform(Message message, DataType from, DataType to) {
LOG.info("Bean: XOrderResponse -> Other");
message.setBody("name=XOrderResponse");
}
}
public static | XOrderResponseToOtherTransformer |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/info/SslInfoTests.java | {
"start": 1636,
"end": 10186
} | class ____ {
private static final Clock CLOCK = Clock.fixed(Instant.parse("2025-06-18T13:00:00Z"), ZoneId.of("UTC"));
@Test
@WithPackageResources("test.p12")
void validCertificatesShouldProvideSslInfo() {
SslInfo sslInfo = createSslInfo("classpath:test.p12");
assertThat(sslInfo.getBundles()).hasSize(1);
BundleInfo bundle = sslInfo.getBundles().get(0);
assertThat(bundle.getName()).isEqualTo("test-0");
assertThat(bundle.getCertificateChains()).hasSize(4);
assertThat(bundle.getCertificateChains().get(0).getAlias()).isEqualTo("spring-boot");
assertThat(bundle.getCertificateChains().get(0).getCertificates()).hasSize(1);
assertThat(bundle.getCertificateChains().get(1).getAlias()).isEqualTo("test-alias");
assertThat(bundle.getCertificateChains().get(1).getCertificates()).hasSize(1);
assertThat(bundle.getCertificateChains().get(2).getAlias()).isEqualTo("spring-boot-cert");
assertThat(bundle.getCertificateChains().get(2).getCertificates()).isEmpty();
assertThat(bundle.getCertificateChains().get(3).getAlias()).isEqualTo("test-alias-cert");
assertThat(bundle.getCertificateChains().get(3).getCertificates()).isEmpty();
CertificateInfo cert1 = bundle.getCertificateChains().get(0).getCertificates().get(0);
assertThat(cert1.getSubject()).isEqualTo("CN=localhost,OU=Spring,O=VMware,L=Palo Alto,ST=California,C=US");
assertThat(cert1.getIssuer()).isEqualTo(cert1.getSubject());
assertThat(cert1.getSerialNumber()).isNotEmpty();
assertThat(cert1.getVersion()).isEqualTo("V3");
assertThat(cert1.getSignatureAlgorithmName()).isEqualTo("SHA256withRSA");
assertThat(cert1.getValidityStarts()).isBefore(CLOCK.instant());
assertThat(cert1.getValidityEnds()).isAfter(CLOCK.instant());
assertThat(cert1.getValidity()).isNotNull();
assertThat(cert1.getValidity().getStatus()).isSameAs(Status.VALID);
assertThat(cert1.getValidity().getMessage()).isNull();
CertificateInfo cert2 = bundle.getCertificateChains().get(1).getCertificates().get(0);
assertThat(cert2.getSubject()).isEqualTo("CN=localhost,OU=Spring,O=VMware,L=Palo Alto,ST=California,C=US");
assertThat(cert2.getIssuer()).isEqualTo(cert2.getSubject());
assertThat(cert2.getSerialNumber()).isNotEmpty();
assertThat(cert2.getVersion()).isEqualTo("V3");
assertThat(cert2.getSignatureAlgorithmName()).isEqualTo("SHA256withRSA");
assertThat(cert2.getValidityStarts()).isBefore(CLOCK.instant());
assertThat(cert2.getValidityEnds()).isAfter(CLOCK.instant());
assertThat(cert2.getValidity()).isNotNull();
assertThat(cert2.getValidity().getStatus()).isSameAs(Status.VALID);
assertThat(cert2.getValidity().getMessage()).isNull();
}
@Test
@WithPackageResources("test-not-yet-valid.p12")
void notYetValidCertificateShouldProvideSslInfo() {
SslInfo sslInfo = createSslInfo("classpath:test-not-yet-valid.p12");
assertThat(sslInfo.getBundles()).hasSize(1);
BundleInfo bundle = sslInfo.getBundles().get(0);
assertThat(bundle.getName()).isEqualTo("test-0");
assertThat(bundle.getCertificateChains()).hasSize(1);
CertificateChainInfo certificateChain = bundle.getCertificateChains().get(0);
assertThat(certificateChain.getAlias()).isEqualTo("spring-boot");
List<CertificateInfo> certs = certificateChain.getCertificates();
assertThat(certs).hasSize(1);
CertificateInfo cert = certs.get(0);
assertThat(cert.getSubject()).isEqualTo("CN=localhost,OU=Spring,O=VMware,L=Palo Alto,ST=California,C=US");
assertThat(cert.getIssuer()).isEqualTo(cert.getSubject());
assertThat(cert.getSerialNumber()).isNotEmpty();
assertThat(cert.getVersion()).isEqualTo("V3");
assertThat(cert.getSignatureAlgorithmName()).isEqualTo("SHA256withRSA");
assertThat(cert.getValidityStarts()).isAfter(CLOCK.instant());
assertThat(cert.getValidityEnds()).isAfter(CLOCK.instant());
assertThat(cert.getValidity()).isNotNull();
assertThat(cert.getValidity().getStatus()).isSameAs(Status.NOT_YET_VALID);
assertThat(cert.getValidity().getMessage()).startsWith("Not valid before");
}
@Test
@WithPackageResources("test-expired.p12")
void expiredCertificateShouldProvideSslInfo() {
SslInfo sslInfo = createSslInfo("classpath:test-expired.p12");
assertThat(sslInfo.getBundles()).hasSize(1);
BundleInfo bundle = sslInfo.getBundles().get(0);
assertThat(bundle.getName()).isEqualTo("test-0");
assertThat(bundle.getCertificateChains()).hasSize(1);
CertificateChainInfo certificateChain = bundle.getCertificateChains().get(0);
assertThat(certificateChain.getAlias()).isEqualTo("spring-boot");
List<CertificateInfo> certs = certificateChain.getCertificates();
assertThat(certs).hasSize(1);
CertificateInfo cert = certs.get(0);
assertThat(cert.getSubject()).isEqualTo("CN=localhost,OU=Spring,O=VMware,L=Palo Alto,ST=California,C=US");
assertThat(cert.getIssuer()).isEqualTo(cert.getSubject());
assertThat(cert.getSerialNumber()).isNotEmpty();
assertThat(cert.getVersion()).isEqualTo("V3");
assertThat(cert.getSignatureAlgorithmName()).isEqualTo("SHA256withRSA");
assertThat(cert.getValidityStarts()).isBefore(CLOCK.instant());
assertThat(cert.getValidityEnds()).isBefore(CLOCK.instant());
assertThat(cert.getValidity()).isNotNull();
assertThat(cert.getValidity().getStatus()).isSameAs(Status.EXPIRED);
assertThat(cert.getValidity().getMessage()).startsWith("Not valid after");
}
@Test
@WithPackageResources({ "test.p12", "test-not-yet-valid.p12", "test-expired.p12", "will-expire-soon.p12" })
void multipleBundlesShouldProvideSslInfo() {
SslInfo sslInfo = createSslInfo("classpath:test.p12", "classpath:test-not-yet-valid.p12",
"classpath:test-expired.p12", "classpath:will-expire-soon.p12");
assertThat(sslInfo.getBundles()).hasSize(4);
assertThat(sslInfo.getBundles()).allSatisfy((bundle) -> assertThat(bundle.getName()).startsWith("test-"));
List<CertificateInfo> certs = sslInfo.getBundles()
.stream()
.flatMap((bundle) -> bundle.getCertificateChains().stream())
.flatMap((certificateChain) -> certificateChain.getCertificates().stream())
.toList();
assertThat(certs).hasSize(5);
assertThat(certs).allSatisfy((cert) -> {
assertThat(cert.getSubject()).isEqualTo("CN=localhost,OU=Spring,O=VMware,L=Palo Alto,ST=California,C=US");
assertThat(cert.getIssuer()).isEqualTo(cert.getSubject());
assertThat(cert.getSerialNumber()).isNotEmpty();
assertThat(cert.getVersion()).isEqualTo("V3");
assertThat(cert.getSignatureAlgorithmName()).isNotEmpty();
assertThat(cert.getValidity()).isNotNull();
});
assertThat(certs).anySatisfy((cert) -> {
assertThat(cert.getValidityStarts()).isBefore(CLOCK.instant());
assertThat(cert.getValidityEnds()).isAfter(CLOCK.instant());
assertThat(cert.getValidity()).isNotNull();
assertThat(cert.getValidity().getStatus()).isSameAs(Status.VALID);
assertThat(cert.getValidity().getMessage()).isNull();
});
assertThat(certs).satisfiesOnlyOnce((cert) -> {
assertThat(cert.getValidityStarts()).isAfter(CLOCK.instant());
assertThat(cert.getValidityEnds()).isAfter(CLOCK.instant());
assertThat(cert.getValidity()).isNotNull();
assertThat(cert.getValidity().getStatus()).isSameAs(Status.NOT_YET_VALID);
assertThat(cert.getValidity().getMessage()).startsWith("Not valid before");
});
assertThat(certs).satisfiesOnlyOnce((cert) -> {
assertThat(cert.getValidityStarts()).isBefore(CLOCK.instant());
assertThat(cert.getValidityEnds()).isBefore(CLOCK.instant());
assertThat(cert.getValidity()).isNotNull();
assertThat(cert.getValidity().getStatus()).isSameAs(Status.EXPIRED);
assertThat(cert.getValidity().getMessage()).startsWith("Not valid after");
});
}
@Test
void nullKeyStore() {
DefaultSslBundleRegistry sslBundleRegistry = new DefaultSslBundleRegistry();
sslBundleRegistry.registerBundle("test", SslBundle.of(SslStoreBundle.NONE, SslBundleKey.NONE));
SslInfo sslInfo = new SslInfo(sslBundleRegistry, CLOCK);
assertThat(sslInfo.getBundles()).hasSize(1);
assertThat(sslInfo.getBundles().get(0).getCertificateChains()).isEmpty();
}
private SslInfo createSslInfo(String... locations) {
DefaultSslBundleRegistry sslBundleRegistry = new DefaultSslBundleRegistry();
for (int i = 0; i < locations.length; i++) {
JksSslStoreDetails keyStoreDetails = JksSslStoreDetails.forLocation(locations[i]).withPassword("secret");
SslStoreBundle sslStoreBundle = new JksSslStoreBundle(keyStoreDetails, null);
sslBundleRegistry.registerBundle("test-%d".formatted(i), SslBundle.of(sslStoreBundle));
}
return new SslInfo(sslBundleRegistry, CLOCK);
}
}
| SslInfoTests |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/internal/ShadedProtobufHelper.java | {
"start": 5915,
"end": 5982
} | interface ____<T> {
T call() throws ServiceException;
}
}
| IpcCall |
java | alibaba__nacos | naming/src/main/java/com/alibaba/nacos/naming/model/form/InstanceListForm.java | {
"start": 1106,
"end": 3946
} | class ____ implements NacosForm {
private static final long serialVersionUID = -3760300561436525429L;
private String namespaceId;
private String groupName;
private String serviceName;
private String clusterName;
private Boolean healthyOnly;
/**
* check param.
*
* @throws NacosApiException NacosApiException
*/
public void validate() throws NacosApiException {
fillDefaultValue();
if (StringUtils.isBlank(serviceName)) {
throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.PARAMETER_MISSING,
"Required parameter 'serviceName' type String is not present");
}
}
/**
* fill default value.
*/
public void fillDefaultValue() {
if (StringUtils.isBlank(namespaceId)) {
namespaceId = Constants.DEFAULT_NAMESPACE_ID;
}
if (StringUtils.isBlank(groupName)) {
groupName = Constants.DEFAULT_GROUP;
}
if (StringUtils.isBlank(clusterName)) {
clusterName = UtilsAndCommons.DEFAULT_CLUSTER_NAME;
}
if (null == healthyOnly) {
healthyOnly = false;
}
}
public String getNamespaceId() {
return namespaceId;
}
public void setNamespaceId(String namespaceId) {
this.namespaceId = namespaceId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public Boolean getHealthyOnly() {
return healthyOnly;
}
public void setHealthyOnly(Boolean healthyOnly) {
this.healthyOnly = healthyOnly;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InstanceListForm that = (InstanceListForm) o;
return Objects.equals(namespaceId, that.namespaceId) && Objects.equals(groupName, that.groupName)
&& Objects.equals(serviceName, that.serviceName) && Objects.equals(clusterName, that.clusterName)
&& Objects.equals(healthyOnly, that.healthyOnly);
}
@Override
public int hashCode() {
return Objects.hash(namespaceId, groupName, serviceName, clusterName, healthyOnly);
}
}
| InstanceListForm |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/acl/common/SessionCredentials.java | {
"start": 1047,
"end": 5023
} | class ____ {
public static final Charset CHARSET = StandardCharsets.UTF_8;
public static final String ACCESS_KEY = "AccessKey";
public static final String SECRET_KEY = "SecretKey";
public static final String SIGNATURE = "Signature";
public static final String SECURITY_TOKEN = "SecurityToken";
public static final String KEY_FILE = System.getProperty("rocketmq.client.keyFile",
System.getProperty("user.home") + File.separator + "key");
private String accessKey;
private String secretKey;
private String securityToken;
private String signature;
public SessionCredentials() {
String keyContent = null;
try {
keyContent = MixAll.file2String(KEY_FILE);
} catch (IOException ignore) {
}
if (keyContent != null) {
Properties prop = MixAll.string2Properties(keyContent);
if (prop != null) {
this.updateContent(prop);
}
}
}
public SessionCredentials(String accessKey, String secretKey) {
this.accessKey = accessKey;
this.secretKey = secretKey;
}
public SessionCredentials(String accessKey, String secretKey, String securityToken) {
this(accessKey, secretKey);
this.securityToken = securityToken;
}
public void updateContent(Properties prop) {
{
String value = prop.getProperty(ACCESS_KEY);
if (value != null) {
this.accessKey = value.trim();
}
}
{
String value = prop.getProperty(SECRET_KEY);
if (value != null) {
this.secretKey = value.trim();
}
}
{
String value = prop.getProperty(SECURITY_TOKEN);
if (value != null) {
this.securityToken = value.trim();
}
}
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getSecurityToken() {
return securityToken;
}
public void setSecurityToken(final String securityToken) {
this.securityToken = securityToken;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accessKey == null) ? 0 : accessKey.hashCode());
result = prime * result + ((secretKey == null) ? 0 : secretKey.hashCode());
result = prime * result + ((signature == null) ? 0 : signature.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SessionCredentials other = (SessionCredentials) obj;
if (accessKey == null) {
if (other.accessKey != null)
return false;
} else if (!accessKey.equals(other.accessKey))
return false;
if (secretKey == null) {
if (other.secretKey != null)
return false;
} else if (!secretKey.equals(other.secretKey))
return false;
if (signature == null) {
return other.signature == null;
} else return signature.equals(other.signature);
}
@Override
public String toString() {
return "SessionCredentials [accessKey=" + accessKey + ", secretKey=" + secretKey + ", signature="
+ signature + ", SecurityToken=" + securityToken + "]";
}
} | SessionCredentials |
java | apache__camel | components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/BindyKeyValuePairFactory.java | {
"start": 16401,
"end": 17194
} | class ____ defined in another bundle
Class<?> cl = null;
try {
cl = Thread.currentThread().getContextClassLoader().loadClass(targetClass);
} catch (ClassNotFoundException e) {
cl = getClass().getClassLoader().loadClass(targetClass);
}
if (!lists.containsKey(cl.getName())) {
lists.put(cl.getName(), new ArrayList<>());
}
generateModelFromKeyValueMap(cl, null, results, line, lists);
// Add list of objects
field.set(obj, lists.get(cl.getName()));
} else {
throw new IllegalArgumentException("No target | is |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedMethodTest.java | {
"start": 993,
"end": 1467
} | class ____ {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(UnusedMethod.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(UnusedMethod.class, getClass());
@Test
public void unusedNative() {
helper
.addSourceLines(
"UnusedNative.java",
"""
package unusedvars;
public | UnusedMethodTest |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/support/store/NamespacedHierarchicalStore.java | {
"start": 18512,
"end": 19254
} | interface ____<N> {
/**
* Static factory method for creating a {@link CloseAction} which
* {@linkplain #close(Object, Object, Object) closes} any value that
* implements {@link AutoCloseable}.
*
* @since 6.0
*/
@API(status = EXPERIMENTAL, since = "6.0")
static <N> CloseAction<N> closeAutoCloseables() {
return (__, ___, value) -> {
if (value instanceof AutoCloseable closeable) {
closeable.close();
}
};
}
/**
* Close the supplied {@code value}.
*
* @param namespace the namespace; never {@code null}
* @param key the key; never {@code null}
* @param value the value; never {@code null}
*/
void close(N namespace, Object key, Object value) throws Throwable;
}
}
| CloseAction |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/error/ShouldBeEmptyDirectory.java | {
"start": 729,
"end": 1595
} | class ____ extends BasicErrorMessageFactory {
private static final String SHOULD_BE_EMPTY_DIRECTORY = "%nExpecting actual:%n %s%nto be an empty directory but it contained:%n %s";
public static ErrorMessageFactory shouldBeEmptyDirectory(final Path actual, List<Path> directoryContent) {
return new ShouldBeEmptyDirectory(actual, directoryContent);
}
public static ErrorMessageFactory shouldBeEmptyDirectory(final File actual, List<File> directoryContent) {
return new ShouldBeEmptyDirectory(actual, directoryContent);
}
private ShouldBeEmptyDirectory(final Path actual, List<Path> directoryContent) {
super(SHOULD_BE_EMPTY_DIRECTORY, actual, directoryContent);
}
private ShouldBeEmptyDirectory(final File actual, List<File> directoryContent) {
super(SHOULD_BE_EMPTY_DIRECTORY, actual, directoryContent);
}
}
| ShouldBeEmptyDirectory |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/action/DelegatePkiAuthenticationRequestTests.java | {
"start": 1128,
"end": 5288
} | class ____ extends AbstractXContentTestCase<DelegatePkiAuthenticationRequest> {
public void testRequestValidation() {
expectThrows(NullPointerException.class, () -> new DelegatePkiAuthenticationRequest((List<X509Certificate>) null));
DelegatePkiAuthenticationRequest request = new DelegatePkiAuthenticationRequest(Arrays.asList(new X509Certificate[0]));
ActionRequestValidationException ve = request.validate();
assertNotNull(ve);
assertEquals(1, ve.validationErrors().size());
assertThat(ve.validationErrors().get(0), is("certificates chain must not be empty"));
List<X509Certificate> mockCertChain = new ArrayList<>(2);
mockCertChain.add(mock(X509Certificate.class));
when(mockCertChain.get(0).getIssuerX500Principal()).thenReturn(new X500Principal("CN=Test, OU=elasticsearch, O=org"));
mockCertChain.add(mock(X509Certificate.class));
when(mockCertChain.get(1).getSubjectX500Principal()).thenReturn(new X500Principal("CN=Not Test, OU=elasticsearch, O=org"));
request = new DelegatePkiAuthenticationRequest(mockCertChain);
ve = request.validate();
assertNotNull(ve);
assertEquals(1, ve.validationErrors().size());
assertThat(ve.validationErrors().get(0), is("certificates chain must be an ordered chain"));
request = new DelegatePkiAuthenticationRequest(Arrays.asList(randomArray(1, 3, X509Certificate[]::new, () -> {
X509Certificate mockX509Certificate = mock(X509Certificate.class);
when(mockX509Certificate.getSubjectX500Principal()).thenReturn(new X500Principal("CN=Test, OU=elasticsearch, O=org"));
when(mockX509Certificate.getIssuerX500Principal()).thenReturn(new X500Principal("CN=Test, OU=elasticsearch, O=org"));
return mockX509Certificate;
})));
ve = request.validate();
assertNull(ve);
}
public void testSerialization() throws Exception {
List<X509Certificate> certificates = randomCertificateList();
DelegatePkiAuthenticationRequest request = new DelegatePkiAuthenticationRequest(certificates);
try (BytesStreamOutput out = new BytesStreamOutput()) {
request.writeTo(out);
try (StreamInput in = out.bytes().streamInput()) {
final DelegatePkiAuthenticationRequest serialized = new DelegatePkiAuthenticationRequest(in);
assertThat(request.getCertificateChain(), is(certificates));
assertThat(request, is(serialized));
assertThat(request.hashCode(), is(serialized.hashCode()));
}
}
}
private List<X509Certificate> randomCertificateList() {
List<X509Certificate> certificates = Arrays.asList(randomArray(1, 3, X509Certificate[]::new, () -> {
try {
return readCert(
getDataPath(
"/org/elasticsearch/xpack/security/transport/ssl/certs/simple/"
+ randomFrom("testclient.crt", "testnode.crt", "testnode-ip-only.crt", "openldap.crt", "samba4.crt")
)
);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
return certificates;
}
private X509Certificate readCert(Path path) throws Exception {
try (InputStream in = Files.newInputStream(path)) {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
return (X509Certificate) factory.generateCertificate(in);
}
}
@Override
protected DelegatePkiAuthenticationRequest createTestInstance() {
List<X509Certificate> certificates = randomCertificateList();
return new DelegatePkiAuthenticationRequest(certificates);
}
@Override
protected DelegatePkiAuthenticationRequest doParseInstance(XContentParser parser) throws IOException {
return DelegatePkiAuthenticationRequest.fromXContent(parser);
}
@Override
protected boolean supportsUnknownFields() {
return false;
}
}
| DelegatePkiAuthenticationRequestTests |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_2200/Issue2238.java | {
"start": 147,
"end": 707
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
CapitalLimitMonenyDTO capitalLimitMonenyDTO =new CapitalLimitMonenyDTO();
capitalLimitMonenyDTO.setMaxChargeMoney(new BigDecimal("200000"));
capitalLimitMonenyDTO.setMinChargeMoney(new BigDecimal(0.01));
capitalLimitMonenyDTO.setMaxWithdrawMoney(new BigDecimal(0.01));
capitalLimitMonenyDTO.setMinWithdrawMoney(new BigDecimal("500000"));
System.out.println(JSON.toJSONString(capitalLimitMonenyDTO));
}
public static | Issue2238 |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/ir/ThrowNode.java | {
"start": 616,
"end": 1409
} | class ____ extends StatementNode {
/* ---- begin tree structure ---- */
private ExpressionNode expressionNode;
public void setExpressionNode(ExpressionNode expressionNode) {
this.expressionNode = expressionNode;
}
public ExpressionNode getExpressionNode() {
return expressionNode;
}
/* ---- end tree structure, begin visitor ---- */
@Override
public <Scope> void visit(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) {
irTreeVisitor.visitThrow(this, scope);
}
@Override
public <Scope> void visitChildren(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) {
// do nothing; terminal node
}
/* ---- end visitor ---- */
public ThrowNode(Location location) {
super(location);
}
}
| ThrowNode |
java | spring-projects__spring-boot | documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/health/HealthEndpointDocumentationTests.java | {
"start": 5239,
"end": 6421
} | class ____ {
@Bean
HealthEndpoint healthEndpoint(Map<String, HealthContributor> contributors) {
HealthContributorRegistry registry = new DefaultHealthContributorRegistry(null,
HealthContributorNameGenerator.withoutStandardSuffixes().registrar(contributors));
HealthEndpointGroup primary = new TestHealthEndpointGroup();
HealthEndpointGroups groups = HealthEndpointGroups.of(primary, Collections.emptyMap());
return new HealthEndpoint(registry, null, groups, null);
}
@Bean
DiskSpaceHealthIndicator diskSpaceHealthIndicator() {
return new DiskSpaceHealthIndicator(new File("."), DataSize.ofMegabytes(10));
}
@Bean
DataSourceHealthIndicator dbHealthIndicator(DataSource dataSource) {
return new DataSourceHealthIndicator(dataSource);
}
@Bean
CompositeHealthContributor brokerHealthContributor() {
Map<String, HealthIndicator> indicators = new LinkedHashMap<>();
indicators.put("us1", () -> Health.up().withDetail("version", "1.0.2").build());
indicators.put("us2", () -> Health.up().withDetail("version", "1.0.4").build());
return CompositeHealthContributor.fromMap(indicators);
}
}
private static final | TestConfiguration |
java | netty__netty | common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java | {
"start": 13162,
"end": 41795
} | class ____ {@link SingleThreadEventExecutor} will not do any blocking
* calls on the this {@link Queue} it may make sense to {@code @Override} this and return some more performant
* implementation that does not support blocking operations at all.
*/
protected Queue<Runnable> newTaskQueue(int maxPendingTasks) {
return new LinkedBlockingQueue<Runnable>(maxPendingTasks);
}
/**
* Interrupt the current running {@link Thread}.
*/
protected void interruptThread() {
Thread currentThread = thread;
if (currentThread == null) {
interrupted = true;
} else {
currentThread.interrupt();
}
}
/**
* @see Queue#poll()
*/
protected Runnable pollTask() {
assert inEventLoop();
return pollTaskFrom(taskQueue);
}
protected static Runnable pollTaskFrom(Queue<Runnable> taskQueue) {
for (;;) {
Runnable task = taskQueue.poll();
if (task != WAKEUP_TASK) {
return task;
}
}
}
/**
* Take the next {@link Runnable} from the task queue and so will block if no task is currently present.
* <p>
* Be aware that this method will throw an {@link UnsupportedOperationException} if the task queue, which was
* created via {@link #newTaskQueue()}, does not implement {@link BlockingQueue}.
* </p>
*
* @return {@code null} if the executor thread has been interrupted or waken up.
*/
protected Runnable takeTask() {
assert inEventLoop();
if (!(taskQueue instanceof BlockingQueue)) {
throw new UnsupportedOperationException();
}
BlockingQueue<Runnable> taskQueue = (BlockingQueue<Runnable>) this.taskQueue;
for (;;) {
ScheduledFutureTask<?> scheduledTask = peekScheduledTask();
if (scheduledTask == null) {
Runnable task = null;
try {
task = taskQueue.take();
if (task == WAKEUP_TASK) {
task = null;
}
} catch (InterruptedException e) {
// Ignore
}
return task;
} else {
long delayNanos = scheduledTask.delayNanos();
Runnable task = null;
if (delayNanos > 0) {
try {
task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
// Waken up.
return null;
}
}
if (task == null) {
// We need to fetch the scheduled tasks now as otherwise there may be a chance that
// scheduled tasks are never executed if there is always one task in the taskQueue.
// This is for example true for the read task of OIO Transport
// See https://github.com/netty/netty/issues/1614
fetchFromScheduledTaskQueue();
task = taskQueue.poll();
}
if (task != null) {
if (task == WAKEUP_TASK) {
return null;
}
return task;
}
}
}
}
private boolean fetchFromScheduledTaskQueue() {
return fetchFromScheduledTaskQueue(taskQueue);
}
/**
* @return {@code true} if at least one scheduled task was executed.
*/
private boolean executeExpiredScheduledTasks() {
if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) {
return false;
}
long nanoTime = getCurrentTimeNanos();
Runnable scheduledTask = pollScheduledTask(nanoTime);
if (scheduledTask == null) {
return false;
}
do {
safeExecute(scheduledTask);
} while ((scheduledTask = pollScheduledTask(nanoTime)) != null);
return true;
}
/**
* @see Queue#peek()
*/
protected Runnable peekTask() {
assert inEventLoop();
return taskQueue.peek();
}
/**
* @see Queue#isEmpty()
*/
protected boolean hasTasks() {
assert inEventLoop();
return !taskQueue.isEmpty();
}
/**
* Return the number of tasks that are pending for processing.
*/
public int pendingTasks() {
return taskQueue.size();
}
/**
* Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown
* before.
*/
protected void addTask(Runnable task) {
ObjectUtil.checkNotNull(task, "task");
if (!offerTask(task)) {
reject(task);
}
}
final boolean offerTask(Runnable task) {
if (isShutdown()) {
reject();
}
return taskQueue.offer(task);
}
/**
* @see Queue#remove(Object)
*/
protected boolean removeTask(Runnable task) {
return taskQueue.remove(ObjectUtil.checkNotNull(task, "task"));
}
/**
* Poll all tasks from the task queue and run them via {@link Runnable#run()} method.
*
* @return {@code true} if and only if at least one task was run
*/
protected boolean runAllTasks() {
assert inEventLoop();
boolean fetchedAll;
boolean ranAtLeastOne = false;
do {
fetchedAll = fetchFromScheduledTaskQueue(taskQueue);
if (runAllTasksFrom(taskQueue)) {
ranAtLeastOne = true;
}
} while (!fetchedAll); // keep on processing until we fetched all scheduled tasks.
if (ranAtLeastOne) {
lastExecutionTime = getCurrentTimeNanos();
}
afterRunningAllTasks();
return ranAtLeastOne;
}
/**
* Execute all expired scheduled tasks and all current tasks in the executor queue until both queues are empty,
* or {@code maxDrainAttempts} has been exceeded.
* @param maxDrainAttempts The maximum amount of times this method attempts to drain from queues. This is to prevent
* continuous task execution and scheduling from preventing the EventExecutor thread to
* make progress and return to the selector mechanism to process inbound I/O events.
* @return {@code true} if at least one task was run.
*/
protected final boolean runScheduledAndExecutorTasks(final int maxDrainAttempts) {
assert inEventLoop();
boolean ranAtLeastOneTask;
int drainAttempt = 0;
do {
// We must run the taskQueue tasks first, because the scheduled tasks from outside the EventLoop are queued
// here because the taskQueue is thread safe and the scheduledTaskQueue is not thread safe.
ranAtLeastOneTask = runExistingTasksFrom(taskQueue) | executeExpiredScheduledTasks();
} while (ranAtLeastOneTask && ++drainAttempt < maxDrainAttempts);
if (drainAttempt > 0) {
lastExecutionTime = getCurrentTimeNanos();
}
afterRunningAllTasks();
return drainAttempt > 0;
}
/**
* Runs all tasks from the passed {@code taskQueue}.
*
* @param taskQueue To poll and execute all tasks.
*
* @return {@code true} if at least one task was executed.
*/
protected final boolean runAllTasksFrom(Queue<Runnable> taskQueue) {
Runnable task = pollTaskFrom(taskQueue);
if (task == null) {
return false;
}
for (;;) {
safeExecute(task);
task = pollTaskFrom(taskQueue);
if (task == null) {
return true;
}
}
}
/**
* What ever tasks are present in {@code taskQueue} when this method is invoked will be {@link Runnable#run()}.
* @param taskQueue the task queue to drain.
* @return {@code true} if at least {@link Runnable#run()} was called.
*/
private boolean runExistingTasksFrom(Queue<Runnable> taskQueue) {
Runnable task = pollTaskFrom(taskQueue);
if (task == null) {
return false;
}
int remaining = Math.min(maxPendingTasks, taskQueue.size());
safeExecute(task);
// Use taskQueue.poll() directly rather than pollTaskFrom() since the latter may
// silently consume more than one item from the queue (skips over WAKEUP_TASK instances)
while (remaining-- > 0 && (task = taskQueue.poll()) != null) {
safeExecute(task);
}
return true;
}
/**
* Poll all tasks from the task queue and run them via {@link Runnable#run()} method. This method stops running
* the tasks in the task queue and returns if it ran longer than {@code timeoutNanos}.
*/
@SuppressWarnings("NonAtomicOperationOnVolatileField")
protected boolean runAllTasks(long timeoutNanos) {
fetchFromScheduledTaskQueue(taskQueue);
Runnable task = pollTask();
if (task == null) {
afterRunningAllTasks();
return false;
}
final long deadline = timeoutNanos > 0 ? getCurrentTimeNanos() + timeoutNanos : 0;
long runTasks = 0;
long lastExecutionTime;
long workStartTime = ticker().nanoTime();
for (;;) {
safeExecute(task);
runTasks ++;
// Check timeout every 64 tasks because nanoTime() is relatively expensive.
// XXX: Hard-coded value - will make it configurable if it is really a problem.
if ((runTasks & 0x3F) == 0) {
lastExecutionTime = getCurrentTimeNanos();
if (lastExecutionTime >= deadline) {
break;
}
}
task = pollTask();
if (task == null) {
lastExecutionTime = getCurrentTimeNanos();
break;
}
}
long workEndTime = ticker().nanoTime();
accumulatedActiveTimeNanos += workEndTime - workStartTime;
lastActivityTimeNanos = workEndTime;
afterRunningAllTasks();
this.lastExecutionTime = lastExecutionTime;
return true;
}
/**
* Invoked before returning from {@link #runAllTasks()} and {@link #runAllTasks(long)}.
*/
protected void afterRunningAllTasks() { }
/**
* Returns the amount of time left until the scheduled task with the closest dead line is executed.
*/
protected long delayNanos(long currentTimeNanos) {
currentTimeNanos -= ticker().initialNanoTime();
ScheduledFutureTask<?> scheduledTask = peekScheduledTask();
if (scheduledTask == null) {
return SCHEDULE_PURGE_INTERVAL;
}
return scheduledTask.delayNanos(currentTimeNanos);
}
/**
* Returns the absolute point in time (relative to {@link #getCurrentTimeNanos()}) at which the next
* closest scheduled task should run.
*/
protected long deadlineNanos() {
ScheduledFutureTask<?> scheduledTask = peekScheduledTask();
if (scheduledTask == null) {
return getCurrentTimeNanos() + SCHEDULE_PURGE_INTERVAL;
}
return scheduledTask.deadlineNanos();
}
/**
* Updates the internal timestamp that tells when a submitted task was executed most recently.
* {@link #runAllTasks()} and {@link #runAllTasks(long)} updates this timestamp automatically, and thus there's
* usually no need to call this method. However, if you take the tasks manually using {@link #takeTask()} or
* {@link #pollTask()}, you have to call this method at the end of task execution loop for accurate quiet period
* checks.
*/
protected void updateLastExecutionTime() {
long now = getCurrentTimeNanos();
lastExecutionTime = now;
lastActivityTimeNanos = now;
}
/**
* Returns the number of registered channels for auto-scaling related decisions.
* This is intended to be used by {@link MultithreadEventExecutorGroup} for dynamic scaling.
*
* @return The number of registered channels, or {@code -1} if not applicable.
*/
protected int getNumOfRegisteredChannels() {
return -1;
}
/**
* Adds the given duration to the total active time for the current measurement window.
* <p>
* <strong>Note:</strong> This method is not thread-safe and must only be called from the
* {@link #inEventLoop() event loop thread}.
*
* @param nanos The active time in nanoseconds to add.
*/
@SuppressWarnings("NonAtomicOperationOnVolatileField")
protected void reportActiveIoTime(long nanos) {
assert inEventLoop();
if (nanos > 0) {
accumulatedActiveTimeNanos += nanos;
lastActivityTimeNanos = ticker().nanoTime();
}
}
/**
* Returns the accumulated active time since the last call and resets the counter.
*/
protected long getAndResetAccumulatedActiveTimeNanos() {
return ACCUMULATED_ACTIVE_TIME_NANOS_UPDATER.getAndSet(this, 0);
}
/**
* Returns the timestamp of the last known activity (tasks + I/O).
*/
protected long getLastActivityTimeNanos() {
return lastActivityTimeNanos;
}
/**
* Atomically increments the counter for consecutive monitor cycles where utilization was below the
* scale-down threshold. This is used by the auto-scaling monitor to track sustained idleness.
*
* @return The number of consecutive idle cycles before the increment.
*/
protected int getAndIncrementIdleCycles() {
return CONSECUTIVE_IDLE_CYCLES_UPDATER.getAndIncrement(this);
}
/**
* Resets the counter for consecutive idle cycles to zero. This is typically called when the
* executor's utilization is no longer considered idle, breaking the streak.
*/
protected void resetIdleCycles() {
CONSECUTIVE_IDLE_CYCLES_UPDATER.set(this, 0);
}
/**
* Atomically increments the counter for consecutive monitor cycles where utilization was above the
* scale-up threshold. This is used by the auto-scaling monitor to track a sustained high load.
*
* @return The number of consecutive busy cycles before the increment.
*/
protected int getAndIncrementBusyCycles() {
return CONSECUTIVE_BUSY_CYCLES_UPDATER.getAndIncrement(this);
}
/**
* Resets the counter for consecutive busy cycles to zero. This is typically called when the
* executor's utilization is no longer considered busy, breaking the streak.
*/
protected void resetBusyCycles() {
CONSECUTIVE_BUSY_CYCLES_UPDATER.set(this, 0);
}
/**
* Returns {@code true} if this {@link SingleThreadEventExecutor} supports suspension.
*/
protected boolean isSuspensionSupported() {
return supportSuspension;
}
/**
* Run the tasks in the {@link #taskQueue}
*/
protected abstract void run();
/**
* Do nothing, sub-classes may override
*/
protected void cleanup() {
// NOOP
}
protected void wakeup(boolean inEventLoop) {
if (!inEventLoop) {
// Use offer as we actually only need this to unblock the thread and if offer fails we do not care as there
// is already something in the queue.
taskQueue.offer(WAKEUP_TASK);
}
}
@Override
public boolean inEventLoop(Thread thread) {
return thread == this.thread;
}
/**
* Add a {@link Runnable} which will be executed on shutdown of this instance
*/
public void addShutdownHook(final Runnable task) {
if (inEventLoop()) {
shutdownHooks.add(task);
} else {
execute(new Runnable() {
@Override
public void run() {
shutdownHooks.add(task);
}
});
}
}
/**
* Remove a previous added {@link Runnable} as a shutdown hook
*/
public void removeShutdownHook(final Runnable task) {
if (inEventLoop()) {
shutdownHooks.remove(task);
} else {
execute(new Runnable() {
@Override
public void run() {
shutdownHooks.remove(task);
}
});
}
}
private boolean runShutdownHooks() {
boolean ran = false;
// Note shutdown hooks can add / remove shutdown hooks.
while (!shutdownHooks.isEmpty()) {
List<Runnable> copy = new ArrayList<Runnable>(shutdownHooks);
shutdownHooks.clear();
for (Runnable task: copy) {
try {
runTask(task);
} catch (Throwable t) {
logger.warn("Shutdown hook raised an exception.", t);
} finally {
ran = true;
}
}
}
if (ran) {
lastExecutionTime = getCurrentTimeNanos();
}
return ran;
}
private void shutdown0(long quietPeriod, long timeout, int shutdownState) {
if (isShuttingDown()) {
return;
}
boolean inEventLoop = inEventLoop();
boolean wakeup;
int oldState;
for (;;) {
if (isShuttingDown()) {
return;
}
int newState;
wakeup = true;
oldState = state;
if (inEventLoop) {
newState = shutdownState;
} else {
switch (oldState) {
case ST_NOT_STARTED:
case ST_STARTED:
case ST_SUSPENDING:
case ST_SUSPENDED:
newState = shutdownState;
break;
default:
newState = oldState;
wakeup = false;
}
}
if (STATE_UPDATER.compareAndSet(this, oldState, newState)) {
break;
}
}
if (quietPeriod != -1) {
gracefulShutdownQuietPeriod = quietPeriod;
}
if (timeout != -1) {
gracefulShutdownTimeout = timeout;
}
if (ensureThreadStarted(oldState)) {
return;
}
if (wakeup) {
taskQueue.offer(WAKEUP_TASK);
if (!addTaskWakesUp) {
wakeup(inEventLoop);
}
}
}
@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
ObjectUtil.checkPositiveOrZero(quietPeriod, "quietPeriod");
if (timeout < quietPeriod) {
throw new IllegalArgumentException(
"timeout: " + timeout + " (expected >= quietPeriod (" + quietPeriod + "))");
}
ObjectUtil.checkNotNull(unit, "unit");
shutdown0(unit.toNanos(quietPeriod), unit.toNanos(timeout), ST_SHUTTING_DOWN);
return terminationFuture();
}
@Override
public Future<?> terminationFuture() {
return terminationFuture;
}
@Override
@Deprecated
public void shutdown() {
shutdown0(-1, -1, ST_SHUTDOWN);
}
@Override
public boolean isShuttingDown() {
return state >= ST_SHUTTING_DOWN;
}
@Override
public boolean isShutdown() {
return state >= ST_SHUTDOWN;
}
@Override
public boolean isTerminated() {
return state == ST_TERMINATED;
}
@Override
public boolean isSuspended() {
int currentState = state;
return currentState == ST_SUSPENDED || currentState == ST_SUSPENDING;
}
@Override
public boolean trySuspend() {
if (supportSuspension) {
if (STATE_UPDATER.compareAndSet(this, ST_STARTED, ST_SUSPENDING)) {
wakeup(inEventLoop());
return true;
} else if (STATE_UPDATER.compareAndSet(this, ST_NOT_STARTED, ST_SUSPENDED)) {
return true;
}
int currentState = state;
return currentState == ST_SUSPENDED || currentState == ST_SUSPENDING;
}
return false;
}
/**
* Returns {@code true} if this {@link SingleThreadEventExecutor} can be suspended at the moment, {@code false}
* otherwise.
*
* @return if suspension is possible at the moment.
*/
protected boolean canSuspend() {
return canSuspend(state);
}
/**
* Returns {@code true} if this {@link SingleThreadEventExecutor} can be suspended at the moment, {@code false}
* otherwise.
*
* Subclasses might override this method to add extra checks.
*
* @param state the current internal state of the {@link SingleThreadEventExecutor}.
* @return if suspension is possible at the moment.
*/
protected boolean canSuspend(int state) {
assert inEventLoop();
return supportSuspension && (state == ST_SUSPENDED || state == ST_SUSPENDING)
&& !hasTasks() && nextScheduledTaskDeadlineNanos() == -1;
}
/**
* Confirm that the shutdown if the instance should be done now!
*/
protected boolean confirmShutdown() {
if (!isShuttingDown()) {
return false;
}
if (!inEventLoop()) {
throw new IllegalStateException("must be invoked from an event loop");
}
cancelScheduledTasks();
if (gracefulShutdownStartTime == 0) {
gracefulShutdownStartTime = getCurrentTimeNanos();
}
if (runAllTasks() || runShutdownHooks()) {
if (isShutdown()) {
// Executor shut down - no new tasks anymore.
return true;
}
// There were tasks in the queue. Wait a little bit more until no tasks are queued for the quiet period or
// terminate if the quiet period is 0.
// See https://github.com/netty/netty/issues/4241
if (gracefulShutdownQuietPeriod == 0) {
return true;
}
taskQueue.offer(WAKEUP_TASK);
return false;
}
final long nanoTime = getCurrentTimeNanos();
if (isShutdown() || nanoTime - gracefulShutdownStartTime > gracefulShutdownTimeout) {
return true;
}
if (nanoTime - lastExecutionTime <= gracefulShutdownQuietPeriod) {
// Check if any tasks were added to the queue every 100ms.
// TODO: Change the behavior of takeTask() so that it returns on timeout.
taskQueue.offer(WAKEUP_TASK);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Ignore
}
return false;
}
// No tasks were added for last quiet period - hopefully safe to shut down.
// (Hopefully because we really cannot make a guarantee that there will be no execute() calls by a user.)
return true;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
ObjectUtil.checkNotNull(unit, "unit");
if (inEventLoop()) {
throw new IllegalStateException("cannot await termination of the current thread");
}
threadLock.await(timeout, unit);
return isTerminated();
}
@Override
public void execute(Runnable task) {
execute0(task);
}
@Override
public void lazyExecute(Runnable task) {
lazyExecute0(task);
}
private void execute0(@Schedule Runnable task) {
ObjectUtil.checkNotNull(task, "task");
execute(task, wakesUpForTask(task));
}
private void lazyExecute0(@Schedule Runnable task) {
execute(ObjectUtil.checkNotNull(task, "task"), false);
}
@Override
void scheduleRemoveScheduled(final ScheduledFutureTask<?> task) {
ObjectUtil.checkNotNull(task, "task");
int currentState = state;
if (supportSuspension && currentState == ST_SUSPENDED) {
// In the case of scheduling for removal we need to also ensure we will recover the "suspend" state
// after it if it was set before. Otherwise we will always end up "unsuspending" things on cancellation
// which is not optimal.
execute(new Runnable() {
@Override
public void run() {
task.run();
if (canSuspend(ST_SUSPENDED)) {
// Try suspending again to recover the state before we submitted the new task that will
// handle cancellation itself.
trySuspend();
}
}
}, true);
} else {
// task will remove itself from scheduled task queue when it runs
execute(task, false);
}
}
private void execute(Runnable task, boolean immediate) {
boolean inEventLoop = inEventLoop();
addTask(task);
if (!inEventLoop) {
startThread();
if (isShutdown()) {
boolean reject = false;
try {
if (removeTask(task)) {
reject = true;
}
} catch (UnsupportedOperationException e) {
// The task queue does not support removal so the best thing we can do is to just move on and
// hope we will be able to pick-up the task before its completely terminated.
// In worst case we will log on termination.
}
if (reject) {
reject();
}
}
}
if (!addTaskWakesUp && immediate) {
wakeup(inEventLoop);
}
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
throwIfInEventLoop("invokeAny");
return super.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
throwIfInEventLoop("invokeAny");
return super.invokeAny(tasks, timeout, unit);
}
@Override
public <T> List<java.util.concurrent.Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
throwIfInEventLoop("invokeAll");
return super.invokeAll(tasks);
}
@Override
public <T> List<java.util.concurrent.Future<T>> invokeAll(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
throwIfInEventLoop("invokeAll");
return super.invokeAll(tasks, timeout, unit);
}
private void throwIfInEventLoop(String method) {
if (inEventLoop()) {
throw new RejectedExecutionException("Calling " + method + " from within the EventLoop is not allowed");
}
}
/**
* Returns the {@link ThreadProperties} of the {@link Thread} that powers the {@link SingleThreadEventExecutor}.
* If the {@link SingleThreadEventExecutor} is not started yet, this operation will start it and block until
* it is fully started.
*/
public final ThreadProperties threadProperties() {
ThreadProperties threadProperties = this.threadProperties;
if (threadProperties == null) {
Thread thread = this.thread;
if (thread == null) {
assert !inEventLoop();
submit(NOOP_TASK).syncUninterruptibly();
thread = this.thread;
assert thread != null;
}
threadProperties = new DefaultThreadProperties(thread);
if (!PROPERTIES_UPDATER.compareAndSet(this, null, threadProperties)) {
threadProperties = this.threadProperties;
}
}
return threadProperties;
}
/**
* @deprecated override {@link SingleThreadEventExecutor#wakesUpForTask} to re-create this behaviour
*/
@Deprecated
protected | of |
java | alibaba__fastjson | src/test/java/com/derbysoft/spitfire/fastjson/dto/RoomRateDTO.java | {
"start": 77,
"end": 301
} | class ____ extends AbstractDTO{
private List<RateDTO> rates;
public List<RateDTO> getRates() {
return rates;
}
public void setRates(List<RateDTO> rates) {
this.rates = rates;
}
}
| RoomRateDTO |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/node/stats/NodesStatsRequestParameters.java | {
"start": 1194,
"end": 2851
} | class ____ implements Writeable {
private CommonStatsFlags indices = new CommonStatsFlags();
private final EnumSet<Metric> requestedMetrics;
private boolean includeShardsStats = true;
public NodesStatsRequestParameters() {
this.requestedMetrics = EnumSet.noneOf(Metric.class);
}
public NodesStatsRequestParameters(StreamInput in) throws IOException {
indices = new CommonStatsFlags(in);
requestedMetrics = Metric.readSetFrom(in);
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_12_0)) {
includeShardsStats = in.readBoolean();
} else {
includeShardsStats = true;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
indices.writeTo(out);
Metric.writeSetTo(out, requestedMetrics);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_12_0)) {
out.writeBoolean(includeShardsStats);
}
}
public CommonStatsFlags indices() {
return indices;
}
public void setIndices(CommonStatsFlags indices) {
this.indices = indices;
}
public EnumSet<Metric> requestedMetrics() {
return requestedMetrics;
}
public boolean includeShardsStats() {
return includeShardsStats;
}
public void setIncludeShardsStats(boolean includeShardsStats) {
this.includeShardsStats = includeShardsStats;
}
/**
* An enumeration of the "core" sections of metrics that may be requested
* from the nodes stats endpoint. Eventually this list will be pluggable.
*/
public | NodesStatsRequestParameters |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/internal/impl/EventSpyImpl.java | {
"start": 2024,
"end": 2231
} | enum ____ Maven4 enum.
*/
protected EventType convert(ExecutionEvent.Type type) {
return EventType.values()[type.ordinal()];
}
@Override
public void close() throws Exception {}
}
| to |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/PersistentTableStrategy.java | {
"start": 1268,
"end": 5720
} | class ____ {
private static final Logger LOG = Logger.getLogger( PersistentTableStrategy.class );
public static final String SHORT_NAME = "persistent";
public static final String CREATE_ID_TABLES = "hibernate.query.mutation_strategy.persistent.create_tables";
public static final String DROP_ID_TABLES = "hibernate.query.mutation_strategy.persistent.drop_tables";
public static final String SCHEMA = "hibernate.query.mutation_strategy.persistent.schema";
public static final String CATALOG = "hibernate.query.mutation_strategy.persistent.catalog";
private final TemporaryTable temporaryTable;
private final SessionFactoryImplementor sessionFactory;
private boolean prepared;
private boolean dropIdTables;
public PersistentTableStrategy(
TemporaryTable temporaryTable,
SessionFactoryImplementor sessionFactory) {
this.temporaryTable = temporaryTable;
this.sessionFactory = sessionFactory;
if ( sessionFactory.getJdbcServices().getDialect().getPersistentTemporaryTableStrategy().getTemporaryTableAfterUseAction() == AfterUseAction.DROP ) {
throw new IllegalArgumentException( "Persistent ID tables cannot use AfterUseAction.DROP : " + temporaryTable.getTableExpression() );
}
}
public TemporaryTableStrategy getTemporaryTableStrategy() {
return castNonNull( sessionFactory.getJdbcServices().getDialect().getPersistentTemporaryTableStrategy() );
}
public void prepare(
MappingModelCreationProcess mappingModelCreationProcess,
JdbcConnectionAccess connectionAccess) {
if ( prepared ) {
return;
}
prepared = true;
final ConfigurationService configService =
mappingModelCreationProcess.getCreationContext()
.getBootstrapContext().getServiceRegistry()
.requireService( ConfigurationService.class );
boolean createIdTables = configService.getSetting(
CREATE_ID_TABLES,
StandardConverters.BOOLEAN,
true
);
if (!createIdTables ) {
return;
}
LOG.debugf( "Creating persistent ID table : %s", getTemporaryTable().getTableExpression() );
final TemporaryTableHelper.TemporaryTableCreationWork temporaryTableCreationWork = new TemporaryTableHelper.TemporaryTableCreationWork(
getTemporaryTable(),
sessionFactory
);
Connection connection;
try {
connection = connectionAccess.obtainConnection();
}
catch (UnsupportedOperationException e) {
// assume this comes from org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl
LOG.debug( "Unable to obtain JDBC connection; assuming ID tables already exist or wont be needed" );
return;
}
catch (SQLException e) {
LOG.error( "Unable obtain JDBC Connection", e );
return;
}
try {
temporaryTableCreationWork.execute( connection );
this.dropIdTables = configService.getSetting(
DROP_ID_TABLES,
StandardConverters.BOOLEAN,
false
);
}
finally {
try {
connectionAccess.releaseConnection( connection );
}
catch (SQLException exception) {
JDBC_LOGGER.unableToReleaseConnection( exception );
}
}
}
public void release(
SessionFactoryImplementor sessionFactory,
JdbcConnectionAccess connectionAccess) {
if ( !dropIdTables ) {
return;
}
dropIdTables = false;
final TemporaryTable temporaryTable = getTemporaryTable();
LOG.tracef( "Dropping persistent ID table: %s", temporaryTable.getTableExpression() );
final TemporaryTableHelper.TemporaryTableDropWork temporaryTableDropWork =
new TemporaryTableHelper.TemporaryTableDropWork( temporaryTable, sessionFactory );
Connection connection;
try {
connection = connectionAccess.obtainConnection();
}
catch (UnsupportedOperationException e) {
// assume this comes from org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl
LOG.debugf( "Unable to obtain JDBC connection; unable to drop persistent ID table : %s", temporaryTable.getTableExpression() );
return;
}
catch (SQLException e) {
LOG.error( "Unable obtain JDBC Connection", e );
return;
}
try {
temporaryTableDropWork.execute( connection );
}
finally {
try {
connectionAccess.releaseConnection( connection );
}
catch (SQLException exception) {
JDBC_LOGGER.unableToReleaseConnection( exception );
}
}
}
public TemporaryTable getTemporaryTable() {
return temporaryTable;
}
public SessionFactoryImplementor getSessionFactory() {
return sessionFactory;
}
}
| PersistentTableStrategy |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FromFtpConsumerTemplateRollbackIT.java | {
"start": 1356,
"end": 3162
} | class ____ extends FtpServerTestSupport {
protected String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}/deletefile?password=admin&binary=false&delete=true";
}
protected String getFtpUrlInvalid() {
// use invalid starting directory and do not allow creating it so we
// force the poll to fail
return "ftp://admin@localhost:{{ftp.server.port}}/unknown?password=admin&binary=false&delete=true&autoCreate=false";
}
@Override
public void doPostSetup() throws Exception {
prepareFtpServer();
}
@Test
public void testConsumerTemplateRollback() {
try {
consumer.receiveBody(getFtpUrlInvalid(), 2000, String.class);
fail("Should fail and rollback");
} catch (Exception e) {
GenericFileOperationFailedException ge = assertIsInstanceOf(GenericFileOperationFailedException.class, e);
assertEquals(550, ge.getCode());
}
}
private void prepareFtpServer() throws Exception {
// prepares the FTP Server by creating a file on the server that we want
// to unit
// test that we can pool and store as a local file
Endpoint endpoint = context.getEndpoint(getFtpUrl());
Exchange exchange = endpoint.createExchange();
exchange.getIn().setBody("Hello World this file will be deleted");
exchange.getIn().setHeader(Exchange.FILE_NAME, "hello.txt");
Producer producer = endpoint.createProducer();
producer.start();
producer.process(exchange);
producer.stop();
// assert file is created
File file = service.ftpFile("deletefile/hello.txt").toFile();
assertTrue(file.exists(), "The file should exists");
}
}
| FromFtpConsumerTemplateRollbackIT |
java | apache__thrift | lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java | {
"start": 15233,
"end": 15594
} | class ____ extends java.security.Provider {
public SaslAnonymousProvider() {
super("ThriftSaslAnonymous", 1.0, "Thrift Anonymous SASL provider");
put("SaslClientFactory.ANONYMOUS", SaslAnonymousFactory.class.getName());
put("SaslServerFactory.ANONYMOUS", SaslAnonymousFactory.class.getName());
}
}
private static | SaslAnonymousProvider |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/streaming/JavaRecoverableNetworkWordCount.java | {
"start": 3895,
"end": 7774
} | class ____ {
private static final Pattern SPACE = Pattern.compile(" ");
private static JavaStreamingContext createContext(String ip,
int port,
String checkpointDirectory,
String outputPath) {
// If you do not see this printed, that means the StreamingContext has been loaded
// from the new checkpoint
System.out.println("Creating new context");
File outputFile = new File(outputPath);
if (outputFile.exists()) {
outputFile.delete();
}
SparkConf sparkConf = new SparkConf().setAppName("JavaRecoverableNetworkWordCount");
// Create the context with a 1 second batch size
JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));
ssc.checkpoint(checkpointDirectory);
// Create a socket stream on target ip:port and count the
// words in input stream of \n delimited text (e.g. generated by 'nc')
JavaReceiverInputDStream<String> lines = ssc.socketTextStream(ip, port);
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(SPACE.split(x)).iterator());
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
.reduceByKey((i1, i2) -> i1 + i2);
wordCounts.foreachRDD((rdd, time) -> {
// Get or register the excludeList Broadcast
Broadcast<List<String>> excludeList =
JavaWordExcludeList.getInstance(new JavaSparkContext(rdd.context()));
// Get or register the droppedWordsCounter Accumulator
LongAccumulator droppedWordsCounter =
JavaDroppedWordsCounter.getInstance(new JavaSparkContext(rdd.context()));
// Use excludeList to drop words and use droppedWordsCounter to count them
String counts = rdd.filter(wordCount -> {
if (excludeList.value().contains(wordCount._1())) {
droppedWordsCounter.add(wordCount._2());
return false;
} else {
return true;
}
}).collect().toString();
String output = "Counts at time " + time + " " + counts;
System.out.println(output);
System.out.println("Dropped " + droppedWordsCounter.value() + " word(s) totally");
System.out.println("Appending to " + outputFile.getAbsolutePath());
Files.writeString(outputFile.toPath(), output + "\n", StandardOpenOption.APPEND);
});
return ssc;
}
public static void main(String[] args) throws Exception {
if (args.length != 4) {
System.err.println("You arguments were " + Arrays.asList(args));
System.err.println(
"Usage: JavaRecoverableNetworkWordCount <hostname> <port> <checkpoint-directory>\n" +
" <output-file>. <hostname> and <port> describe the TCP server that Spark\n" +
" Streaming would connect to receive data. <checkpoint-directory> directory to\n" +
" HDFS-compatible file system which checkpoint data <output-file> file to which\n" +
" the word counts will be appended\n" +
"\n" +
"In local mode, <master> should be 'local[n]' with n > 1\n" +
"Both <checkpoint-directory> and <output-file> must be absolute paths");
System.exit(1);
}
String ip = args[0];
int port = Integer.parseInt(args[1]);
String checkpointDirectory = args[2];
String outputPath = args[3];
// Function to create JavaStreamingContext without any output operations
// (used to detect the new context)
Function0<JavaStreamingContext> createContextFunc =
() -> createContext(ip, port, checkpointDirectory, outputPath);
JavaStreamingContext ssc =
JavaStreamingContext.getOrCreate(checkpointDirectory, createContextFunc);
ssc.start();
ssc.awaitTermination();
}
}
| JavaRecoverableNetworkWordCount |
java | quarkusio__quarkus | extensions/hibernate-validator/runtime/src/main/java/io/quarkus/hibernate/validator/runtime/jaxrs/ResteasyReactiveViolationException.java | {
"start": 634,
"end": 1115
} | class ____ extends ConstraintViolationException {
private static final long serialVersionUID = 657697354453281559L;
public ResteasyReactiveViolationException(String message, Set<? extends ConstraintViolation<?>> constraintViolations) {
super(message, constraintViolations);
}
public ResteasyReactiveViolationException(Set<? extends ConstraintViolation<?>> constraintViolations) {
super(constraintViolations);
}
}
| ResteasyReactiveViolationException |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 80098,
"end": 80449
} | class ____ {
private @Nullable List<Class<? extends Throwable>> list;
@Nullable List<Class<? extends Throwable>> getList() {
return this.list;
}
void setList(@Nullable List<Class<? extends Throwable>> list) {
this.list = list;
}
}
@EnableConfigurationProperties
@ConfigurationProperties("test")
static | ListOfGenericClassProperties |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFilter.java | {
"start": 885,
"end": 1327
} | class ____<T> extends AbstractObservableWithUpstream<T, T> {
final Predicate<? super T> predicate;
public ObservableFilter(ObservableSource<T> source, Predicate<? super T> predicate) {
super(source);
this.predicate = predicate;
}
@Override
public void subscribeActual(Observer<? super T> observer) {
source.subscribe(new FilterObserver<>(observer, predicate));
}
static final | ObservableFilter |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/elastic/request/ElasticInferenceServiceUnifiedChatCompletionRequest.java | {
"start": 1228,
"end": 3229
} | class ____ extends ElasticInferenceServiceRequest {
private final ElasticInferenceServiceCompletionModel model;
private final UnifiedChatInput unifiedChatInput;
private final TraceContextHandler traceContextHandler;
public ElasticInferenceServiceUnifiedChatCompletionRequest(
UnifiedChatInput unifiedChatInput,
ElasticInferenceServiceCompletionModel model,
TraceContext traceContext,
ElasticInferenceServiceRequestMetadata requestMetadata,
CCMAuthenticationApplierFactory.AuthApplier authApplier
) {
super(requestMetadata, authApplier);
this.unifiedChatInput = Objects.requireNonNull(unifiedChatInput);
this.model = Objects.requireNonNull(model);
this.traceContextHandler = new TraceContextHandler(traceContext);
}
@Override
public HttpRequestBase createHttpRequestBase() {
var httpPost = new HttpPost(model.uri());
var requestEntity = Strings.toString(
new ElasticInferenceServiceUnifiedChatCompletionRequestEntity(unifiedChatInput, model.getServiceSettings().modelId())
);
ByteArrayEntity byteEntity = new ByteArrayEntity(requestEntity.getBytes(StandardCharsets.UTF_8));
httpPost.setEntity(byteEntity);
traceContextHandler.propagateTraceContext(httpPost);
httpPost.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, XContentType.JSON.mediaType()));
return httpPost;
}
@Override
public URI getURI() {
return model.uri();
}
@Override
public Request truncate() {
// No truncation
return this;
}
@Override
public boolean[] getTruncationInfo() {
// No truncation
return null;
}
@Override
public String getInferenceEntityId() {
return model.getInferenceEntityId();
}
@Override
public boolean isStreaming() {
return unifiedChatInput.stream();
}
}
| ElasticInferenceServiceUnifiedChatCompletionRequest |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/deployment/ConnectorAttributeLiteral.java | {
"start": 178,
"end": 2159
} | class ____ implements ConnectorAttribute {
private final String name;
private final String description;
private final boolean hidden;
private final boolean mandatory;
private final Direction direction;
private final String defaultValue;
private final boolean deprecated;
private final String alias;
private final String type;
public ConnectorAttributeLiteral(String name, String description, boolean hidden, boolean mandatory,
Direction direction, String defaultValue, boolean deprecated, String alias, String type) {
this.name = name;
this.description = description;
this.hidden = hidden;
this.mandatory = mandatory;
this.direction = direction;
this.defaultValue = defaultValue;
this.deprecated = deprecated;
this.alias = alias;
this.type = type;
}
public static ConnectorAttribute create(String name, String description, boolean hidden, boolean mandatory,
Direction direction, String defaultValue, boolean deprecated, String alias, String type) {
return new ConnectorAttributeLiteral(name, description, hidden, mandatory, direction, defaultValue, deprecated, alias,
type);
}
public String name() {
return name;
}
public String description() {
return description;
}
public boolean hiddenFromDocumentation() {
return hidden;
}
public boolean mandatory() {
return mandatory;
}
public Direction direction() {
return direction;
}
public String defaultValue() {
return defaultValue;
}
public boolean deprecated() {
return deprecated;
}
public String alias() {
return alias;
}
public String type() {
return type;
}
@Override
public Class<? extends Annotation> annotationType() {
return ConnectorAttribute.class;
}
}
| ConnectorAttributeLiteral |
java | alibaba__nacos | example/src/main/java/com/alibaba/nacos/example/App.java | {
"start": 930,
"end": 1688
} | class ____ {
public static void main(String[] args) throws NacosException {
Properties properties = new Properties();
properties.setProperty("serverAddr", "localhost:8848");
properties.setProperty("namespace", "quickStart");
NamingService naming = NamingFactory.createNamingService(properties);
naming.registerInstance("nacos.test.3", "11.11.11.11", 8888, "TEST1");
System.out.println("[Instances after register] " + naming.getAllInstances("nacos.test.3", Lists.newArrayList("TEST1")));
naming.registerInstance("nacos.test.3", "2.2.2.2", 9999, "DEFAULT");
System.out.println("[Instances after register] " + naming.getAllInstances("nacos.test.3", Lists.newArrayList("DEFAULT")));
}
}
| App |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/cache/postprocessor/SetStatusCodeAfterCacheExchangeMutator.java | {
"start": 1005,
"end": 1299
} | class ____ implements AfterCacheExchangeMutator {
@Override
public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(cachedResponse.statusCode());
}
}
| SetStatusCodeAfterCacheExchangeMutator |
java | google__guava | android/guava/src/com/google/common/collect/FilteredKeyMultimap.java | {
"start": 3356,
"end": 4052
} | class ____<K extends @Nullable Object, V extends @Nullable Object>
extends ForwardingSet<V> {
@ParametricNullness final K key;
AddRejectingSet(@ParametricNullness K key) {
this.key = key;
}
@Override
public boolean add(@ParametricNullness V element) {
throw new IllegalArgumentException("Key does not satisfy predicate: " + key);
}
@Override
public boolean addAll(Collection<? extends V> collection) {
checkNotNull(collection);
throw new IllegalArgumentException("Key does not satisfy predicate: " + key);
}
@Override
protected Set<V> delegate() {
return emptySet();
}
}
private static final | AddRejectingSet |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java | {
"start": 10129,
"end": 10181
} | class ____ implements EmptyService {}
}
| EmptyServiceImpl |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/Plant.java | {
"start": 297,
"end": 736
} | class ____ {
@Id
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@PrePersist
private void defineId() {
//some (stupid) id generation
if ( name.length() > 5 ) {
setId( name.substring( 0, 5 ) );
}
else {
setId( name );
}
}
}
| Plant |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/ChannelStateHolder.java | {
"start": 1067,
"end": 1248
} | interface ____ {
/** Injects the {@link ChannelStateWriter}. Must only be called once. */
void setChannelStateWriter(ChannelStateWriter channelStateWriter);
}
| ChannelStateHolder |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/serialization/SerializerConfigImpl.java | {
"start": 6303,
"end": 6943
} | class ____ serializer.");
}
@SuppressWarnings("unchecked")
Class<? extends Serializer<?>> castedSerializerClass =
(Class<? extends Serializer<?>>) serializerClass;
registeredTypesWithKryoSerializerClasses.put(type, castedSerializerClass);
}
/**
* Registers the given type with the serialization stack. If the type is eventually serialized
* as a POJO, then the type is registered with the POJO serializer. If the type ends up being
* serialized with Kryo, then it will be registered at Kryo to make sure that only tags are
* written.
*
* @param type The | or |
java | spring-projects__spring-boot | module/spring-boot-webclient-test/src/main/java/org/springframework/boot/webclient/test/autoconfigure/WebClientTypeExcludeFilter.java | {
"start": 1182,
"end": 2467
} | class ____ extends StandardAnnotationCustomizableTypeExcludeFilter<WebClientTest> {
private static final Class<?>[] NO_COMPONENTS = {};
private static final String DATABIND_MODULE_CLASS_NAME = "tools.jackson.databind.JacksonModule";
private static final Set<Class<?>> KNOWN_INCLUDES;
static {
Set<Class<?>> includes = new LinkedHashSet<>();
if (ClassUtils.isPresent(DATABIND_MODULE_CLASS_NAME, WebClientTypeExcludeFilter.class.getClassLoader())) {
try {
includes.add(Class.forName(DATABIND_MODULE_CLASS_NAME, true,
WebClientTypeExcludeFilter.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Failed to load " + DATABIND_MODULE_CLASS_NAME, ex);
}
includes.add(JacksonComponent.class);
}
KNOWN_INCLUDES = Collections.unmodifiableSet(includes);
}
private final Class<?>[] components;
WebClientTypeExcludeFilter(Class<?> testClass) {
super(testClass);
this.components = getAnnotation().getValue("components", Class[].class).orElse(NO_COMPONENTS);
}
@Override
protected Set<Class<?>> getKnownIncludes() {
return KNOWN_INCLUDES;
}
@Override
protected Set<Class<?>> getComponentIncludes() {
return new LinkedHashSet<>(Arrays.asList(this.components));
}
}
| WebClientTypeExcludeFilter |
java | apache__camel | components/camel-mllp/src/main/java/org/apache/camel/component/mllp/internal/Hl7Util.java | {
"start": 1258,
"end": 21049
} | class ____ {
public static final String NULL_REPLACEMENT_VALUE = "<null>";
public static final String EMPTY_REPLACEMENT_VALUE = "<>";
public static final Map<Character, String> CHARACTER_REPLACEMENTS;
public static final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss.SSSZZZZ");
static final int STRING_BUFFER_PAD_SIZE = 100;
static final Logger LOG = LoggerFactory.getLogger(Hl7Util.class);
static {
CHARACTER_REPLACEMENTS = new HashMap<>();
CHARACTER_REPLACEMENTS.put((char) 0x00, "<0x00 NUL>");
CHARACTER_REPLACEMENTS.put((char) 0x01, "<0x01 SOH>");
CHARACTER_REPLACEMENTS.put((char) 0x02, "<0x02 STX>");
CHARACTER_REPLACEMENTS.put((char) 0x03, "<0x03 ETX>");
CHARACTER_REPLACEMENTS.put((char) 0x04, "<0x04 EOT>");
CHARACTER_REPLACEMENTS.put((char) 0x05, "<0x05 ENQ>");
CHARACTER_REPLACEMENTS.put((char) 0x06, "<0x06 ACK>");
CHARACTER_REPLACEMENTS.put((char) 0x07, "<0x07 BEL>");
CHARACTER_REPLACEMENTS.put((char) 0x08, "<0x08 BS>");
CHARACTER_REPLACEMENTS.put((char) 0x09, "<0x09 TAB>");
CHARACTER_REPLACEMENTS.put((char) 0x0A, "<0x0A LF>");
CHARACTER_REPLACEMENTS.put((char) 0x0B, "<0x0B VT>");
CHARACTER_REPLACEMENTS.put((char) 0x0C, "<0x0C FF>");
CHARACTER_REPLACEMENTS.put((char) 0x0D, "<0x0D CR>");
CHARACTER_REPLACEMENTS.put((char) 0x0E, "<0x0E SO>");
CHARACTER_REPLACEMENTS.put((char) 0x0F, "<0x0F SI>");
CHARACTER_REPLACEMENTS.put((char) 0x10, "<0x10 DLE>");
CHARACTER_REPLACEMENTS.put((char) 0x11, "<0x11 DC1>");
CHARACTER_REPLACEMENTS.put((char) 0x12, "<0x12 DC2>");
CHARACTER_REPLACEMENTS.put((char) 0x13, "<0x13 DC3>");
CHARACTER_REPLACEMENTS.put((char) 0x14, "<0x14 DC4>");
CHARACTER_REPLACEMENTS.put((char) 0x15, "<0x15 NAK>");
CHARACTER_REPLACEMENTS.put((char) 0x16, "<0x16 SYN>");
CHARACTER_REPLACEMENTS.put((char) 0x17, "<0x17 ETB>");
CHARACTER_REPLACEMENTS.put((char) 0x18, "<0x18 CAN>");
CHARACTER_REPLACEMENTS.put((char) 0x19, "<0x19 EM>");
CHARACTER_REPLACEMENTS.put((char) 0x1A, "<0x1A SUB>");
CHARACTER_REPLACEMENTS.put((char) 0x1B, "<0x1B ESC>");
CHARACTER_REPLACEMENTS.put((char) 0x1C, "<0x1C FS>");
CHARACTER_REPLACEMENTS.put((char) 0x1D, "<0x1D GS>");
CHARACTER_REPLACEMENTS.put((char) 0x1E, "<0x1E RS>");
CHARACTER_REPLACEMENTS.put((char) 0x1F, "<0x1F US>");
CHARACTER_REPLACEMENTS.put((char) 0x7F, "<0x7F DEL>");
}
private final int logPhiMaxBytes;
private final boolean logPhi;
public Hl7Util(int logPhiMaxBytes, boolean logPhi) {
this.logPhiMaxBytes = logPhiMaxBytes;
this.logPhi = logPhi;
}
public int getLogPhiMaxBytes() {
return logPhiMaxBytes;
}
public String generateInvalidPayloadExceptionMessage(final byte[] hl7Bytes) {
if (hl7Bytes == null) {
return "HL7 payload is null";
}
return generateInvalidPayloadExceptionMessage(hl7Bytes, hl7Bytes.length);
}
/**
* Verifies that the HL7 payload array
* <p>
* The MLLP protocol does not allow embedded START_OF_BLOCK or END_OF_BLOCK characters. The END_OF_DATA character is
* allowed (and expected) because it is also the segment delimiter for an HL7 message
*
* @param hl7Bytes the HL7 payload to validate
*
* @return If the payload is invalid, an error message suitable for inclusion in an exception is returned.
* If the payload is valid, null is returned;
*/
public static String generateInvalidPayloadExceptionMessage(final byte[] hl7Bytes, final int length) {
if (hl7Bytes == null) {
return "HL7 payload is null";
}
if (hl7Bytes.length <= 0) {
return "HL7 payload is empty";
}
if (length > hl7Bytes.length) {
LOG.warn(
"The length specified for the HL7 payload array <{}> is greater than the actual length of the array <{}> - only validating {} bytes",
length, hl7Bytes.length, hl7Bytes.length);
}
if (hl7Bytes.length < 3 || hl7Bytes[0] != 'M' || hl7Bytes[1] != 'S' || hl7Bytes[2] != 'H') {
return String.format("The first segment of the HL7 payload {%s} is not an MSH segment",
new String(hl7Bytes, 0, Math.min(3, hl7Bytes.length)));
}
int validationLength = Math.min(length, hl7Bytes.length);
if (hl7Bytes[validationLength - 1] != MllpProtocolConstants.SEGMENT_DELIMITER
&& hl7Bytes[validationLength - 1] != MllpProtocolConstants.MESSAGE_TERMINATOR) {
String format = "The HL7 payload terminating byte [%#x] is incorrect - expected [%#x] {ASCII [<CR>]}";
return String.format(format, hl7Bytes[validationLength - 2], (byte) MllpProtocolConstants.SEGMENT_DELIMITER);
}
for (int i = 0; i < validationLength; ++i) {
switch (hl7Bytes[i]) {
case MllpProtocolConstants.START_OF_BLOCK:
return String.format("HL7 payload contains an embedded START_OF_BLOCK {%#x, ASCII <VT>} at index %d",
hl7Bytes[i], i);
case MllpProtocolConstants.END_OF_BLOCK:
return String.format("HL7 payload contains an embedded END_OF_BLOCK {%#x, ASCII <FS>} at index %d",
hl7Bytes[i], i);
default:
// continue on
}
}
return null;
}
/**
* Find the field separator indices in the Segment.
*
* NOTE: The last element of the list will be the index of the end of the segment.
*
* @param hl7MessageBytes the HL7 binary message
* @param startingIndex index of the beginning of the HL7 Segment
*
* @return List of the field separator indices, which may be empty.
*/
public static List<Integer> findFieldSeparatorIndicesInSegment(byte[] hl7MessageBytes, int startingIndex) {
List<Integer> fieldSeparatorIndices = new LinkedList<>();
if (hl7MessageBytes != null && hl7MessageBytes.length > startingIndex && hl7MessageBytes.length > 3) {
final byte fieldSeparator = hl7MessageBytes[3];
for (int i = startingIndex; i < hl7MessageBytes.length; ++i) {
if (fieldSeparator == hl7MessageBytes[i]) {
fieldSeparatorIndices.add(i);
} else if (MllpProtocolConstants.SEGMENT_DELIMITER == hl7MessageBytes[i]) {
fieldSeparatorIndices.add(i);
break;
}
}
}
return fieldSeparatorIndices;
}
/**
* Find the String value of MSH-18 (Character set).
*
* @param hl7Message the HL7 binary data to search
*
* @return the String value of MSH-18, or an empty String if not found.
*/
public String findMsh18(byte[] hl7Message, Charset charset) {
String answer = "";
if (hl7Message != null && hl7Message.length > 0) {
List<Integer> fieldSeparatorIndexes = findFieldSeparatorIndicesInSegment(hl7Message, 0);
if (fieldSeparatorIndexes.size() > 17) {
int startOfMsh19 = fieldSeparatorIndexes.get(16) + 1;
int length = fieldSeparatorIndexes.get(17) - fieldSeparatorIndexes.get(16) - 1;
if (length > 0) {
answer = new String(hl7Message, startOfMsh19, length, charset);
}
}
}
return answer;
}
public void generateAcknowledgementPayload(
MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode)
throws MllpAcknowledgementGenerationException {
generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null);
}
public void generateAcknowledgementPayload(
MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode, String msa3)
throws MllpAcknowledgementGenerationException {
if (hl7MessageBytes == null) {
throw new MllpAcknowledgementGenerationException("Null HL7 message received for parsing operation", logPhi);
}
List<Integer> fieldSeparatorIndexes = findFieldSeparatorIndicesInSegment(hl7MessageBytes, 0);
if (fieldSeparatorIndexes.isEmpty()) {
throw new MllpAcknowledgementGenerationException(
"Failed to find the end of the MSH Segment while attempting to generate response", hl7MessageBytes, logPhi);
}
if (fieldSeparatorIndexes.size() < 8) {
String exceptionMessage = String.format(
"Insufficient number of fields found in MSH to generate a response - 10 are required but %d were found",
fieldSeparatorIndexes.size() - 1);
throw new MllpAcknowledgementGenerationException(exceptionMessage, hl7MessageBytes, logPhi);
}
final byte fieldSeparator = hl7MessageBytes[3];
// Start building the MLLP Envelope
mllpSocketBuffer.openMllpEnvelope();
// Build the MSH Segment
mllpSocketBuffer.write(hl7MessageBytes, 0, fieldSeparatorIndexes.get(1)); // through MSH-2 (without trailing field separator)
writeFieldToBuffer(3, mllpSocketBuffer, hl7MessageBytes, fieldSeparatorIndexes); // MSH-5
writeFieldToBuffer(4, mllpSocketBuffer, hl7MessageBytes, fieldSeparatorIndexes); // MSH-6
writeFieldToBuffer(1, mllpSocketBuffer, hl7MessageBytes, fieldSeparatorIndexes); // MSH-3
writeFieldToBuffer(2, mllpSocketBuffer, hl7MessageBytes, fieldSeparatorIndexes); // MSH-4
// MSH-7
mllpSocketBuffer.write(fieldSeparator);
// TODO static field TIMESTAMP_FORMAT of type java.text.DateFormat isn't thread safe! Think about using ThreadLocal
mllpSocketBuffer.write(TIMESTAMP_FORMAT.format(new Date()).getBytes());
// Don't copy MSH-8
mllpSocketBuffer.write(fieldSeparator);
// Need to generate the correct MSH-9
mllpSocketBuffer.write(fieldSeparator);
mllpSocketBuffer.write("ACK".getBytes()); // MSH-9.1
int msh92start = -1;
final byte componentSeparator = hl7MessageBytes[4];
for (int j = fieldSeparatorIndexes.get(7) + 1; j < fieldSeparatorIndexes.get(8); ++j) {
if (componentSeparator == hl7MessageBytes[j]) {
msh92start = j;
break;
}
}
// MSH-9.2
if (-1 == msh92start) {
LOG.warn("Didn't find component separator for MSH-9.2 - sending ACK in MSH-9");
} else {
final String msh9Content = convertToPrintFriendlyString(hl7MessageBytes, fieldSeparatorIndexes.get(7) + 1,
fieldSeparatorIndexes.get(8));
final int[] componentIndexesInMsh9 = caretPositionsIn(msh9Content);
final int componentDiff = componentIndexesInMsh9[componentIndexesInMsh9.length - 1] - componentIndexesInMsh9[0];
if (componentIndexesInMsh9.length == 2) { //MSH-9.3 is an optional field since 2.3.1, required since 2.5; this is a non-breaking change by just checking the number of the components in the field MSH-9
mllpSocketBuffer.write(componentSeparator);
mllpSocketBuffer.write(hl7MessageBytes, msh92start + 1, componentDiff - 1);
mllpSocketBuffer.write(componentSeparator);
mllpSocketBuffer.write("ACK".getBytes()); // MSH-9.3
} else {
mllpSocketBuffer.write(hl7MessageBytes, msh92start, fieldSeparatorIndexes.get(8) - msh92start);
}
}
// MSH-10 - use the original control ID, but add an "A" as a suffix
writeFieldToBuffer(8, mllpSocketBuffer, hl7MessageBytes, fieldSeparatorIndexes);
if (fieldSeparatorIndexes.get(9) - fieldSeparatorIndexes.get(8) > 1) {
mllpSocketBuffer.write('A');
}
// MSH-10 through the end of the MSH
mllpSocketBuffer.write(hl7MessageBytes, fieldSeparatorIndexes.get(9),
fieldSeparatorIndexes.get(fieldSeparatorIndexes.size() - 1) - fieldSeparatorIndexes.get(9));
mllpSocketBuffer.write(MllpProtocolConstants.SEGMENT_DELIMITER);
// Build the MSA Segment
mllpSocketBuffer.write("MSA".getBytes(), 0, 3);
mllpSocketBuffer.write(fieldSeparator);
mllpSocketBuffer.write(acknowledgementCode.getBytes(), 0, 2);
writeFieldToBuffer(8, mllpSocketBuffer, hl7MessageBytes, fieldSeparatorIndexes); // MSH-10 => MSA-2
if (msa3 != null && !msa3.isEmpty()) {
mllpSocketBuffer.write(fieldSeparator);
mllpSocketBuffer.write(msa3.getBytes());
}
mllpSocketBuffer.write(MllpProtocolConstants.SEGMENT_DELIMITER);
// Close the MLLP Envelope
mllpSocketBuffer.write(MllpProtocolConstants.PAYLOAD_TERMINATOR);
return;
}
public String convertToPrintFriendlyString(String phiString) {
if (null == phiString) {
return NULL_REPLACEMENT_VALUE;
} else if (phiString.isEmpty()) {
return EMPTY_REPLACEMENT_VALUE;
}
int conversionLength = (logPhiMaxBytes > 0) ? Integer.min(phiString.length(), logPhiMaxBytes) : phiString.length();
StringBuilder builder = new StringBuilder(conversionLength + STRING_BUFFER_PAD_SIZE);
for (int i = 0; i < conversionLength; ++i) {
appendCharacterAsPrintFriendlyString(builder, phiString.charAt(i));
}
return builder.toString();
}
public String convertToPrintFriendlyString(byte[] phiBytes) {
return bytesToPrintFriendlyStringBuilder(phiBytes).toString();
}
/**
* Convert a PHI byte[] to a String, replacing specific non-printable characters with readable strings.
*
* NOTE: this conversion uses the default character set, so not all characters my convert correctly.
*
* @param phiBytes the PHI byte[] to log
* @param startPosition the starting position/index of the data
* @param endPosition the ending position/index of the data - will not be included in String
*
* @return a String representation of the byte[]
*/
public String convertToPrintFriendlyString(byte[] phiBytes, int startPosition, int endPosition) {
return bytesToPrintFriendlyStringBuilder(phiBytes, startPosition, endPosition).toString();
}
/**
* Convert a PHI byte[] to a StringBuilder, replacing specific non-printable characters with readable strings.
*
* NOTE: this conversion uses the default character set, so not all characters my convert correctly.
*
* @param phiBytes the PHI byte[] to log
*
* @return
*/
public StringBuilder bytesToPrintFriendlyStringBuilder(byte[] phiBytes) {
return bytesToPrintFriendlyStringBuilder(phiBytes, 0, phiBytes != null ? phiBytes.length : -1);
}
/**
* Convert a PHI byte[] to a StringBuilder, replacing specific non-printable characters with readable strings.
*
* NOTE: this conversion uses the default character set, so not all characters my convert correctly.
*
* @param phiBytes the PHI byte[] to log
* @param startPosition the starting position/index of the data
* @param endPosition the ending position/index of the data - will not be included in StringBuilder
*
* @return a String representation of the byte[]
*/
public StringBuilder bytesToPrintFriendlyStringBuilder(
byte[] phiBytes, int startPosition, int endPosition) {
StringBuilder answer = new StringBuilder();
appendBytesAsPrintFriendlyString(answer, phiBytes, startPosition, endPosition);
return answer;
}
public void appendBytesAsPrintFriendlyString(StringBuilder builder, byte[] phiBytes) {
appendBytesAsPrintFriendlyString(builder, phiBytes, 0, phiBytes != null ? phiBytes.length : 0);
}
/**
* Append a PHI byte[] to a StringBuilder, replacing specific non-printable characters with readable strings.
*
* NOTE: this conversion uses the default character set, so not all characters my convert correctly.
*
* @param phiBytes the PHI byte[] to log
* @param startPosition the starting position/index of the data
* @param endPosition the ending position/index of the data - will not be included in String
*/
public void appendBytesAsPrintFriendlyString(
StringBuilder builder, byte[] phiBytes, int startPosition, int endPosition) {
if (builder == null) {
throw new IllegalArgumentException("StringBuilder cannot be null");
}
if (null == phiBytes) {
builder.append(NULL_REPLACEMENT_VALUE);
} else if (phiBytes.length == 0) {
builder.append(EMPTY_REPLACEMENT_VALUE);
} else if (startPosition <= endPosition) {
if (startPosition < 0) {
startPosition = 0;
}
if (startPosition < phiBytes.length) {
if (endPosition >= -1) {
if (endPosition == -1 || endPosition >= phiBytes.length) {
endPosition = phiBytes.length;
}
int length = endPosition - startPosition;
if (length > 0) {
int conversionLength = (logPhiMaxBytes > 0) ? Integer.min(length, logPhiMaxBytes) : length;
if (builder.capacity() - builder.length() < conversionLength + STRING_BUFFER_PAD_SIZE) {
builder.ensureCapacity(builder.length() + conversionLength + STRING_BUFFER_PAD_SIZE);
}
for (int i = 0; i < conversionLength; ++i) {
appendCharacterAsPrintFriendlyString(builder, (char) phiBytes[startPosition + i]);
}
}
}
}
}
}
static void appendCharacterAsPrintFriendlyString(StringBuilder builder, char c) {
if (CHARACTER_REPLACEMENTS.containsKey(c)) {
builder.append(CHARACTER_REPLACEMENTS.get(c));
} else {
builder.append(c);
}
}
public static String getCharacterAsPrintFriendlyString(char c) {
if (CHARACTER_REPLACEMENTS.containsKey(c)) {
return CHARACTER_REPLACEMENTS.get(c);
}
return String.valueOf(c);
}
private int[] caretPositionsIn(String data) {
return java.util.stream.IntStream.range(0, data.length())
.filter(i -> data.charAt(i) == '^')
.toArray();
}
/**
* Copy a field from the HL7 Message Bytes to the supplied MllpSocketBuffer.
*
* NOTE: Internal function - no error checking
*
* @param mllpSocketBuffer the destination for the field
* @param hl7MessageBytes the HL7 message bytes
* @param fieldSeparatorIndexes the list of the indices of the field separators
*/
private static void writeFieldToBuffer(
int fieldNumber, MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, List<Integer> fieldSeparatorIndexes) {
mllpSocketBuffer.write(hl7MessageBytes, fieldSeparatorIndexes.get(fieldNumber),
fieldSeparatorIndexes.get(fieldNumber + 1) - fieldSeparatorIndexes.get(fieldNumber));
}
}
| Hl7Util |
java | apache__camel | test-infra/camel-test-infra-aws-v2/src/test/java/org/apache/camel/test/infra/aws2/services/AWSTestServices.java | {
"start": 1411,
"end": 1539
} | class ____ extends AWSEC2LocalContainerInfraService implements AWSService {
}
public static | AWSEC2LocalContainerTestService |
java | quarkusio__quarkus | extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/properties/ResourceProperties.java | {
"start": 195,
"end": 3010
} | class ____ {
private final boolean exposed;
private final String path;
private final boolean paged;
private final boolean hal;
private final String halCollectionName;
private final String[] rolesAllowed;
private final boolean isAuthenticated;
private final Collection<AnnotationInstance> classAnnotations;
private final Map<String, MethodProperties> methodProperties;
public ResourceProperties(boolean exposed, String path, boolean paged, boolean hal, String halCollectionName,
String[] rolesAllowed, boolean isAuthenticated, Collection<AnnotationInstance> classAnnotations,
Map<String, MethodProperties> methodProperties) {
this.exposed = exposed;
this.path = path;
this.paged = paged;
this.hal = hal;
this.halCollectionName = halCollectionName;
this.rolesAllowed = rolesAllowed;
this.isAuthenticated = isAuthenticated;
this.classAnnotations = classAnnotations;
this.methodProperties = methodProperties;
}
public boolean isExposed() {
if (exposed) {
return true;
}
// If at least one method is explicitly exposed, resource should also be exposed
for (MethodProperties properties : this.methodProperties.values()) {
if (properties.isExposed()) {
return true;
}
}
return false;
}
public boolean isExposed(String methodName) {
if (methodProperties.containsKey(methodName)) {
return methodProperties.get(methodName).isExposed();
}
return exposed;
}
public String getPath() {
return path;
}
public String getPath(String methodName) {
if (methodProperties.containsKey(methodName)) {
return methodProperties.get(methodName).getPath();
}
return "";
}
public boolean isPaged() {
return paged;
}
public boolean isHal() {
return hal;
}
public String getHalCollectionName() {
return halCollectionName;
}
public String[] getRolesAllowed(String methodName) {
if (methodProperties.containsKey(methodName)) {
return methodProperties.get(methodName).getRolesAllowed();
}
return rolesAllowed;
}
public boolean isAuthenticated() {
return isAuthenticated;
}
public Collection<AnnotationInstance> getClassAnnotations() {
return classAnnotations;
}
public Collection<AnnotationInstance> getMethodAnnotations(String methodName) {
if (methodProperties.containsKey(methodName)) {
return methodProperties.get(methodName).getMethodAnnotations();
}
return Collections.emptyList();
}
}
| ResourceProperties |
java | spring-projects__spring-boot | module/spring-boot-cache/src/main/java/org/springframework/boot/cache/metrics/Cache2kCacheMeterBinderProvider.java | {
"start": 1004,
"end": 1265
} | class ____ implements CacheMeterBinderProvider<SpringCache2kCache> {
@Override
public MeterBinder getMeterBinder(SpringCache2kCache cache, Iterable<Tag> tags) {
return new Cache2kCacheMetrics(cache.getNativeCache(), tags);
}
}
| Cache2kCacheMeterBinderProvider |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/discriminatedcollections/TempTest.java | {
"start": 917,
"end": 4875
} | class ____ {
@BeforeEach
public void prepareTestData(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final Client c = new Client( 1, "Gavin" );
final DebitAccount da = new DebitAccount( 10, c );
final CreditAccount ca = new CreditAccount( 11, c );
c.getDebitAccounts().add( da );
c.getCreditAccounts().add( ca );
session.persist( c );
} );
}
@AfterEach
public void dropTestData(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void findClientTest(SessionFactoryScope scope) {
scope.inSession(
session -> {
final Client client = session.find( Client.class, 1 );
assertEquals( 1, client.getDebitAccounts().size() );
assertEquals( 1, client.getCreditAccounts().size() );
assertNotEquals(
client.getDebitAccounts().iterator().next().getId(),
client.getCreditAccounts().iterator().next().getId()
);
}
);
}
@Test
public void hqlFromClientTest(SessionFactoryScope scope) {
scope.inSession(
session -> {
Client client = session.createQuery( "from Client", Client.class ).getSingleResult();
assertEquals( 1, client.getDebitAccounts().size() );
assertEquals( 1, client.getCreditAccounts().size() );
assertNotEquals(
client.getDebitAccounts().iterator().next().getId(),
client.getCreditAccounts().iterator().next().getId()
);
}
);
}
@Test
public void hqlFromClientFetchDebitTest(SessionFactoryScope scope) {
scope.inSession(
session -> {
Client client = session.createQuery( "from Client c left join fetch c.debitAccounts", Client.class )
.getSingleResult();
assertEquals( 1, client.getDebitAccounts().size() );
assertEquals( 1, client.getCreditAccounts().size() );
assertNotEquals(
client.getDebitAccounts().iterator().next().getId(),
client.getCreditAccounts().iterator().next().getId()
);
}
);
}
@Test
public void hqlFromClientFetchDebitAndCreditTest(SessionFactoryScope scope) {
scope.inSession(
session -> {
Client client = session.createQuery(
"from Client c left join fetch c.debitAccounts left join fetch c.creditAccounts",
Client.class
).getSingleResult();
assertEquals( 1, client.getDebitAccounts().size() );
assertEquals( 1, client.getCreditAccounts().size() );
assertNotEquals(
client.getDebitAccounts().iterator().next().getId(),
client.getCreditAccounts().iterator().next().getId()
);
}
);
}
@Test
public void criteriaFromClientFetchCreditTest(SessionFactoryScope scope) {
scope.inSession(
session -> {
JpaCriteriaQuery<Client> query = scope.getSessionFactory()
.getCriteriaBuilder()
.createQuery( Client.class );
query.from( Client.class ).fetch( Client_.creditAccounts, JoinType.LEFT );
Client client = session.createQuery( query ).getSingleResult();
assertEquals( 1, client.getDebitAccounts().size() );
assertEquals( 1, client.getCreditAccounts().size() );
assertNotEquals(
client.getDebitAccounts().iterator().next().getId(),
client.getCreditAccounts().iterator().next().getId()
);
}
);
}
@Test
public void hqlSelectAccountTest(SessionFactoryScope scope) {
scope.inSession(
session -> {
List<Object[]> clients = session.createQuery( "select c, da from Client c inner join c.debitAccounts da", Object[].class)
.getResultList();
assertEquals( 1, clients.size() );
assertTrue( clients.get(0)[1] instanceof DebitAccount );
List<Object[]> accounts = session.createQuery( "select ca, da from Client c inner join c.creditAccounts ca inner join c.debitAccounts da", Object[].class)
.getResultList();
assertEquals( 1, accounts.size() );
assertTrue( accounts.get(0)[0] instanceof CreditAccount );
assertTrue( accounts.get(0)[1] instanceof DebitAccount );
}
);
}
}
| TempTest |
java | quarkusio__quarkus | extensions/elytron-security/runtime/src/main/java/io/quarkus/elytron/security/runtime/ElytronTrustedIdentityProvider.java | {
"start": 991,
"end": 3459
} | class ____ implements IdentityProvider<TrustedAuthenticationRequest> {
private static final Logger log = Logger.getLogger(ElytronTrustedIdentityProvider.class);
@Inject
SecurityDomain domain;
@Override
public Class<TrustedAuthenticationRequest> getRequestType() {
return TrustedAuthenticationRequest.class;
}
@Override
public Uni<SecurityIdentity> authenticate(TrustedAuthenticationRequest request,
AuthenticationRequestContext context) {
return context.runBlocking(new Supplier<SecurityIdentity>() {
@Override
public SecurityIdentity get() {
org.wildfly.security.auth.server.SecurityIdentity result;
try {
RealmIdentity id = domain.getIdentity(request.getPrincipal());
if (!id.exists()) {
return null;
}
PasswordCredential cred = id.getCredential(PasswordCredential.class);
try (ServerAuthenticationContext ac = domain.createNewAuthenticationContext()) {
ac.setAuthenticationName(request.getPrincipal());
if (cred != null) {
ac.addPrivateCredential(cred);
}
ac.authorize();
result = ac.getAuthorizedIdentity();
if (result == null) {
throw new AuthenticationFailedException();
}
QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
for (Attributes.Entry entry : result.getAttributes().entries()) {
builder.addAttribute(entry.getKey(), entry);
}
builder.setPrincipal(result.getPrincipal());
for (String i : result.getRoles()) {
builder.addRole(i);
}
return builder.build();
}
} catch (RealmUnavailableException e) {
throw new RuntimeException(e);
} catch (SecurityException e) {
log.debug("Authentication failed", e);
throw new AuthenticationFailedException(e);
}
}
});
}
}
| ElytronTrustedIdentityProvider |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultProjectBuilder.java | {
"start": 2254,
"end": 8219
} | class ____ implements ProjectBuilder {
private final org.apache.maven.project.ProjectBuilder builder;
@Inject
public DefaultProjectBuilder(org.apache.maven.project.ProjectBuilder builder) {
this.builder = builder;
}
@SuppressWarnings("MethodLength")
@Nonnull
@Override
public ProjectBuilderResult build(ProjectBuilderRequest request)
throws ProjectBuilderException, IllegalArgumentException {
InternalSession session = InternalSession.from(request.getSession());
return session.request(request, this::doBuild);
}
protected ProjectBuilderResult doBuild(ProjectBuilderRequest request)
throws ProjectBuilderException, IllegalArgumentException {
InternalMavenSession session = InternalMavenSession.from(request.getSession());
RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(request.getSession(), request);
try {
List<ArtifactRepository> repositories = session.toArtifactRepositories(
request.getRepositories() != null ? request.getRepositories() : session.getRemoteRepositories());
ProjectBuildingRequest req = new DefaultProjectBuildingRequest()
.setRepositorySession(session.getSession())
.setRemoteRepositories(repositories)
.setPluginArtifactRepositories(repositories)
.setProcessPlugins(request.isProcessPlugins());
ProjectBuildingResult res;
if (request.getPath().isPresent()) {
Path path = request.getPath().get();
res = builder.build(path.toFile(), req);
} else if (request.getSource().isPresent()) {
Source source = request.getSource().get();
ModelSource2 modelSource = new SourceWrapper(source);
res = builder.build(modelSource, req);
} else {
throw new IllegalArgumentException("Invalid request");
}
return new ProjectBuilderResult() {
@Override
public ProjectBuilderRequest getRequest() {
return request;
}
@Nonnull
@Override
public String getProjectId() {
return res.getProjectId();
}
@Nonnull
@Override
public Optional<Path> getPomFile() {
return Optional.ofNullable(res.getPomFile()).map(File::toPath);
}
@Nonnull
@Override
public Optional<Project> getProject() {
return Optional.ofNullable(session.getProject(res.getProject()));
}
@Nonnull
@Override
public Collection<BuilderProblem> getProblems() {
return new MappedCollection<>(res.getProblems(), this::toProblem);
}
private BuilderProblem toProblem(ModelProblem problem) {
return new BuilderProblem() {
@Override
public String getSource() {
return problem.getSource();
}
@Override
public int getLineNumber() {
return problem.getLineNumber();
}
@Override
public int getColumnNumber() {
return problem.getColumnNumber();
}
@Override
public String getLocation() {
StringBuilder buffer = new StringBuilder(256);
if (!getSource().isEmpty()) {
buffer.append(getSource());
}
if (getLineNumber() > 0) {
if (!buffer.isEmpty()) {
buffer.append(", ");
}
buffer.append("line ").append(getLineNumber());
}
if (getColumnNumber() > 0) {
if (!buffer.isEmpty()) {
buffer.append(", ");
}
buffer.append("column ").append(getColumnNumber());
}
return buffer.toString();
}
@Override
public Exception getException() {
return problem.getException();
}
@Override
public String getMessage() {
return problem.getMessage();
}
@Override
public Severity getSeverity() {
return Severity.valueOf(problem.getSeverity().name());
}
};
}
@Nonnull
@Override
public Optional<DependencyResolverResult> getDependencyResolverResult() {
return Optional.ofNullable(res.getDependencyResolutionResult())
.map(r -> new DefaultDependencyResolverResult(
null, r.getCollectionErrors(), session.getNode(r.getDependencyGraph()), 0));
}
};
} catch (ProjectBuildingException e) {
throw new ProjectBuilderException("Unable to build project", e);
} finally {
RequestTraceHelper.exit(trace);
}
}
private static | DefaultProjectBuilder |
java | quarkusio__quarkus | extensions/smallrye-metrics/deployment/src/test/java/io/quarkus/smallrye/metrics/registration/DefaultMethodTest.java | {
"start": 686,
"end": 2520
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(A.class, B.class, Y.class, C.class,
D.class, ClashA.class, I.class, ClashB.class));
@Inject
B b;
@Inject
@Named("C")
C c;
@Inject
D d;
@Inject
Y y;
@Inject
ClashA clashA;
@Inject
MetricRegistry metricRegistry;
@BeforeEach
void cleanup() {
// reset all counters to zero
metricRegistry.getCounters().keySet().forEach(metricID -> {
metricRegistry.remove(metricID);
metricRegistry.counter(metricID);
});
}
@Test
public void defaultMethodInherited() {
b.foo();
b.foo();
Assertions.assertEquals(2L, metricRegistry.getCounters().get(new MetricID("B.foo")).getCount());
}
@Test
public void defaultMethodOverriddenByMetricBean() {
c.foo();
c.foo();
Assertions.assertEquals(2L, metricRegistry.getCounters().get(new MetricID("C.foo")).getCount());
}
@Test
public void defaultMethodOverriddenBySuperclass() {
d.foo();
d.foo();
Assertions.assertEquals(2L, metricRegistry.getCounters().get(new MetricID("D.foo")).getCount());
}
@Test
public void defaultMethodOverriddenByAnotherInterface() {
y.foo();
y.foo();
Assertions.assertEquals(2L, metricRegistry.getCounters().get(new MetricID("Y.foo")).getCount());
}
@Test
public void twoMethodsWithTheSameNameAreInherited() {
clashA.doSomething();
clashA.doSomething();
Assertions.assertEquals(2L, metricRegistry.getCounters().get(new MetricID("ClashA.doSomething")).getCount());
}
| DefaultMethodTest |
java | spring-projects__spring-boot | loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ExtractCommand.java | {
"start": 14748,
"end": 16401
} | class ____ implements FileResolver {
private final Layers layers;
private final Set<String> layersToExtract;
private final File directory;
private final String applicationFilename;
LayersFileResolver(File directory, Layers layers, Set<String> layersToExtract, String applicationFilename) {
this.layers = layers;
this.layersToExtract = layersToExtract;
this.directory = directory;
this.applicationFilename = applicationFilename;
}
@Override
public void createDirectories() throws IOException {
for (String layer : this.layers) {
if (shouldExtractLayer(layer)) {
mkdirs(getLayerDirectory(layer));
}
}
}
@Override
public @Nullable File resolve(String originalName, String newName) throws IOException {
String layer = this.layers.getLayer(originalName);
if (shouldExtractLayer(layer)) {
File directory = getLayerDirectory(layer);
return assertFileIsContainedInDirectory(directory, new File(directory, newName), newName);
}
return null;
}
@Override
public @Nullable File resolveApplication() throws IOException {
String layer = this.layers.getApplicationLayerName();
if (shouldExtractLayer(layer)) {
File directory = getLayerDirectory(layer);
return assertFileIsContainedInDirectory(directory, new File(directory, this.applicationFilename),
this.applicationFilename);
}
return null;
}
private File getLayerDirectory(String layer) {
return new File(this.directory, layer);
}
private boolean shouldExtractLayer(String layer) {
return this.layersToExtract.isEmpty() || this.layersToExtract.contains(layer);
}
}
}
| LayersFileResolver |
java | apache__camel | core/camel-console/src/main/java/org/apache/camel/impl/console/TypeConverterConsole.java | {
"start": 1171,
"end": 3710
} | class ____ extends AbstractDevConsole {
public TypeConverterConsole() {
super("camel", "type-converters", "Type Converters", "Camel Type Converter information");
}
@Override
protected String doCallText(Map<String, Object> options) {
StringBuilder sb = new StringBuilder();
TypeConverterRegistry reg = getCamelContext().getTypeConverterRegistry();
sb.append(String.format("\n Converters: %s", reg.size()));
sb.append(String.format("\n Exists: %s", reg.getTypeConverterExists().name()));
sb.append(String.format("\n Exists LoggingLevel: %s", reg.getTypeConverterExistsLoggingLevel()));
final TypeConverterRegistry.Statistics statistics = reg.getStatistics();
statistics.computeIfEnabled(statistics::getAttemptCounter, v -> sb.append(String.format("\n Attempts: %s", v)));
statistics.computeIfEnabled(statistics::getHitCounter, v -> sb.append(String.format("\n Hit: %s", v)));
statistics.computeIfEnabled(statistics::getMissCounter, v -> sb.append(String.format("\n Miss: %s", v)));
statistics.computeIfEnabled(statistics::getFailedCounter, v -> sb.append(String.format("\n Failed: %s", v)));
statistics.computeIfEnabled(statistics::getNoopCounter, v -> sb.append(String.format("\n Noop: %s", v)));
return sb.toString();
}
@Override
protected JsonObject doCallJson(Map<String, Object> options) {
JsonObject root = new JsonObject();
TypeConverterRegistry reg = getCamelContext().getTypeConverterRegistry();
root.put("size", reg.size());
root.put("exists", reg.getTypeConverterExists().name());
root.put("existsLoggingLevel", reg.getTypeConverterExistsLoggingLevel().name());
final TypeConverterRegistry.Statistics statistics = reg.getStatistics();
JsonObject props = new JsonObject();
statistics.computeIfEnabled(statistics::getAttemptCounter, v -> props.put("attemptCounter", v));
statistics.computeIfEnabled(statistics::getHitCounter, v -> props.put("hitCounter", v));
statistics.computeIfEnabled(statistics::getMissCounter, v -> props.put("missCounter", v));
statistics.computeIfEnabled(statistics::getFailedCounter, v -> props.put("failedCounter", v));
statistics.computeIfEnabled(statistics::getFailedCounter, v -> props.put("noopCounter", v));
if (!props.isEmpty()) {
root.put("statistics", props);
}
return root;
}
}
| TypeConverterConsole |
java | elastic__elasticsearch | modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/BengaliAnalyzerProvider.java | {
"start": 883,
"end": 1453
} | class ____ extends AbstractIndexAnalyzerProvider<BengaliAnalyzer> {
private final BengaliAnalyzer analyzer;
BengaliAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(name);
analyzer = new BengaliAnalyzer(
Analysis.parseStopWords(env, settings, BengaliAnalyzer.getDefaultStopSet()),
Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET)
);
}
@Override
public BengaliAnalyzer get() {
return this.analyzer;
}
}
| BengaliAnalyzerProvider |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/inlineme/InlinabilityResult.java | {
"start": 14072,
"end": 16291
} | enum ____ {
PRIVATE,
PACKAGE,
PROTECTED,
PUBLIC;
}
private static Visibility getVisibility(Symbol symbol) {
if (symbol.getModifiers().contains(Modifier.PRIVATE)) {
return Visibility.PRIVATE;
} else if (symbol.getModifiers().contains(Modifier.PROTECTED)) {
return Visibility.PROTECTED;
} else if (symbol.getModifiers().contains(Modifier.PUBLIC)) {
return Visibility.PUBLIC;
} else {
return Visibility.PACKAGE;
}
}
private static boolean hasArgumentInPossiblyNonExecutedPosition(
MethodTree methodTree, ExpressionTree statement) {
AtomicBoolean paramReferred = new AtomicBoolean(false);
ImmutableSet<VarSymbol> params =
methodTree.getParameters().stream().map(ASTHelpers::getSymbol).collect(toImmutableSet());
new TreeScanner<Void, Void>() {
Tree currentContextTree = null;
@Override
public Void visitLambdaExpression(LambdaExpressionTree lambda, Void unused) {
Tree lastContext = currentContextTree;
currentContextTree = lambda;
scan(lambda.getBody(), null);
currentContextTree = lastContext;
return null;
}
@Override
public Void visitConditionalExpression(ConditionalExpressionTree conditional, Void unused) {
scan(conditional.getCondition(), null);
// If the variables show up in the left or right side, they may conditionally not be
// executed.
Tree lastContext = currentContextTree;
currentContextTree = conditional;
scan(conditional.getTrueExpression(), null);
scan(conditional.getFalseExpression(), null);
currentContextTree = lastContext;
return null;
}
@Override
public Void visitIdentifier(IdentifierTree identifier, Void unused) {
// If the lambda captures method parameters, inlining the method body can change the
// timing of the evaluation of the arguments.
if (currentContextTree != null && params.contains(getSymbol(identifier))) {
paramReferred.set(true);
}
return super.visitIdentifier(identifier, null);
}
}.scan(statement, null);
return paramReferred.get();
}
}
| Visibility |
java | apache__flink | flink-core/src/main/java/org/apache/flink/util/ExceptionUtils.java | {
"start": 1855,
"end": 5239
} | class ____ {
/** The stringified representation of a null exception reference. */
public static final String STRINGIFIED_NULL_EXCEPTION = "(null)";
/**
* Makes a string representation of the exception's stack trace, or "(null)", if the exception
* is null.
*
* <p>This method makes a best effort and never fails.
*
* @param e The exception to stringify.
* @return A string with exception name and call stack.
*/
public static String stringifyException(final Throwable e) {
if (e == null) {
return STRINGIFIED_NULL_EXCEPTION;
}
try {
StringWriter stm = new StringWriter();
PrintWriter wrt = new PrintWriter(stm);
e.printStackTrace(wrt);
wrt.close();
return stm.toString();
} catch (Throwable t) {
return e.getClass().getName() + " (error while printing stack trace)";
}
}
/**
* Checks whether the given exception indicates a situation that may leave the JVM in a
* corrupted state, meaning a state where continued normal operation can only be guaranteed via
* clean process restart.
*
* <p>Currently considered fatal exceptions are Virtual Machine errors indicating that the JVM
* is corrupted, like {@link InternalError}, {@link UnknownError}, and {@link
* java.util.zip.ZipError} (a special case of InternalError). The {@link ThreadDeath} exception
* is also treated as a fatal error, because when a thread is forcefully stopped, there is a
* high chance that parts of the system are in an inconsistent state.
*
* @param t The exception to check.
* @return True, if the exception is considered fatal to the JVM, false otherwise.
*/
public static boolean isJvmFatalError(Throwable t) {
return (t instanceof InternalError)
|| (t instanceof UnknownError)
|| (t instanceof ThreadDeath);
}
/**
* Checks whether the given exception indicates a situation that may leave the JVM in a
* corrupted state, or an out-of-memory error.
*
* <p>See {@link ExceptionUtils#isJvmFatalError(Throwable)} for a list of fatal JVM errors. This
* method additionally classifies the {@link OutOfMemoryError} as fatal, because it may occur in
* any thread (not the one that allocated the majority of the memory) and thus is often not
* recoverable by destroying the particular thread that threw the exception.
*
* @param t The exception to check.
* @return True, if the exception is fatal to the JVM or and OutOfMemoryError, false otherwise.
*/
public static boolean isJvmFatalOrOutOfMemoryError(Throwable t) {
return isJvmFatalError(t) || t instanceof OutOfMemoryError;
}
/**
* Tries to enrich OutOfMemoryErrors being part of the passed root Throwable's cause tree.
*
* <p>This method improves error messages for direct and metaspace {@link OutOfMemoryError}. It
* adds description about the possible causes and ways of resolution.
*
* @param root The Throwable of which the cause tree shall be traversed.
* @param jvmMetaspaceOomNewErrorMessage The message being used for JVM metaspace-related
* OutOfMemoryErrors. Passing <code>null</code> will disable handling this | ExceptionUtils |
java | netty__netty | transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueDomainDatagramUnicastTest.java | {
"start": 1648,
"end": 6575
} | class ____ extends DatagramUnicastTest {
@Test
void testBind(TestInfo testInfo) throws Throwable {
run(testInfo, new Runner<Bootstrap, Bootstrap>() {
@Override
public void run(Bootstrap bootstrap, Bootstrap bootstrap2) throws Throwable {
testBind(bootstrap2);
}
});
}
private void testBind(Bootstrap cb) throws Throwable {
Channel channel = null;
try {
channel = cb.handler(new ChannelInboundHandlerAdapter())
.bind(newSocketAddress()).sync().channel();
assertThat(channel.localAddress()).isNotNull()
.isInstanceOf(DomainSocketAddress.class);
} finally {
closeChannel(channel);
}
}
@Override
protected boolean supportDisconnect() {
return false;
}
@Override
protected boolean isConnected(Channel channel) {
return ((DomainDatagramChannel) channel).isConnected();
}
@Override
protected List<TestsuitePermutation.BootstrapComboFactory<Bootstrap, Bootstrap>> newFactories() {
return KQueueSocketTestPermutation.INSTANCE.domainDatagram();
}
@Override
protected SocketAddress newSocketAddress() {
return KQueueSocketTestPermutation.newSocketAddress();
}
@Override
protected Channel setupClientChannel(Bootstrap cb, final byte[] bytes, final CountDownLatch latch,
final AtomicReference<Throwable> errorRef) throws Throwable {
cb.handler(new SimpleChannelInboundHandler<DomainDatagramPacket>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, DomainDatagramPacket msg) {
try {
ByteBuf buf = msg.content();
assertEquals(bytes.length, buf.readableBytes());
for (int i = 0; i < bytes.length; i++) {
assertEquals(bytes[i], buf.getByte(buf.readerIndex() + i));
}
assertEquals(ctx.channel().localAddress(), msg.recipient());
} finally {
latch.countDown();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
errorRef.compareAndSet(null, cause);
}
});
return cb.bind(newSocketAddress()).sync().channel();
}
@Override
protected Channel setupServerChannel(Bootstrap sb, final byte[] bytes, final SocketAddress sender,
final CountDownLatch latch, final AtomicReference<Throwable> errorRef,
final boolean echo) throws Throwable {
sb.handler(new SimpleChannelInboundHandler<DomainDatagramPacket>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, DomainDatagramPacket msg) {
try {
if (sender == null) {
assertNotNull(msg.sender());
} else {
assertEquals(sender, msg.sender());
}
ByteBuf buf = msg.content();
assertEquals(bytes.length, buf.readableBytes());
for (int i = 0; i < bytes.length; i++) {
assertEquals(bytes[i], buf.getByte(buf.readerIndex() + i));
}
assertEquals(ctx.channel().localAddress(), msg.recipient());
if (echo) {
ctx.writeAndFlush(new DomainDatagramPacket(buf.retainedDuplicate(), msg.sender()));
}
} finally {
latch.countDown();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
errorRef.compareAndSet(null, cause);
}
});
return sb.bind(newSocketAddress()).sync().channel();
}
@Override
protected ChannelFuture write(Channel cc, ByteBuf buf, SocketAddress remote, WrapType wrapType) {
switch (wrapType) {
case DUP:
return cc.write(new DomainDatagramPacket(buf.retainedDuplicate(), (DomainSocketAddress) remote));
case SLICE:
return cc.write(new DomainDatagramPacket(buf.retainedSlice(), (DomainSocketAddress) remote));
case READ_ONLY:
return cc.write(new DomainDatagramPacket(buf.retain().asReadOnly(), (DomainSocketAddress) remote));
case NONE:
return cc.write(new DomainDatagramPacket(buf.retain(), (DomainSocketAddress) remote));
default:
throw new Error("Unexpected wrap type: " + wrapType);
}
}
}
| KQueueDomainDatagramUnicastTest |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringEnrichVariableTest.java | {
"start": 1039,
"end": 1295
} | class ____ extends EnrichVariableTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/EnrichVariableTest.xml");
}
}
| SpringEnrichVariableTest |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/utils/LogicalTypeCasts.java | {
"start": 5198,
"end": 6311
} | class ____ to be compatible with the SQL standard. It is inspired by Apache Calcite's
* {@code SqlTypeUtil#canCastFrom} method.
*
* <p>Casts can be performed in two ways: implicit or explicit.
*
* <p>Explicit casts correspond to the SQL cast specification and represent the logic behind a
* {@code CAST(sourceType AS targetType)} operation. For example, it allows for converting most
* types of the {@link LogicalTypeFamily#PREDEFINED} family to types of the {@link
* LogicalTypeFamily#CHARACTER_STRING} family.
*
* <p>Implicit casts are used for safe type widening and type generalization (finding a common
* supertype for a set of types) without loss of information. Implicit casts are similar to the Java
* semantics (e.g. this is not possible: {@code int x = (String) z}).
*
* <p>Conversions that are defined by the {@link LogicalType} (e.g. interpreting a {@link DateType}
* as integer value) are not considered here. They are an internal bridging feature that is not
* standard compliant. If at all, {@code CONVERT} methods should make such conversions available.
*/
@Internal
public final | aims |
java | quarkusio__quarkus | independent-projects/tools/devtools-common/src/main/java/io/quarkus/cli/plugin/PluginManagerSettings.java | {
"start": 355,
"end": 3742
} | class ____ {
public static String DEFAULT_PLUGIN_PREFIX = "quarkus";
public static String FALLBACK_REMOTE_JBANG_CATALOG = "quarkusio";
public static String[] DEFAULT_REMOTE_JBANG_CATALOGS = new String[0];
public static Function<Path, Path> DEFAULT_RELATIVE_PATH_FUNC = p -> p.resolve(".quarkus").resolve("cli").resolve("plugins")
.resolve("quarkus-cli-catalog.json");
private final boolean interactiveMode;
private final String pluginPrefix;
private final String fallbackJBangCatalog;
private final String[] remoteJBangCatalogs;
private final Function<Path, Path> toRelativePath;
public PluginManagerSettings(boolean interactiveMode, String pluginPrefix, String fallbackJBangCatalog,
String[] remoteJBangCatalogs,
Function<Path, Path> toRelativePath) {
this.interactiveMode = interactiveMode;
this.pluginPrefix = pluginPrefix;
this.fallbackJBangCatalog = fallbackJBangCatalog;
this.remoteJBangCatalogs = remoteJBangCatalogs;
this.toRelativePath = toRelativePath;
}
public static PluginManagerSettings defaultSettings() {
return new PluginManagerSettings(false, DEFAULT_PLUGIN_PREFIX, FALLBACK_REMOTE_JBANG_CATALOG,
DEFAULT_REMOTE_JBANG_CATALOGS,
DEFAULT_RELATIVE_PATH_FUNC);
}
public PluginManagerSettings withPluignPrefix(String pluginPrefix) {
return new PluginManagerSettings(interactiveMode, pluginPrefix, fallbackJBangCatalog, remoteJBangCatalogs,
toRelativePath);
}
public PluginManagerSettings withCatalogs(Set<String> remoteJBangCatalogs) {
return new PluginManagerSettings(interactiveMode, pluginPrefix, fallbackJBangCatalog,
remoteJBangCatalogs.toArray(new String[0]), toRelativePath);
}
public PluginManagerSettings withCatalogs(String... remoteJBangCatalogs) {
return new PluginManagerSettings(interactiveMode, pluginPrefix, fallbackJBangCatalog, remoteJBangCatalogs,
toRelativePath);
}
public PluginManagerSettings withInteractivetMode(boolean interactiveMode) {
return new PluginManagerSettings(interactiveMode, pluginPrefix, fallbackJBangCatalog, remoteJBangCatalogs,
toRelativePath);
}
/**
* The prefix of the {@link Plugin}.
* This value is used to strip the prefix for the location
* when creating the name.
*
* @return the prefix.
*/
public String getPluginPrefix() {
return pluginPrefix;
}
/**
* The name of the fallback JBang catalogs to get plugins from.
*
* @return the name of the catalog.
*/
public String getFallbackJBangCatalog() {
return fallbackJBangCatalog;
}
/**
* The names of the JBang catalogs to get plugins from.
*
* @return the name of the catalog.
*/
public String[] getRemoteJBangCatalogs() {
return remoteJBangCatalogs;
}
public boolean isInteractiveMode() {
return interactiveMode;
}
/**
* A {@link Function} from getting the relative path to the catalog.
* For example: `~ -> ~/.quarkus/cli/plugins/quarkus-cli-catalog.json`.
*
* @return the path.
*/
public Function<Path, Path> getToRelativePath() {
return toRelativePath;
}
}
| PluginManagerSettings |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/AndroidInjectionBeforeSuperTest.java | {
"start": 6994,
"end": 7283
} | class ____ extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
}
}
public | CorrectOrder |
java | apache__camel | core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedAsyncProcessorAwaitManager.java | {
"start": 1622,
"end": 5238
} | class ____ extends ManagedService implements ManagedAsyncProcessorAwaitManagerMBean {
private final AsyncProcessorAwaitManager manager;
public ManagedAsyncProcessorAwaitManager(CamelContext context, AsyncProcessorAwaitManager manager) {
super(context, manager);
this.manager = manager;
}
public AsyncProcessorAwaitManager getAsyncProcessorAwaitManager() {
return manager;
}
@Override
public boolean isInterruptThreadsWhileStopping() {
return manager.isInterruptThreadsWhileStopping();
}
@Override
public void setInterruptThreadsWhileStopping(boolean interruptThreadsWhileStopping) {
manager.setInterruptThreadsWhileStopping(interruptThreadsWhileStopping);
}
@Override
public int getSize() {
return manager.size();
}
@Override
public TabularData browse() {
try {
TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.listAwaitThreadsTabularType());
Collection<AsyncProcessorAwaitManager.AwaitThread> threads = manager.browse();
for (AsyncProcessorAwaitManager.AwaitThread entry : threads) {
CompositeType ct = CamelOpenMBeanTypes.listAwaitThreadsCompositeType();
final CompositeData data = toCompositeData(entry, ct);
answer.put(data);
}
return answer;
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
private static CompositeData toCompositeData(AsyncProcessorAwaitManager.AwaitThread entry, CompositeType ct)
throws OpenDataException {
// TODO Update once baseline is Java 21
// String id = Long.toString(entry.getBlockedThread().threadId());
String id = Long.toString(entry.getBlockedThread().getId());
String name = entry.getBlockedThread().getName();
String exchangeId = entry.getExchange().getExchangeId();
String routeId = entry.getRouteId();
String nodeId = entry.getNodeId();
String duration = Long.toString(entry.getWaitDuration());
return new CompositeDataSupport(
ct,
new String[] { "id", "name", "exchangeId", "routeId", "nodeId", "duration" },
new Object[] { id, name, exchangeId, routeId, nodeId, duration });
}
@Override
public void interrupt(String exchangeId) {
manager.interrupt(exchangeId);
}
@Override
public long getThreadsBlocked() {
return manager.getStatistics().getThreadsBlocked();
}
@Override
public long getThreadsInterrupted() {
return manager.getStatistics().getThreadsInterrupted();
}
@Override
public long getTotalDuration() {
return manager.getStatistics().getTotalDuration();
}
@Override
public long getMinDuration() {
return manager.getStatistics().getMinDuration();
}
@Override
public long getMaxDuration() {
return manager.getStatistics().getMaxDuration();
}
@Override
public long getMeanDuration() {
return manager.getStatistics().getMeanDuration();
}
@Override
public void resetStatistics() {
manager.getStatistics().reset();
}
@Override
public boolean isStatisticsEnabled() {
return manager.getStatistics().isStatisticsEnabled();
}
@Override
public void setStatisticsEnabled(boolean statisticsEnabled) {
manager.getStatistics().setStatisticsEnabled(statisticsEnabled);
}
}
| ManagedAsyncProcessorAwaitManager |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/RequestLeakDetectionTest.java | {
"start": 2976,
"end": 9008
} | class ____ {
@Inject
MyRequestScopeBean bean;
@Inject
Barrier barrier;
@RestClient
RemoteClient client;
@GET
@Path("/reactive-server-and-client/{val}")
public Uni<Foo> reactiveServerAndClient(int val) {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
Vertx.currentContext().putLocal("count", val);
bean.setValue(val);
return Uni.createFrom().<Integer> emitter(e -> {
barrier.enqueue(Vertx.currentContext(), () -> {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
Assertions.assertEquals(bean.getValue(), val);
int rBefore = Vertx.currentContext().getLocal("count");
client.invokeReactive(Integer.toString(val))
.invoke(s -> {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
int rAfter = Vertx.currentContext().getLocal("count");
Assertions.assertEquals(s, "hello " + rAfter);
Assertions.assertEquals(rBefore, rAfter);
Assertions.assertEquals(rAfter, val);
Assertions.assertEquals(bean.getValue(), val);
}).subscribe().with(x -> e.complete(val), e::fail);
});
}).map(i -> {
Assertions.assertEquals(bean.getValue(), val);
return new Foo(Integer.toString(i));
});
}
@GET
@Path("/blocking-server-and-reactive-client/{val}")
public Foo blockingServerWithReactiveClient(int val) {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
Vertx.currentContext().putLocal("count", val);
bean.setValue(val);
return Uni.createFrom().<Integer> emitter(e -> {
barrier.enqueue(Vertx.currentContext(), () -> {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
int rBefore = Vertx.currentContext().getLocal("count");
Assertions.assertEquals(bean.getValue(), val);
client.invokeReactive(Integer.toString(val))
.invoke(s -> {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
int rAfter = Vertx.currentContext().getLocal("count");
Assertions.assertEquals(s, "hello " + rAfter);
Assertions.assertEquals(rBefore, rAfter);
Assertions.assertEquals(rAfter, val);
Assertions.assertEquals(bean.getValue(), val);
}).subscribe().with(x -> e.complete(val), e::fail);
});
}).map(i -> {
Assertions.assertEquals(bean.getValue(), val);
return new Foo(Integer.toString(i));
})
.await().indefinitely();
}
@GET
@Path("/blocking-server-and-client/{val}")
public Foo blockingServerAndBlockingClient(int val) {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
Vertx.currentContext().putLocal("count", val);
bean.setValue(val);
return Uni.createFrom().<Integer> emitter(e -> {
barrier.enqueue(Vertx.currentContext(), () -> {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
int rBefore = Vertx.currentContext().getLocal("count");
Assertions.assertEquals(bean.getValue(), val);
String s = client.invokeBlocking(Integer.toString(val));
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
int rAfter = Vertx.currentContext().getLocal("count");
Assertions.assertEquals(s, "hello " + rAfter);
Assertions.assertEquals(rBefore, rAfter);
Assertions.assertEquals(rAfter, val);
Assertions.assertEquals(bean.getValue(), val);
e.complete(val);
}, true);
}).map(i -> {
Assertions.assertEquals(bean.getValue(), val);
return new Foo(Integer.toString(i));
})
.await().indefinitely();
}
@GET
@Path("/reactive-server-and-blocking-client/{val}")
public Uni<Foo> reactiveServerWithBlockingClient(int val) {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
Vertx.currentContext().putLocal("count", val);
bean.setValue(val);
return Uni.createFrom().<Integer> emitter(e -> {
barrier.enqueue(Vertx.currentContext(), () -> {
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
int rBefore = Vertx.currentContext().getLocal("count");
Assertions.assertEquals(bean.getValue(), val);
String s = client.invokeBlocking(Integer.toString(val));
Assertions.assertTrue(VertxContext.isOnDuplicatedContext());
int rAfter = Vertx.currentContext().getLocal("count");
Assertions.assertEquals(s, "hello " + rAfter);
Assertions.assertEquals(rBefore, rAfter);
Assertions.assertEquals(rAfter, val);
Assertions.assertEquals(bean.getValue(), val);
e.complete(val);
}, true);
}).map(i -> {
Assertions.assertEquals(bean.getValue(), val);
return new Foo(Integer.toString(i));
});
}
}
@Path("/remote")
public static | MyRestAPI |
java | grpc__grpc-java | opentelemetry/src/main/java/io/grpc/opentelemetry/OpenTelemetryPlugin.java | {
"start": 1700,
"end": 1900
} | interface ____ {
default void inboundHeaders(Metadata headers) {}
default void inboundTrailers(Metadata trailers) {}
default void addLabels(AttributesBuilder to) {}
}
| ClientStreamPlugin |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java | {
"start": 1239,
"end": 2378
} | class ____ {
private final BeanFactory beanFactory = new DefaultListableBeanFactory();
@BeforeEach
void setUp() {
new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory).loadBeanDefinitions(
new ClassPathResource("FactoryBeanLookupTests-context.xml", getClass()));
}
@Test
void factoryBeanLookupByNameDereferencing() {
Object fooFactory = beanFactory.getBean("&fooFactory");
assertThat(fooFactory).isInstanceOf(FooFactoryBean.class);
}
@Test
void factoryBeanLookupByType() {
FooFactoryBean fooFactory = beanFactory.getBean(FooFactoryBean.class);
assertThat(fooFactory).isNotNull();
}
@Test
void factoryBeanLookupByTypeAndNameDereference() {
FooFactoryBean fooFactory = beanFactory.getBean("&fooFactory", FooFactoryBean.class);
assertThat(fooFactory).isNotNull();
}
@Test
void factoryBeanObjectLookupByName() {
Object fooFactory = beanFactory.getBean("fooFactory");
assertThat(fooFactory).isInstanceOf(Foo.class);
}
@Test
void factoryBeanObjectLookupByNameAndType() {
Foo foo = beanFactory.getBean("fooFactory", Foo.class);
assertThat(foo).isNotNull();
}
}
| FactoryBeanLookupTests |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/bridge/ChildWithBridgeMethods.java | {
"start": 581,
"end": 947
} | class ____ extends PackagePrivateParent {
@BeforeEach
public void anotherBeforeEach() {
BridgeMethodTests.sequence.add("child.anotherBeforeEach()");
}
@Test
void test() {
BridgeMethodTests.sequence.add("child.test()");
}
@AfterEach
public void anotherAfterEach() {
BridgeMethodTests.sequence.add("child.anotherAfterEach()");
}
}
| ChildWithBridgeMethods |
java | apache__kafka | generator/src/main/java/org/apache/kafka/message/FieldType.java | {
"start": 870,
"end": 935
} | interface ____ {
String ARRAY_PREFIX = "[]";
final | FieldType |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointPlanCalculatorContext.java | {
"start": 1035,
"end": 1409
} | interface ____ {
/**
* Acquires the main thread executor for this job.
*
* @return The main thread executor.
*/
ScheduledExecutor getMainExecutor();
/**
* Detects whether there are already some tasks finished.
*
* @return Whether there are finished tasks.
*/
boolean hasFinishedTasks();
}
| CheckpointPlanCalculatorContext |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/introspect/TestPropertyRename.java | {
"start": 1079,
"end": 2169
} | class ____ {
@JsonProperty("b")
private int a;
public Bean323WithExplicitCleave2(@JsonProperty("a") final int a ) {
this.a = a;
}
@JsonProperty("b")
private int getA () {
return a;
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
@Test
public void testCreatorPropRenameWithIgnore() throws Exception
{
Bean323WithIgnore input = new Bean323WithIgnore(7);
assertEquals("{\"b\":7}", objectWriter().writeValueAsString(input));
}
@Test
public void testCreatorPropRenameWithCleave() throws Exception
{
assertEquals("{\"a\":7,\"b\":7}",
objectWriter().writeValueAsString(new Bean323WithExplicitCleave1(7)));
// note: 'a' NOT included as only ctor property found for it, no getter/field
assertEquals("{\"b\":7}", objectWriter().writeValueAsString(new Bean323WithExplicitCleave2(7)));
}
}
| Bean323WithExplicitCleave2 |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/AnnotationIntrospector.java | {
"start": 49530,
"end": 49690
} | class ____ (EXCEPT possible
* 0-parameter ("default") constructor which is passed separately)
* @param declaredFactories Factory methods value | declares |
java | apache__camel | components/camel-twitter/src/generated/java/org/apache/camel/component/twitter/util/TwitterConverterLoader.java | {
"start": 888,
"end": 3871
} | class ____ implements TypeConverterLoader, CamelContextAware {
private CamelContext camelContext;
public TwitterConverterLoader() {
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException {
registerConverters(registry);
}
private void registerConverters(TypeConverterRegistry registry) {
addTypeConverter(registry, java.lang.String.class, twitter4j.v1.DirectMessage.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.component.twitter.util.TwitterConverter.toString((twitter4j.v1.DirectMessage) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, java.lang.String.class, twitter4j.v1.Status.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.component.twitter.util.TwitterConverter.toString((twitter4j.v1.Status) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, java.lang.String.class, twitter4j.v1.Trend.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.component.twitter.util.TwitterConverter.toString((twitter4j.v1.Trend) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, java.lang.String.class, twitter4j.v1.Trends.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.component.twitter.util.TwitterConverter.toString((twitter4j.v1.Trends) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
addTypeConverter(registry, java.lang.String.class, twitter4j.v1.UserList.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.component.twitter.util.TwitterConverter.toString((twitter4j.v1.UserList) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
}
private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) {
registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method));
}
}
| TwitterConverterLoader |
java | grpc__grpc-java | examples/example-hostname/src/main/java/io/grpc/examples/hostname/HostnameServer.java | {
"start": 1175,
"end": 3634
} | class ____ {
public static void main(String[] args) throws IOException, InterruptedException {
int port = 50051;
String hostname = null;
if (args.length >= 1) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
System.err.println("Usage: [port [hostname]]");
System.err.println("");
System.err.println(" port The listen port. Defaults to " + port);
System.err.println(" hostname The name clients will see in greet responses. ");
System.err.println(" Defaults to the machine's hostname");
System.exit(1);
}
}
if (args.length >= 2) {
hostname = args[1];
}
HealthStatusManager health = new HealthStatusManager();
final Server server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create())
.addService(new HostnameGreeter(hostname))
.addService(ProtoReflectionServiceV1.newInstance())
.addService(health.getHealthService())
.build()
.start();
System.out.println("Listening on port " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Start graceful shutdown
server.shutdown();
try {
// Wait up to 30 seconds for RPCs to complete processing.
server.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// Cancel any remaining RPCs. If awaitTermination() returned true above, then there are no
// RPCs and the server is already terminated. But it is safe to call even when terminated.
server.shutdownNow();
// shutdownNow isn't instantaneous, so you want an additional awaitTermination() to give
// time to clean resources up gracefully. Normally it will return in well under a second. In
// this example, the server.awaitTermination() in main() provides that delay.
}
});
// This would normally be tied to the service's dependencies. For example, if HostnameGreeter
// used a Channel to contact a required service, then when 'channel.getState() ==
// TRANSIENT_FAILURE' we'd want to set NOT_SERVING. But HostnameGreeter has no dependencies, so
// hard-coding SERVING is appropriate.
health.setStatus("", ServingStatus.SERVING);
server.awaitTermination();
}
}
| HostnameServer |
java | google__guice | core/src/com/google/inject/internal/RealMultibinder.java | {
"start": 12441,
"end": 18835
} | class ____.
if (permitDuplicates || elementHandles.size() == 1) {
// we just want to construct an ImmutableSet.Builder, and add everything to it.
// This generates exactly the code a human would write.
return MethodHandles.dropArguments(
InternalMethodHandles.buildImmutableSetFactory(elementHandles), 1, Dependency.class);
} else {
// Duplicates are not permitted, so we need to check for duplicates by constructing all
// elements and then checking the size of the set.
// ()-> Object[]
var elements = InternalMethodHandles.buildObjectArrayFactory(elementHandles);
// (Object[]) -> ImmutableSet<T>
var collector = MAKE_IMMUTABLE_SET_AND_CHECK_DUPLICATES_HANDLE.bindTo(this);
// (InternalContext ctx) -> ImmutableSet<T>
collector = MethodHandles.filterArguments(collector, 0, elements);
// (InternalContext, Dependency) -> Object
return MethodHandles.dropArguments(castReturnToObject(collector), 1, Dependency.class);
}
}
/**
* Recursive helper to populate an array.
*
* <p>REturns a handle of type (Object[], InternalContext) -> void
*/
static MethodHandle populateArray(
MethodHandle arrayElementSetter, int offset, List<MethodHandle> elementFactories) {
var size = elementFactories.size();
checkState(size != 0);
if (size < 32) {
var setter =
MethodHandles.filterArguments(
MethodHandles.insertArguments(arrayElementSetter, 1, offset),
1,
elementFactories.get(0));
for (int i = 1; i < size; i++) {
setter =
MethodHandles.foldArguments(
MethodHandles.filterArguments(
MethodHandles.insertArguments(arrayElementSetter, 1, offset + i),
1,
elementFactories.get(i)),
setter);
}
return setter;
}
var left = elementFactories.subList(0, size / 2);
var right = elementFactories.subList(size / 2, size);
var leftHandle = populateArray(arrayElementSetter, offset, left);
var rightHandle = populateArray(arrayElementSetter, offset + left.size(), right);
return MethodHandles.foldArguments(rightHandle, leftHandle);
}
private static final MethodHandle MAKE_IMMUTABLE_SET_AND_CHECK_DUPLICATES_HANDLE =
InternalMethodHandles.findVirtualOrDie(
RealMultibinderProvider.class,
"makeImmutableSetAndCheckDuplicates",
methodType(ImmutableSet.class, Object[].class));
@Keep
ImmutableSet<T> makeImmutableSetAndCheckDuplicates(T[] elements)
throws InternalProvisionException {
// Avoid ImmutableSet.copyOf(T[]), because it assumes there'll be duplicates in the input, but
// in the usual case of permitDuplicates==false, we know the exact size must be
// `localInjector.length` (otherwise we fail). This uses `builderWithExpectedSize` to avoid
// the overhead of copyOf or an unknown builder size.
var set = ImmutableSet.<T>builderWithExpectedSize(elements.length).add(elements).build();
if (set.size() < elements.length) {
throw newDuplicateValuesException(elements);
}
return set;
}
private static final MethodHandle NULL_CHECK_RESULT_HANDLE =
InternalMethodHandles.findStaticOrDie(
RealMultibinderProvider.class,
"nullCheckResult",
methodType(Object.class, Object.class, Object.class));
@Keep
static Object nullCheckResult(Object result, Object source) throws InternalProvisionException {
if (result == null) {
throw InternalProvisionException.create(
ErrorId.NULL_ELEMENT_IN_SET,
"Set injection failed due to null element bound at: %s",
source);
}
return result;
}
@Override
protected Provider<Set<T>> doMakeProvider(InjectorImpl injector, Dependency<?> dependency) {
if (injectors == null) {
return InternalFactory.makeProviderFor(ImmutableSet.of(), this);
}
return InternalFactory.makeDefaultProvider(this, injector, dependency);
}
private InternalProvisionException newNullEntryException(int i) {
return InternalProvisionException.create(
ErrorId.NULL_ELEMENT_IN_SET,
"Set injection failed due to null element bound at: %s",
bindings.get(i).getSource());
}
private InternalProvisionException newDuplicateValuesException(T[] values) {
Message message =
new Message(
GuiceInternal.GUICE_INTERNAL,
ErrorId.DUPLICATE_ELEMENT,
new DuplicateElementError<T>(
bindingSelection.getSetKey(), bindings, values, ImmutableList.of(getSource())));
return new InternalProvisionException(message);
}
@SuppressWarnings("unchecked")
@Override
public <B, V> V acceptExtensionVisitor(
BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) {
if (visitor instanceof MultibindingsTargetVisitor) {
return ((MultibindingsTargetVisitor<Set<T>, V>) visitor).visit(this);
} else {
return visitor.visit(binding);
}
}
@Override
public Key<Set<T>> getSetKey() {
return bindingSelection.getSetKey();
}
@Override
public ImmutableSet<Key<?>> getAlternateSetKeys() {
return ImmutableSet.of(
(Key<?>) bindingSelection.getCollectionOfProvidersKey(),
(Key<?>) bindingSelection.getCollectionOfJakartaProvidersKey(),
(Key<?>) bindingSelection.getSetOfExtendsKey());
}
@Override
public TypeLiteral<?> getElementTypeLiteral() {
return bindingSelection.getElementTypeLiteral();
}
@Override
public List<Binding<?>> getElements() {
return bindingSelection.getElements();
}
@Override
public boolean permitsDuplicates() {
return bindingSelection.permitsDuplicates();
}
@Override
public boolean containsElement(com.google.inject.spi.Element element) {
return bindingSelection.containsElement(element);
}
}
/**
* Implementation of BaseFactory that exposes a collection of providers of the values in the set.
*/
private static final | directly |
java | elastic__elasticsearch | x-pack/plugin/searchable-snapshots/src/main/java/org/elasticsearch/xpack/searchablesnapshots/store/input/DirectBlobContainerIndexInput.java | {
"start": 16250,
"end": 17530
} | class ____ implements Closeable {
private final InputStream inputStream;
private final int part;
private long pos; // position within this part
private final long maxPos;
StreamForSequentialReads(InputStream inputStream, int part, long pos, long streamLength) {
this.inputStream = Objects.requireNonNull(inputStream);
this.part = part;
this.pos = pos;
this.maxPos = pos + streamLength;
}
boolean canContinueSequentialRead(int part, long pos) {
return this.part == part && this.pos == pos;
}
int read(ByteBuffer b, int length) throws IOException {
assert this.pos < maxPos : "should not try and read from a fully-read stream";
int totalRead = Streams.read(inputStream, b, length);
final int read = totalRead > 0 ? totalRead : -1;
assert read <= length : read + " vs " + length;
pos += read;
return read;
}
boolean isFullyRead() {
assert this.pos <= maxPos;
return this.pos >= maxPos;
}
@Override
public void close() throws IOException {
inputStream.close();
}
}
}
| StreamForSequentialReads |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/collection/spi/PersistentList.java | {
"start": 13058,
"end": 13261
} | class ____ extends AbstractValueDelayedOperation {
public SimpleRemove(E orphan) {
super( null, orphan );
}
@Override
public void operate() {
list.remove( getOrphan() );
}
}
}
| SimpleRemove |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googlevertexai/action/GoogleVertexAiEmbeddingsActionTests.java | {
"start": 2362,
"end": 6329
} | class ____ extends ESTestCase {
private static final TimeValue TIMEOUT = new TimeValue(30, TimeUnit.SECONDS);
private final MockWebServer webServer = new MockWebServer();
private ThreadPool threadPool;
private HttpClientManager clientManager;
@Before
public void init() throws Exception {
webServer.start();
threadPool = createThreadPool(inferenceUtilityExecutors());
clientManager = HttpClientManager.create(Settings.EMPTY, threadPool, mockClusterServiceEmpty(), mock(ThrottlerManager.class));
}
@After
public void shutdown() throws IOException {
clientManager.close();
terminate(threadPool);
webServer.close();
}
// Successful case tested via end-to-end notebook tests in AppEx repo
public void testExecute_ThrowsElasticsearchException() {
var sender = mock(Sender.class);
doThrow(new ElasticsearchException("failed")).when(sender).send(any(), any(), any(), any());
var action = createAction(getUrl(webServer), "location", "projectId", "model", sender);
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
action.execute(
new EmbeddingsInput(List.of("abc"), InputTypeTests.randomWithNull()),
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var thrownException = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(thrownException.getMessage(), is("failed"));
}
public void testExecute_ThrowsElasticsearchException_WhenSenderOnFailureIsCalled() {
var sender = mock(Sender.class);
doAnswer(invocation -> {
ActionListener<InferenceServiceResults> listener = invocation.getArgument(3);
listener.onFailure(new IllegalStateException("failed"));
return Void.TYPE;
}).when(sender).send(any(), any(), any(), any());
var action = createAction(getUrl(webServer), "location", "projectId", "model", sender);
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
action.execute(
new EmbeddingsInput(List.of("abc"), InputTypeTests.randomWithNull()),
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var thrownException = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(thrownException.getMessage(), is("Failed to send Google Vertex AI embeddings request. Cause: failed"));
}
public void testExecute_ThrowsException() {
var sender = mock(Sender.class);
doThrow(new IllegalArgumentException("failed")).when(sender).send(any(), any(), any(), any());
var action = createAction(getUrl(webServer), "location", "projectId", "model", sender);
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
action.execute(
new EmbeddingsInput(List.of("abc"), InputTypeTests.randomWithNull()),
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var thrownException = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(thrownException.getMessage(), is("Failed to send Google Vertex AI embeddings request. Cause: failed"));
}
private ExecutableAction createAction(String url, String location, String projectId, String modelName, Sender sender) {
var model = createModel(location, projectId, modelName, url, "{}");
var requestManager = new GoogleVertexAiEmbeddingsRequestManager(model, TruncatorTests.createTruncator(), threadPool);
var failedToSendRequestErrorMessage = constructFailedToSendRequestMessage("Google Vertex AI embeddings");
return new SenderExecutableAction(sender, requestManager, failedToSendRequestErrorMessage);
}
}
| GoogleVertexAiEmbeddingsActionTests |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/license/TestUtils.java | {
"start": 16794,
"end": 17590
} | class ____ extends XPackLicenseState {
public final List<License.OperationMode> modeUpdates = new ArrayList<>();
public final List<Boolean> activeUpdates = new ArrayList<>();
public final List<String> expiryWarnings = new ArrayList<>();
public AssertingLicenseState() {
super(() -> 0);
}
@Override
protected void update(XPackLicenseStatus xPackLicenseStatus) {
modeUpdates.add(xPackLicenseStatus.mode());
activeUpdates.add(xPackLicenseStatus.active());
expiryWarnings.add(xPackLicenseStatus.expiryWarning());
}
}
/**
* A license state that makes the {@link #update(XPackLicenseStatus)}
* method public for use in tests.
*/
public static | AssertingLicenseState |
java | quarkusio__quarkus | extensions/quartz/deployment/src/test/java/io/quarkus/quartz/test/customDelegate/DelegateNotIndexedTest.java | {
"start": 710,
"end": 2241
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest()
// add a mock pretending to provide Agroal Capability to pass our validation
.addBuildChainCustomizer(new Consumer<>() {
@Override
public void accept(BuildChainBuilder buildChainBuilder) {
buildChainBuilder.addBuildStep(new BuildStep() {
@Override
public void execute(BuildContext context) {
context.produce(
new CapabilityBuildItem(Capability.AGROAL, "fakeProvider"));
}
}).produces(CapabilityBuildItem.class).build();
}
})
.assertException(t -> {
assertEquals(ConfigurationException.class, t.getClass());
Assertions.assertTrue(t.getMessage().contains(
"Custom JDBC delegate implementation class 'org.acme.DoesNotExist' was not found in Jandex index"));
})
.withApplicationRoot((jar) -> jar
.addClasses(SimpleJobs.class)
.addAsResource(new StringAsset(
"quarkus.quartz.driver-delegate=org.acme.DoesNotExist\nquarkus.quartz.store-type=jdbc-cmt"),
"application.properties"));
@Test
public void shouldFailWhenNotIndexed() {
Assertions.fail();
}
}
| DelegateNotIndexedTest |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/util/Nouns.java | {
"start": 3938,
"end": 4739
} | class ____ {
private final String regexp;
private final String replacement;
private final Pattern pattern;
private ReplaceRule(String regexp, String replacement) {
this.regexp = regexp;
this.replacement = replacement;
this.pattern = Pattern.compile( this.regexp, Pattern.CASE_INSENSITIVE );
}
private String apply(String input) {
String result = null;
Matcher matcher = this.pattern.matcher( input );
if ( matcher.find() ) {
result = matcher.replaceAll( this.replacement );
}
return result;
}
@Override
public String toString() {
return "'" + regexp + "' -> '" + replacement;
}
}
}
| ReplaceRule |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/aggregate/SumSerializationTests.java | {
"start": 2332,
"end": 4391
} | class ____ extends AggregateFunction {
public OldSum(Source source, Expression field, Expression filter, Expression window) {
super(source, field, filter, window, List.of());
}
@Override
public AggregateFunction withFilter(Expression filter) {
return new OldSum(source(), filter, filter, window());
}
@Override
public DataType dataType() {
return field().dataType();
}
@Override
public Expression replaceChildren(List<Expression> newChildren) {
return new OldSum(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2));
}
@Override
protected NodeInfo<? extends Expression> info() {
return NodeInfo.create(this, OldSum::new, field(), filter(), window());
}
@Override
public String getWriteableName() {
return Sum.ENTRY.name;
}
}
public void testSerializeOldSum() throws IOException {
var oldSum = new OldSum(randomSource(), randomChild(), randomChild(), randomChild());
try (BytesStreamOutput out = new BytesStreamOutput()) {
PlanStreamOutput planOut = new PlanStreamOutput(out, configuration());
planOut.writeNamedWriteable(oldSum);
try (StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), getNamedWriteableRegistry())) {
PlanStreamInput planIn = new PlanStreamInput(
in,
getNamedWriteableRegistry(),
configuration(),
new SerializationTestUtils.TestNameIdMapper()
);
Sum serialized = (Sum) planIn.readNamedWriteable(categoryClass());
assertThat(serialized.source(), equalTo(oldSum.source()));
assertThat(serialized.field(), equalTo(oldSum.field()));
assertThat(serialized.summationMode(), equalTo(SummationMode.COMPENSATED_LITERAL));
}
}
}
}
| OldSum |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java | {
"start": 30227,
"end": 36961
} | class ____ TrustingNullnessPropagation to avoid this
Nullness standardFieldNullness(
ClassAndField accessed, @Nullable AccessPath path, AccessPathValues<Nullness> store) {
// First, check the store for a dataflow-computed nullness value and return it if it exists
// Otherwise, check for nullness annotations on the field's symbol (including type annotations)
// If there are none, check for nullness annotations on generic type bounds, if any
// If there are none, fall back to the defaultAssumption
Nullness dataflowResult = (path == null) ? BOTTOM : store.valueOfAccessPath(path, BOTTOM);
if (dataflowResult != BOTTOM) {
return dataflowResult;
}
Optional<Nullness> declaredNullness = NullnessAnnotations.fromAnnotationsOn(accessed.symbol);
if (declaredNullness.isEmpty()) {
Type ftype = accessed.symbol.type;
if (ftype instanceof TypeVariable typeVariable) {
declaredNullness = NullnessAnnotations.getUpperBound(typeVariable);
} else {
declaredNullness = NullnessAnnotations.fromDefaultAnnotations(accessed.symbol);
}
}
return declaredNullness.orElse(defaultAssumption);
}
private Nullness returnValueNullness(MethodInvocationNode node, @Nullable ClassAndMethod callee) {
if (callee == null) {
return defaultAssumption;
}
Optional<Nullness> declaredNullness =
NullnessAnnotations.fromAnnotationMirrors(callee.annotations);
if (declaredNullness.isPresent()) {
return declaredNullness.get();
}
// Auto Value accessors are nonnull unless explicitly annotated @Nullable.
if (AccessPath.isAutoValueAccessor(node.getTree())) {
return NONNULL;
}
Nullness assumedNullness = methodReturnsNonNull.test(callee) ? NONNULL : NULLABLE;
if (!callee.isGenericResult) {
// We only care about inference results for methods that return a type variable.
return assumedNullness;
}
// Method has a generic result, so ask inference to infer a qualifier for that type parameter
return getInferredNullness(node).orElse(assumedNullness);
}
private @Nullable Nullness fieldInitializerNullnessIfAvailable(ClassAndField accessed) {
if (!traversed.add(accessed.symbol)) {
// Circular dependency between initializers results in null. Note static fields can also be
// null if they're observed before initialized, but we're ignoring that case for simplicity.
// TODO(kmb): Try to recognize problems with initialization order
return NULL;
}
try {
JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(context);
TreePath fieldDeclPath = Trees.instance(javacEnv).getPath(accessed.symbol);
// Skip initializers in other compilation units as analysis of such nodes can fail due to
// missing types.
if (fieldDeclPath == null
|| fieldDeclPath.getCompilationUnit() != compilationUnit
|| !(fieldDeclPath.getLeaf() instanceof VariableTree variableTree)) {
return null;
}
ExpressionTree initializer = variableTree.getInitializer();
if (initializer == null) {
return null;
}
ClassTree classTree = (ClassTree) fieldDeclPath.getParentPath().getLeaf();
// Run flow analysis on field initializer. This is inefficient compared to just walking
// the initializer expression tree but it avoids duplicating the logic from this transfer
// function into a method that operates on Javac Nodes.
TreePath initializerPath = TreePath.getPath(fieldDeclPath, initializer);
UnderlyingAST ast = new UnderlyingAST.CFGStatement(initializerPath.getLeaf(), classTree);
ControlFlowGraph cfg =
CFGBuilder.build(
initializerPath,
ast,
/* assumeAssertionsEnabled= */ false,
/* assumeAssertionsDisabled= */ false,
javacEnv);
Analysis<Nullness, AccessPathStore<Nullness>, NullnessPropagationTransfer> analysis =
new ForwardAnalysisImpl<>(this);
analysis.performAnalysis(cfg);
return analysis.getValue(initializerPath.getLeaf());
} finally {
traversed.remove(accessed.symbol);
}
}
private static void setNonnullIfTrackable(Updates updates, Node node) {
if (node instanceof LocalVariableNode localVariableNode) {
updates.set(localVariableNode, NONNULL);
} else if (node instanceof FieldAccessNode fieldAccessNode) {
updates.set(fieldAccessNode, NONNULL);
} else if (node instanceof VariableDeclarationNode variableDeclarationNode) {
updates.set(variableDeclarationNode, NONNULL);
}
}
/**
* Records which arguments are guaranteed to be non-null if the method completes without
* exception. For example, if {@code checkNotNull(foo, message)} completes successfully, then
* {@code foo} is not null.
*/
private static void setUnconditionalArgumentNullness(
Updates bothUpdates, List<Node> arguments, ClassAndMethod callee) {
ImmutableSet<Integer> requiredNonNullParameters =
REQUIRED_NON_NULL_PARAMETERS.get(callee.name());
for (LocalVariableNode var : variablesAtIndexes(requiredNonNullParameters, arguments)) {
bothUpdates.set(var, NONNULL);
}
}
/**
* Records which arguments are guaranteed to be non-null only if the method completes by returning
* {@code true} or only if the method completes by returning {@code false}. For example, if {@code
* Strings.isNullOrEmpty(s)} returns {@code false}, then {@code s} is not null.
*/
private static void setConditionalArgumentNullness(
Updates thenUpdates,
Updates elseUpdates,
List<Node> arguments,
ClassAndMethod callee,
Types types,
Symtab symtab) {
MemberName calleeName = callee.name();
for (LocalVariableNode var :
variablesAtIndexes(NULL_IMPLIES_TRUE_PARAMETERS.get(calleeName), arguments)) {
elseUpdates.set(var, NONNULL);
}
for (LocalVariableNode var :
variablesAtIndexes(NONNULL_IFF_TRUE_PARAMETERS.get(calleeName), arguments)) {
thenUpdates.set(var, NONNULL);
elseUpdates.set(var, NULL);
}
for (LocalVariableNode var :
variablesAtIndexes(NULL_IFF_TRUE_PARAMETERS.get(calleeName), arguments)) {
thenUpdates.set(var, NULL);
elseUpdates.set(var, NONNULL);
}
if (isEqualsMethod(calleeName, arguments, types, symtab)) {
LocalVariableNode var = variablesAtIndexes(ImmutableSet.of(0), arguments).getFirst();
thenUpdates.set(var, NONNULL);
}
}
private static boolean isEqualsMethod(
MemberName calleeName, List<Node> arguments, Types types, Symtab symtab) {
// we don't care about | and |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterDefinitionOrderTest.java | {
"start": 2370,
"end": 2848
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(nullable = false)
private Long id;
public String field;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
@Entity(name = "XEntity")
@FilterDef(name = "x_filter", defaultCondition = "field = 'Hello'")
public static | AMyEntity |
java | google__auto | value/src/test/java/com/google/auto/value/extension/memoized/MemoizedTest.java | {
"start": 17127,
"end": 17766
} | class ____<InputT> extends AbstractTypePath<InputT, ResourceUri> {
static <InputT> ResourceUriPath<InputT> create(TypeEdgeIterable<InputT, ResourceUri> edges) {
return new AutoValue_MemoizedTest_ResourceUriPath<>(edges);
}
@Memoized
TypePath<InputT, String> toServiceName() {
return new TypePath<InputT, String>() {};
}
}
@Test
public void methodTypeFromTypeVariableSubsitution() {
ResourceUriPath<String> path =
ResourceUriPath.create(new TypeEdgeIterable<String, ResourceUri>() {});
assertThat(path.edges()).isNotNull();
}
@Immutable
@AutoValue
abstract static | ResourceUriPath |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/sql_load_script/NoFileOptionTestCase.java | {
"start": 300,
"end": 962
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(MyEntity.class, SqlLoadScriptTestResource.class)
.addAsResource("application-no-file-option-test.properties", "application.properties")
.addAsResource("import.sql"));
@Test
public void testSqlLoadScriptFileAbsentTest() {
String name = "no entity";
//despite the presence of import.sql, the file is not processed
RestAssured.when().get("/orm-sql-load-script/1").then().body(Matchers.is(name));
}
}
| NoFileOptionTestCase |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/ScriptDocValues.java | {
"start": 7355,
"end": 8127
} | interface ____ {
/** Returns the dimensional type of this geometry */
int getDimensionalType();
/** Returns the bounding box of this geometry */
GeoBoundingBox getBoundingBox();
/** Returns the suggested label position */
GeoPoint getLabelPosition();
/** Returns the centroid of this geometry */
GeoPoint getCentroid();
/** returns the size of the geometry */
int size();
/** Returns the width of the bounding box diagonal in the spherical Mercator projection (meters) */
double getMercatorWidth();
/** Returns the height of the bounding box diagonal in the spherical Mercator projection (meters) */
double getMercatorHeight();
}
public | Geometry |
java | micronaut-projects__micronaut-core | inject-java-test/src/test/groovy/io/micronaut/inject/visitor/beans/TestBean.java | {
"start": 718,
"end": 1429
} | class ____ {
private boolean flag;
private String name;
private int age;
private String[] stringArray;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getStringArray() {
return stringArray;
}
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}
// variation with getter
public boolean getFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
| TestBean |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/mapper_type_parameter/BaseMapper.java | {
"start": 1014,
"end": 1639
} | interface ____<S, T> {
@SelectProvider(type = StatementProvider.class, method = "provideSelect")
S select(S param);
@SelectProvider(type = StatementProvider.class, method = "provideSelect")
List<S> selectList(S param);
@SelectProvider(type = StatementProvider.class, method = "provideSelect")
@MapKey("id")
Map<T, S> selectMap(S param);
@InsertProvider(type = StatementProvider.class, method = "provideInsert")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(List<S> param);
@UpdateProvider(type = StatementProvider.class, method = "provideUpdate")
int update(S param);
| BaseMapper |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BytecodeTransformer.java | {
"start": 121,
"end": 1456
} | class ____ {
public static BytecodeTransformer forInputTransformer(String classToTransform,
BiFunction<String, byte[], byte[]> inputTransformer) {
return new BytecodeTransformer(classToTransform, null, inputTransformer);
}
private final String classToTransform;
private final BiFunction<String, ClassVisitor, ClassVisitor> visitorFunction;
private final BiFunction<String, byte[], byte[]> inputTransformer;
public BytecodeTransformer(String classToTransform,
BiFunction<String, ClassVisitor, ClassVisitor> visitorFunction) {
this(classToTransform, visitorFunction, null);
}
private BytecodeTransformer(String classToTransform, BiFunction<String, ClassVisitor, ClassVisitor> visitorFunction,
BiFunction<String, byte[], byte[]> inputTransformer) {
super();
this.classToTransform = classToTransform;
this.visitorFunction = visitorFunction;
this.inputTransformer = inputTransformer;
}
public String getClassToTransform() {
return classToTransform;
}
public BiFunction<String, ClassVisitor, ClassVisitor> getVisitorFunction() {
return visitorFunction;
}
public BiFunction<String, byte[], byte[]> getInputTransformer() {
return inputTransformer;
}
}
| BytecodeTransformer |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/utils/TaskRetrieverTests.java | {
"start": 1801,
"end": 9482
} | class ____ extends ESTestCase {
private static final TimeValue TIMEOUT = new TimeValue(30, TimeUnit.SECONDS);
private ThreadPool threadPool;
@Before
public void setUpThreadPool() {
threadPool = new TestThreadPool(getTestName());
}
@After
public void tearDownThreadPool() {
terminate(threadPool);
}
public void testGetExistingTaskInfoCallsOnFailureForAnError() {
var client = mockListTasksClient(threadPool);
doAnswer(invocationOnMock -> {
@SuppressWarnings("unchecked")
ActionListener<ListTasksResponse> actionListener = (ActionListener<ListTasksResponse>) invocationOnMock.getArguments()[2];
actionListener.onFailure(new Exception("error"));
return Void.TYPE;
}).when(client).execute(same(TransportListTasksAction.TYPE), any(), any());
var listener = new PlainActionFuture<TaskInfo>();
getDownloadTaskInfo(client, "inferenceEntityId", false, TIMEOUT, () -> "", listener);
var exception = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(exception.status(), is(RestStatus.INTERNAL_SERVER_ERROR));
assertThat(exception.getMessage(), is("Unable to retrieve task information for model id [inferenceEntityId]"));
}
public void testGetExistingTaskInfoCallsListenerWithNullWhenNoTasksExist() {
var client = mockClientWithTasksResponse(Collections.emptyList(), threadPool);
var listener = new PlainActionFuture<TaskInfo>();
getDownloadTaskInfo(client, "inferenceEntityId", false, TIMEOUT, () -> "", listener);
assertThat(listener.actionGet(TIMEOUT), nullValue());
}
public void testGetExistingTaskInfoCallsListenerWithTaskInfoWhenTaskExists() {
List<TaskInfo> listTaskInfo = getTaskInfoListOfOne();
var client = mockClientWithTasksResponse(listTaskInfo, threadPool);
var listener = new PlainActionFuture<TaskInfo>();
getDownloadTaskInfo(client, "inferenceEntityId", false, TIMEOUT, () -> "", listener);
assertThat(listener.actionGet(TIMEOUT), is(listTaskInfo.get(0)));
}
public void testGetExistingTaskInfoCallsListenerWithFirstTaskInfoWhenMultipleTasksExist() {
List<TaskInfo> listTaskInfo = getTaskInfoList(2);
var client = mockClientWithTasksResponse(listTaskInfo, threadPool);
var listener = new PlainActionFuture<TaskInfo>();
getDownloadTaskInfo(client, "inferenceEntityId", false, TIMEOUT, () -> "", listener);
assertThat(listener.actionGet(TIMEOUT), is(listTaskInfo.get(0)));
}
public void testGetTimeoutOnWaitForCompletion() {
var client = mockListTasksClient(threadPool);
doAnswer(invocationOnMock -> {
@SuppressWarnings("unchecked")
ActionListener<ListTasksResponse> actionListener = (ActionListener<ListTasksResponse>) invocationOnMock.getArguments()[2];
actionListener.onResponse(
new ListTasksResponse(
List.of(),
List.of(),
List.of(new ElasticsearchStatusException("node timeout", RestStatus.REQUEST_TIMEOUT))
)
);
return Void.TYPE;
}).when(client).execute(same(TransportListTasksAction.TYPE), any(), any());
var listener = new PlainActionFuture<TaskInfo>();
getDownloadTaskInfo(client, "inferenceEntityId", true, TIMEOUT, () -> "Testing timeout", listener);
var exception = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(exception.status(), is(RestStatus.REQUEST_TIMEOUT));
assertThat(exception.getMessage(), is("Testing timeout"));
}
/**
* A helper method for setting up a mock cluster client to return the passed in list of tasks.
*
* @param taskInfo a list of {@link TaskInfo} objects representing the tasks to return
* when {@code Client.execute(ListTasksAction.INSTANCE, ...)} is called
* @param threadPool a test thread pool to associate with the client
* @return the mocked {@link Client}
*/
public static Client mockClientWithTasksResponse(List<TaskInfo> taskInfo, ThreadPool threadPool) {
var client = mockListTasksClient(threadPool);
var listTasksResponse = mock(ListTasksResponse.class);
when(listTasksResponse.getTasks()).thenReturn(taskInfo);
doAnswer(invocationOnMock -> {
@SuppressWarnings("unchecked")
ActionListener<ListTasksResponse> actionListener = (ActionListener<ListTasksResponse>) invocationOnMock.getArguments()[2];
actionListener.onResponse(listTasksResponse);
return Void.TYPE;
}).when(client).execute(same(TransportListTasksAction.TYPE), any(), any());
return client;
}
/**
* A helper method for setting up the mock cluster client so that it will return a valid {@link ListTasksRequestBuilder}.
*
* @param threadPool a test thread pool to associate with the client
* @return a mocked Client
*/
public static Client mockListTasksClient(ThreadPool threadPool) {
var client = mockClusterClient(threadPool);
mockListTasksClient(client);
return client;
}
/**
* A helper method for setting up the mock cluster client so that it will return a valid {@link ListTasksRequestBuilder}.
*
* @param client a Client that already has the admin and cluster clients mocked
* @return a mocked Client
*/
public static Client mockListTasksClient(Client client) {
var cluster = client.admin().cluster();
when(cluster.prepareListTasks()).thenReturn(new ListTasksRequestBuilder(client));
return client;
}
/**
* A helper method for setting up the mock cluster client.
*
* @param threadPool a test thread pool to associate with the client
* @return a mocked Client
*/
public static Client mockClusterClient(ThreadPool threadPool) {
var client = mock(Client.class);
var cluster = mock(ClusterAdminClient.class);
var admin = mock(AdminClient.class);
when(client.threadPool()).thenReturn(threadPool);
when(client.admin()).thenReturn(admin);
when(admin.cluster()).thenReturn(cluster);
return client;
}
/**
* A helper method for returning a list of one test {@link TaskInfo} object
*
* @return a list with a single TaskInfo object within it
*/
public static List<TaskInfo> getTaskInfoListOfOne() {
return getTaskInfoList(1);
}
/**
* A helper method for returning a list of the specified number of test {@link TaskInfo} objects
*
* @param size the number of TaskInfo objects to create
* @return a list of TaskInfo objects
*/
public static List<TaskInfo> getTaskInfoList(int size) {
final int ID_BASE = 100;
final int PARENT_ID_BASE = 200;
var list = new ArrayList<TaskInfo>(size);
for (int i = 0; i < size; i++) {
list.add(
new TaskInfo(
new TaskId("test", ID_BASE + i),
"test",
"test",
"test",
"test",
null,
0,
0,
true,
false,
new TaskId("test", PARENT_ID_BASE + i),
Collections.emptyMap()
)
);
}
return list;
}
}
| TaskRetrieverTests |
java | apache__camel | components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/runtime/BedrockOperations.java | {
"start": 868,
"end": 1124
} | enum ____ {
invokeTextModel,
invokeImageModel,
invokeEmbeddingsModel,
invokeTextModelStreaming,
invokeImageModelStreaming,
invokeEmbeddingsModelStreaming,
converse,
converseStream,
applyGuardrail
}
| BedrockOperations |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/UnsecuredResourceInterface.java | {
"start": 1010,
"end": 1126
} | interface ____ overridden with @GET and @Path
return "interface-overridden-declared-on-implementor";
}
}
| is |
java | netty__netty | codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/Socks5PasswordAuthStatus.java | {
"start": 791,
"end": 2465
} | class ____ implements Comparable<Socks5PasswordAuthStatus> {
public static final Socks5PasswordAuthStatus SUCCESS = new Socks5PasswordAuthStatus(0x00, "SUCCESS");
public static final Socks5PasswordAuthStatus FAILURE = new Socks5PasswordAuthStatus(0xFF, "FAILURE");
public static Socks5PasswordAuthStatus valueOf(byte b) {
switch (b) {
case 0x00:
return SUCCESS;
case (byte) 0xFF:
return FAILURE;
}
return new Socks5PasswordAuthStatus(b);
}
private final byte byteValue;
private final String name;
private String text;
public Socks5PasswordAuthStatus(int byteValue) {
this(byteValue, "UNKNOWN");
}
public Socks5PasswordAuthStatus(int byteValue, String name) {
this.name = ObjectUtil.checkNotNull(name, "name");
this.byteValue = (byte) byteValue;
}
public byte byteValue() {
return byteValue;
}
public boolean isSuccess() {
return byteValue == 0;
}
@Override
public int hashCode() {
return byteValue;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Socks5PasswordAuthStatus)) {
return false;
}
return byteValue == ((Socks5PasswordAuthStatus) obj).byteValue;
}
@Override
public int compareTo(Socks5PasswordAuthStatus o) {
return byteValue - o.byteValue;
}
@Override
public String toString() {
String text = this.text;
if (text == null) {
this.text = text = name + '(' + (byteValue & 0xFF) + ')';
}
return text;
}
}
| Socks5PasswordAuthStatus |
java | mockito__mockito | mockito-integration-tests/osgi-tests/src/otherBundle/java/org/mockito/osgitest/otherbundle/Methods.java | {
"start": 170,
"end": 251
} | class ____ {
public int intReturningMethod() {
return 0;
}
}
| Methods |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CouchDbEndpointBuilderFactory.java | {
"start": 8894,
"end": 14713
} | interface ____
extends
EndpointConsumerBuilder {
default CouchDbEndpointConsumerBuilder basic() {
return (CouchDbEndpointConsumerBuilder) this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedCouchDbEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedCouchDbEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedCouchDbEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedCouchDbEndpointConsumerBuilder exceptionHandler(String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedCouchDbEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedCouchDbEndpointConsumerBuilder exchangePattern(String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
}
/**
* Builder for endpoint producers for the CouchDB component.
*/
public | AdvancedCouchDbEndpointConsumerBuilder |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/multipart/StreamingFileUpload.java | {
"start": 1532,
"end": 3886
} | interface ____ extends FileUpload, Publisher<PartData> {
/**
* <p>A convenience method to write this uploaded item to disk.</p>
*
* <p>This method will return a no-op {@link Publisher} if called multiple times for the same location</p>
*
* @param location the name of the file to which the stream will be written. The file is created relative to
* the location as specified in the {@code MultipartConfiguration}
* @return A {@link Publisher} that outputs whether the transfer was successful
* @deprecated Use {@link #transferTo(File)} or {@link #transferTo(OutputStream)} instead.
*/
@Deprecated
Publisher<Boolean> transferTo(String location);
/**
* <p>A convenience method to write this uploaded item to disk.</p>
*
* <p>This method will return a no-op {@link Publisher} if called multiple times for the same location</p>
*
* @param destination the destination of the file to which the stream will be written.
* @return A {@link Publisher} that outputs whether the transfer was successful
*/
Publisher<Boolean> transferTo(File destination);
/**
* <p>A convenience method to write this uploaded item the provided output stream.</p>
*
* @param outputStream the destination to which the stream will be written.
* @return A {@link Publisher} that outputs whether the transfer was successful
* @since 3.1.0
*/
default Publisher<Boolean> transferTo(OutputStream outputStream) {
throw new UnsupportedOperationException("StreamingFileUpload doesn't support transferTo OutputStream");
}
/**
* Deletes the underlying storage for a file item, including deleting any associated temporary disk file.
*
* @return A {@link Publisher} that outputs whether to delete was successful
*/
Publisher<Boolean> delete();
/**
* Create an {@link InputStream} that reads this file. The returned stream must be closed after
* use. The stream may block when data isn't yet available.
*
* @return An {@link InputStream} that reads this file's contents
* @since 4.2.0
*/
@NonNull
default InputStream asInputStream() {
throw new UnsupportedOperationException("StreamingFileUpload doesn't support asInputStream");
}
}
| StreamingFileUpload |
java | apache__camel | components/camel-mllp/src/main/java/org/apache/camel/component/mllp/MllpTcpClientProducer.java | {
"start": 32067,
"end": 32852
} | class ____ implements ThreadFactory {
final String endpointKey;
IdleTimeoutThreadFactory(String endpointKey) {
this.endpointKey = endpointKey;
}
@Override
public Thread newThread(Runnable r) {
Thread timeoutThread = Executors.defaultThreadFactory().newThread(r);
timeoutThread.setName(
String.format("%s[%s]-idle-timeout-thread", MllpTcpClientProducer.class.getSimpleName(), endpointKey));
return timeoutThread;
}
}
@Override
public MllpEndpoint getEndpoint() {
return (MllpEndpoint) super.getEndpoint();
}
public MllpConfiguration getConfiguration() {
return this.getEndpoint().getConfiguration();
}
}
| IdleTimeoutThreadFactory |
java | apache__camel | components/camel-stax/src/test/java/org/apache/camel/language/xtokenizer/XMLTokenizeLanguageTest.java | {
"start": 1137,
"end": 7573
} | class ____ extends CamelTestSupport {
@Test
public void testSendClosedTagMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child some_attr='a' anotherAttr='a' xmlns:c=\"urn:c\"></c:child>",
"<c:child some_attr='b' anotherAttr='b' xmlns:c=\"urn:c\"></c:child>" };
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a'></c:child><c:child some_attr='b' anotherAttr='b'></c:child></c:parent>");
verify(expected);
}
@Test
public void testSendClosedTagWithLineBreaksMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child some_attr='a' anotherAttr='a' xmlns:c=\"urn:c\">\n</c:child>",
"<c:child some_attr='b' anotherAttr='b' xmlns:c=\"urn:c\">\n</c:child>" };
template.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?>\n" + "<c:parent xmlns:c='urn:c'>\n"
+ "<c:child some_attr='a' anotherAttr='a'>\n" + "</c:child>\n"
+ "<c:child some_attr='b' anotherAttr='b'>\n" + "</c:child>\n" + "</c:parent>");
verify(expected);
}
@Test
public void testSendSelfClosingTagMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child some_attr='a' anotherAttr='a' xmlns:c=\"urn:c\"/>",
"<c:child some_attr='b' anotherAttr='b' xmlns:c=\"urn:c\"/>" };
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a' /><c:child some_attr='b' anotherAttr='b' /></c:parent>");
verify(expected);
}
@Test
public void testSendMixedClosingTagMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child some_attr='a' anotherAttr='a' xmlns:c=\"urn:c\">ha</c:child>",
"<c:child some_attr='b' anotherAttr='b' xmlns:c=\"urn:c\"/>",
"<c:child some_attr='c' xmlns:c=\"urn:c\"></c:child>" };
template.sendBody(
"direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child some_attr='a' anotherAttr='a'>ha</c:child>"
+ "<c:child some_attr='b' anotherAttr='b' /><c:child some_attr='c'></c:child></c:parent>");
verify(expected);
}
@Test
public void testSendMixedClosingTagInsideMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child name='child1' xmlns:c=\"urn:c\"><grandchild name='grandchild1'/> <grandchild name='grandchild2'/></c:child>",
"<c:child name='child2' xmlns:c=\"urn:c\"><grandchild name='grandchild1'></grandchild><grandchild name='grandchild2'></grandchild></c:child>" };
template.sendBody(
"direct:start",
"<c:parent xmlns:c='urn:c'><c:child name='child1'><grandchild name='grandchild1'/> <grandchild name='grandchild2'/></c:child>"
+ "<c:child name='child2'><grandchild name='grandchild1'></grandchild><grandchild name='grandchild2'></grandchild></c:child></c:parent>");
verify(expected);
}
@Test
public void testSendNamespacedChildMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child xmlns:c='urn:c' some_attr='a' anotherAttr='a'></c:child>",
"<c:child xmlns:c='urn:c' some_attr='b' anotherAttr='b' />" };
template.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c'><c:child xmlns:c='urn:c' some_attr='a' anotherAttr='a'></c:child>"
+ "<c:child xmlns:c='urn:c' some_attr='b' anotherAttr='b' /></c:parent>");
verify(expected);
}
@Test
public void testSendNamespacedParentMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child some_attr='a' anotherAttr='a' xmlns:d=\"urn:d\" xmlns:c=\"urn:c\"></c:child>",
"<c:child some_attr='b' anotherAttr='b' xmlns:d=\"urn:d\" xmlns:c=\"urn:c\"/>" };
template.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><c:parent xmlns:c='urn:c' xmlns:d=\"urn:d\"><c:child some_attr='a' anotherAttr='a'></c:child>"
+ "<c:child some_attr='b' anotherAttr='b'/></c:parent>");
verify(expected);
}
@Test
public void testSendMoreParentsMessageToTokenize() throws Exception {
String[] expected = new String[] {
"<c:child some_attr='a' anotherAttr='a' xmlns:c=\"urn:c\" xmlns:d=\"urn:d\" xmlns:g=\"urn:g\"></c:child>",
"<c:child some_attr='b' anotherAttr='b' xmlns:c=\"urn:c\" xmlns:d=\"urn:d\" xmlns:g=\"urn:g\"/>" };
template
.sendBody("direct:start",
"<?xml version='1.0' encoding='UTF-8'?><g:greatgrandparent xmlns:g='urn:g'><grandparent><uncle/><aunt>emma</aunt><c:parent xmlns:c='urn:c' xmlns:d=\"urn:d\">"
+ "<c:child some_attr='a' anotherAttr='a'></c:child><c:child some_attr='b' anotherAttr='b'/></c:parent></grandparent></g:greatgrandparent>");
verify(expected);
}
private void verify(String... expected) throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(expected.length);
MockEndpoint.assertIsSatisfied(context);
int i = 0;
for (String target : expected) {
String body = getMockEndpoint("mock:result").getReceivedExchanges().get(i).getMessage().getBody(String.class);
XmlAssert.assertThat(body).and(target).areIdentical();
i++;
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
Namespaces ns = new Namespaces("C", "urn:c");
public void configure() {
from("direct:start").split().xtokenize("//C:child", ns).to("mock:result").end();
}
};
}
}
| XMLTokenizeLanguageTest |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableDelaySubscriptionOther.java | {
"start": 2663,
"end": 3191
} | class ____ implements Observer<T> {
@Override
public void onSubscribe(Disposable d) {
serial.update(d);
}
@Override
public void onNext(T value) {
child.onNext(value);
}
@Override
public void onError(Throwable e) {
child.onError(e);
}
@Override
public void onComplete() {
child.onComplete();
}
}
}
}
| OnComplete |
java | apache__camel | components/camel-coap/src/main/java/org/apache/camel/coap/CoAPComponent.java | {
"start": 2484,
"end": 10811
} | class ____ extends DefaultComponent implements RestConsumerFactory {
static final int DEFAULT_PORT = 5684;
private static final Logger LOG = LoggerFactory.getLogger(CoAPComponent.class);
@Metadata
private String configurationFile;
final Map<Integer, CoapServer> servers = new ConcurrentHashMap<>();
public CoAPComponent() {
}
public CoapServer getServer(int port, CoAPEndpoint endpoint) throws IOException, GeneralSecurityException {
lock.lock();
try {
CoapServer server = servers.get(port);
if (server == null && port == -1) {
server = getServer(DEFAULT_PORT, endpoint);
}
if (server == null) {
CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
Configuration config = loadConfiguration();
builder.setConfiguration(config);
// Configure TLS and / or TCP
InetSocketAddress address = new InetSocketAddress(port);
if (CoAPEndpoint.enableDTLS(endpoint.getUri())) {
doEnableDTLS(endpoint, config, address, builder);
} else if (CoAPEndpoint.enableTCP(endpoint.getUri())) {
doEnableTCP(endpoint, config, address, builder);
} else {
builder.setInetSocketAddress(address);
}
server = new CoapServer();
server.addEndpoint(builder.build());
servers.put(port, server);
if (this.isStarted()) {
server.start();
}
}
return server;
} finally {
lock.unlock();
}
}
public Configuration loadConfiguration() throws IOException {
Configuration config;
if (configurationFile != null) {
InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), configurationFile);
config = Configuration.createStandardFromStream(is);
} else {
config = Configuration.createStandardWithoutFile();
}
return config;
}
private void doEnableTCP(
CoAPEndpoint endpoint, Configuration config, InetSocketAddress address, CoapEndpoint.Builder coapBuilder)
throws GeneralSecurityException, IOException {
TcpServerConnector tcpConnector;
// TLS + TCP
if (endpoint.getUri().getScheme().startsWith("coaps")) {
tcpConnector = doEnableTLSTCP(endpoint, config, address);
} else {
tcpConnector = new TcpServerConnector(address, config);
}
coapBuilder.setConnector(tcpConnector);
}
private TcpServerConnector doEnableTLSTCP(CoAPEndpoint endpoint, Configuration config, InetSocketAddress address)
throws GeneralSecurityException, IOException {
TcpServerConnector tcpConnector;
SSLContext sslContext = endpoint.getSslContextParameters().createSSLContext(getCamelContext());
if (endpoint.isClientAuthenticationRequired()) {
config.set(TcpConfig.TLS_CLIENT_AUTHENTICATION_MODE, CertificateAuthenticationMode.NEEDED);
} else if (endpoint.isClientAuthenticationWanted()) {
config.set(TcpConfig.TLS_CLIENT_AUTHENTICATION_MODE, CertificateAuthenticationMode.WANTED);
} else {
config.set(TcpConfig.TLS_CLIENT_AUTHENTICATION_MODE, CertificateAuthenticationMode.NONE);
}
tcpConnector = new TlsServerConnector(
sslContext, address, config);
return tcpConnector;
}
private static void doEnableDTLS(
CoAPEndpoint endpoint, Configuration config, InetSocketAddress address, CoapEndpoint.Builder coapBuilder)
throws IOException {
DTLSConnector connector = endpoint.createDTLSConnector(address, false, config);
coapBuilder.setConnector(connector);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
Endpoint endpoint = new CoAPEndpoint(uri, this);
setProperties(endpoint, parameters);
return endpoint;
}
@Override
public Consumer createConsumer(
CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate, String consumes,
String produces,
RestConfiguration configuration, Map<String, Object> parameters)
throws Exception {
String path = basePath;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
path = path + uriTemplate;
} else {
path = path + "/" + uriTemplate;
}
}
path = FileUtil.stripLeadingSeparator(path);
RestConfiguration config = configuration;
if (config == null) {
config = CamelContextHelper.getRestConfiguration(getCamelContext(), "coap");
}
if (config.isEnableCORS()) {
LOG.info("CORS configuration will be ignored as CORS is not supported by the CoAP component");
}
final String host = doGetHost(config);
Map<String, Object> map = new HashMap<>();
// setup endpoint options
if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) {
map.putAll(config.getEndpointProperties());
}
String scheme = config.getScheme() == null ? "coap" : config.getScheme();
String query = URISupport.createQueryString(map);
int port = 0;
int num = config.getPort();
if (num > 0) {
port = num;
}
// prefix path with context-path if configured in rest-dsl configuration
String contextPath = config.getContextPath();
if (ObjectHelper.isNotEmpty(contextPath)) {
contextPath = FileUtil.stripTrailingSeparator(contextPath);
contextPath = FileUtil.stripLeadingSeparator(contextPath);
if (ObjectHelper.isNotEmpty(contextPath)) {
path = contextPath + "/" + path;
}
}
String restrict = verb.toUpperCase(Locale.US);
String url = String.format("%s://%s:%d/%s?coapMethodRestrict=%s", scheme, host, port, path, restrict);
if (!query.isEmpty()) {
url += "&" + query;
}
CoAPEndpoint endpoint = (CoAPEndpoint) camelContext.getEndpoint(url, parameters);
// configure consumer properties
Consumer consumer = endpoint.createConsumer(processor);
if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {
setProperties(camelContext, consumer, config.getConsumerProperties());
}
return consumer;
}
private static String doGetHost(RestConfiguration config) throws UnknownHostException {
String host = config.getHost();
if (ObjectHelper.isEmpty(host)) {
if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
host = "0.0.0.0";
} else if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
host = HostUtils.getLocalHostName();
} else if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
host = HostUtils.getLocalIp();
}
}
return host;
}
public String getConfigurationFile() {
return configurationFile;
}
/**
* Name of COAP configuration file to load and use. Will by default load from classpath, so use file: as prefix to
* load from file system.
*/
public void setConfigurationFile(String configurationFile) {
this.configurationFile = configurationFile;
}
@Override
protected void doStart() throws Exception {
super.doStart();
for (CoapServer s : servers.values()) {
s.start();
}
}
@Override
protected void doStop() throws Exception {
for (CoapServer s : servers.values()) {
s.stop();
}
super.doStop();
}
}
| CoAPComponent |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/MySqlParameterizedOutputVisitorTest_63.java | {
"start": 386,
"end": 2814
} | class ____ extends TestCase {
public void test_for_parameterize() throws Exception {
String sql = "select * from abc where id in (null)";
List<Object> params = new ArrayList<Object>();
String psql = ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL, params, VisitorFeature.OutputParameterizedUnMergeShardingTable);
assertEquals("SELECT *\n" +
"FROM abc\n" +
"WHERE id IN (?)", psql);
assertEquals(1, params.size());
assertEquals("null", JSON.toJSONString(params.get(0)));
String rsql = ParameterizedOutputVisitorUtils.restore(sql, JdbcConstants.MYSQL, params);
assertEquals("SELECT *\n" +
"FROM abc\n" +
"WHERE id IN (NULL)", rsql);
}
public void test_for_parameterize_1() throws Exception {
String sql = "select * from abc where id in (1)";
List<Object> params = new ArrayList<Object>();
String psql = ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL, params, VisitorFeature.OutputParameterizedUnMergeShardingTable);
assertEquals("SELECT *\n" +
"FROM abc\n" +
"WHERE id IN (?)", psql);
assertEquals(1, params.size());
assertEquals("1", JSON.toJSONString(params.get(0)));
String rsql = ParameterizedOutputVisitorUtils.restore(sql, JdbcConstants.MYSQL, params);
assertEquals("SELECT *\n" +
"FROM abc\n" +
"WHERE id IN (1)", rsql);
}
public void test_for_parameterize_2() throws Exception {
String sql = "select * from abc where id in (null, null)";
List<Object> params = new ArrayList<Object>();
String psql = ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL, params, VisitorFeature.OutputParameterizedUnMergeShardingTable);
assertEquals("SELECT *\n" +
"FROM abc\n" +
"WHERE id IN (?)", psql);
assertEquals(2, params.size());
assertEquals("null", JSON.toJSONString(params.get(0)));
assertEquals("null", JSON.toJSONString(params.get(1)));
String rsql = ParameterizedOutputVisitorUtils.restore(sql, JdbcConstants.MYSQL, params);
assertEquals("SELECT *\n" +
"FROM abc\n" +
"WHERE id IN (NULL, NULL)", rsql);
}
}
| MySqlParameterizedOutputVisitorTest_63 |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/accessibility/referenced/SourceTargetMapperPrivate.java | {
"start": 392,
"end": 636
} | interface ____ {
SourceTargetMapperPrivate INSTANCE = Mappers.getMapper( SourceTargetMapperPrivate.class );
@Mapping(target = "referencedTarget", source = "referencedSource")
Target toTarget(Source source);
}
| SourceTargetMapperPrivate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.