language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | elastic__elasticsearch | modules/analysis-common/src/test/java/org/elasticsearch/analysis/common/StemmerTokenFilterFactoryTests.java | {
"start": 1680,
"end": 5625
} | class ____ extends ESTokenStreamTestCase {
private static final CommonAnalysisPlugin PLUGIN = new CommonAnalysisPlugin();
public void testEnglishFilterFactory() throws IOException {
int iters = scaledRandomIntBetween(20, 100);
for (int i = 0; i < iters; i++) {
IndexVersion v = IndexVersionUtils.randomVersion();
Settings settings = Settings.builder()
.put("index.analysis.filter.my_english.type", "stemmer")
.put("index.analysis.filter.my_english.language", "english")
.put("index.analysis.analyzer.my_english.tokenizer", "whitespace")
.put("index.analysis.analyzer.my_english.filter", "my_english")
.put(SETTING_VERSION_CREATED, v)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
ESTestCase.TestAnalysis analysis = AnalysisTestsHelper.createTestAnalysisFromSettings(settings, PLUGIN);
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_english");
assertThat(tokenFilter, instanceOf(StemmerTokenFilterFactory.class));
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader("foo bar"));
TokenStream create = tokenFilter.create(tokenizer);
IndexAnalyzers indexAnalyzers = analysis.indexAnalyzers;
NamedAnalyzer analyzer = indexAnalyzers.get("my_english");
assertThat(create, instanceOf(PorterStemFilter.class));
assertAnalyzesTo(analyzer, "consolingly", new String[] { "consolingli" });
}
}
public void testPorter2FilterFactory() throws IOException {
int iters = scaledRandomIntBetween(20, 100);
for (int i = 0; i < iters; i++) {
IndexVersion v = IndexVersionUtils.randomVersion();
Settings settings = Settings.builder()
.put("index.analysis.filter.my_porter2.type", "stemmer")
.put("index.analysis.filter.my_porter2.language", "porter2")
.put("index.analysis.analyzer.my_porter2.tokenizer", "whitespace")
.put("index.analysis.analyzer.my_porter2.filter", "my_porter2")
.put(SETTING_VERSION_CREATED, v)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
ESTestCase.TestAnalysis analysis = AnalysisTestsHelper.createTestAnalysisFromSettings(settings, PLUGIN);
TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_porter2");
assertThat(tokenFilter, instanceOf(StemmerTokenFilterFactory.class));
Tokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setReader(new StringReader("foo bar"));
TokenStream create = tokenFilter.create(tokenizer);
IndexAnalyzers indexAnalyzers = analysis.indexAnalyzers;
NamedAnalyzer analyzer = indexAnalyzers.get("my_porter2");
assertThat(create, instanceOf(SnowballFilter.class));
assertAnalyzesTo(analyzer, "possibly", new String[] { "possibl" });
}
}
public void testMultipleLanguagesThrowsException() throws IOException {
IndexVersion v = IndexVersionUtils.randomVersion();
Settings settings = Settings.builder()
.put("index.analysis.filter.my_english.type", "stemmer")
.putList("index.analysis.filter.my_english.language", "english", "light_english")
.put(SETTING_VERSION_CREATED, v)
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> AnalysisTestsHelper.createTestAnalysisFromSettings(settings, PLUGIN)
);
assertEquals("Invalid stemmer | StemmerTokenFilterFactoryTests |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/MethodParameter.java | {
"start": 14582,
"end": 14819
} | class ____ resolve the parameter type against.
*/
@Deprecated(since = "5.2")
void setContainingClass(Class<?> containingClass) {
this.containingClass = containingClass;
this.parameterType = null;
}
/**
* Return the containing | to |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/TransactionalNestedTests.java | {
"start": 5041,
"end": 5355
} | class ____ {
@Bean
TransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
DataSource dataSource() {
return new EmbeddedDatabaseBuilder().generateUniqueName(true).build();
}
}
@Transactional(propagation = NOT_SUPPORTED)
| Config |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire.java | {
"start": 195,
"end": 758
} | class ____ extends TestCase {
public void test_for_spitFire() throws Exception {
GenericDTO<MyDTO> object = new GenericDTO<MyDTO>();
object.setFiled(new MyDTO());
String text = JSON.toJSONString(object, SerializerFeature.WriteClassName);
GenericDTO<MyDTO> object2 = (GenericDTO<MyDTO>) JSON.parseObject(text, GenericDTO.class);
Assert.assertEquals(object.getName(), object2.getName());
Assert.assertEquals(object.getFiled().getId(), object2.getFiled().getId());
}
public static | Bug_for_SpitFire |
java | apache__dubbo | dubbo-spring-boot-project/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboActuatorProperties.java | {
"start": 1127,
"end": 1627
} | class ____ {
private Map<String, Boolean> dubbo;
public Map<String, Boolean> getDubbo() {
return dubbo;
}
public void setDubbo(Map<String, Boolean> dubbo) {
this.dubbo = dubbo;
}
public boolean isEnabled(String command) {
if (StringUtils.hasText(command)) {
Boolean enabled = dubbo.get(command + ".enabled");
return enabled != null && enabled;
} else {
return false;
}
}
}
| DubboActuatorProperties |
java | apache__camel | components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/cluster/utils/LeaderRecorder.java | {
"start": 3883,
"end": 4314
} | class ____ {
private String leader;
private long changeTimestamp;
public LeadershipInfo(String leader, long changeTimestamp) {
this.leader = leader;
this.changeTimestamp = changeTimestamp;
}
public String getLeader() {
return leader;
}
public long getChangeTimestamp() {
return changeTimestamp;
}
}
}
| LeadershipInfo |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java | {
"start": 2211,
"end": 10367
} | class ____ implements ClientCall, ClientStream.Listener {
private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(TripleClientCall.class);
private final AbstractConnectionClient connectionClient;
private final Executor executor;
private final FrameworkModel frameworkModel;
private final TripleWriteQueue writeQueue;
private RequestMetadata requestMetadata;
private ClientStream stream;
private ClientCall.Listener listener;
private boolean canceled;
private boolean headerSent;
private boolean autoRequest = true;
private boolean done;
private StreamException streamException;
public TripleClientCall(
AbstractConnectionClient connectionClient,
Executor executor,
FrameworkModel frameworkModel,
TripleWriteQueue writeQueue) {
this.connectionClient = connectionClient;
this.executor = executor;
this.frameworkModel = frameworkModel;
this.writeQueue = writeQueue;
}
// stream listener start
@Override
public void onMessage(byte[] message, boolean isReturnTriException) {
if (done) {
LOGGER.warn(
PROTOCOL_STREAM_LISTENER,
"",
"",
"Received message from closed stream,connection=" + connectionClient + " service="
+ requestMetadata.service + " method="
+ requestMetadata.method.getMethodName());
return;
}
try {
Object unpacked = requestMetadata.packableMethod.parseResponse(message, isReturnTriException);
listener.onMessage(unpacked, message.length);
} catch (Throwable t) {
TriRpcStatus status = TriRpcStatus.INTERNAL
.withDescription("Deserialize response failed")
.withCause(t);
cancelByLocal(status.asException());
listener.onClose(status, null, false);
LOGGER.error(
PROTOCOL_FAILED_RESPONSE,
"",
"",
String.format(
"Failed to deserialize triple response, service=%s, method=%s,connection=%s",
requestMetadata.service, requestMetadata.service, requestMetadata.method.getMethodName()),
t);
}
}
@Override
public void onCancelByRemote(TriRpcStatus status) {
if (canceled) {
return;
}
canceled = true;
if (requestMetadata.cancellationContext != null) {
requestMetadata.cancellationContext.cancel(status.asException());
}
onComplete(status, null, null, false);
}
@Override
public void onComplete(
TriRpcStatus status,
Map<String, Object> attachments,
Map<CharSequence, String> excludeHeaders,
boolean isReturnTriException) {
if (done) {
return;
}
done = true;
try {
listener.onClose(status, StreamUtils.toAttachments(attachments), isReturnTriException);
} catch (Throwable t) {
cancelByLocal(TriRpcStatus.INTERNAL
.withDescription("Close stream error")
.withCause(t)
.asException());
}
if (requestMetadata.cancellationContext != null) {
requestMetadata.cancellationContext.cancel(null);
}
}
@Override
public void onClose() {
if (done) {
return;
}
onCancelByRemote(TriRpcStatus.CANCELLED);
}
@Override
public void onStart() {
listener.onStart(this);
}
@Override
public void cancelByLocal(Throwable t) {
if (canceled) {
return;
}
// did not create stream
if (!headerSent) {
return;
}
canceled = true;
if (stream == null) {
return;
}
if (t instanceof StreamException && ((StreamException) t).error().equals(FLOW_CONTROL_ERROR)) {
TriRpcStatus status = TriRpcStatus.CANCELLED
.withCause(t)
.withDescription("Due flowcontrol over pendingbytes, Cancelled by client");
stream.cancelByLocal(status);
streamException = (StreamException) t;
} else {
TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t).withDescription("Cancelled by client");
stream.cancelByLocal(status);
}
TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t).withDescription("Cancelled by client");
stream.cancelByLocal(status);
if (requestMetadata.cancellationContext != null) {
requestMetadata.cancellationContext.cancel(t);
}
}
@Override
public void request(int messageNumber) {
stream.request(messageNumber);
}
@Override
public void sendMessage(Object message) {
if (canceled && null != streamException) {
throw new IllegalStateException("Due flowcontrol over pendingbytes, Call already canceled");
} else if (canceled) {
throw new IllegalStateException("Call already canceled");
}
if (!headerSent) {
headerSent = true;
stream.sendHeader(requestMetadata.toHeaders());
}
final byte[] data;
try {
data = requestMetadata.packableMethod.packRequest(message);
int compressed = Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) ? 0 : 1;
final byte[] compress = requestMetadata.compressor.compress(data);
stream.sendMessage(compress, compressed).addListener(f -> {
if (!f.isSuccess()) {
cancelByLocal(f.cause());
}
});
} catch (Throwable t) {
LOGGER.error(
PROTOCOL_FAILED_SERIALIZE_TRIPLE,
"",
"",
String.format(
"Serialize triple request failed, service=%s method=%s",
requestMetadata.service, requestMetadata.method.getMethodName()),
t);
cancelByLocal(t);
listener.onClose(
TriRpcStatus.INTERNAL
.withDescription("Serialize request failed")
.withCause(t),
null,
false);
}
}
// stream listener end
@Override
public void halfClose() {
if (!headerSent) {
return;
}
if (canceled) {
return;
}
stream.halfClose().addListener(f -> {
if (!f.isSuccess()) {
cancelByLocal(new IllegalStateException("Half close failed", f.cause()));
}
});
}
@Override
public void setCompression(String compression) {
requestMetadata.compressor = Compressor.getCompressor(frameworkModel, compression);
}
@Override
public StreamObserver<Object> start(RequestMetadata metadata, ClientCall.Listener responseListener) {
ClientStream stream;
for (ClientStreamFactory factory : frameworkModel.getActivateExtensions(ClientStreamFactory.class)) {
stream = factory.createClientStream(connectionClient, frameworkModel, executor, this, writeQueue);
if (stream != null) {
this.requestMetadata = metadata;
this.listener = responseListener;
this.stream = stream;
return new ClientCallToObserverAdapter<>(this);
}
}
throw new IllegalStateException("No available ClientStreamFactory");
}
@Override
public boolean isAutoRequest() {
return autoRequest;
}
@Override
public void setAutoRequest(boolean autoRequest) {
this.autoRequest = autoRequest;
}
}
| TripleClientCall |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/unused/RemoveUnusedBeansTest.java | {
"start": 1003,
"end": 3277
} | class ____ extends RemoveUnusedComponentsTest {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(HasObserver.class, Foo.class, FooAlternative.class, HasName.class, UnusedProducers.class,
InjectedViaInstance.class, InjectedViaInstanceWithWildcard.class, InjectedViaProvider.class, Excluded.class,
UsedProducers.class, UnusedProducerButInjected.class, UsedViaInstanceWithUnusedProducer.class,
UsesBeanViaInstance.class, UsedViaAllList.class, UnusedBean.class, OnlyInjectedInUnusedBean.class)
.removeUnusedBeans(true)
.addRemovalExclusion(b -> b.getBeanClass().toString().equals(Excluded.class.getName()))
.build();
@Test
public void testRemoval() {
assertPresent(HasObserver.class);
assertPresent(HasName.class);
assertPresent(InjectedViaInstance.class);
assertPresent(InjectedViaInstanceWithWildcard.class);
assertPresent(InjectedViaProvider.class);
assertPresent(String.class);
assertPresent(UsedProducers.class);
assertNotPresent(UnusedProducers.class);
assertNotPresent(BigDecimal.class);
ArcContainer container = Arc.container();
// Foo is injected in HasObserver#observe()
Foo foo = container.instance(Foo.class).get();
assertEquals(FooAlternative.class.getName(), foo.ping());
assertTrue(foo.provider.get().isValid());
assertEquals(1, container.beanManager().getBeans(Foo.class).size());
assertEquals("pong", container.instance(Excluded.class).get().ping());
// Producer is unused but declaring bean is injected
assertPresent(UnusedProducerButInjected.class);
assertNotPresent(BigInteger.class);
// Producer is unused, declaring bean is only used via Instance
assertPresent(UsedViaInstanceWithUnusedProducer.class);
assertNotPresent(Long.class);
assertFalse(ArcContainerImpl.instance().getRemovedBeans().isEmpty());
assertNotPresent(UnusedBean.class);
assertNotPresent(OnlyInjectedInUnusedBean.class);
assertPresent(UsedViaAllList.class);
}
@Dependent
static | RemoveUnusedBeansTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java | {
"start": 7091,
"end": 10103
} | class ____ {
private final MockMvcTester mockMvc = MockMvcTester.of(new AsyncController());
@Test
void callable() {
assertThat(mockMvc.get().uri("/1").param("callable", "true"))
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
.hasBodyTextEqualTo("{\"name\":\"Joe\",\"someBoolean\":false,\"someDouble\":0.0}");
}
@Test
void streaming() {
assertThat(this.mockMvc.get().uri("/1").param("streaming", "true"))
.hasStatusOk().hasBodyTextEqualTo("name=Joe");
}
@Test
void streamingSlow() {
assertThat(this.mockMvc.get().uri("/1").param("streamingSlow", "true"))
.hasStatusOk().hasBodyTextEqualTo("name=Joe&someBoolean=true");
}
@Test
void streamingJson() {
assertThat(this.mockMvc.get().uri("/1").param("streamingJson", "true"))
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
.hasBodyTextEqualTo("{\"name\":\"Joe\",\"someDouble\":0.5}");
}
@Test
void deferredResult() {
assertThat(this.mockMvc.get().uri("/1").param("deferredResult", "true"))
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
.hasBodyTextEqualTo("{\"name\":\"Joe\",\"someBoolean\":false,\"someDouble\":0.0}");
}
@Test
void deferredResultWithImmediateValue() {
assertThat(this.mockMvc.get().uri("/1").param("deferredResultWithImmediateValue", "true"))
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
.hasBodyTextEqualTo("{\"name\":\"Joe\",\"someBoolean\":false,\"someDouble\":0.0}");
}
@Test // SPR-13079
void deferredResultWithDelayedError() {
assertThat(this.mockMvc.get().uri("/1").param("deferredResultWithDelayedError", "true"))
.hasStatus5xxServerError().hasBodyTextEqualTo("Delayed Error");
}
@Test // SPR-12597
void completableFutureWithImmediateValue() {
assertThat(this.mockMvc.get().uri("/1").param("completableFutureWithImmediateValue", "true"))
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
.hasBodyTextEqualTo("{\"name\":\"Joe\",\"someBoolean\":false,\"someDouble\":0.0}");
}
@Test // SPR-12735
void printAsyncResult() {
StringWriter asyncWriter = new StringWriter();
MvcTestResult result = this.mockMvc.get().uri("/1").param("deferredResult", "true").asyncExchange();
assertThat(result).debug(asyncWriter).request().hasAsyncStarted(true);
assertThat(asyncWriter.toString()).contains("Async started = true");
asyncWriter = new StringWriter(); // Reset
assertThat(this.mockMvc.perform(asyncDispatch(result.getMvcResult())))
.debug(asyncWriter)
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
.hasBodyTextEqualTo("{\"name\":\"Joe\",\"someBoolean\":false,\"someDouble\":0.0}");
assertThat(asyncWriter.toString()).contains("Async started = false");
}
}
@RestController
@RequestMapping(path = "/{id}", produces = "application/json")
private static | MockMvcTesterTests |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/immutable/ImmutablePrimitiveWithDefaultsProperties.java | {
"start": 901,
"end": 1762
} | class ____ {
private final boolean flag;
private final byte octet;
private final char letter;
private final short number;
private final int counter;
private final long value;
private final float percentage;
private final double ratio;
public ImmutablePrimitiveWithDefaultsProperties(@TestDefaultValue("true") boolean flag,
@TestDefaultValue("120") byte octet, @TestDefaultValue("a") char letter,
@TestDefaultValue("1000") short number, @TestDefaultValue("42") int counter,
@TestDefaultValue("2000") long value, @TestDefaultValue("0.5") float percentage,
@TestDefaultValue("42.42") double ratio) {
this.flag = flag;
this.octet = octet;
this.letter = letter;
this.number = number;
this.counter = counter;
this.value = value;
this.percentage = percentage;
this.ratio = ratio;
}
}
| ImmutablePrimitiveWithDefaultsProperties |
java | apache__flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/operators/StreamSourceOperatorWatermarksTest.java | {
"start": 1857,
"end": 6048
} | class ____ {
@Test
void testEmitMaxWatermarkForFiniteSource() throws Exception {
StreamSource<String, ?> sourceOperator = new StreamSource<>(new FiniteSource<>());
StreamTaskTestHarness<String> testHarness =
setupSourceStreamTask(sourceOperator, BasicTypeInfo.STRING_TYPE_INFO);
testHarness.invoke();
testHarness.waitForTaskCompletion();
assertThat(testHarness.getOutput()).hasSize(1);
assertThat(testHarness.getOutput().peek()).isEqualTo(Watermark.MAX_WATERMARK);
}
@Test
void testDisabledProgressiveWatermarksForFiniteSource() throws Exception {
StreamSource<String, ?> sourceOperator =
new StreamSource<>(new FiniteSourceWithWatermarks<>(), false);
StreamTaskTestHarness<String> testHarness =
setupSourceStreamTask(sourceOperator, BasicTypeInfo.STRING_TYPE_INFO);
testHarness.invoke();
testHarness.waitForTaskCompletion();
// sent by source function
assertThat(testHarness.getOutput().poll()).isEqualTo(Watermark.MAX_WATERMARK);
// sent by framework
assertThat(testHarness.getOutput().poll()).isEqualTo(Watermark.MAX_WATERMARK);
assertThat(testHarness.getOutput()).isEmpty();
}
@Test
void testNoMaxWatermarkOnImmediateCancel() throws Exception {
StreamSource<String, ?> sourceOperator = new StreamSource<>(new InfiniteSource<>());
StreamTaskTestHarness<String> testHarness =
setupSourceStreamTask(sourceOperator, BasicTypeInfo.STRING_TYPE_INFO, true);
testHarness.invoke();
assertThatThrownBy(testHarness::waitForTaskCompletion)
.hasCauseInstanceOf(CancelTaskException.class);
assertThat(testHarness.getOutput()).isEmpty();
}
@Test
void testNoMaxWatermarkOnAsyncCancel() throws Exception {
StreamSource<String, ?> sourceOperator = new StreamSource<>(new InfiniteSource<>());
StreamTaskTestHarness<String> testHarness =
setupSourceStreamTask(sourceOperator, BasicTypeInfo.STRING_TYPE_INFO);
testHarness.invoke();
testHarness.waitForTaskRunning();
Thread.sleep(200);
testHarness.getTask().cancel();
try {
testHarness.waitForTaskCompletion();
} catch (Throwable t) {
if (!ExceptionUtils.findThrowable(t, CancelTaskException.class).isPresent()) {
throw t;
}
}
assertThat(testHarness.getOutput()).isEmpty();
}
// ------------------------------------------------------------------------
private static <T> StreamTaskTestHarness<T> setupSourceStreamTask(
StreamSource<T, ?> sourceOperator, TypeInformation<T> outputType) {
return setupSourceStreamTask(sourceOperator, outputType, false);
}
private static <T> StreamTaskTestHarness<T> setupSourceStreamTask(
StreamSource<T, ?> sourceOperator,
TypeInformation<T> outputType,
final boolean cancelImmediatelyAfterCreation) {
final StreamTaskTestHarness<T> testHarness =
new StreamTaskTestHarness<>(
(env) -> {
SourceStreamTask<T, ?, ?> sourceTask = new SourceStreamTask<>(env);
if (cancelImmediatelyAfterCreation) {
try {
sourceTask.cancel();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sourceTask;
},
outputType);
testHarness.setupOutputForSingletonOperatorChain();
StreamConfig streamConfig = testHarness.getStreamConfig();
streamConfig.setStreamOperator(sourceOperator);
streamConfig.setOperatorID(new OperatorID());
return testHarness;
}
// ------------------------------------------------------------------------
private static final | StreamSourceOperatorWatermarksTest |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0761MissingSnapshotDistRepoTest.java | {
"start": 1036,
"end": 1891
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that a deployment of a snapshot falls back to a non-snapshot repository if no snapshot repository is
* specified.
*
* @throws Exception in case of failure
*/
@Test
public void testitMNG761() throws Exception {
File testDir = extractResources("/mng-0761");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.deleteArtifacts("org.apache.maven.its.mng0761");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyFilePresent("target/repo/org/apache/maven/its/mng0761/test/1.0-SNAPSHOT/test-1.0-*.jar");
}
}
| MavenITmng0761MissingSnapshotDistRepoTest |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java | {
"start": 1047,
"end": 4344
} | class ____ {
@Test
public void fromWhenAuthorizationConsentNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizationConsent.from(null))
.withMessage("authorizationConsent cannot be null");
}
@Test
public void withIdWhenRegisteredClientIdNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizationConsent.withId(null, "some-user"))
.withMessage("registeredClientId cannot be empty");
}
@Test
public void withIdWhenPrincipalNameNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizationConsent.withId("some-client", null))
.withMessage("principalName cannot be empty");
}
@Test
public void buildWhenAuthoritiesEmptyThenThrowIllegalArgumentException() {
OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId("some-client", "some-user");
assertThatIllegalArgumentException().isThrownBy(builder::build).withMessage("authorities cannot be empty");
}
@Test
public void buildWhenAllAttributesAreProvidedThenAllAttributesAreSet() {
OAuth2AuthorizationConsent authorizationConsent = OAuth2AuthorizationConsent.withId("some-client", "some-user")
.scope("resource.read")
.scope("resource.write")
.authority(new SimpleGrantedAuthority("CLAIM_email"))
.build();
assertThat(authorizationConsent.getRegisteredClientId()).isEqualTo("some-client");
assertThat(authorizationConsent.getPrincipalName()).isEqualTo("some-user");
assertThat(authorizationConsent.getScopes()).containsExactlyInAnyOrder("resource.read", "resource.write");
assertThat(authorizationConsent.getAuthorities()).containsExactlyInAnyOrder(
new SimpleGrantedAuthority("SCOPE_resource.read"), new SimpleGrantedAuthority("SCOPE_resource.write"),
new SimpleGrantedAuthority("CLAIM_email"));
}
@Test
public void fromWhenAuthorizationConsentProvidedThenCopied() {
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
.withId("some-client", "some-principal")
.scope("first.scope")
.scope("second.scope")
.authority(new SimpleGrantedAuthority("CLAIM_email"))
.build();
OAuth2AuthorizationConsent authorizationConsent = OAuth2AuthorizationConsent.from(previousAuthorizationConsent)
.build();
assertThat(authorizationConsent.getRegisteredClientId()).isEqualTo("some-client");
assertThat(authorizationConsent.getPrincipalName()).isEqualTo("some-principal");
assertThat(authorizationConsent.getAuthorities()).containsExactlyInAnyOrder(
new SimpleGrantedAuthority("SCOPE_first.scope"), new SimpleGrantedAuthority("SCOPE_second.scope"),
new SimpleGrantedAuthority("CLAIM_email"));
}
@Test
public void authoritiesThenCustomizesAuthorities() {
OAuth2AuthorizationConsent authorizationConsent = OAuth2AuthorizationConsent.withId("some-client", "some-user")
.authority(new SimpleGrantedAuthority("some.authority"))
.authorities((authorities) -> {
authorities.clear();
authorities.add(new SimpleGrantedAuthority("other.authority"));
})
.build();
assertThat(authorizationConsent.getAuthorities())
.containsExactly(new SimpleGrantedAuthority("other.authority"));
}
}
| OAuth2AuthorizationConsentTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java | {
"start": 27260,
"end": 27517
} | class ____ {
int a = foo(1);
private int foo(int b) {
b = 1;
return 1;
}
}
""")
.addOutputLines(
"Test.java",
"""
| Test |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java | {
"start": 110753,
"end": 110894
} | class ____ extends AsyncScalarFunction {
public void eval(CompletableFuture<Integer> f) {}
}
private static | ZeroArgFunctionAsync |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/SnappyCodec.java | {
"start": 1303,
"end": 1362
} | class ____ snappy compressors/decompressors.
*/
public | creates |
java | apache__thrift | lib/java/src/main/java/org/apache/thrift/partial/ThriftMetadata.java | {
"start": 2689,
"end": 2900
} | class ____ implements Serializable {
public final ThriftObject parent;
public final TFieldIdEnum fieldId;
public final FieldMetaData data;
// Placeholder to attach additional data. This | ThriftObject |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/Spawner.java | {
"start": 1442,
"end": 7507
} | class ____ implements Closeable {
/*
* References to the processes that have been spawned, so that we can destroy them.
*/
private final List<Process> processes = new ArrayList<>();
private final List<Thread> pumpThreads = new ArrayList<>();
private AtomicBoolean spawned = new AtomicBoolean();
@Override
public void close() throws IOException {
List<Closeable> closeables = new ArrayList<>();
closeables.addAll(processes.stream().map(s -> (Closeable) s::destroy).toList());
closeables.addAll(pumpThreads.stream().map(t -> (Closeable) () -> {
try {
t.join(); // wait for thread to complete now that the spawned process is destroyed
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // best effort, ignore
}
}).toList());
IOUtils.close(closeables);
}
/**
* Spawns the native controllers for each module.
*
* @param environment The node environment
* @throws IOException if an I/O error occurs reading the module or spawning a native process
*/
void spawnNativeControllers(final Environment environment) throws IOException {
if (spawned.compareAndSet(false, true) == false) {
throw new IllegalStateException("native controllers already spawned");
}
if (Files.exists(environment.modulesDir()) == false) {
throw new IllegalStateException("modules directory [" + environment.modulesDir() + "] not found");
}
/*
* For each module, attempt to spawn the controller daemon. Silently ignore any module that doesn't include a controller for the
* correct platform.
*/
List<Path> paths = PluginsUtils.findPluginDirs(environment.modulesDir());
for (final Path modules : paths) {
final PluginDescriptor info = PluginDescriptor.readFromProperties(modules);
final Path spawnPath = Platforms.nativeControllerPath(modules);
if (Files.isRegularFile(spawnPath) == false) {
continue;
}
if (info.hasNativeController() == false) {
final String message = String.format(
Locale.ROOT,
"module [%s] does not have permission to fork native controller",
modules.getFileName()
);
throw new IllegalArgumentException(message);
}
final Process process = spawnNativeController(spawnPath, environment.tmpDir());
// The process _shouldn't_ write any output via its stdout or stderr, but if it does then
// it will block if nothing is reading that output. To avoid this we can pipe the
// outputs and create pump threads to write any messages there to the ES log.
startPumpThread(info.getName(), "stdout", process.getInputStream());
startPumpThread(info.getName(), "stderr", process.getErrorStream());
processes.add(process);
}
}
private void startPumpThread(String componentName, String streamName, InputStream stream) {
String loggerName = componentName + "-controller-" + streamName;
final Logger logger = LogManager.getLogger(loggerName);
Thread t = new Thread(() -> {
try (var br = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
// since we do not expect native controllers to ever write to stdout/stderr, we always log at warn level
logger.warn(line);
}
} catch (IOException e) {
logger.error("error while reading " + streamName, e);
}
}, loggerName + "-pump");
t.start();
pumpThreads.add(t);
}
/**
* Attempt to spawn the controller daemon for a given module. The spawned process will remain connected to this JVM via its stdin,
* stdout, and stderr streams, but the references to these streams are not available to code outside this package.
*/
private static Process spawnNativeController(final Path spawnPath, final Path tmpPath) throws IOException {
final String command;
if (Constants.WINDOWS) {
/*
* We have to get the short path name or starting the process could fail due to max path limitations. The underlying issue here
* is that starting the process on Windows ultimately involves the use of CreateProcessW. CreateProcessW has a limitation that
* if its first argument (the application name) is null, then its second argument (the command line for the process to start) is
* restricted in length to 260 characters (cf. https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425.aspx). Since
* this is exactly how the JDK starts the process on Windows (cf.
* http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/native/java/lang/ProcessImpl_md.c#l319), this
* limitation is in force. As such, we use the short name to avoid any such problems.
*/
command = NativeAccess.instance().getWindowsFunctions().getShortPathName(spawnPath.toString());
} else {
command = spawnPath.toString();
}
final ProcessBuilder pb = new ProcessBuilder(command);
// the only environment variable passes on the path to the temporary directory
pb.environment().clear();
pb.environment().put("TMPDIR", tmpPath.toString());
// the output stream of the process object corresponds to the daemon's stdin
return pb.start();
}
/**
* The collection of processes representing spawned native controllers.
*
* @return the processes
*/
List<Process> getProcesses() {
return Collections.unmodifiableList(processes);
}
}
| Spawner |
java | apache__flink | flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/api/java/hadoop/mapreduce/HadoopInputFormatBase.java | {
"start": 3273,
"end": 13610
} | class ____ using a custom serialization logic, without a defaultWriteObject()
// method.
// Hence, all fields here are "transient".
private org.apache.hadoop.mapreduce.InputFormat<K, V> mapreduceInputFormat;
protected Class<K> keyClass;
protected Class<V> valueClass;
private org.apache.hadoop.conf.Configuration configuration;
protected transient RecordReader<K, V> recordReader;
protected boolean fetched = false;
protected boolean hasNext;
public HadoopInputFormatBase(
org.apache.hadoop.mapreduce.InputFormat<K, V> mapreduceInputFormat,
Class<K> key,
Class<V> value,
Job job) {
super(Preconditions.checkNotNull(job, "Job can not be null").getCredentials());
this.mapreduceInputFormat = Preconditions.checkNotNull(mapreduceInputFormat);
this.keyClass = Preconditions.checkNotNull(key);
this.valueClass = Preconditions.checkNotNull(value);
this.configuration = job.getConfiguration();
HadoopUtils.mergeHadoopConf(configuration);
}
public org.apache.hadoop.conf.Configuration getConfiguration() {
return this.configuration;
}
// --------------------------------------------------------------------------------------------
// InputFormat
// --------------------------------------------------------------------------------------------
@Override
public void configure(Configuration parameters) {
// enforce sequential configuration() calls
synchronized (CONFIGURE_MUTEX) {
if (mapreduceInputFormat instanceof Configurable) {
((Configurable) mapreduceInputFormat).setConf(configuration);
}
}
}
@Override
public BaseStatistics getStatistics(BaseStatistics cachedStats) throws IOException {
// only gather base statistics for FileInputFormats
if (!(mapreduceInputFormat instanceof FileInputFormat)) {
return null;
}
JobContext jobContext = new JobContextImpl(configuration, null);
final FileBaseStatistics cachedFileStats =
(cachedStats instanceof FileBaseStatistics)
? (FileBaseStatistics) cachedStats
: null;
try {
final org.apache.hadoop.fs.Path[] paths = FileInputFormat.getInputPaths(jobContext);
return getFileStats(cachedFileStats, paths, new ArrayList<FileStatus>(1));
} catch (IOException ioex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not determine statistics due to an io error: " + ioex.getMessage());
}
} catch (Throwable t) {
if (LOG.isErrorEnabled()) {
LOG.error(
"Unexpected problem while getting the file statistics: " + t.getMessage(),
t);
}
}
// no statistics available
return null;
}
@Override
public HadoopInputSplit[] createInputSplits(int minNumSplits) throws IOException {
configuration.setInt("mapreduce.input.fileinputformat.split.minsize", minNumSplits);
JobContext jobContext = new JobContextImpl(configuration, new JobID());
jobContext.getCredentials().addAll(this.credentials);
Credentials currentUserCreds = getCredentialsFromUGI(UserGroupInformation.getCurrentUser());
if (currentUserCreds != null) {
jobContext.getCredentials().addAll(currentUserCreds);
}
List<org.apache.hadoop.mapreduce.InputSplit> splits;
try {
splits = this.mapreduceInputFormat.getSplits(jobContext);
} catch (InterruptedException e) {
throw new IOException("Could not get Splits.", e);
}
HadoopInputSplit[] hadoopInputSplits = new HadoopInputSplit[splits.size()];
for (int i = 0; i < hadoopInputSplits.length; i++) {
hadoopInputSplits[i] = new HadoopInputSplit(i, splits.get(i), jobContext);
}
return hadoopInputSplits;
}
@Override
public InputSplitAssigner getInputSplitAssigner(HadoopInputSplit[] inputSplits) {
return new LocatableInputSplitAssigner(inputSplits);
}
@Override
public void open(HadoopInputSplit split) throws IOException {
// enforce sequential open() calls
synchronized (OPEN_MUTEX) {
TaskAttemptContext context =
new TaskAttemptContextImpl(configuration, new TaskAttemptID());
try {
this.recordReader =
this.mapreduceInputFormat.createRecordReader(
split.getHadoopInputSplit(), context);
this.recordReader.initialize(split.getHadoopInputSplit(), context);
} catch (InterruptedException e) {
throw new IOException("Could not create RecordReader.", e);
} finally {
this.fetched = false;
}
}
}
@Override
public boolean reachedEnd() throws IOException {
if (!this.fetched) {
fetchNext();
}
return !this.hasNext;
}
protected void fetchNext() throws IOException {
try {
this.hasNext = this.recordReader.nextKeyValue();
} catch (InterruptedException e) {
throw new IOException("Could not fetch next KeyValue pair.", e);
} finally {
this.fetched = true;
}
}
@Override
public void close() throws IOException {
if (this.recordReader != null) {
// enforce sequential close() calls
synchronized (CLOSE_MUTEX) {
this.recordReader.close();
}
}
}
// --------------------------------------------------------------------------------------------
// Helper methods
// --------------------------------------------------------------------------------------------
private FileBaseStatistics getFileStats(
FileBaseStatistics cachedStats,
org.apache.hadoop.fs.Path[] hadoopFilePaths,
ArrayList<FileStatus> files)
throws IOException {
long latestModTime = 0L;
// get the file info and check whether the cached statistics are still valid.
for (org.apache.hadoop.fs.Path hadoopPath : hadoopFilePaths) {
final Path filePath = new Path(hadoopPath.toUri());
final FileSystem fs = FileSystem.get(filePath.toUri());
final FileStatus file = fs.getFileStatus(filePath);
latestModTime = Math.max(latestModTime, file.getModificationTime());
// enumerate all files and check their modification time stamp.
if (file.isDir()) {
FileStatus[] fss = fs.listStatus(filePath);
files.ensureCapacity(files.size() + fss.length);
for (FileStatus s : fss) {
if (!s.isDir()) {
files.add(s);
latestModTime = Math.max(s.getModificationTime(), latestModTime);
}
}
} else {
files.add(file);
}
}
// check whether the cached statistics are still valid, if we have any
if (cachedStats != null && latestModTime <= cachedStats.getLastModificationTime()) {
return cachedStats;
}
// calculate the whole length
long len = 0;
for (FileStatus s : files) {
len += s.getLen();
}
// sanity check
if (len <= 0) {
len = BaseStatistics.SIZE_UNKNOWN;
}
return new FileBaseStatistics(latestModTime, len, BaseStatistics.AVG_RECORD_BYTES_UNKNOWN);
}
// --------------------------------------------------------------------------------------------
// Custom serialization methods
// --------------------------------------------------------------------------------------------
private void writeObject(ObjectOutputStream out) throws IOException {
super.write(out);
out.writeUTF(this.mapreduceInputFormat.getClass().getName());
out.writeUTF(this.keyClass.getName());
out.writeUTF(this.valueClass.getName());
this.configuration.write(out);
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
super.read(in);
String hadoopInputFormatClassName = in.readUTF();
String keyClassName = in.readUTF();
String valueClassName = in.readUTF();
org.apache.hadoop.conf.Configuration configuration =
new org.apache.hadoop.conf.Configuration();
configuration.readFields(in);
if (this.configuration == null) {
this.configuration = configuration;
}
try {
this.mapreduceInputFormat =
(org.apache.hadoop.mapreduce.InputFormat<K, V>)
Class.forName(
hadoopInputFormatClassName,
true,
Thread.currentThread().getContextClassLoader())
.newInstance();
} catch (Exception e) {
throw new RuntimeException("Unable to instantiate the hadoop input format", e);
}
try {
this.keyClass =
(Class<K>)
Class.forName(
keyClassName,
true,
Thread.currentThread().getContextClassLoader());
} catch (Exception e) {
throw new RuntimeException("Unable to find key class.", e);
}
try {
this.valueClass =
(Class<V>)
Class.forName(
valueClassName,
true,
Thread.currentThread().getContextClassLoader());
} catch (Exception e) {
throw new RuntimeException("Unable to find value class.", e);
}
}
}
| is |
java | apache__camel | dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java | {
"start": 701956,
"end": 707775
} | class ____ extends YamlDeserializerBase<PGPDataFormat> {
public PGPDataFormatDeserializer() {
super(PGPDataFormat.class);
}
@Override
protected PGPDataFormat newInstance() {
return new PGPDataFormat();
}
@Override
protected boolean setProperty(PGPDataFormat target, String propertyKey, String propertyName,
Node node) {
propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey);
switch(propertyKey) {
case "algorithm": {
String val = asText(node);
target.setAlgorithm(val);
break;
}
case "armored": {
String val = asText(node);
target.setArmored(val);
break;
}
case "compressionAlgorithm": {
String val = asText(node);
target.setCompressionAlgorithm(val);
break;
}
case "hashAlgorithm": {
String val = asText(node);
target.setHashAlgorithm(val);
break;
}
case "id": {
String val = asText(node);
target.setId(val);
break;
}
case "integrity": {
String val = asText(node);
target.setIntegrity(val);
break;
}
case "keyFileName": {
String val = asText(node);
target.setKeyFileName(val);
break;
}
case "keyUserid": {
String val = asText(node);
target.setKeyUserid(val);
break;
}
case "password": {
String val = asText(node);
target.setPassword(val);
break;
}
case "provider": {
String val = asText(node);
target.setProvider(val);
break;
}
case "signatureKeyFileName": {
String val = asText(node);
target.setSignatureKeyFileName(val);
break;
}
case "signatureKeyRing": {
String val = asText(node);
target.setSignatureKeyRing(val);
break;
}
case "signatureKeyUserid": {
String val = asText(node);
target.setSignatureKeyUserid(val);
break;
}
case "signaturePassword": {
String val = asText(node);
target.setSignaturePassword(val);
break;
}
case "signatureVerificationOption": {
String val = asText(node);
target.setSignatureVerificationOption(val);
break;
}
default: {
return false;
}
}
return true;
}
}
@YamlType(
nodes = "pqc",
types = org.apache.camel.model.dataformat.PQCDataFormat.class,
order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1,
displayName = "PQC (Post-Quantum Cryptography)",
description = "Encrypt and decrypt messages using Post-Quantum Cryptography Key Encapsulation Mechanisms (KEM).",
deprecated = false,
properties = {
@YamlProperty(name = "bufferSize", type = "number", defaultValue = "4096", description = "The size of the buffer used for streaming encryption/decryption.", displayName = "Buffer Size"),
@YamlProperty(name = "id", type = "string", description = "The id of this node", displayName = "Id"),
@YamlProperty(name = "keyEncapsulationAlgorithm", type = "enum:MLKEM,BIKE,HQC,CMCE,SABER,FRODO,NTRU,NTRULPRime,SNTRUPrime,KYBER", defaultValue = "MLKEM", description = "The Post-Quantum KEM algorithm to use for key encapsulation. Supported values: MLKEM, BIKE, HQC, CMCE, SABER, FRODO, NTRU, NTRULPRime, SNTRUPrime, KYBER", displayName = "Key Encapsulation Algorithm"),
@YamlProperty(name = "keyGenerator", type = "string", description = "Refers to a custom KeyGenerator to lookup from the register for KEM operations.", displayName = "Key Generator"),
@YamlProperty(name = "keyPair", type = "string", description = "Refers to the KeyPair to lookup from the register to use for KEM operations.", displayName = "Key Pair"),
@YamlProperty(name = "provider", type = "string", description = "The JCE security provider to use.", displayName = "Provider"),
@YamlProperty(name = "symmetricKeyAlgorithm", type = "enum:AES,ARIA,RC2,RC5,CAMELLIA,CAST5,CAST6,CHACHA7539,DSTU7624,GOST28147,GOST3412_2015,GRAIN128,HC128,HC256,SALSA20,SEED,SM4,DESEDE", defaultValue = "AES", description = "The symmetric encryption algorithm to use with the shared secret. Supported values: AES, ARIA, RC2, RC5, CAMELLIA, CAST5, CAST6, CHACHA7539, etc.", displayName = "Symmetric Key Algorithm"),
@YamlProperty(name = "symmetricKeyLength", type = "number", defaultValue = "128", description = "The length (in bits) of the symmetric key.", displayName = "Symmetric Key Length")
}
)
public static | PGPDataFormatDeserializer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/JavaTimeDefaultTimeZoneTest.java | {
"start": 7054,
"end": 7553
} | class ____ {
// BUG: Diagnostic matches: REPLACEME
JapaneseDate now = JapaneseDate.now();
JapaneseDate nowWithZone = JapaneseDate.now(systemDefault());
}
""")
.doTest();
}
@Test
public void minguoDate() {
helper
.addSourceLines(
"TestClass.java",
"""
import static java.time.ZoneId.systemDefault;
import java.time.chrono.MinguoDate;
public | TestClass |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/errors/StreamsNotStartedException.java | {
"start": 1260,
"end": 1642
} | class ____ extends InvalidStateStoreException {
private static final long serialVersionUID = 1L;
public StreamsNotStartedException(final String message) {
super(message);
}
@SuppressWarnings("unused")
public StreamsNotStartedException(final String message, final Throwable throwable) {
super(message, throwable);
}
}
| StreamsNotStartedException |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/conditional/EmployeeDto.java | {
"start": 199,
"end": 777
} | class ____ {
private String name;
private String country;
private String uniqueIdNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getUniqueIdNumber() {
return uniqueIdNumber;
}
public void setUniqueIdNumber(String uniqueIdNumber) {
this.uniqueIdNumber = uniqueIdNumber;
}
}
| EmployeeDto |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/aggregate/SQLServerAggregateSupport.java | {
"start": 21554,
"end": 23403
} | class ____ implements XmlWriteExpression {
private final SelectableMapping selectableMapping;
private final String[] customWriteExpressionParts;
BasicXmlWriteExpression(SelectableMapping selectableMapping, String customWriteExpression) {
this.selectableMapping = selectableMapping;
if ( customWriteExpression.equals( "?" ) ) {
this.customWriteExpressionParts = new String[]{ "", "" };
}
else {
assert !customWriteExpression.startsWith( "?" );
final String[] parts = StringHelper.split( "?", customWriteExpression );
assert parts.length == 2 || (parts.length & 1) == 1;
this.customWriteExpressionParts = parts;
}
}
@Override
public void append(
SqlAppender sb,
String path,
SqlAstTranslator<?> translator,
AggregateColumnWriteExpression expression) {
final JdbcType jdbcType = selectableMapping.getJdbcMapping().getJdbcType();
final boolean isArray = jdbcType.getDefaultSqlTypeCode() == XML_ARRAY;
if ( isArray ) {
sb.append( '(' );
}
sb.append( customWriteExpressionParts[0] );
for ( int i = 1; i < customWriteExpressionParts.length; i++ ) {
// We use NO_UNTYPED here so that expressions which require type inference are casted explicitly,
// since we don't know how the custom write expression looks like where this is embedded,
// so we have to be pessimistic and avoid ambiguities
translator.render( expression.getValueExpression( selectableMapping ), SqlAstNodeRenderingMode.NO_UNTYPED );
sb.append( customWriteExpressionParts[i] );
}
if ( isArray ) {
// Remove the <Collection> tag to wrap the value into the selectable specific tag
sb.append( ").query('/Collection/*')" );
}
sb.append( ' ' );
sb.appendDoubleQuoteEscapedString( selectableMapping.getSelectableName() );
}
}
private static | BasicXmlWriteExpression |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/recording/BytecodeRecorderImpl.java | {
"start": 113950,
"end": 114107
} | interface ____ {
void writeInstruction(InstructionGroup writer);
ResultHandle loadDeferred(DeferredParameter parameter);
}
}
| MethodContext |
java | apache__camel | components/camel-mock/src/generated/java/org/apache/camel/component/mock/MockEndpointUriFactory.java | {
"start": 514,
"end": 2523
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":name";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(14);
props.add("assertPeriod");
props.add("browseLimit");
props.add("copyOnExchange");
props.add("expectedCount");
props.add("failFast");
props.add("lazyStartProducer");
props.add("log");
props.add("name");
props.add("reportGroup");
props.add("resultMinimumWaitTime");
props.add("resultWaitTime");
props.add("retainFirst");
props.add("retainLast");
props.add("sleepForEmptyTest");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
SECRET_PROPERTY_NAMES = Collections.emptySet();
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "mock".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "name", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return true;
}
}
| MockEndpointUriFactory |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/junit/MockitoJUnitRunner.java | {
"start": 4789,
"end": 5431
} | class ____ extends MockitoJUnitRunner {
public Silent(Class<?> klass) throws InvocationTargetException {
super(new RunnerFactory().create(klass));
}
}
/**
* Detects unused stubs and reports them as failures. Default behavior in Mockito 2.x.
* To improve productivity and quality of tests please consider newer API, the {@link StrictStubs}.
* <p>
* For more information on detecting unused stubs, see {@link UnnecessaryStubbingException}.
* For more information on stubbing argument mismatch warnings see {@link MockitoHint}.
*
* @since 2.1.0
*/
public static | Silent |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/RequiresDialect.java | {
"start": 804,
"end": 1441
} | interface ____ {
/**
* The dialects against which to run the test
*
* @return The dialects
*/
Class<? extends Dialect> value();
/**
* Used to indicate if the dialects should be matched strictly (classes equal) or
* non-strictly (instanceof).
*
* @return Should strict matching be used?
*/
boolean strictMatching() default false;
/**
* Comment describing the reason why the dialect is required.
*
* @return The comment
*/
String comment() default "";
/**
* The key of a JIRA issue which relates this this restriction
*
* @return The jira issue key
*/
String jiraKey() default "";
}
| RequiresDialect |
java | quarkusio__quarkus | integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/config/RecordedBuildProfileInRuntimeTest.java | {
"start": 582,
"end": 1537
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class))
.withConfigurationResource("application.properties");
@Inject
SmallRyeConfig config;
@Test
void recordedBuildProfileInRuntime() {
ConfigValue profile = config.getConfigValue("quarkus.test.profile");
assertEquals("test", profile.getValue());
// Recorded by ProfileBuildStep
assertEquals("DefaultValuesConfigSource", profile.getConfigSourceName());
Optional<ConfigSource> defaultValuesConfigSource = config.getConfigSource("DefaultValuesConfigSource");
assertTrue(defaultValuesConfigSource.isPresent());
// The default set in ConfigUtils, based on the LaunchMode
assertEquals("test", defaultValuesConfigSource.get().getValue("quarkus.test.profile"));
}
}
| RecordedBuildProfileInRuntimeTest |
java | elastic__elasticsearch | test/framework/src/test/java/org/elasticsearch/test/VersionUtilsTests.java | {
"start": 931,
"end": 4989
} | class ____ these don't need to change with each release
// full range
Version got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), Version.CURRENT);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), null, Version.CURRENT);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), null);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
// sub range
got = VersionUtils.randomVersionBetween(random(), fromId(7000099), fromId(7010099));
assertTrue(got.onOrAfter(fromId(7000099)));
assertTrue(got.onOrBefore(fromId(7010099)));
// unbounded lower
got = VersionUtils.randomVersionBetween(random(), null, fromId(7000099));
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(fromId(7000099)));
got = VersionUtils.randomVersionBetween(random(), null, VersionUtils.allVersions().getFirst());
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(VersionUtils.allVersions().getFirst()));
// unbounded upper
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), null);
assertTrue(got.onOrAfter(VersionUtils.getFirstVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getPreviousVersion(), null);
assertTrue(got.onOrAfter(VersionUtils.getPreviousVersion()));
assertTrue(got.onOrBefore(Version.CURRENT));
// range of one
got = VersionUtils.randomVersionBetween(random(), VersionUtils.getFirstVersion(), VersionUtils.getFirstVersion());
assertEquals(got, VersionUtils.getFirstVersion());
got = VersionUtils.randomVersionBetween(random(), Version.CURRENT, Version.CURRENT);
assertEquals(got, Version.CURRENT);
got = VersionUtils.randomVersionBetween(random(), fromId(7000099), fromId(7000099));
assertEquals(got, fromId(7000099));
// implicit range of one
got = VersionUtils.randomVersionBetween(random(), null, VersionUtils.getFirstVersion());
assertEquals(got, VersionUtils.getFirstVersion());
got = VersionUtils.randomVersionBetween(random(), Version.CURRENT, null);
assertEquals(got, Version.CURRENT);
}
/**
* Tests that {@link Version#minimumCompatibilityVersion()} and {@link VersionUtils#allVersions()}
* agree with the list of wire compatible versions we build in gradle.
*/
public void testGradleVersionsMatchVersionUtils() {
// First check the index compatible versions
List<String> versions = VersionUtils.allVersions()
.stream()
/* Java lists all versions from the 5.x series onwards, but we only want to consider
* ones that we're supposed to be compatible with. */
.filter(v -> v.onOrAfter(Version.CURRENT.minimumCompatibilityVersion()))
.map(Version::toString)
.toList();
List<String> gradleVersions = versionFromProperty("tests.gradle_wire_compat_versions");
assertEquals(versions, gradleVersions);
}
private List<String> versionFromProperty(String property) {
List<String> versions = new ArrayList<>();
String versionsString = System.getProperty(property);
assertNotNull("Couldn't find [" + property + "]. Gradle should set this before running the tests.", versionsString);
logger.info("Looked up versions [{}={}]", property, versionsString);
for (String version : versionsString.split(",")) {
versions.add(version);
}
return versions;
}
}
| so |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/orm/common/BaseTransactionIsolationConfigTest.java | {
"start": 867,
"end": 4028
} | class ____ {
protected abstract ConnectionProvider getConnectionProviderUnderTest(ServiceRegistryScope registryScope);
@Test
public void testSettingIsolationAsNumeric(ServiceRegistryScope registryScope) throws Exception {
Properties properties = Environment.getProperties();
properties.put( AvailableSettings.ISOLATION, Connection.TRANSACTION_SERIALIZABLE );
ConnectionProvider provider = getConnectionProviderUnderTest( registryScope );
try {
( (Configurable) provider ).configure( PropertiesHelper.map( properties ) );
if ( provider instanceof Startable ) {
( (Startable) provider ).start();
}
Connection connection = provider.getConnection();
assertEquals( Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation() );
provider.closeConnection( connection );
}
finally {
( (Stoppable) provider ).stop();
}
}
@Test
public void testSettingIsolationAsNumericString(ServiceRegistryScope registryScope) throws Exception {
Properties properties = Environment.getProperties();
properties.put( AvailableSettings.ISOLATION, Integer.toString( Connection.TRANSACTION_SERIALIZABLE ) );
ConnectionProvider provider = getConnectionProviderUnderTest( registryScope );
try {
( (Configurable) provider ).configure( PropertiesHelper.map( properties ) );
if ( provider instanceof Startable ) {
( (Startable) provider ).start();
}
Connection connection = provider.getConnection();
assertEquals( Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation() );
provider.closeConnection( connection );
}
finally {
( (Stoppable) provider ).stop();
}
}
@Test
public void testSettingIsolationAsName(ServiceRegistryScope registryScope) throws Exception {
Properties properties = Environment.getProperties();
properties.put( AvailableSettings.ISOLATION, "TRANSACTION_SERIALIZABLE" );
ConnectionProvider provider = getConnectionProviderUnderTest( registryScope );
try {
( (Configurable) provider ).configure( PropertiesHelper.map( properties ) );
if ( provider instanceof Startable ) {
( (Startable) provider ).start();
}
Connection connection = provider.getConnection();
assertEquals( Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation() );
provider.closeConnection( connection );
}
finally {
( (Stoppable) provider ).stop();
}
}
@Test
public void testSettingIsolationAsNameAlt(ServiceRegistryScope registryScope) throws Exception {
Properties properties = Environment.getProperties();
properties.put( AvailableSettings.ISOLATION, "SERIALIZABLE" );
ConnectionProvider provider = getConnectionProviderUnderTest( registryScope );
try {
( (Configurable) provider ).configure( PropertiesHelper.map( properties ) );
if ( provider instanceof Startable ) {
( (Startable) provider ).start();
}
Connection connection = provider.getConnection();
assertEquals( Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation() );
provider.closeConnection( connection );
}
finally {
( (Stoppable) provider ).stop();
}
}
}
| BaseTransactionIsolationConfigTest |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/compare/ComparableUtilsTest.java | {
"start": 3290,
"end": 5466
} | class ____ {
BigDecimal c = BigDecimal.TEN;
@Test
void between_returns_true() {
assertTrue(ComparableUtils.is(a).between(b, c));
}
@Test
void betweenExclusive_returns_true() {
assertTrue(ComparableUtils.is(a).betweenExclusive(b, c));
}
@Test
void static_between_returns_true() {
assertTrue(ComparableUtils.between(b, c).test(a));
}
@Test
void static_betweenExclusive_returns_true() {
assertTrue(ComparableUtils.betweenExclusive(b, c).test(a));
}
}
BigDecimal b = BigDecimal.ZERO;
@Test
void equalTo_returns_false() {
assertFalse(ComparableUtils.is(a).equalTo(b));
}
@Test
void greaterThan_returns_true() {
assertTrue(ComparableUtils.is(a).greaterThan(b));
}
@Test
void greaterThanOrEqualTo_returns_true() {
assertTrue(ComparableUtils.is(a).greaterThanOrEqualTo(b));
}
@Test
void lessThan_returns_false() {
assertFalse(ComparableUtils.is(a).lessThan(b));
}
@Test
void lessThanOrEqualTo_returns_false() {
assertFalse(ComparableUtils.is(a).lessThanOrEqualTo(b));
}
@Test
void static_ge_returns_true() {
assertTrue(ComparableUtils.ge(b).test(a));
}
@Test
void static_gt_returns_true() {
assertTrue(ComparableUtils.gt(b).test(a));
}
@Test
void static_le_returns_false() {
assertFalse(ComparableUtils.le(b).test(a));
}
@Test
void static_lt_returns_false() {
assertFalse(ComparableUtils.lt(b).test(a));
}
}
@DisplayName("B is 1 (B = A)")
@Nested
final | C_is_10 |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/BedrockAgentEndpointBuilderFactory.java | {
"start": 83116,
"end": 85182
} | interface ____ {
/**
* AWS Bedrock Agent (camel-aws-bedrock)
* Operate on AWS Bedrock through its Agent.
*
* Category: ai,cloud
* Since: 4.5
* Maven coordinates: org.apache.camel:camel-aws-bedrock
*
* @return the dsl builder for the headers' name.
*/
default BedrockAgentHeaderNameBuilder awsBedrockAgent() {
return BedrockAgentHeaderNameBuilder.INSTANCE;
}
/**
* AWS Bedrock Agent (camel-aws-bedrock)
* Operate on AWS Bedrock through its Agent.
*
* Category: ai,cloud
* Since: 4.5
* Maven coordinates: org.apache.camel:camel-aws-bedrock
*
* Syntax: <code>aws-bedrock-agent:label</code>
*
* Path parameter: label (required)
* Logical name
*
* @param path label
* @return the dsl builder
*/
default BedrockAgentEndpointBuilder awsBedrockAgent(String path) {
return BedrockAgentEndpointBuilderFactory.endpointBuilder("aws-bedrock-agent", path);
}
/**
* AWS Bedrock Agent (camel-aws-bedrock)
* Operate on AWS Bedrock through its Agent.
*
* Category: ai,cloud
* Since: 4.5
* Maven coordinates: org.apache.camel:camel-aws-bedrock
*
* Syntax: <code>aws-bedrock-agent:label</code>
*
* Path parameter: label (required)
* Logical name
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path label
* @return the dsl builder
*/
default BedrockAgentEndpointBuilder awsBedrockAgent(String componentName, String path) {
return BedrockAgentEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the AWS Bedrock Agent component.
*/
public static | BedrockAgentBuilders |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java | {
"start": 32111,
"end": 34671
} | interface ____);</li>
* <li>the number of actual and formal parameters differ;</li>
* <li>an unwrapping conversion for primitive arguments fails; or</li>
* <li>after possible unwrapping, a parameter value can't be converted to the corresponding formal parameter type by a
* method invocation conversion.</li>
* </ul>
* @throws InvocationTargetException Thrown if the underlying method throws an exception.
* @throws NullPointerException Thrown if the specified {@code object} is null.
* @throws ExceptionInInitializerError Thrown if the initialization provoked by this method fails.
*/
public static Object invokeExactMethod(final Object object, final String methodName, final Object[] args, final Class<?>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
final Class<?> cls = Objects.requireNonNull(object, "object").getClass();
final Class<?>[] paramTypes = ArrayUtils.nullToEmpty(parameterTypes);
final Method method = getAccessibleMethod(cls, methodName, paramTypes);
requireNonNull(method, cls, methodName, paramTypes);
return method.invoke(object, ArrayUtils.nullToEmpty(args));
}
/**
* Invokes a {@code static} method whose parameter types match exactly the object types.
*
* <p>
* This uses reflection to invoke the method obtained from a call to {@link #getAccessibleMethod(Class, String, Class[])}.
* </p>
*
* @param cls invoke static method on this class.
* @param methodName get method with this name.
* @param args use these arguments - treat {@code null} as empty array.
* @return The value returned by the invoked method.
* @throws NoSuchMethodException Thrown if there is no such accessible method.
* @throws IllegalAccessException Thrown if this found {@code Method} is enforcing Java language access control and the underlying method is
* inaccessible.
* @throws IllegalArgumentException Thrown if:
* <ul>
* <li>the found {@code Method} is an instance method and the specified {@code object} argument is not an instance of
* the | implementor |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/token/RefreshTokenAction.java | {
"start": 372,
"end": 669
} | class ____ extends ActionType<CreateTokenResponse> {
public static final String NAME = "cluster:admin/xpack/security/token/refresh";
public static final RefreshTokenAction INSTANCE = new RefreshTokenAction();
private RefreshTokenAction() {
super(NAME);
}
}
| RefreshTokenAction |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/spi/SharedSessionContractImplementor.java | {
"start": 3068,
"end": 12205
} | interface ____
extends SharedSessionContract, JdbcSessionOwner, Options, LobCreationContext, WrapperOptions,
QueryProducerImplementor, JavaType.CoercionContext {
/**
* Obtain the {@linkplain SessionFactoryImplementor factory} which created this session.
*/
@Override
SessionFactoryImplementor getFactory();
/**
* Obtain the {@linkplain SessionFactoryImplementor factory} which created this session.
*/
@Override
default SessionFactoryImplementor getSessionFactory() {
return getFactory();
}
/**
* Obtain the {@link TypeConfiguration} for the factory which created this session.
*/
@Override
default TypeConfiguration getTypeConfiguration() {
return getFactory().getTypeConfiguration();
}
/**
* Obtain the {@link Dialect}.
*/
@Override
default Dialect getDialect() {
return getSessionFactory().getJdbcServices().getDialect();
}
/**
* Get the {@link SessionEventListenerManager} associated with this session.
*/
SessionEventListenerManager getEventListenerManager();
/**
* Get the persistence context for this session.
* <p>
* See {@link #getPersistenceContextInternal()} for
* a faster alternative.
*
* @implNote This method is not extremely fast: if you need to
* call the {@link PersistenceContext} multiple times,
* prefer keeping a reference to it instead of invoking
* this method multiple times.
*/
PersistenceContext getPersistenceContext();
/**
* Obtain the {@link JdbcCoordinator} for this session.
*/
JdbcCoordinator getJdbcCoordinator();
/**
* Obtain the {@link JdbcServices} for the factory which created this session.
*/
JdbcServices getJdbcServices();
/**
* Obtain a {@link UUID} which uniquely identifies this session.
* <p>
* The UUID is useful mainly for logging.
*/
UUID getSessionIdentifier();
/**
* Returns this object, fulfilling the contract of {@link WrapperOptions}.
*/
@Override
default SharedSessionContractImplementor getSession() {
return this;
}
/**
* Obtain a "token" which uniquely identifies this session.
*/
default Object getSessionToken() {
return this;
}
/**
* Determines whether the session is closed.
* <p>
* @apiNote Provided separately from {@link #isOpen()} as this method
* does not attempt any JTA synchronization registration,
* whereas {@link #isOpen()} does. This one is better for most
* internal purposes.
*
* @return {@code true} if the session is closed; {@code false} otherwise.
*/
boolean isClosed();
/**
* Determines whether the session is open or is waiting for auto-close.
*
* @return {@code true} if the session is closed, or if it's waiting
* for auto-close; {@code false} otherwise.
*/
default boolean isOpenOrWaitingForAutoClose() {
return !isClosed();
}
/**
* Check whether the session is open, and if not:
* <ul>
* <li>mark the current transaction, if any, for rollback only,
* and</li>
* <li>throw an {@code IllegalStateException}.
* (JPA specifies this exception type.)</li>
* </ul>
*/
default void checkOpen() {
checkOpen( true );
}
/**
* Check whether the session is open, and if not:
* <ul>
* <li>if {@code markForRollbackIfClosed = true}, mark the
* current transaction, if any, for rollback only, and
* <li>throw an {@code IllegalStateException}.
* (JPA specifies this exception type.)
* </ul>
*/
void checkOpen(boolean markForRollbackIfClosed);
/**
* Prepare for the execution of a {@link Query} or
* {@link org.hibernate.procedure.ProcedureCall}
*/
void prepareForQueryExecution(boolean requiresTxn);
/**
* Marks current transaction, if any, for rollback only.
*/
void markForRollbackOnly();
/**
* The current {@link CacheTransactionSynchronization} associated
* with this session. This may be {@code null} if the session is not
* currently associated with an active transaction.
*/
CacheTransactionSynchronization getCacheTransactionSynchronization();
/**
* Does this session have an active Hibernate transaction, or is it
* associated with a JTA transaction currently in progress?
*/
boolean isTransactionInProgress();
/**
* Check if an active {@link Transaction} is available before performing
* an update operation against the database.
* <p>
* If an active transaction is necessary, but no transaction is active,
* a {@link TransactionRequiredException} is raised.
*
* @param exceptionMessage the message to use for the {@link TransactionRequiredException}
*/
default void checkTransactionNeededForUpdateOperation(String exceptionMessage) {
if ( !isTransactionInProgress() ) {
throw new TransactionRequiredException( exceptionMessage );
}
}
/**
* Retrieves the current {@link Transaction}, or creates a new transaction
* if there is no transaction active.
* <p>
* This method is primarily for internal or integrator use.
*
* @return the {@link Transaction}
*/
Transaction accessTransaction();
/**
* The current {@link Transaction} object associated with this session,
* if it has already been created, or {@code null} otherwise.
*
* @since 7.2
*/
@Incubating
Transaction getCurrentTransaction();
/**
* Access to register callbacks for transaction completion processing.
*
* @since 7.2
*/
@Incubating
TransactionCompletionCallbacks getTransactionCompletionCallbacks();
/**
* Access to registered callbacks for transaction completion processing.
*
* @since 7.2
*/
@Incubating
TransactionCompletionCallbacksImplementor getTransactionCompletionCallbacksImplementor();
/**
* Instantiate an {@link EntityKey} with the given id and for the
* entity represented by the given {@link EntityPersister}.
*
* @param id The entity id
* @param persister The entity persister
*
* @return The entity key
*/
EntityKey generateEntityKey(Object id, EntityPersister persister);
/**
* Retrieves the {@link Interceptor} associated with this session.
*/
Interceptor getInterceptor();
/**
* Initialize the given collection (if not already initialized).
*/
void initializeCollection(PersistentCollection<?> collection, boolean writing)
throws HibernateException;
/**
* Obtain an entity instance with the given id, without checking if it was
* deleted or scheduled for deletion.
* <ul>
* <li>When {@code nullable = false}, this method may create a new proxy or
* return an existing proxy; if it does not exist, an exception is thrown.
* <li>When {@code nullable = true}, the method does not create new proxies,
* though it might return an existing proxy; if it does not exist, a
* {@code null} value is returned.
* </ul>
* <p>
* When {@code eager = true}, the object is eagerly fetched from the database.
*/
Object internalLoad(String entityName, Object id, boolean eager, boolean nullable)
throws HibernateException;
/**
* Load an instance immediately.
* This method is only called when lazily initializing a proxy.
* Do not return the proxy.
*/
Object immediateLoad(String entityName, Object id) throws HibernateException;
/**
* Get the {@link EntityPersister} for the given entity instance.
*
* @param entityName optional entity name
* @param object the entity instance
*/
EntityPersister getEntityPersister(@Nullable String entityName, Object object) throws HibernateException;
/**
* Get the entity instance associated with the given {@link EntityKey},
* calling the {@link Interceptor} if necessary.
*/
Object getEntityUsingInterceptor(EntityKey key) throws HibernateException;
/**
* Return the identifier of the persistent object, or null if it is
* not associated with this session.
*/
Object getContextEntityIdentifier(Object object);
/**
* Obtain the best estimate of the entity name of the given entity
* instance, which is not involved in an association, by also
* considering information held in the proxy, and whether the object
* is already associated with this session.
*/
String bestGuessEntityName(Object object);
/**
* Obtain the best estimate of the entity name of the given entity
* instance, which is not involved in an association, by also
* considering information held in the proxy, and whether the object
* is already associated with this session.
*/
default String bestGuessEntityName(Object object, EntityEntry entry) {
return bestGuessEntityName( object );
}
/**
* Obtain an estimate of the entity name of the given entity instance,
* which is not involved in an association, using only the
* {@link org.hibernate.EntityNameResolver}.
*/
String guessEntityName(Object entity) throws HibernateException;
/**
* Instantiate the entity class, initializing with the given identifier.
*
* @deprecated No longer used, replaced by {@link #instantiate(EntityPersister, Object)}
*/
@Deprecated(since = "7", forRemoval = true)
Object instantiate(String entityName, Object id) throws HibernateException;
/**
* Instantiate the entity | SharedSessionContractImplementor |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/task/SimpleAsyncTaskExecutor.java | {
"start": 2504,
"end": 14969
} | class ____ extends CustomizableThreadCreator
implements AsyncTaskExecutor, Serializable, AutoCloseable {
/**
* Permit any number of concurrent invocations: that is, don't throttle concurrency.
* @see ConcurrencyThrottleSupport#UNBOUNDED_CONCURRENCY
*/
public static final int UNBOUNDED_CONCURRENCY = ConcurrencyThrottleSupport.UNBOUNDED_CONCURRENCY;
/**
* Switch concurrency 'off': that is, don't allow any concurrent invocations.
* @see ConcurrencyThrottleSupport#NO_CONCURRENCY
*/
public static final int NO_CONCURRENCY = ConcurrencyThrottleSupport.NO_CONCURRENCY;
/** Internal concurrency throttle used by this executor. */
private final ConcurrencyThrottleAdapter concurrencyThrottle = new ConcurrencyThrottleAdapter();
private @Nullable VirtualThreadDelegate virtualThreadDelegate;
private @Nullable ThreadFactory threadFactory;
private @Nullable TaskDecorator taskDecorator;
private long taskTerminationTimeout;
private @Nullable Set<Thread> activeThreads;
private boolean cancelRemainingTasksOnClose = false;
private boolean rejectTasksWhenLimitReached = false;
private volatile boolean active = true;
/**
* Create a new SimpleAsyncTaskExecutor with default thread name prefix.
*/
public SimpleAsyncTaskExecutor() {
super();
}
/**
* Create a new SimpleAsyncTaskExecutor with the given thread name prefix.
* @param threadNamePrefix the prefix to use for the names of newly created threads
*/
public SimpleAsyncTaskExecutor(String threadNamePrefix) {
super(threadNamePrefix);
}
/**
* Create a new SimpleAsyncTaskExecutor with the given external thread factory.
* @param threadFactory the factory to use for creating new Threads
*/
public SimpleAsyncTaskExecutor(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
/**
* Switch this executor to virtual threads. Requires Java 21 or higher.
* <p>The default is {@code false}, indicating platform threads.
* Set this flag to {@code true} in order to create virtual threads instead.
* @since 6.1
*/
public void setVirtualThreads(boolean virtual) {
this.virtualThreadDelegate = (virtual ? new VirtualThreadDelegate() : null);
}
/**
* Specify an external factory to use for creating new Threads,
* instead of relying on the local properties of this executor.
* <p>You may specify an inner ThreadFactory bean or also a ThreadFactory reference
* obtained from JNDI (on a Jakarta EE server) or some other lookup mechanism.
* @see #setThreadNamePrefix
* @see #setThreadPriority
*/
public void setThreadFactory(@Nullable ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
/**
* Return the external factory to use for creating new Threads, if any.
*/
public final @Nullable ThreadFactory getThreadFactory() {
return this.threadFactory;
}
/**
* Specify a custom {@link TaskDecorator} to be applied to any {@link Runnable}
* about to be executed.
* <p>Note that such a decorator is not necessarily being applied to the
* user-supplied {@code Runnable}/{@code Callable} but rather to the actual
* execution callback (which may be a wrapper around the user-supplied task).
* <p>The primary use case is to set some execution context around the task's
* invocation, or to provide some monitoring/statistics for task execution.
* <p><b>NOTE:</b> Exception handling in {@code TaskDecorator} implementations
* is limited to plain {@code Runnable} execution via {@code execute} calls.
* In case of {@code #submit} calls, the exposed {@code Runnable} will be a
* {@code FutureTask} which does not propagate any exceptions; you might
* have to cast it and call {@code Future#get} to evaluate exceptions.
* @since 4.3
*/
public void setTaskDecorator(TaskDecorator taskDecorator) {
this.taskDecorator = taskDecorator;
}
/**
* Specify a timeout (in milliseconds) for task termination when closing
* this executor. The default is 0, not waiting for task termination at all.
* <p>Note that a concrete >0 timeout specified here will lead to the
* wrapping of every submitted task into a task-tracking runnable which
* involves considerable overhead in case of a high number of tasks.
* However, for a modest level of submissions with longer-running
* tasks, this is feasible in order to arrive at a graceful shutdown.
* <p>Note that {@code SimpleAsyncTaskExecutor} does not participate in
* a coordinated lifecycle stop but rather just awaits task termination
* on {@link #close()}.
* @param timeout the timeout in milliseconds
* @since 6.1
* @see #close()
* @see #setCancelRemainingTasksOnClose
* @see org.springframework.scheduling.concurrent.ExecutorConfigurationSupport#setAwaitTerminationMillis
*/
public void setTaskTerminationTimeout(long timeout) {
Assert.isTrue(timeout >= 0, "Timeout value must be >=0");
this.taskTerminationTimeout = timeout;
trackActiveThreadsIfNecessary();
}
/**
* Specify whether to cancel remaining tasks on close: that is, whether to
* interrupt any active threads at the time of the {@link #close()} call.
* <p>The default is {@code false}, not tracking active threads at all or
* just interrupting any remaining threads that still have not finished after
* the specified {@link #setTaskTerminationTimeout taskTerminationTimeout}.
* Switch this to {@code true} for immediate interruption on close, either in
* combination with a subsequent termination timeout or without any waiting
* at all, depending on whether a {@code taskTerminationTimeout} has been
* specified as well.
* @since 6.2.11
* @see #close()
* @see #setTaskTerminationTimeout
* @see org.springframework.scheduling.concurrent.ExecutorConfigurationSupport#setWaitForTasksToCompleteOnShutdown
*/
public void setCancelRemainingTasksOnClose(boolean cancelRemainingTasksOnClose) {
this.cancelRemainingTasksOnClose = cancelRemainingTasksOnClose;
trackActiveThreadsIfNecessary();
}
/**
* Specify whether to reject tasks when the concurrency limit has been reached,
* throwing {@link TaskRejectedException} on any further submission attempts.
* <p>The default is {@code false}, blocking the caller until the submission can
* be accepted. Switch this to {@code true} for immediate rejection instead.
* @since 6.2.6
*/
public void setRejectTasksWhenLimitReached(boolean rejectTasksWhenLimitReached) {
this.rejectTasksWhenLimitReached = rejectTasksWhenLimitReached;
}
/**
* Set the maximum number of parallel task executions allowed.
* The default of -1 indicates no concurrency limit at all.
* <p>This is the equivalent of a maximum pool size in a thread pool,
* preventing temporary overload of the thread management system.
* However, in contrast to a thread pool with a managed task queue,
* this executor will block the submitter until the task can be
* accepted when the configured concurrency limit has been reached.
* If you prefer queue-based task hand-offs without such blocking,
* consider using a {@code ThreadPoolTaskExecutor} instead.
* @see #UNBOUNDED_CONCURRENCY
* @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor#setMaxPoolSize
*/
public void setConcurrencyLimit(int concurrencyLimit) {
this.concurrencyThrottle.setConcurrencyLimit(concurrencyLimit);
}
/**
* Return the maximum number of parallel task executions allowed.
*/
public final int getConcurrencyLimit() {
return this.concurrencyThrottle.getConcurrencyLimit();
}
/**
* Return whether the concurrency throttle is currently active.
* @return {@code true} if the concurrency limit for this instance is active
* @see #getConcurrencyLimit()
* @see #setConcurrencyLimit
*/
public final boolean isThrottleActive() {
return this.concurrencyThrottle.isThrottleActive();
}
/**
* Return whether this executor is still active, i.e. not closed yet,
* and therefore accepts further task submissions. Otherwise, it is
* either in the task termination phase or entirely shut down already.
* @since 6.1
* @see #setTaskTerminationTimeout
* @see #close()
*/
public boolean isActive() {
return this.active;
}
/**
* Track active threads only when a task termination timeout has been
* specified or interruption of remaining threads has been requested.
*/
private void trackActiveThreadsIfNecessary() {
this.activeThreads = (this.taskTerminationTimeout > 0 || this.cancelRemainingTasksOnClose ?
ConcurrentHashMap.newKeySet() : null);
}
/**
* Executes the given task, within a concurrency throttle
* if configured (through the superclass's settings).
* @see #doExecute(Runnable)
*/
@SuppressWarnings("deprecation")
@Override
public void execute(Runnable task) {
execute(task, TIMEOUT_INDEFINITE);
}
/**
* Executes the given task, within a concurrency throttle
* if configured (through the superclass's settings).
* <p>Executes urgent tasks (with 'immediate' timeout) directly,
* bypassing the concurrency throttle (if active). All other
* tasks are subject to throttling.
* @see #TIMEOUT_IMMEDIATE
* @see #doExecute(Runnable)
*/
@Deprecated(since = "5.3.16")
@Override
public void execute(Runnable task, long startTimeout) {
Assert.notNull(task, "Runnable must not be null");
if (!isActive()) {
throw new TaskRejectedException(getClass().getSimpleName() + " has been closed already");
}
Runnable taskToUse = (this.taskDecorator != null ? this.taskDecorator.decorate(task) : task);
if (isThrottleActive() && startTimeout > TIMEOUT_IMMEDIATE) {
this.concurrencyThrottle.beforeAccess();
try {
doExecute(new TaskTrackingRunnable(taskToUse));
}
catch (Throwable ex) {
// Release concurrency permit if thread creation fails
this.concurrencyThrottle.afterAccess();
throw new TaskRejectedException(
"Failed to start execution thread for task: " + task, ex);
}
}
else if (this.activeThreads != null) {
doExecute(new TaskTrackingRunnable(taskToUse));
}
else {
doExecute(taskToUse);
}
}
@SuppressWarnings("deprecation")
@Override
public Future<?> submit(Runnable task) {
FutureTask<Object> future = new FutureTask<>(task, null);
execute(future, TIMEOUT_INDEFINITE);
return future;
}
@SuppressWarnings("deprecation")
@Override
public <T> Future<T> submit(Callable<T> task) {
FutureTask<T> future = new FutureTask<>(task);
execute(future, TIMEOUT_INDEFINITE);
return future;
}
/**
* Template method for the actual execution of a task.
* <p>The default implementation creates a new Thread and starts it.
* @param task the Runnable to execute
* @see #newThread
* @see Thread#start()
*/
protected void doExecute(Runnable task) {
newThread(task).start();
}
/**
* Create a new Thread for the given task.
* @param task the Runnable to create a Thread for
* @return the new Thread instance
* @since 6.1
* @see #setVirtualThreads
* @see #setThreadFactory
* @see #createThread
*/
protected Thread newThread(Runnable task) {
if (this.virtualThreadDelegate != null) {
return this.virtualThreadDelegate.newVirtualThread(nextThreadName(), task);
}
else {
return (this.threadFactory != null ? this.threadFactory.newThread(task) : createThread(task));
}
}
/**
* This close method tracks the termination of active threads if a concrete
* {@link #setTaskTerminationTimeout task termination timeout} has been set.
* Otherwise, it is not necessary to close this executor.
* @since 6.1
*/
@Override
public void close() {
if (this.active) {
this.active = false;
Set<Thread> threads = this.activeThreads;
if (threads != null) {
if (this.cancelRemainingTasksOnClose) {
// Early interrupt for remaining tasks on close
threads.forEach(Thread::interrupt);
}
if (this.taskTerminationTimeout > 0) {
synchronized (threads) {
try {
if (!threads.isEmpty()) {
threads.wait(this.taskTerminationTimeout);
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
if (!this.cancelRemainingTasksOnClose) {
// Late interrupt for remaining tasks after timeout
threads.forEach(Thread::interrupt);
}
}
}
}
}
/**
* Subclass of the general ConcurrencyThrottleSupport class,
* making {@code beforeAccess()} and {@code afterAccess()}
* visible to the surrounding class.
*/
private | SimpleAsyncTaskExecutor |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/messages/webmonitor/MultipleJobsDetails.java | {
"start": 1388,
"end": 2593
} | class ____ implements ResponseBody, Serializable {
private static final long serialVersionUID = -1526236139616019127L;
public static final String FIELD_NAME_JOBS = "jobs";
@JsonProperty(FIELD_NAME_JOBS)
private final Collection<JobDetails> jobs;
@JsonCreator
public MultipleJobsDetails(@JsonProperty(FIELD_NAME_JOBS) Collection<JobDetails> jobs) {
this.jobs = Preconditions.checkNotNull(jobs);
}
// ------------------------------------------------------------------------
public Collection<JobDetails> getJobs() {
return jobs;
}
@Override
public String toString() {
return "MultipleJobsDetails{" + "jobs=" + jobs + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MultipleJobsDetails that = (MultipleJobsDetails) o;
return Objects.equals(jobs, that.jobs);
}
@Override
public int hashCode() {
return Objects.hash(jobs);
}
// ------------------------------------------------------------------------
}
| MultipleJobsDetails |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/asm/ClassReader.java | {
"start": 9150,
"end": 9321
} | class ____ as well
// if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V26) {
// throw new IllegalArgumentException(
// "Unsupported | files |
java | apache__camel | components/camel-http-common/src/test/java/org/apache/camel/http/common/DefaultHttpBindingTest.java | {
"start": 1148,
"end": 2872
} | class ____ extends CamelTestSupport {
@Test
public void testConvertDate() {
DefaultHttpBinding binding = new DefaultHttpBinding();
Date date = new Date();
Exchange exchange = super.createExchangeWithBody(null);
String value = binding.convertHeaderValueToString(exchange, date);
assertNotEquals(value, date.toString());
assertEquals(value, DefaultHttpBinding.getHttpDateFormat().format(date));
}
@Test
public void testConvertDateTypeConverter() {
DefaultHttpBinding binding = new DefaultHttpBinding();
Date date = new Date();
Exchange exchange = super.createExchangeWithBody(null);
exchange.setProperty(DefaultHttpBinding.DATE_LOCALE_CONVERSION, false);
String value = binding.convertHeaderValueToString(exchange, date);
assertEquals(value, date.toString());
}
@Test
public void testConvertLocale() {
DefaultHttpBinding binding = new DefaultHttpBinding();
Locale l = Locale.SIMPLIFIED_CHINESE;
Exchange exchange = super.createExchangeWithBody(null);
String value = binding.convertHeaderValueToString(exchange, l);
assertNotEquals(value, l.toString());
assertEquals("zh-CN", value);
}
@Test
public void testConvertLocaleTypeConverter() {
DefaultHttpBinding binding = new DefaultHttpBinding();
Locale l = Locale.SIMPLIFIED_CHINESE;
Exchange exchange = super.createExchangeWithBody(null);
exchange.setProperty(DefaultHttpBinding.DATE_LOCALE_CONVERSION, false);
String value = binding.convertHeaderValueToString(exchange, l);
assertEquals(value, l.toString());
}
}
| DefaultHttpBindingTest |
java | micronaut-projects__micronaut-core | inject-java-test/src/test/groovy/io/micronaut/inject/visitor/beans/NullabilityBean.java | {
"start": 157,
"end": 368
} | class ____ {
@NonNull
String name;
@NonNull
public String getName() {
return name;
}
public void setName(@NonNull String name) {
this.name = name;
}
}
| NullabilityBean |
java | apache__maven | api/maven-api-core/src/main/java/org/apache/maven/api/PathScope.java | {
"start": 1320,
"end": 1825
} | enum ____ four defined values, {@link #MAIN_COMPILE}, {@link #MAIN_RUNTIME},
* {@link #TEST_COMPILE} and {@link #TEST_RUNTIME}, but can be extended by registering a
* {@code org.apache.maven.api.spi.PathScopeProvider}.
* <p>
* Implementation must have {@code equals()} and {@code hashCode()} implemented, so implementations of this interface
* can be used as keys.
*
* @since 4.0.0
* @see org.apache.maven.api.services.DependencyResolver
* @see DependencyScope
*/
@Experimental
@Immutable
public | has |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/authentication/ott/reactive/InMemoryReactiveOneTimeTokenService.java | {
"start": 1280,
"end": 2162
} | class ____ implements ReactiveOneTimeTokenService {
private final InMemoryOneTimeTokenService oneTimeTokenService = new InMemoryOneTimeTokenService();
@Override
public Mono<OneTimeToken> generate(GenerateOneTimeTokenRequest request) {
return Mono.just(request).map(this.oneTimeTokenService::generate);
}
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Mono<OneTimeToken> consume(OneTimeTokenAuthenticationToken authenticationToken) {
return Mono.just(authenticationToken).mapNotNull(this.oneTimeTokenService::consume);
}
/**
* Sets the {@link Clock} used when generating one-time token and checking token
* expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.oneTimeTokenService.setClock(clock);
}
}
| InMemoryReactiveOneTimeTokenService |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/LoopDefinition.java | {
"start": 1449,
"end": 6283
} | class ____ extends OutputExpressionNode {
@XmlTransient
private Processor onPrepareProcessor;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String copy;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String doWhile;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String breakOnShutdown;
@XmlAttribute
@Metadata(label = "advanced", javaType = "org.apache.camel.Processor")
private String onPrepare;
public LoopDefinition() {
}
protected LoopDefinition(LoopDefinition source) {
super(source);
this.copy = source.copy;
this.doWhile = source.doWhile;
this.breakOnShutdown = source.breakOnShutdown;
this.onPrepareProcessor = source.onPrepareProcessor;
this.onPrepare = source.onPrepare;
}
public LoopDefinition(Expression expression) {
super(expression);
}
public LoopDefinition(Predicate predicate) {
super(predicate);
setDoWhile(Boolean.toString(true));
}
public LoopDefinition(ExpressionDefinition expression) {
super(expression);
}
@Override
public LoopDefinition copyDefinition() {
return new LoopDefinition(this);
}
public Processor getOnPrepareProcessor() {
return onPrepareProcessor;
}
/**
* Enables copy mode so a copy of the input Exchange is used for each iteration.
*/
public LoopDefinition copy() {
setCopy(Boolean.toString(true));
return this;
}
/**
* Uses the {@link Processor} when preparing the {@link org.apache.camel.Exchange} for each loop iteration. This can
* be used to deep-clone messages, or any custom logic needed before the looping executes.
*
* @param onPrepare reference to the processor to lookup in the {@link org.apache.camel.spi.Registry}
* @return the builder
*/
public LoopDefinition onPrepare(Processor onPrepare) {
this.onPrepareProcessor = onPrepare;
return this;
}
/**
* Uses the {@link Processor} when preparing the {@link org.apache.camel.Exchange} for each loop iteration. This can
* be used to deep-clone messages, or any custom logic needed before the looping executes.
*
* @param onPrepare reference to the processor to lookup in the {@link org.apache.camel.spi.Registry}
* @return the builder
*/
public LoopDefinition onPrepare(String onPrepare) {
setOnPrepare(onPrepare);
return this;
}
public String getCopy() {
return copy;
}
public String getDoWhile() {
return doWhile;
}
/**
* Enables the while loop that loops until the predicate evaluates to false or null.
*/
public void setDoWhile(String doWhile) {
this.doWhile = doWhile;
}
/**
* If the copy attribute is true, a copy of the input Exchange is used for each iteration. That means each iteration
* will start from a copy of the same message.
* <p/>
* By default loop will loop the same exchange all over, so each iteration may have different message content.
*/
public void setCopy(String copy) {
this.copy = copy;
}
public LoopDefinition breakOnShutdown() {
setBreakOnShutdown(Boolean.toString(true));
return this;
}
/**
* If the breakOnShutdown attribute is true, then the loop will not iterate until it reaches the end when Camel is
* shut down.
*/
public void setBreakOnShutdown(String breakOnShutdown) {
this.breakOnShutdown = breakOnShutdown;
}
public String getBreakOnShutdown() {
return breakOnShutdown;
}
public String getOnPrepare() {
return onPrepare;
}
public void setOnPrepare(String onPrepare) {
this.onPrepare = onPrepare;
}
@Override
public String toString() {
return "Loop[" + getExpression() + " -> " + getOutputs() + "]";
}
@Override
public String getShortName() {
return "loop";
}
@Override
public String getLabel() {
return "loop[" + getExpression() + "]";
}
/**
* Expression to define how many times we should loop. Notice the expression is only evaluated once, and should
* return a number as how many times to loop. A value of zero or negative means no looping. The loop is like a
* for-loop fashion, if you want a while loop, then the dynamic router may be a better choice.
*/
@Override
public void setExpression(ExpressionDefinition expression) {
// override to include javadoc what the expression is used for
super.setExpression(expression);
}
}
| LoopDefinition |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/DefaultValueComponent2.java | {
"start": 201,
"end": 1409
} | class ____ {
private String str1 = "defaultValue";
private String str2;
public static final DefaultValueComponent2 of(String str1, String str2) {
DefaultValueComponent2 instance = new DefaultValueComponent2();
instance.setStr1( str1 );
instance.setStr2( str2 );
return instance;
}
public String getStr2() {
return str2;
}
public void setStr2(String str2) {
this.str2 = str2;
}
public String getStr1() {
return str1;
}
public void setStr1(String str1) {
this.str1 = str1;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof DefaultValueComponent2) ) {
return false;
}
DefaultValueComponent2 that = (DefaultValueComponent2) o;
if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) {
return false;
}
if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (str1 != null ? str1.hashCode() : 0);
result = 31 * result + (str2 != null ? str2.hashCode() : 0);
return result;
}
public String toString() {
return "Comp2(str1 = " + str1 + ", str2 = " + str2 + ")";
}
}
| DefaultValueComponent2 |
java | square__moshi | moshi/records-tests/src/test/java/com/squareup/moshi/records/RecordsTest.java | {
"start": 6791,
"end": 6902
} | interface ____ {}
/** Converts strings like #ff0000 to the corresponding color ints. */
public static | HexColor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AbstractCompositeIdAndNaturalIdTest.java | {
"start": 877,
"end": 3021
} | class ____ {
@Test
@JiraKey( value = "HHH-10360")
public void testNaturalIdNullability(SessionFactoryScope scope) {
final EntityMappingType accountMapping = scope.getSessionFactory().getRuntimeMetamodels().getEntityMappingType( Account.class );
final SingularAttributeMapping shortCodeMapping = ((SimpleNaturalIdMapping) accountMapping.getNaturalIdMapping()).getAttribute();
final AttributeMetadata shortCodeMetadata = shortCodeMapping.getAttributeMetadata();
assertThat( shortCodeMetadata.isNullable(), is( false ) );
final EntityPersister rootEntityPersister = accountMapping.getRootEntityDescriptor().getEntityPersister();
final int shortCodeLegacyPropertyIndex = rootEntityPersister.getPropertyIndex( "shortCode" );
assertThat( shortCodeLegacyPropertyIndex, is ( 0 ) );
assertThat( rootEntityPersister.getPropertyNullability()[ shortCodeLegacyPropertyIndex ], is( false ) );
}
public static final String NATURAL_ID_VALUE = "testAcct";
@BeforeEach
public void prepareTestData(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
// prepare some test data...
Account account = new Account( new AccountId( 1 ), NATURAL_ID_VALUE );
session.persist( account );
}
);
}
@AfterEach
public void cleanUpTestData(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void testNaturalIdCriteria(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
final Account account = session.bySimpleNaturalId( Account.class ).load( NATURAL_ID_VALUE );
assertThat( account, notNullValue() );
}
);
}
@Test
public void testNaturalIdApi(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
final Account account = session.bySimpleNaturalId( Account.class ).load( NATURAL_ID_VALUE );
assertThat( account, notNullValue() );
}
);
scope.inTransaction(
(session) -> {
final Account account = session.byNaturalId( Account.class ).using( "shortCode", NATURAL_ID_VALUE ).load();
assertThat( account, notNullValue() );
}
);
}
}
| AbstractCompositeIdAndNaturalIdTest |
java | junit-team__junit5 | junit-jupiter-params/src/main/java/org/junit/jupiter/params/provider/MethodSource.java | {
"start": 6766,
"end": 6846
} | interface ____ {
/**
* The names of factory methods within the test | MethodSource |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/node/Node.java | {
"start": 28950,
"end": 34394
} | class ____ part of infrastructure to react to signals from the operating system - most graceful shutdown
* logic should use Node Shutdown, see {@link org.elasticsearch.cluster.metadata.NodesShutdownMetadata}.
*/
public void prepareForClose() {
injector.getInstance(ShutdownPrepareService.class)
.prepareForShutdown(injector.getInstance(TransportService.class).getTaskManager());
}
/**
* Wait for this node to be effectively closed.
*/
// synchronized to prevent running concurrently with close()
public synchronized boolean awaitClose(long timeout, TimeUnit timeUnit) throws InterruptedException {
if (lifecycle.closed() == false) {
// We don't want to shutdown the threadpool or interrupt threads on a node that is not
// closed yet.
throw new IllegalStateException("Call close() first");
}
ThreadPool threadPool = injector.getInstance(ThreadPool.class);
final boolean terminated = ThreadPool.terminate(threadPool, timeout, timeUnit);
if (terminated) {
// All threads terminated successfully. Because search, recovery and all other operations
// that run on shards run in the threadpool, indices should be effectively closed by now.
if (nodeService.awaitClose(0, TimeUnit.MILLISECONDS) == false) {
throw new IllegalStateException(
"Some shards are still open after the threadpool terminated. "
+ "Something is leaking index readers or store references."
);
}
}
return terminated;
}
/**
* Returns {@code true} if the node is closed.
*/
public boolean isClosed() {
return lifecycle.closed();
}
public Injector injector() {
return this.injector;
}
/**
* Hook for validating the node after network
* services are started but before the cluster service is started
* and before the network service starts accepting incoming network
* requests.
*
* @param context the bootstrap context for this node
* @param boundTransportAddress the network addresses the node is
* bound and publishing to
*/
@SuppressWarnings("unused")
protected void validateNodeBeforeAcceptingRequests(
final BootstrapContext context,
final BoundTransportAddress boundTransportAddress,
List<BootstrapCheck> bootstrapChecks
) throws NodeValidationException {}
/**
* Writes a file to the logs dir containing the ports for the given transport type
*/
private void writePortsFile(String type, BoundTransportAddress boundAddress) {
Path tmpPortsFile = environment.logsDir().resolve(type + ".ports.tmp");
try (BufferedWriter writer = Files.newBufferedWriter(tmpPortsFile, StandardCharsets.UTF_8)) {
for (TransportAddress address : boundAddress.boundAddresses()) {
InetAddress inetAddress = InetAddress.getByName(address.getAddress());
writer.write(NetworkAddress.format(new InetSocketAddress(inetAddress, address.getPort())) + "\n");
}
} catch (IOException e) {
throw new RuntimeException("Failed to write ports file", e);
}
Path portsFile = environment.logsDir().resolve(type + ".ports");
try {
Files.move(tmpPortsFile, portsFile, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
throw new RuntimeException("Failed to rename ports file", e);
}
}
/**
* The {@link PluginsService} used to build this node's components.
*/
protected PluginsService getPluginsService() {
return pluginsService;
}
/**
* Plugins can provide additional settings for the node, but two plugins
* cannot provide the same setting.
* @param pluginMap A map of plugin names to plugin instances
* @param originalSettings The node's original settings, which silently override any setting provided by the plugins.
* @return A {@link Settings} with the merged node and plugin settings
* @throws IllegalArgumentException if two plugins provide the same additional setting key
*/
static Settings mergePluginSettings(Map<String, Plugin> pluginMap, Settings originalSettings) {
Map<String, String> foundSettings = new HashMap<>();
final Settings.Builder builder = Settings.builder();
for (Map.Entry<String, Plugin> entry : pluginMap.entrySet()) {
Settings settings = entry.getValue().additionalSettings();
for (String setting : settings.keySet()) {
String oldPlugin = foundSettings.put(setting, entry.getKey());
if (oldPlugin != null) {
throw new IllegalArgumentException(
"Cannot have additional setting ["
+ setting
+ "] "
+ "in plugin ["
+ entry.getKey()
+ "], already added in plugin ["
+ oldPlugin
+ "]"
);
}
}
builder.put(settings);
}
return builder.put(originalSettings).build();
}
static | is |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterServiceCapacity.java | {
"start": 3449,
"end": 16009
} | class ____ extends
ApplicationMasterServiceTestBase {
private static final String DEFAULT_QUEUE = "default";
@Override
protected YarnConfiguration createYarnConfig() {
CapacitySchedulerConfiguration csConf =
new CapacitySchedulerConfiguration();
csConf.setResourceComparator(DominantResourceCalculator.class);
YarnConfiguration yarnConf = new YarnConfiguration(csConf);
yarnConf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class,
ResourceScheduler.class);
return yarnConf;
}
@Override
protected Resource getResourceUsageForQueue(ResourceManager rm,
String queue) {
CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler();
LeafQueue leafQueue = (LeafQueue) cs.getQueue(DEFAULT_QUEUE);
return leafQueue.getUsedResources();
}
@Override
protected String getDefaultQueueName() {
return DEFAULT_QUEUE;
}
private void sentRMContainerLaunched(MockRM rm, ContainerId containerId) {
CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler();
RMContainer rmContainer = cs.getRMContainer(containerId);
if (rmContainer != null) {
rmContainer.handle(
new RMContainerEvent(containerId, RMContainerEventType.LAUNCHED));
} else {
fail("Cannot find RMContainer");
}
}
@Test
@Timeout(value = 60)
public void testInvalidIncreaseDecreaseRequest() throws Exception {
conf = new YarnConfiguration();
conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class,
ResourceScheduler.class);
try (MockRM rm = new MockRM(conf)) {
rm.start();
// Register node1
MockNM nm1 = rm.registerNode(DEFAULT_HOST + ":" + DEFAULT_PORT, 6 * GB);
// Submit an application
RMApp app1 = MockRMAppSubmitter.submitWithMemory(1024, rm);
// kick the scheduling
nm1.nodeHeartbeat(true);
RMAppAttempt attempt1 = app1.getCurrentAppAttempt();
MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId());
RegisterApplicationMasterResponse registerResponse =
am1.registerAppAttempt();
sentRMContainerLaunched(rm,
ContainerId.newContainerId(am1.getApplicationAttemptId(), 1));
// Ask for a normal increase should be successful
am1.sendContainerResizingRequest(Arrays.asList(
UpdateContainerRequest.newInstance(
0, ContainerId.newContainerId(attempt1.getAppAttemptId(), 1),
ContainerUpdateType.INCREASE_RESOURCE,
Resources.createResource(2048), null)));
// Target resource is negative, should fail
AllocateResponse response =
am1.sendContainerResizingRequest(Arrays.asList(
UpdateContainerRequest.newInstance(0,
ContainerId.newContainerId(attempt1.getAppAttemptId(), 1),
ContainerUpdateType.INCREASE_RESOURCE,
Resources.createResource(-1), null)));
assertEquals(1, response.getUpdateErrors().size());
assertEquals("RESOURCE_OUTSIDE_ALLOWED_RANGE",
response.getUpdateErrors().get(0).getReason());
// Target resource is more than maxAllocation, should fail
response = am1.sendContainerResizingRequest(Arrays.asList(
UpdateContainerRequest.newInstance(0,
ContainerId.newContainerId(attempt1.getAppAttemptId(), 1),
ContainerUpdateType.INCREASE_RESOURCE,
Resources.add(
registerResponse.getMaximumResourceCapability(),
Resources.createResource(1)), null)));
assertEquals(1, response.getUpdateErrors().size());
assertEquals("RESOURCE_OUTSIDE_ALLOWED_RANGE",
response.getUpdateErrors().get(0).getReason());
// Contains multiple increase/decrease requests for same containerId
response = am1.sendContainerResizingRequest(Arrays.asList(
UpdateContainerRequest.newInstance(0,
ContainerId.newContainerId(attempt1.getAppAttemptId(), 1),
ContainerUpdateType.INCREASE_RESOURCE,
Resources.createResource(2048, 4), null),
UpdateContainerRequest.newInstance(0,
ContainerId.newContainerId(attempt1.getAppAttemptId(), 1),
ContainerUpdateType.DECREASE_RESOURCE,
Resources.createResource(1024, 1), null)));
assertEquals(1, response.getUpdateErrors().size());
assertEquals("UPDATE_OUTSTANDING_ERROR",
response.getUpdateErrors().get(0).getReason());
}
}
@Test
@Timeout(value = 300)
public void testPriorityInAllocatedResponse() throws Exception {
conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class,
ResourceScheduler.class);
// Set Max Application Priority as 10
conf.setInt(YarnConfiguration.MAX_CLUSTER_LEVEL_APPLICATION_PRIORITY, 10);
MockRM rm = new MockRM(conf);
rm.start();
// Register node1
MockNM nm1 = rm.registerNode(DEFAULT_HOST + ":" + DEFAULT_PORT, 6 * GB);
// Submit an application
Priority appPriority1 = Priority.newInstance(5);
MockRMAppSubmissionData data = MockRMAppSubmissionData.Builder
.createWithMemory(2048, rm)
.withAppPriority(appPriority1)
.build();
RMApp app1 = MockRMAppSubmitter.submit(rm, data);
nm1.nodeHeartbeat(true);
RMAppAttempt attempt1 = app1.getCurrentAppAttempt();
MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId());
am1.registerAppAttempt();
AllocateRequestPBImpl allocateRequest = new AllocateRequestPBImpl();
List<ContainerId> release = new ArrayList<>();
List<ResourceRequest> ask = new ArrayList<>();
allocateRequest.setReleaseList(release);
allocateRequest.setAskList(ask);
AllocateResponse response1 = am1.allocate(allocateRequest);
assertEquals(appPriority1, response1.getApplicationPriority());
// Change the priority of App1 to 8
Priority appPriority2 = Priority.newInstance(8);
UserGroupInformation ugi = UserGroupInformation
.createRemoteUser(app1.getUser());
rm.getRMAppManager().updateApplicationPriority(ugi, app1.getApplicationId(),
appPriority2);
AllocateResponse response2 = am1.allocate(allocateRequest);
assertEquals(appPriority2, response2.getApplicationPriority());
rm.stop();
}
@Test
@Timeout(value = 300)
public void testGetNMNumInAllocatedResponseWithOutNodeLabel() throws Exception {
conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class);
MockRM rm = new MockRM(conf);
rm.start();
// Register node1 node2 node3 node4
MockNM nm1 = rm.registerNode("host1:1234", 6 * GB);
MockNM nm2 = rm.registerNode("host2:1234", 6 * GB);
MockNM nm3 = rm.registerNode("host3:1234", 6 * GB);
// Submit an application
MockRMAppSubmissionData data = MockRMAppSubmissionData.Builder
.createWithMemory(2048, rm)
.build();
RMApp app1 = MockRMAppSubmitter.submit(rm, data);
nm1.nodeHeartbeat(true);
nm2.nodeHeartbeat(true);
nm3.nodeHeartbeat(true);
RMAppAttempt attempt1 = app1.getCurrentAppAttempt();
MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId());
am1.registerAppAttempt();
AllocateRequestPBImpl allocateRequest = new AllocateRequestPBImpl();
List<ContainerId> release = new ArrayList<ContainerId>();
List<ResourceRequest> ask = new ArrayList<ResourceRequest>();
allocateRequest.setReleaseList(release);
allocateRequest.setAskList(ask);
AllocateResponse response1 = am1.allocate(allocateRequest);
assertEquals(3, response1.getNumClusterNodes());
rm.stop();
}
private Configuration getConfigurationWithQueueLabels(Configuration config) {
CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(config);
// Define top-level queues
final QueuePath root = new QueuePath(CapacitySchedulerConfiguration.ROOT);
conf.setQueues(root, new String[] {"a", "b"});
conf.setCapacityByLabel(root, "x", 100);
conf.setCapacityByLabel(root, "y", 100);
final String aPath = CapacitySchedulerConfiguration.ROOT + ".a";
final QueuePath a = new QueuePath(aPath);
conf.setCapacity(a, 50);
conf.setMaximumCapacity(a, 100);
conf.setAccessibleNodeLabels(a, toSet("x"));
conf.setDefaultNodeLabelExpression(a, "x");
conf.setCapacityByLabel(a, "x", 100);
final String bPath = CapacitySchedulerConfiguration.ROOT + ".b";
final QueuePath b = new QueuePath(bPath);
conf.setCapacity(b, 50);
conf.setMaximumCapacity(b, 100);
conf.setAccessibleNodeLabels(b, toSet("y"));
conf.setDefaultNodeLabelExpression(b, "y");
conf.setCapacityByLabel(b, "y", 100);
return conf;
}
@Test
@Timeout(value = 300)
public void testGetNMNumInAllocatedResponseWithNodeLabel() throws Exception {
conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class);
conf.setBoolean(YarnConfiguration.NODE_LABELS_ENABLED, true);
MockRM rm = new MockRM(getConfigurationWithQueueLabels(conf)) {
@Override
protected RMNodeLabelsManager createNodeLabelManager() {
RMNodeLabelsManager mgr = new RMNodeLabelsManager();
mgr.init(getConfig());
return mgr;
}
};
// add node label "x","y" and set node to label mapping
Set<String> clusterNodeLabels = new HashSet<String>();
clusterNodeLabels.add("x");
clusterNodeLabels.add("y");
RMNodeLabelsManager nodeLabelManager = rm.getRMContext().getNodeLabelManager();
nodeLabelManager.
addToCluserNodeLabelsWithDefaultExclusivity(clusterNodeLabels);
//has 3 nodes with node label "x",1 node with node label "y"
nodeLabelManager
.addLabelsToNode(ImmutableMap.of(NodeId.newInstance("host1", 1234), toSet("x")));
nodeLabelManager
.addLabelsToNode(ImmutableMap.of(NodeId.newInstance("host2", 1234), toSet("x")));
nodeLabelManager
.addLabelsToNode(ImmutableMap.of(NodeId.newInstance("host3", 1234), toSet("x")));
nodeLabelManager
.addLabelsToNode(ImmutableMap.of(NodeId.newInstance("host4", 1234), toSet("y")));
rm.start();
// Register node1 node2 node3 node4
MockNM nm1 = rm.registerNode("host1:1234", 6 * GB);
MockNM nm2 = rm.registerNode("host2:1234", 6 * GB);
MockNM nm3 = rm.registerNode("host3:1234", 6 * GB);
MockNM nm4 = rm.registerNode("host4:1234", 6 * GB);
// submit an application to queue root.a expression as "x"
MockRMAppSubmissionData data1 = MockRMAppSubmissionData.Builder
.createWithMemory(2048, rm)
.withAppName("someApp1")
.withUser("someUser")
.withQueue("root.a")
.build();
RMApp app1 = MockRMAppSubmitter.submit(rm, data1);
MockAM am1 = MockRM.launchAndRegisterAM(app1, rm, nm1);
// submit an application to queue root.b expression as "y"
MockRMAppSubmissionData data2 = MockRMAppSubmissionData.Builder
.createWithMemory(2048, rm)
.withAppName("someApp2")
.withUser("someUser")
.withQueue("root.b")
.build();
RMApp app2 = MockRMAppSubmitter.submit(rm, data2);
MockAM am2 = MockRM.launchAndRegisterAM(app2, rm, nm4);
AllocateRequestPBImpl allocateRequest = new AllocateRequestPBImpl();
List<ContainerId> release = new ArrayList<ContainerId>();
List<ResourceRequest> ask = new ArrayList<ResourceRequest>();
allocateRequest.setReleaseList(release);
allocateRequest.setAskList(ask);
AllocateResponse response1 = am1.allocate(allocateRequest);
AllocateResponse response2 = am2.allocate(allocateRequest);
CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler();
RMNode rmNode1 = rm.getRMContext().getRMNodes().get(nm1.getNodeId());
RMNode rmNode2 = rm.getRMContext().getRMNodes().get(nm2.getNodeId());
RMNode rmNode3 = rm.getRMContext().getRMNodes().get(nm3.getNodeId());
RMNode rmNode4 = rm.getRMContext().getRMNodes().get(nm4.getNodeId());
// Do node heartbeats many times
for (int i = 0; i < 3; i++) {
cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
cs.handle(new NodeUpdateSchedulerEvent(rmNode2));
cs.handle(new NodeUpdateSchedulerEvent(rmNode3));
cs.handle(new NodeUpdateSchedulerEvent(rmNode4));
}
//has 3 nodes with node label "x"
assertEquals(3, response1.getNumClusterNodes());
//has 1 node with node label "y"
assertEquals(1, response2.getNumClusterNodes());
rm.stop();
}
}
| TestApplicationMasterServiceCapacity |
java | apache__camel | components/camel-seda/src/main/java/org/apache/camel/component/seda/SedaConsumer.java | {
"start": 1921,
"end": 14465
} | class ____ extends DefaultConsumer implements Runnable, ShutdownAware, Suspendable {
private static final Logger LOG = LoggerFactory.getLogger(SedaConsumer.class);
private final AtomicInteger taskCount = new AtomicInteger();
private volatile CountDownLatch latch;
private volatile boolean shutdownPending;
private volatile boolean forceShutdown;
private ExecutorService executor;
private final int pollTimeout;
public SedaConsumer(SedaEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.pollTimeout = endpoint.getPollTimeout();
}
@Override
public SedaEndpoint getEndpoint() {
return (SedaEndpoint) super.getEndpoint();
}
@Override
public boolean deferShutdown(ShutdownRunningTask shutdownRunningTask) {
// deny stopping on shutdown as we want seda consumers to run in case some other queues
// depend on this consumer to run, so it can complete its exchanges
return true;
}
@Override
public int getPendingExchangesSize() {
// the route is shutting down, so either we should purge the queue,
// or return how many exchanges are still on the queue
if (getEndpoint().isPurgeWhenStopping()) {
getEndpoint().purgeQueue();
}
return getEndpoint().getQueue().size();
}
@Override
public void prepareShutdown(boolean suspendOnly, boolean forced) {
// if we are suspending then we want to keep the thread running but just not route the exchange
// this logic is only when we stop or shutdown the consumer
if (suspendOnly) {
LOG.debug("Skip preparing to shutdown as consumer is being suspended");
return;
}
// signal we want to shutdown
shutdownPending = true;
forceShutdown = forced;
if (latch != null) {
LOG.debug("Preparing to shutdown, waiting for {} consumer threads to complete.", latch.getCount());
// wait for all threads to end
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@Override
public boolean isRunAllowed() {
// if we force shutdown then do not allow running anymore
if (forceShutdown) {
return false;
}
if (isSuspending() || isSuspended()) {
// allow to run even if we are suspended as we want to
// keep the thread task running
return true;
}
return super.isRunAllowed();
}
@Override
public void run() {
taskCount.incrementAndGet();
try {
doRun();
} finally {
taskCount.decrementAndGet();
latch.countDown();
LOG.debug("Ending this polling consumer thread, there are still {} consumer threads left.", latch.getCount());
}
}
protected void doRun() {
BlockingQueue<Exchange> queue = getEndpoint().getQueue();
// loop while we are allowed, or if we are stopping loop until the queue is empty
while (queue != null && isRunAllowed()) {
// do not poll during CamelContext is starting, as we should only poll when CamelContext is fully started
if (getEndpoint().getCamelContext().getStatus().isStarting()) {
LOG.trace("CamelContext is starting so skip polling");
try {
// sleep at most 1 sec
Thread.sleep(Math.min(pollTimeout, 1000));
} catch (InterruptedException e) {
LOG.debug("Sleep interrupted, are we stopping? {}", isStopping() || isStopped());
Thread.currentThread().interrupt();
}
continue;
}
// do not poll if we are suspended or starting again after resuming
if (isSuspending() || isSuspended() || isStarting()) {
if (shutdownPending && queue.isEmpty()) {
LOG.trace(
"Consumer is suspended and shutdown is pending, so this consumer thread is breaking out because the task queue is empty.");
// we want to shutdown so break out if there queue is empty
break;
} else {
LOG.trace("Consumer is suspended so skip polling");
try {
// sleep at most 1 sec
Thread.sleep(Math.min(pollTimeout, 1000));
} catch (InterruptedException e) {
LOG.debug("Sleep interrupted, are we stopping? {}", isStopping() || isStopped());
Thread.currentThread().interrupt();
}
continue;
}
}
Exchange exchange = null;
try {
// use the end user configured poll timeout
exchange = queue.poll(pollTimeout, TimeUnit.MILLISECONDS);
if (LOG.isTraceEnabled()) {
LOG.trace("Polled queue {} with timeout {} ms. -> {}", ObjectHelper.getIdentityHashCode(queue), pollTimeout,
exchange);
}
if (exchange != null) {
try {
final Exchange original = exchange;
// prepare the exchange before sending to consumer
final Exchange prepared = prepareExchange(exchange);
// callback to be executed when sending to consumer and processing is done
AsyncCallback callback = doneSync -> onProcessingDone(original, prepared);
// process the exchange
sendToConsumers(prepared, callback);
} catch (Exception e) {
getExceptionHandler().handleException("Error processing exchange", exchange, e);
}
} else if (shutdownPending && queue.isEmpty()) {
LOG.trace("Shutdown is pending, so this consumer thread is breaking out because the task queue is empty.");
// we want to shutdown so break out if there queue is empty
break;
}
} catch (InterruptedException e) {
LOG.debug("Sleep interrupted, are we stopping? {}", isStopping() || isStopped());
Thread.currentThread().interrupt();
} catch (Exception e) {
if (exchange != null) {
getExceptionHandler().handleException("Error processing exchange", exchange, e);
} else {
getExceptionHandler().handleException(e);
}
}
}
}
/**
* Strategy to invoke when the exchange is done being processed.
* <p/>
* This method is meant to be overridden by subclasses to be able to mimic the behavior of the legacy component
* camel-vm, that is why the parameter {@code prepared} is not used by default.
*
* @param original the exchange before being processed
* @param prepared the exchange processed
*/
protected void onProcessingDone(Exchange original, Exchange prepared) {
// log exception if an exception occurred and was not handled
if (original.getException() != null) {
getExceptionHandler().handleException("Error processing exchange", original,
original.getException());
}
}
/**
* Strategy to prepare exchange for being processed by this consumer
* <p/>
* This method is meant to be overridden by subclasses to be able to mimic the behavior of the legacy component
* camel-vm, that is why the prepared exchange is returned.
*
* @param exchange the exchange
* @return the exchange to process by this consumer
*/
protected Exchange prepareExchange(Exchange exchange) {
// this consumer grabbed the exchange so mark it's from this route/endpoint
ExchangeExtension exchangeExtension = exchange.getExchangeExtension();
exchangeExtension.setFromEndpoint(getEndpoint());
exchangeExtension.setFromRouteId(getRouteId());
return exchange;
}
/**
* Send the given {@link Exchange} to the consumer(s).
* <p/>
* If multiple consumers then they will each receive a copy of the Exchange. A multicast processor will send the
* exchange in parallel to the multiple consumers.
* <p/>
* If there is only a single consumer then its dispatched directly to it using same thread.
*
* @param exchange the exchange
* @param callback exchange callback to continue routing
* @throws Exception can be thrown if processing of the exchange failed
*/
protected void sendToConsumers(final Exchange exchange, final AsyncCallback callback) throws Exception {
// validate multiple consumers has been enabled
int size = getEndpoint().getConsumers().size();
if (size > 1 && !getEndpoint().isMultipleConsumersSupported()) {
throw new IllegalStateException("Multiple consumers for the same endpoint is not allowed: " + getEndpoint());
}
// if there are multiple consumers then multicast to them
if (getEndpoint().isMultipleConsumersSupported()) {
if (LOG.isTraceEnabled()) {
LOG.trace("Multicasting to {} consumers for Exchange: {}", size, exchange);
}
// handover completions, as we need to done this when the multicast is done
final List<Synchronization> completions = exchange.getExchangeExtension().handoverCompletions();
// use a multicast processor to process it
AsyncProcessor mp = getEndpoint().getConsumerMulticastProcessor();
ObjectHelper.notNull(mp, "ConsumerMulticastProcessor", this);
// and use the asynchronous routing engine to support it
mp.process(exchange, doneSync -> {
// done the uow on the completions
try {
UnitOfWorkHelper.doneSynchronizations(exchange, completions);
} finally {
callback.done(doneSync);
}
});
} else {
// use the regular processor and use the asynchronous routing engine to support it
getAsyncProcessor().process(exchange, callback);
}
}
@Override
protected void doStart() throws Exception {
super.doStart();
latch = new CountDownLatch(getEndpoint().getConcurrentConsumers());
shutdownPending = false;
forceShutdown = false;
setupTasks();
getEndpoint().onStarted(this);
}
@Override
protected void doSuspend() throws Exception {
getEndpoint().onStopped(this);
}
@Override
protected void doResume() throws Exception {
getEndpoint().onStarted(this);
}
@Override
protected void doStop() throws Exception {
// ensure queue is purged if we stop the consumer
if (getEndpoint().isPurgeWhenStopping()) {
getEndpoint().purgeQueue();
}
getEndpoint().onStopped(this);
shutdownExecutor();
super.doStop();
}
@Override
protected void doShutdown() throws Exception {
shutdownExecutor();
}
private void shutdownExecutor() {
if (executor != null) {
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(executor);
executor = null;
}
}
/**
* Setup the thread pool and ensures tasks gets executed (if needed)
*/
private void setupTasks() {
int poolSize = getEndpoint().getConcurrentConsumers();
// create thread pool if needed
if (executor == null) {
executor = getEndpoint().getCamelContext().getExecutorServiceManager().newFixedThreadPool(this,
getEndpoint().getEndpointUri(), poolSize);
}
// submit needed number of tasks
int tasks = poolSize - taskCount.get();
LOG.debug("Creating {} consumer tasks with poll timeout {} ms.", tasks, pollTimeout);
for (int i = 0; i < tasks; i++) {
executor.execute(this);
}
}
}
| SedaConsumer |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/view/freemarker/FreeMarkerViewResolver.java | {
"start": 1238,
"end": 2542
} | class ____ all views generated by this resolver can be specified
* via the "viewClass" property. See {@code UrlBasedViewResolver} for details.
*
* <p><b>Note:</b> To ensure that the correct encoding is used when the rendering
* the response, set the {@linkplain #setContentType(String) content type} with an
* appropriate {@code charset} attribute — for example,
* {@code "text/html;charset=UTF-8"}; however, it is not necessary to explicitly set
* the content type in the {@code FreeMarkerViewResolver} if you have set an explicit
* encoding via either {@link FreeMarkerView#setEncoding(String)},
* {@link FreeMarkerConfigurer#setDefaultEncoding(String)}, or
* {@link Configuration#setDefaultEncoding(String)}.
*
* <p><b>Note:</b> When chaining ViewResolvers, a {@code FreeMarkerViewResolver} will
* check for the existence of the specified template resources and only return
* a non-null {@code View} object if the template was actually found.
*
* <p>Note: Spring's FreeMarker support requires FreeMarker 2.3.33 or higher.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 1.1
* @see #setViewClass
* @see #setPrefix
* @see #setSuffix
* @see #setContentType
* @see #setRequestContextAttribute
* @see #setExposeSpringMacroHelpers
* @see FreeMarkerView
*/
public | for |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java | {
"start": 4611,
"end": 6737
} | class ____ will be
* used to load the resource (assuming the location string is prefixed with
* {@code classpath:}).
*/
public ResourcePropertySource(String name, String location) throws IOException {
this(name, new DefaultResourceLoader().getResource(location));
}
/**
* Create a PropertySource based on Properties loaded from the given resource
* location. The name of the PropertySource will be generated based on the
* {@link Resource#getDescription() description} of the resource.
*/
public ResourcePropertySource(String location) throws IOException {
this(new DefaultResourceLoader().getResource(location));
}
private ResourcePropertySource(String name, @Nullable String resourceName, Map<String, Object> source) {
super(name, source);
this.resourceName = resourceName;
}
/**
* Return a potentially adapted variant of this {@link ResourcePropertySource},
* overriding the previously given (or derived) name with the specified name.
* @since 4.0.4
*/
public ResourcePropertySource withName(String name) {
if (this.name.equals(name)) {
return this;
}
// Store the original resource name if necessary...
if (this.resourceName != null) {
if (this.resourceName.equals(name)) {
return new ResourcePropertySource(this.resourceName, null, this.source);
}
else {
return new ResourcePropertySource(name, this.resourceName, this.source);
}
}
else {
// Current name is resource name -> preserve it in the extra field...
return new ResourcePropertySource(name, this.name, this.source);
}
}
/**
* Return a potentially adapted variant of this {@link ResourcePropertySource},
* overriding the previously given name (if any) with the original resource name
* (equivalent to the name generated by the name-less constructor variants).
* @since 4.1
*/
public ResourcePropertySource withResourceName() {
if (this.resourceName == null) {
return this;
}
return new ResourcePropertySource(this.resourceName, null, this.source);
}
/**
* Return the description for the given Resource; if the description is
* empty, return the | loader |
java | apache__maven | impl/maven-core/src/test/java/org/apache/maven/project/ProjectBuildingResultWithLocationAssert.java | {
"start": 1130,
"end": 2776
} | class ____ {
private final ProjectBuildingResult actual;
ProjectBuildingResultWithLocationAssert(ProjectBuildingResult actual) {
this.actual = actual;
}
public static ProjectBuildingResultWithLocationAssert assertThat(ProjectBuildingResult actual) {
return new ProjectBuildingResultWithLocationAssert(actual);
}
public ProjectBuildingResultWithLocationAssert hasLocation(int columnNumber, int lineNumber) {
assertNotNull(actual);
boolean hasLocation = actual.getProblems().stream()
.anyMatch(p -> p.getLineNumber() == lineNumber && p.getColumnNumber() == columnNumber);
if (!hasLocation) {
String actualLocations = actual.getProblems().stream()
.map(p -> formatLocation(p.getColumnNumber(), p.getLineNumber()))
.collect(joining(", "));
String message = String.format(
"Expected ProjectBuildingResult to have location <%s> but had locations <%s>",
formatLocation(columnNumber, lineNumber), actualLocations);
assertTrue(false, message);
}
return this;
}
private String formatLocation(int columnNumber, int lineNumber) {
return String.format("line %d, column %d", lineNumber, columnNumber);
}
// Helper method for backward compatibility
static ProjectBuildingResultWithLocationAssert projectBuildingResultWithLocation(int columnNumber, int lineNumber) {
return new ProjectBuildingResultWithLocationAssert(null).hasLocation(columnNumber, lineNumber);
}
}
| ProjectBuildingResultWithLocationAssert |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ExpensiveLenientFormatStringTest.java | {
"start": 1924,
"end": 2476
} | class ____ {
void f() {
checkNotNull(this, "%s", "hello");
}
void g() {
checkNotNull(this, "hello");
}
void h() {
checkNotNull(this, String.format("%d", 42));
}
void i() {
checkNotNull(this, "%s", "hello");
}
}
""")
.doTest();
}
@Test
public void positive() {
testHelper
.addSourceLines(
"Test.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.base.Preconditions;
/**
* Test for methodIs call involving String.format() and %s
*/
public | Test |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointRecipientListFineGrainedErrorHandlingTest.java | {
"start": 1166,
"end": 3548
} | class ____ extends ContextTestSupport {
private static int counter;
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("fail", new MyFailBean());
return jndi;
}
@Test
public void testAsyncEndpointOK() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
context.addComponent("async", new MyAsyncComponent());
onException(Exception.class).redeliveryDelay(0).maximumRedeliveries(2);
from("direct:start").to("mock:a").recipientList(header("foo")).stopOnException();
}
});
context.start();
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:foo").expectedMessageCount(1);
getMockEndpoint("mock:bar").expectedMessageCount(1);
getMockEndpoint("mock:baz").expectedMessageCount(1);
template.sendBodyAndHeader("direct:start", "Hello World", "foo", "mock:foo,async:bye:camel,mock:bar,mock:baz");
assertMockEndpointsSatisfied();
}
@Test
public void testAsyncEndpointERROR() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
context.addComponent("async", new MyAsyncComponent());
onException(Exception.class).redeliveryDelay(0).maximumRedeliveries(2);
from("direct:start").to("mock:a").recipientList(header("foo")).stopOnException();
}
});
context.start();
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:foo").expectedMessageCount(1);
getMockEndpoint("mock:bar").expectedMessageCount(1);
getMockEndpoint("mock:baz").expectedMessageCount(0);
try {
template.sendBodyAndHeader("direct:start", "Hello World", "foo", "mock:foo,mock:bar,bean:fail,mock:baz");
fail("Should throw exception");
} catch (Exception e) {
// expected
}
assertMockEndpointsSatisfied();
assertEquals(3, counter);
}
@Override
public boolean isUseRouteBuilder() {
return false;
}
public static | AsyncEndpointRecipientListFineGrainedErrorHandlingTest |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/ml/JavaBucketizerExample.java | {
"start": 1426,
"end": 4024
} | class ____ {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("JavaBucketizerExample")
.getOrCreate();
// $example on$
double[] splits = {Double.NEGATIVE_INFINITY, -0.5, 0.0, 0.5, Double.POSITIVE_INFINITY};
List<Row> data = Arrays.asList(
RowFactory.create(-999.9),
RowFactory.create(-0.5),
RowFactory.create(-0.3),
RowFactory.create(0.0),
RowFactory.create(0.2),
RowFactory.create(999.9)
);
StructType schema = new StructType(new StructField[]{
new StructField("features", DataTypes.DoubleType, false, Metadata.empty())
});
Dataset<Row> dataFrame = spark.createDataFrame(data, schema);
Bucketizer bucketizer = new Bucketizer()
.setInputCol("features")
.setOutputCol("bucketedFeatures")
.setSplits(splits);
// Transform original data into its bucket index.
Dataset<Row> bucketedData = bucketizer.transform(dataFrame);
System.out.println("Bucketizer output with " + (bucketizer.getSplits().length-1) + " buckets");
bucketedData.show();
// $example off$
// $example on$
// Bucketize multiple columns at one pass.
double[][] splitsArray = {
{Double.NEGATIVE_INFINITY, -0.5, 0.0, 0.5, Double.POSITIVE_INFINITY},
{Double.NEGATIVE_INFINITY, -0.3, 0.0, 0.3, Double.POSITIVE_INFINITY}
};
List<Row> data2 = Arrays.asList(
RowFactory.create(-999.9, -999.9),
RowFactory.create(-0.5, -0.2),
RowFactory.create(-0.3, -0.1),
RowFactory.create(0.0, 0.0),
RowFactory.create(0.2, 0.4),
RowFactory.create(999.9, 999.9)
);
StructType schema2 = new StructType(new StructField[]{
new StructField("features1", DataTypes.DoubleType, false, Metadata.empty()),
new StructField("features2", DataTypes.DoubleType, false, Metadata.empty())
});
Dataset<Row> dataFrame2 = spark.createDataFrame(data2, schema2);
Bucketizer bucketizer2 = new Bucketizer()
.setInputCols(new String[] {"features1", "features2"})
.setOutputCols(new String[] {"bucketedFeatures1", "bucketedFeatures2"})
.setSplitsArray(splitsArray);
// Transform original data into its bucket index.
Dataset<Row> bucketedData2 = bucketizer2.transform(dataFrame2);
System.out.println("Bucketizer output with [" +
(bucketizer2.getSplitsArray()[0].length-1) + ", " +
(bucketizer2.getSplitsArray()[1].length-1) + "] buckets for each input column");
bucketedData2.show();
// $example off$
spark.stop();
}
}
| JavaBucketizerExample |
java | apache__camel | components/camel-groovy/src/main/java/org/apache/camel/language/groovy/GroovyDevConsole.java | {
"start": 1206,
"end": 3991
} | class ____ extends AbstractDevConsole {
public GroovyDevConsole() {
super("camel", "groovy", "Groovy", "Groovy Language");
}
@Override
protected String doCallText(Map<String, Object> options) {
StringBuilder sb = new StringBuilder();
DefaultGroovyScriptCompiler compiler = getCamelContext().hasService(DefaultGroovyScriptCompiler.class);
if (compiler != null) {
sb.append(String.format(" Script Pattern: %s", compiler.getScriptPattern()));
sb.append(String.format("\n Pre-loaded Counter: %s", compiler.getPreloadedCounter()));
sb.append(String.format("\n Compile Counter: %s", compiler.getCompileCounter()));
sb.append(String.format("\n Compile Time: %s (ms)", compiler.getCompileTime()));
long last = compiler.getLastCompilationTimestamp();
if (last != 0) {
sb.append(String.format("\n Compile Ago: %s",
TimeUtils.printSince(compiler.getLastCompilationTimestamp())));
}
sb.append(String.format("\n Re-compile Enabled: %b", compiler.isRecompileEnabled()));
if (compiler.getWorkDir() != null) {
sb.append(String.format("\n Work Directory: %s", compiler.getWorkDir()));
}
sb.append(String.format("\n Classes: (%d)", compiler.getClassesSize()));
for (String name : compiler.compiledClassNames()) {
sb.append(String.format("\n %s", name));
}
}
return sb.toString();
}
@Override
protected Map<String, Object> doCallJson(Map<String, Object> options) {
JsonObject root = new JsonObject();
DefaultGroovyScriptCompiler compiler = getCamelContext().hasService(DefaultGroovyScriptCompiler.class);
if (compiler != null) {
JsonObject jo = new JsonObject();
jo.put("scriptPattern", compiler.getScriptPattern());
jo.put("compiledCounter", compiler.getCompileCounter());
jo.put("preloadedCounter", compiler.getPreloadedCounter());
jo.put("classesSize", compiler.getClassesSize());
jo.put("compiledTime", compiler.getCompileTime());
jo.put("recompileEnabled", compiler.isRecompileEnabled());
jo.put("lastCompilationTimestamp", compiler.getLastCompilationTimestamp());
if (compiler.getWorkDir() != null) {
jo.put("workDir", compiler.getWorkDir());
}
JsonArray arr = new JsonArray(compiler.compiledClassNames());
if (!arr.isEmpty()) {
jo.put("classes", arr);
}
root.put("compiler", jo);
}
return root;
}
}
| GroovyDevConsole |
java | google__guava | android/guava/src/com/google/common/base/Preconditions.java | {
"start": 4857,
"end": 48191
} | class ____ {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(Platform.stringValueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
* square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(
boolean expression,
String errorMessageTemplate,
@Nullable Object @Nullable ... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(
Platform.lenientFormat(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(boolean expression, String errorMessageTemplate, char p1) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(boolean expression, String errorMessageTemplate, int p1) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(boolean expression, String errorMessageTemplate, long p1) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, @Nullable Object p1) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, char p1, char p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, char p1, int p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, char p1, long p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, char p1, @Nullable Object p2) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, int p1, char p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, int p1, int p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, int p1, long p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, int p1, @Nullable Object p2) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, long p1, char p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, long p1, int p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, long p1, long p2) {
if (!expression) {
throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, long p1, @Nullable Object p2) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, @Nullable Object p1, char p2) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, @Nullable Object p1, int p2) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression, String errorMessageTemplate, @Nullable Object p1, long p2) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression,
// TODO: cl/604933487 - Make errorMessageTemplate consistently @Nullable across overloads.
@Nullable String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression,
String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3) {
if (!expression) {
throw new IllegalArgumentException(Platform.lenientFormat(errorMessageTemplate, p1, p2, p3));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* <p>See {@link #checkArgument(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkArgument(
boolean expression,
String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3,
@Nullable Object p4) {
if (!expression) {
throw new IllegalArgumentException(
Platform.lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
* @see Verify#verify Verify.verify()
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
* @see Verify#verify Verify.verify()
*/
public static void checkState(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalStateException(Platform.stringValueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
* square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @see Verify#verify Verify.verify()
*/
public static void checkState(
boolean expression,
/*
* TODO(cpovirk): Consider removing @Nullable here, as we've done with the other methods'
* errorMessageTemplate parameters: It is unlikely that callers intend for their string
* template to be null (though we do handle that case gracefully at runtime). I've left this
* one as it is because one of our users has defined a wrapper API around Preconditions,
* declaring a checkState method that accepts a possibly null template. So we'd need to update
* that user first.
*/
@Nullable String errorMessageTemplate,
@Nullable Object @Nullable ... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(
Platform.lenientFormat(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, char p1) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, int p1) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, long p1) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, @Nullable Object p1) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, char p1, char p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, char p1, int p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, char p1, long p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, char p1, @Nullable Object p2) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, int p1, char p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, int p1, int p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, int p1, long p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, int p1, @Nullable Object p2) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, long p1, char p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, long p1, int p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(boolean expression, String errorMessageTemplate, long p1, long p2) {
if (!expression) {
throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, long p1, @Nullable Object p2) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, @Nullable Object p1, char p2) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, @Nullable Object p1, int p2) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, @Nullable Object p1, long p2) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression, String errorMessageTemplate, @Nullable Object p1, @Nullable Object p2) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression,
String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2, p3));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
public static void checkState(
boolean expression,
String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3,
@Nullable Object p4) {
if (!expression) {
throw new IllegalStateException(Platform.lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
}
/*
* Preconditions.checkNotNull is *intended* for performing eager null checks on parameters that a
* nullness checker can already "prove" are non-null. That means that the first parameter to
* checkNotNull *should* be annotated to require it to be non-null.
*
* However, for a variety of reasons, Google developers have written a ton of code over the past
* decade that assumes that they can use checkNotNull for non-precondition checks. I had hoped to
* take a principled stand on this, but the amount of such code is simply overwhelming. To avoid
* creating a lot of compile errors that users would not find to be informative, we're giving in
* and allowing callers to pass arguments that a nullness checker believes could be null.
*
* We still encourage people to use requireNonNull over checkNotNull for non-precondition checks.
*/
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
* @see Verify#verifyNotNull Verify.verifyNotNull()
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(@Nullable T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
* @see Verify#verifyNotNull Verify.verifyNotNull()
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(@Nullable T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(Platform.stringValueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
* square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
* @see Verify#verifyNotNull Verify.verifyNotNull()
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference,
String errorMessageTemplate,
@Nullable Object @Nullable ... errorMessageArgs) {
if (reference == null) {
throw new NullPointerException(
Platform.lenientFormat(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(@Nullable T reference, String errorMessageTemplate, char p1) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(@Nullable T reference, String errorMessageTemplate, int p1) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(@Nullable T reference, String errorMessageTemplate, long p1) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, @Nullable Object p1) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, char p1, char p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, char p1, int p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, char p1, long p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, char p1, @Nullable Object p2) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, int p1, char p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, int p1, int p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, int p1, long p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, int p1, @Nullable Object p2) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, long p1, char p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, long p1, int p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, long p1, long p2) {
if (reference == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, long p1, @Nullable Object p2) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, @Nullable Object p1, char p2) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, @Nullable Object p1, int p2) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference, String errorMessageTemplate, @Nullable Object p1, long p2) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference,
String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference,
String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2, p3));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* <p>See {@link #checkNotNull(Object, String, Object...)} for details.
*
* @since 20.0 (varargs overload since 2.0)
*/
@CanIgnoreReturnValue
public static <T> T checkNotNull(
@Nullable T reference,
String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3,
@Nullable Object p4) {
if (reference == null) {
throw new NullPointerException(Platform.lenientFormat(errorMessageTemplate, p1, p2, p3, p4));
}
return reference;
}
/*
* All recent hotspots (as of 2009) *really* like to have the natural code
*
* if (guardExpression) {
* throw new BadException(messageExpression);
* }
*
* refactored so that messageExpression is moved to a separate String-returning method.
*
* if (guardExpression) {
* throw new BadException(badMsg(...));
* }
*
* The alternative natural refactorings into void or Exception-returning methods are much slower.
* This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is
* a hotspot optimizer bug, which should be fixed, but that's a separate, big project).
*
* The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a
* RangeCheckMicroBenchmark in the JDK that was used to test this.
*
* But the methods in this | Preconditions |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/cluster/ClusterTestUtil.java | {
"start": 590,
"end": 2838
} | class ____ {
/**
* Retrieve the cluster node Id from the {@code connection}.
*
* @param connection
* @return
*/
public static String getNodeId(RedisClusterCommands<?, ?> connection) {
RedisClusterNode ownPartition = getOwnPartition(connection);
if (ownPartition != null) {
return ownPartition.getNodeId();
}
return null;
}
/**
* Retrieve the {@link RedisClusterNode} from the {@code connection}.
*
* @param connection
* @return
*/
public static RedisClusterNode getOwnPartition(RedisClusterCommands<?, ?> connection) {
Partitions partitions = ClusterPartitionParser.parse(connection.clusterNodes());
for (RedisClusterNode partition : partitions) {
if (partition.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) {
return partition;
}
}
return null;
}
/**
* Flush databases of all cluster nodes.
*
* @param connection the cluster connection
*/
public static void flushDatabaseOfAllNodes(StatefulRedisClusterConnection<?, ?> connection) {
for (RedisClusterNode node : connection.getPartitions()) {
try {
connection.getConnection(node.getNodeId()).sync().flushall();
connection.getConnection(node.getNodeId()).sync().flushdb();
} catch (Exception o_O) {
// ignore
}
}
}
/**
* Create an API wrapper which exposes the {@link RedisCommands} API by using internally a cluster connection.
*
* @param connection
* @return
*/
public static RedisCommands<String, String> redisCommandsOverCluster(
StatefulRedisClusterConnection<String, String> connection) {
StatefulRedisClusterConnectionImpl clusterConnection = (StatefulRedisClusterConnectionImpl) connection;
InvocationHandler h = new RoutingInvocationHandler(connection.async(), clusterConnection.syncInvocationHandler());
return (RedisCommands<String, String>) Proxy.newProxyInstance(ClusterTestUtil.class.getClassLoader(),
new Class[] { RedisCommands.class }, h);
}
}
| ClusterTestUtil |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java | {
"start": 6946,
"end": 7038
} | class ____ {
}
@SuppressWarnings("deprecation")
private static | ImportWithPrivateReaderConfig |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/CacheAwareContextLoaderDelegate.java | {
"start": 7793,
"end": 8653
} | class ____ is using the application context(s)
* @since 7.0
* @see #unregisterContextUsage(MergedContextConfiguration, Class)
*/
default void registerContextUsage(MergedContextConfiguration key, Class<?> testClass) {
/* no-op */
}
/**
* Unregister usage of the {@linkplain ApplicationContext application context}
* for the supplied {@link MergedContextConfiguration} as well as usage of the
* application context for its {@linkplain MergedContextConfiguration#getParent()
* parent}, recursively.
* <p>This informs the {@code ContextCache} that the application context(s) can be safely
* {@linkplain org.springframework.context.ConfigurableApplicationContext#pause() paused}
* if no other test classes are actively using the same application context(s).
* @param key the context key; never {@code null}
* @param testClass the test | that |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java | {
"start": 4286,
"end": 5107
} | class ____ extends ReusableSimpleMessage {
@Override
public String getFormattedMessage() {
throw new TestMessageException();
}
@Override
public String getFormat() {
throw new TestMessageException();
}
@Override
public Object[] getParameters() {
throw new TestMessageException();
}
@Override
public void formatTo(final StringBuilder buffer) {
throw new TestMessageException();
}
@Override
public Object[] swapParameters(final Object[] emptyReplacement) {
throw new TestMessageException();
}
@Override
public short getParameterCount() {
throw new TestMessageException();
}
}
}
| ExceptionThrowingMessage |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/converter/AbstractMessageConverter.java | {
"start": 5544,
"end": 9071
} | class ____ be byte[] or String: " + payloadClass);
this.serializedPayloadClass = payloadClass;
}
/**
* Return the configured preferred serialization payload class.
*/
public Class<?> getSerializedPayloadClass() {
return this.serializedPayloadClass;
}
@Override
public final @Nullable Object fromMessage(Message<?> message, Class<?> targetClass) {
return fromMessage(message, targetClass, null);
}
@Override
public final @Nullable Object fromMessage(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
if (!canConvertFrom(message, targetClass)) {
return null;
}
return convertFromInternal(message, targetClass, conversionHint);
}
@Override
public final @Nullable Message<?> toMessage(Object payload, @Nullable MessageHeaders headers) {
return toMessage(payload, headers, null);
}
@Override
public final @Nullable Message<?> toMessage(
Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
if (!canConvertTo(payload, headers)) {
return null;
}
Object payloadToUse = convertToInternal(payload, headers, conversionHint);
if (payloadToUse == null) {
return null;
}
MimeType mimeType = getDefaultContentType(payloadToUse);
if (headers != null) {
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, MessageHeaderAccessor.class);
if (accessor != null && accessor.isMutable()) {
if (mimeType != null) {
accessor.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
}
return MessageBuilder.createMessage(payloadToUse, accessor.getMessageHeaders());
}
}
MessageBuilder<?> builder = MessageBuilder.withPayload(payloadToUse);
if (headers != null) {
builder.copyHeaders(headers);
}
if (mimeType != null) {
builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
}
return builder.build();
}
protected boolean canConvertFrom(Message<?> message, Class<?> targetClass) {
return (supports(targetClass) && supportsMimeType(message.getHeaders()));
}
protected boolean canConvertTo(Object payload, @Nullable MessageHeaders headers) {
return (supports(payload.getClass()) && supportsMimeType(headers));
}
protected boolean supportsMimeType(@Nullable MessageHeaders headers) {
if (getSupportedMimeTypes().isEmpty()) {
return true;
}
MimeType mimeType = getMimeType(headers);
if (mimeType == null) {
return !isStrictContentTypeMatch();
}
for (MimeType current : getSupportedMimeTypes()) {
if (current.getType().equals(mimeType.getType()) && current.getSubtype().equals(mimeType.getSubtype())) {
return true;
}
}
return false;
}
protected @Nullable MimeType getMimeType(@Nullable MessageHeaders headers) {
return (this.contentTypeResolver != null ? this.contentTypeResolver.resolve(headers) : null);
}
/**
* Return the default content type for the payload. Called when
* {@link #toMessage(Object, MessageHeaders)} is invoked without
* message headers or without a content type header.
* <p>By default, this returns the first element of the
* {@link #getSupportedMimeTypes() supportedMimeTypes}, if any.
* Can be overridden in subclasses.
* @param payload the payload being converted to a message
* @return the content type, or {@code null} if not known
*/
protected @Nullable MimeType getDefaultContentType(Object payload) {
List<MimeType> mimeTypes = getSupportedMimeTypes();
return (!mimeTypes.isEmpty() ? mimeTypes.get(0) : null);
}
/**
* Whether the given | must |
java | apache__flink | flink-formats/flink-protobuf/src/test/java/org/apache/flink/formats/protobuf/NullValueToProtoTest.java | {
"start": 2633,
"end": 3595
} | enum
____ GenericMapData(mapOf(StringData.fromString("key"), null)),
// message
new GenericMapData(mapOf(StringData.fromString("key"), null)),
// bytes
new GenericMapData(mapOf(StringData.fromString("key"), null)),
// string
new GenericArrayData(new Object[] {null}),
// int
new GenericArrayData(new Object[] {null}),
// long
new GenericArrayData(new Object[] {null}),
// boolean
new GenericArrayData(new Object[] {null}),
// float
new GenericArrayData(new Object[] {null}),
// double
new GenericArrayData(new Object[] {null}),
// | new |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/PathElementException.java | {
"start": 420,
"end": 552
} | class ____ extends IllegalArgumentException {
public PathElementException(String message) {
super(message);
}
}
| PathElementException |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/groups/UnregisteredMetricGroups.java | {
"start": 3519,
"end": 3939
} | class ____ extends ProcessMetricGroup {
private static final String UNREGISTERED_HOST = "UnregisteredHost";
public UnregisteredProcessMetricGroup() {
super(NoOpMetricRegistry.INSTANCE, UNREGISTERED_HOST);
}
}
/**
* A safe drop-in replacement for {@link ResourceManagerMetricGroup
* ResourceManagerMetricGroups}.
*/
public static | UnregisteredProcessMetricGroup |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/creators/SingleImmutableFieldCreatorTest.java | {
"start": 1557,
"end": 1824
} | class ____ {
@JsonProperty("id")
final int id;
public ImmutableIdWithJsonPropertyFieldAnnotation(int id) { this.id = id; }
public int getId() {
return id;
}
}
static | ImmutableIdWithJsonPropertyFieldAnnotation |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/component/ArgumentSubstitutionParser.java | {
"start": 7616,
"end": 9487
} | class ____ {
private final String method;
private final String argName;
private String argType;
private final String replacement;
private boolean replaceWithType;
/**
* Creates a substitution for all argument types.
*
* @param method regex to match method name
* @param argName regex to match argument name
* @param replacement replacement text for argument name
*/
public Substitution(String method, String argName, String replacement) {
this.method = method;
this.argName = argName;
this.replacement = replacement;
}
/**
* Creates a substitution for a specific argument type.
*
* @param method regex to match method name
* @param argName regex to match argument name
* @param argType argument type as String
* @param replacement replacement text for argument name
*/
public Substitution(String method, String argName, String argType, String replacement) {
this(method, argName, replacement);
this.argType = argType;
}
/**
* Create a substitution for a specific argument type and flag to indicate whether the replacement uses
*/
public Substitution(String method, String argName, String argType, String replacement, boolean replaceWithType) {
this(method, argName, argType, replacement);
this.replaceWithType = replaceWithType;
}
public void validate() {
if (method == null || argName == null || replacement == null) {
throw new IllegalArgumentException("Properties method, argName and replacement MUST be provided");
}
}
}
private static | Substitution |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/util/JavaCollectionConstants.java | {
"start": 243,
"end": 361
} | class ____ for conversion registration,
* to achieve Java compatibility.
*
* @author Cause Chung
*/
public final | names |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LightWeightGSet.java | {
"start": 1770,
"end": 1895
} | class ____<K, E extends K> implements GSet<K, E> {
/**
* Elements of {@link LightWeightGSet}.
*/
public | LightWeightGSet |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionCreator.java | {
"start": 502,
"end": 1136
} | class ____ extends BasicConnectionCreator {
public DriverManagerConnectionCreator(
ServiceRegistry serviceRegistry,
String url,
Properties connectionProps,
Boolean autocommit,
Integer isolation,
String initSql) {
super( serviceRegistry, url, connectionProps, autocommit, isolation, initSql );
}
@Override
protected Connection makeConnection(String url, Properties connectionProps) {
try {
return DriverManager.getConnection( url, connectionProps );
}
catch (SQLException e) {
throw convertSqlException( "Error calling JDBC 'DriverManager.getConnection()'", e );
}
}
}
| DriverManagerConnectionCreator |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/NameAbbreviator.java | {
"start": 5197,
"end": 5632
} | class ____ extends NameAbbreviator {
/**
* Constructor.
*/
public NOPAbbreviator() {}
/**
* {@inheritDoc}
*/
@Override
public void abbreviate(final String original, final StringBuilder destination) {
destination.append(original);
}
}
/**
* Abbreviator that drops starting path elements.
*/
private static | NOPAbbreviator |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/jmx/export/annotation/FactoryCreatedAnnotationTestBean.java | {
"start": 765,
"end": 836
} | class ____ extends AnnotationTestBean {
}
| FactoryCreatedAnnotationTestBean |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/HostNatMapper.java | {
"start": 828,
"end": 1384
} | class ____ implements NatMapper {
private Map<String, String> hostsMap;
@Override
public RedisURI map(RedisURI uri) {
String host = hostsMap.get(uri.getHost());
if (host == null) {
return uri;
}
return new RedisURI(uri.getScheme(), host, uri.getPort());
}
/**
* Defines hosts mapping. Host as key mapped to host as value.
*
* @param hostsMap - hosts map
*/
public void setHostsMap(Map<String, String> hostsMap) {
this.hostsMap = hostsMap;
}
}
| HostNatMapper |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/FinishedOnRestoreInput.java | {
"start": 1313,
"end": 2879
} | class ____<IN> implements Input<IN> {
private final RecordWriterOutput<?>[] streamOutputs;
private final int inputCount;
private int watermarksSeen = 0;
public FinishedOnRestoreInput(RecordWriterOutput<?>[] streamOutputs, int inputCount) {
this.streamOutputs = streamOutputs;
this.inputCount = inputCount;
}
@Override
public void processElement(StreamRecord<IN> element) throws Exception {
throw new IllegalStateException();
}
@Override
public void processWatermark(Watermark watermark) {
if (watermark.getTimestamp() != Watermark.MAX_WATERMARK.getTimestamp()) {
throw new IllegalStateException(
String.format(
"We should not receive any watermarks [%s] other than the MAX_WATERMARK if finished on restore",
watermark));
}
if (++watermarksSeen == inputCount) {
for (RecordWriterOutput<?> streamOutput : streamOutputs) {
streamOutput.emitWatermark(watermark);
}
}
}
@Override
public void processWatermarkStatus(WatermarkStatus watermarkStatus) throws Exception {
throw new IllegalStateException();
}
@Override
public void processLatencyMarker(LatencyMarker latencyMarker) throws Exception {
throw new IllegalStateException();
}
@Override
public void setKeyContextElement(StreamRecord<IN> record) throws Exception {
throw new IllegalStateException();
}
}
| FinishedOnRestoreInput |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/reactive/server/assertj/WebTestClientResponseTests.java | {
"start": 3602,
"end": 4034
} | class ____ {
@GetMapping("/greeting")
public String getGreeting() {
return "Hello World";
}
@GetMapping("/message")
public Map<String, ?> getMessage() {
return Map.of("message", "Hello World");
}
@GetMapping("/cookie")
public void getCookie(ServerWebExchange exchange) {
ResponseCookie cookie = ResponseCookie.from("foo", "bar").build();
exchange.getResponse().addCookie(cookie);
}
}
}
| HelloController |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableCache.java | {
"start": 4084,
"end": 4658
} | class ____
extends AtomicBoolean
implements Disposable {
private static final long serialVersionUID = 8943152917179642732L;
final CompletableObserver downstream;
InnerCompletableCache(CompletableObserver downstream) {
this.downstream = downstream;
}
@Override
public boolean isDisposed() {
return get();
}
@Override
public void dispose() {
if (compareAndSet(false, true)) {
remove(this);
}
}
}
}
| InnerCompletableCache |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/search/geo/GeoBoundingBoxQueryBuilderTestCase.java | {
"start": 9592,
"end": 10004
} | class ____ extends PointTester {
public TopTester() {
super(randomDoubleBetween(GeoUtils.MAX_LAT, Double.MAX_VALUE, false));
}
@Override
public void fillIn(double coordinate, GeoBoundingBoxQueryBuilder qb) {
qb.setCorners(coordinate, qb.topLeft().getLon(), qb.bottomRight().getLat(), qb.bottomRight().getLon());
}
}
protected static | TopTester |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java | {
"start": 112419,
"end": 112578
} | class ____ implements ImmutableInterface {
// BUG: Diagnostic contains: has non-final field
Object unsafe;
}
| F |
java | google__guice | core/src/com/google/inject/TypeLiteral.java | {
"start": 1809,
"end": 2342
} | class ____ resolve type parameters. For example, to
* figure out what type {@code keySet()} returns on a {@code Map<Integer, String>}, use this code:
*
* <pre>{@code
* TypeLiteral<Map<Integer, String>> mapType
* = new TypeLiteral<Map<Integer, String>>() {};
* TypeLiteral<?> keySetType
* = mapType.getReturnType(Map.class.getMethod("keySet"));
* System.out.println(keySetType); // prints "Set<Integer>"
* }</pre>
*
* @author crazybob@google.com (Bob Lee)
* @author jessewilson@google.com (Jesse Wilson)
*/
public | can |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/coordination/JoinValidationService.java | {
"start": 3467,
"end": 13187
} | class ____ {
/*
* IMPLEMENTATION NOTES
*
* This component is based around a queue of actions which are processed in a single-threaded fashion on the CLUSTER_COORDINATION
* threadpool. The actions are either:
*
* - send a join validation request to a particular node, or
* - clear the cache
*
* The single-threadedness is arranged by tracking (a lower bound on) the size of the queue in a separate AtomicInteger, and only
* spawning a new processor when the tracked queue size changes from 0 to 1.
*
* The executeRefs ref counter is necessary to handle the possibility of a concurrent shutdown, ensuring that the cache is always
* cleared even if validateJoin is called concurrently to the shutdown.
*/
private static final Logger logger = LogManager.getLogger(JoinValidationService.class);
public static final String JOIN_VALIDATE_ACTION_NAME = "internal:cluster/coordination/join/validate";
// the timeout for each cached value
public static final Setting<TimeValue> JOIN_VALIDATION_CACHE_TIMEOUT_SETTING = Setting.timeSetting(
"cluster.join_validation.cache_timeout",
TimeValue.timeValueSeconds(60),
TimeValue.timeValueMillis(1),
Setting.Property.NodeScope
);
private static final TransportRequestOptions REQUEST_OPTIONS = TransportRequestOptions.of(null, TransportRequestOptions.Type.STATE);
private final TimeValue cacheTimeout;
private final TransportService transportService;
private final Supplier<ClusterState> clusterStateSupplier;
private final AtomicInteger queueSize = new AtomicInteger();
private final Queue<AbstractRunnable> queue = new ConcurrentLinkedQueue<>();
private final Map<TransportVersion, ReleasableBytesReference> statesByVersion = new HashMap<>();
private final RefCounted executeRefs;
private final Executor responseExecutor;
public JoinValidationService(
Settings settings,
TransportService transportService,
NamedWriteableRegistry namedWriteableRegistry,
Supplier<ClusterState> clusterStateSupplier,
Supplier<Metadata> metadataSupplier,
Collection<BiConsumer<DiscoveryNode, ClusterState>> joinValidators
) {
this.cacheTimeout = JOIN_VALIDATION_CACHE_TIMEOUT_SETTING.get(settings);
this.transportService = transportService;
this.clusterStateSupplier = clusterStateSupplier;
this.executeRefs = AbstractRefCounted.of(() -> execute(cacheClearer));
this.responseExecutor = transportService.getThreadPool().executor(ThreadPool.Names.CLUSTER_COORDINATION);
final var dataPaths = Environment.PATH_DATA_SETTING.get(settings);
transportService.registerRequestHandler(
JoinValidationService.JOIN_VALIDATE_ACTION_NAME,
this.responseExecutor,
BytesTransportRequest::new,
(request, channel, task) -> {
final var remoteState = readClusterState(namedWriteableRegistry, request);
final var remoteMetadata = remoteState.metadata();
final var localMetadata = metadataSupplier.get();
if (localMetadata.clusterUUIDCommitted() && localMetadata.clusterUUID().equals(remoteMetadata.clusterUUID()) == false) {
throw new CoordinationStateRejectedException(
"This node previously joined a cluster with UUID ["
+ localMetadata.clusterUUID()
+ "] and is now trying to join a different cluster with UUID ["
+ remoteMetadata.clusterUUID()
+ "]. This is forbidden and usually indicates an incorrect "
+ "discovery or cluster bootstrapping configuration. Note that the cluster UUID persists across restarts and "
+ "can only be changed by deleting the contents of the node's data "
+ (dataPaths.size() == 1 ? "path " : "paths ")
+ dataPaths
+ " which will also remove any data held by this node."
);
}
joinValidators.forEach(joinValidator -> joinValidator.accept(transportService.getLocalNode(), remoteState));
channel.sendResponse(ActionResponse.Empty.INSTANCE);
}
);
}
private static ClusterState readClusterState(NamedWriteableRegistry namedWriteableRegistry, BytesTransportRequest request)
throws IOException {
try (
var bytesStreamInput = request.bytes().streamInput();
var in = new NamedWriteableAwareStreamInput(
CompressorFactory.COMPRESSOR.threadLocalStreamInput(bytesStreamInput),
namedWriteableRegistry
)
) {
in.setTransportVersion(request.version());
return ClusterState.readFrom(in, null);
}
}
public void validateJoin(DiscoveryNode discoveryNode, ActionListener<Void> listener) {
// This node isn't in the cluster yet so ClusterState#getMinTransportVersion() doesn't apply, we must obtain a specific connection
// so we can check its transport version to decide how to proceed.
final Transport.Connection connection;
try {
connection = transportService.getConnection(discoveryNode);
assert connection != null;
} catch (Exception e) {
assert e instanceof NodeNotConnectedException : e;
listener.onFailure(e);
return;
}
if (executeRefs.tryIncRef()) {
try {
execute(new JoinValidation(discoveryNode, connection, listener));
} finally {
executeRefs.decRef();
}
} else {
listener.onFailure(new NodeClosedException(transportService.getLocalNode()));
}
}
public void stop() {
executeRefs.decRef();
}
boolean isIdle() {
// this is for single-threaded tests to assert that the service becomes idle, so it is not properly synchronized
return queue.isEmpty() && queueSize.get() == 0 && statesByVersion.isEmpty();
}
private void execute(AbstractRunnable task) {
assert task == cacheClearer || executeRefs.hasReferences();
queue.add(task);
if (queueSize.getAndIncrement() == 0) {
runProcessor();
}
}
private void runProcessor() {
transportService.getThreadPool().executor(ThreadPool.Names.CLUSTER_COORDINATION).execute(processor);
}
private final AbstractRunnable processor = new AbstractRunnable() {
@Override
protected void doRun() {
processNextItem();
}
@Override
public void onRejection(Exception e) {
assert e instanceof EsRejectedExecutionException esre && esre.isExecutorShutdown();
onShutdown();
}
@Override
public void onFailure(Exception e) {
logger.error("unexpectedly failed to process queue item", e);
assert false : e;
}
@Override
public String toString() {
return "process next task of join validation service";
}
};
private void processNextItem() {
if (executeRefs.hasReferences() == false) {
onShutdown();
return;
}
final var nextItem = queue.poll();
assert nextItem != null;
try {
nextItem.run();
} finally {
try {
final var remaining = queueSize.decrementAndGet();
assert remaining >= 0;
if (remaining > 0) {
runProcessor();
}
} catch (Exception e) {
assert false : e;
/* we only catch so we can assert false, so throwing is ok */
// noinspection ThrowFromFinallyBlock
throw e;
}
}
}
private void onShutdown() {
try {
// shutting down when enqueueing the next processor run which means there is no active processor so it's safe to clear out the
// cache ...
cacheClearer.run();
// ... and drain the queue
do {
final var nextItem = queue.poll();
assert nextItem != null;
if (nextItem != cacheClearer) {
nextItem.onFailure(new NodeClosedException(transportService.getLocalNode()));
}
} while (queueSize.decrementAndGet() > 0);
} catch (Exception e) {
assert false : e;
throw e;
}
}
private final AbstractRunnable cacheClearer = new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
logger.error("unexpectedly failed to clear cache", e);
assert false : e;
}
@Override
protected void doRun() {
// NB this never runs concurrently to JoinValidation actions, nor to itself, (see IMPLEMENTATION NOTES above) so it is safe
// to do these (non-atomic) things to the (unsynchronized) statesByVersion map.
for (final var bytes : statesByVersion.values()) {
bytes.decRef();
}
statesByVersion.clear();
logger.trace("join validation cache cleared");
}
@Override
public String toString() {
return "clear join validation cache";
}
};
private | JoinValidationService |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_catchException_Test.java | {
"start": 1130,
"end": 2442
} | class ____ {
@Test
void catchException_should_fail_with_good_message_if_wrong_type() {
// GIVEN
ThrowingCallable code = () -> catchException(raisingThrowable("boom!!"));
// WHEN
var assertionError = expectAssertionError(code);
// THEN
assertThat(assertionError).hasMessageContainingAll(Exception.class.getName(), Throwable.class.getName());
}
@Test
void catchException_should_succeed_and_return_actual_instance_with_correct_class() {
// GIVEN
final Exception expected = new Exception("boom!!");
// WHEN
Exception actual = catchException(codeThrowing(expected));
// THEN
then(actual).isSameAs(expected);
}
@Test
void catchException_should_succeed_and_return_null_if_no_exception_thrown() {
// WHEN
var error = expectAssertionError(() -> catchException(() -> {}));
// THEN
then(error).hasMessage("Expecting code to raise an Exception");
}
@Test
void catchException_should_catch_mocked_throwable() {
// GIVEN
Exception exception = mock();
// WHEN
Throwable actual = catchException(codeThrowing(exception));
// THEN
then(actual).isSameAs(exception);
}
static ThrowingCallable raisingThrowable(final String reason) {
return codeThrowing(new Throwable(reason));
}
}
| Assertions_catchException_Test |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/common/util/MockBigArrays.java | {
"start": 22524,
"end": 23524
} | class ____<T> extends AbstractArrayWrapper implements ObjectArray<T> {
private final ObjectArray<T> in;
ObjectArrayWrapper(ObjectArray<T> in) {
super(false);
this.in = in;
}
@Override
protected BigArray getDelegate() {
return in;
}
@Override
public T get(long index) {
return in.get(index);
}
@Override
public void set(long index, T value) {
in.set(index, value);
}
@Override
public T getAndSet(long index, T value) {
return in.getAndSet(index, value);
}
@Override
protected void randomizeContent(long from, long to) {
// will be cleared anyway
}
@Override
public Collection<Accountable> getChildResources() {
return Collections.singleton(Accountables.namedAccountable("delegate", in));
}
}
public static | ObjectArrayWrapper |
java | apache__camel | components/camel-ibm/camel-ibm-watson-discovery/src/test/java/org/apache/camel/component/ibm/watson/discovery/WatsonDiscoveryComponentTest.java | {
"start": 1082,
"end": 2944
} | class ____ extends CamelTestSupport {
@Test
public void testComponentCreation() {
WatsonDiscoveryComponent component = new WatsonDiscoveryComponent();
assertNotNull(component);
}
@Test
public void testEndpointCreation() throws Exception {
WatsonDiscoveryComponent component = context.getComponent("ibm-watson-discovery", WatsonDiscoveryComponent.class);
assertNotNull(component);
WatsonDiscoveryConfiguration config = new WatsonDiscoveryConfiguration();
config.setApiKey("test-api-key");
config.setProjectId("test-project-id");
component.setConfiguration(config);
WatsonDiscoveryEndpoint endpoint
= (WatsonDiscoveryEndpoint) component.createEndpoint("ibm-watson-discovery://default");
assertNotNull(endpoint);
assertEquals("test-api-key", endpoint.getConfiguration().getApiKey());
assertEquals("test-project-id", endpoint.getConfiguration().getProjectId());
}
@Test
public void testConfigurationDefaults() {
WatsonDiscoveryConfiguration config = new WatsonDiscoveryConfiguration();
assertEquals("2023-03-31", config.getVersion());
}
@Test
public void testConfigurationCopy() {
WatsonDiscoveryConfiguration config = new WatsonDiscoveryConfiguration();
config.setApiKey("test-key");
config.setServiceUrl("https://test.url");
config.setProjectId("test-project");
config.setVersion("2023-01-01");
WatsonDiscoveryConfiguration copy = config.copy();
assertNotNull(copy);
assertEquals("test-key", copy.getApiKey());
assertEquals("https://test.url", copy.getServiceUrl());
assertEquals("test-project", copy.getProjectId());
assertEquals("2023-01-01", copy.getVersion());
}
}
| WatsonDiscoveryComponentTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/script/UpdateCtxMap.java | {
"start": 633,
"end": 1116
} | class ____ extends CtxMap<UpdateMetadata> {
public UpdateCtxMap(
String index,
String id,
long version,
String routing,
String type,
String op,
long now,
Map<String, Object> source
) {
super(source, new UpdateMetadata(index, id, version, routing, type, op, now));
}
protected UpdateCtxMap(Map<String, Object> source, UpdateMetadata metadata) {
super(source, metadata);
}
}
| UpdateCtxMap |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/support/processor/DefaultMaskingFormatterTest.java | {
"start": 953,
"end": 8174
} | class ____ {
@Test
public void testDefaultOption() {
DefaultMaskingFormatter formatter = new DefaultMaskingFormatter();
String answer
= formatter.format("key=value, myPassword=foo,\n myPassphrase=\"foo bar\", secretKey='!@#$%^&*() -+[]{};:'");
assertEquals("key=value, myPassword=xxxxx,\n myPassphrase=\"xxxxx\", secretKey='xxxxx'", answer);
answer = formatter.format("<xmlPassword>\n foo bar \n</xmlPassword>\n<user password=\"asdf qwert\"/>");
assertEquals("<xmlPassword>\n xxxxx \n</xmlPassword>\n<user password=\"xxxxx\"/>", answer);
answer = formatter.format(
"{\"key\" : \"value\", \"Password\":\"foo\", \"Passphrase\" : \"foo bar\", \"SecretKey\" : \"!@#$%^&*() -+[]{};:'\"}");
assertEquals(
"{\"key\" : \"value\", \"Password\":\"xxxxx\", \"Passphrase\" : \"xxxxx\", \"SecretKey\" : \"xxxxx\"}",
answer);
}
@Test
public void testDisableKeyValueMask() {
DefaultMaskingFormatter formatter = new DefaultMaskingFormatter(false, true, true);
String answer
= formatter.format("key=value, myPassword=foo,\n myPassphrase=\"foo bar\", secretKey='!@#$%^&*() -+[]{};:'");
assertEquals("key=value, myPassword=foo,\n myPassphrase=\"foo bar\", secretKey='!@#$%^&*() -+[]{};:'", answer);
answer = formatter.format("<xmlPassword>\n foo bar \n</xmlPassword>\n<user password=\"asdf qwert\"/>");
assertEquals("<xmlPassword>\n xxxxx \n</xmlPassword>\n<user password=\"asdf qwert\"/>", answer);
answer = formatter.format(
"{\"key\" : \"value\", \"Password\":\"foo\", \"Passphrase\" : \"foo bar\", \"SecretKey\" : \"!@#$%^&*() -+[]{};:'\"}");
assertEquals(
"{\"key\" : \"value\", \"Password\":\"xxxxx\", \"Passphrase\" : \"xxxxx\", \"SecretKey\" : \"xxxxx\"}",
answer);
}
@Test
public void testDisableXmlElementMask() {
DefaultMaskingFormatter formatter = new DefaultMaskingFormatter(true, false, true);
String answer
= formatter.format("key=value, myPassword=foo,\n myPassphrase=\"foo bar\", secretKey='!@#$%^&*() -+[]{};:'");
assertEquals("key=value, myPassword=xxxxx,\n myPassphrase=\"xxxxx\", secretKey='xxxxx'", answer);
answer = formatter.format("<xmlPassword>\n foo bar \n</xmlPassword>\n<user password=\"asdf qwert\"/>");
assertEquals("<xmlPassword>\n foo bar \n</xmlPassword>\n<user password=\"xxxxx\"/>", answer);
answer = formatter.format(
"{\"key\" : \"value\", \"Password\":\"foo\", \"Passphrase\" : \"foo bar\", \"SecretKey\" : \"!@#$%^&*() -+[]{};:'\"}");
assertEquals(
"{\"key\" : \"value\", \"Password\":\"xxxxx\", \"Passphrase\" : \"xxxxx\", \"SecretKey\" : \"xxxxx\"}",
answer);
}
@Test
public void testDisableJsonMask() {
DefaultMaskingFormatter formatter = new DefaultMaskingFormatter(true, true, false);
String answer
= formatter.format("key=value, myPassword=foo,\n myPassphrase=\"foo bar\", secretKey='!@#$%^&*() -+[]{};:'");
assertEquals("key=value, myPassword=xxxxx,\n myPassphrase=\"xxxxx\", secretKey='xxxxx'", answer);
answer = formatter.format("<xmlPassword>\n foo bar \n</xmlPassword>\n<user password=\"asdf qwert\"/>");
assertEquals("<xmlPassword>\n xxxxx \n</xmlPassword>\n<user password=\"xxxxx\"/>", answer);
answer = formatter.format(
"{\"key\" : \"value\", \"My Password\":\"foo\", \"My SecretPassphrase\" : \"foo bar\", \"My SecretKey2\" : \"!@#$%^&*() -+[]{};:'\"}");
assertEquals(
"{\"key\" : \"value\", \"My Password\":\"foo\", \"My SecretPassphrase\" : \"foo bar\", \"My SecretKey2\" : \"!@#$%^&*() -+[]{};:'\"}",
answer);
}
@Test
public void testCustomMaskString() {
DefaultMaskingFormatter formatter = new DefaultMaskingFormatter();
formatter.setMaskString("**********");
String answer
= formatter.format("key=value, myPassword=foo,\n myPassphrase=\"foo bar\", secretKey='!@#$%^&*() -+[]{};:'");
assertEquals("key=value, myPassword=**********,\n myPassphrase=\"**********\", secretKey='**********'", answer);
answer = formatter.format("<xmlPassword>\n foo bar \n</xmlPassword>\n<user password=\"asdf qwert\"/>");
assertEquals("<xmlPassword>\n ********** \n</xmlPassword>\n<user password=\"**********\"/>", answer);
answer = formatter.format(
"{\"key\" : \"value\", \"Password\":\"foo\", \"Passphrase\" : \"foo bar\", \"SecretKey\" : \"!@#$%^&*() -+[]{};:'\"}");
assertEquals(
"{\"key\" : \"value\", \"Password\":\"**********\", \"Passphrase\" : \"**********\", \"SecretKey\" : \"**********\"}",
answer);
}
@Test
public void testDifferentSensitiveKeys() {
DefaultMaskingFormatter formatter = new DefaultMaskingFormatter();
String answer
= formatter.format("key=value, myAccessKey=foo,\n authkey=\"foo bar\", refreshtoken='!@#$%^&*() -+[]{};:'");
assertEquals("key=value, myAccessKey=xxxxx,\n authkey=\"xxxxx\", refreshtoken='xxxxx'", answer);
answer = formatter.format("<subscribeKey>\n foo bar \n</subscribeKey>\n<user verificationCode=\"asdf qwert\"/>");
assertEquals("<subscribeKey>\n xxxxx \n</subscribeKey>\n<user verificationCode=\"xxxxx\"/>", answer);
answer = formatter.format(
"{\"key\" : \"value\", \"subscribeKey\":\"foo\", \"verificationCode\" : \"foo bar\", \"RefreshToken\" : \"!@#$%^&*() -+[]{};:'\"}");
assertEquals(
"{\"key\" : \"value\", \"subscribeKey\":\"xxxxx\", \"verificationCode\" : \"xxxxx\", \"RefreshToken\" : \"xxxxx\"}",
answer);
}
@Test
public void testCustomKeywords() {
DefaultMaskingFormatter formatter = new DefaultMaskingFormatter();
formatter.addKeyword("cheese");
formatter.setMaskString("**********");
String answer
= formatter.format(
"key=value, Cheese=gauda, myPassword=foo,\n myPassphrase=\"foo bar\", secretKey='!@#$%^&*() -+[]{};:'");
assertEquals(
"key=value, Cheese=**********, myPassword=**********,\n myPassphrase=\"**********\", secretKey='**********'",
answer);
answer = formatter
.format("<chEEse>Gauda</chEEse><xmlPassword>\n foo bar \n</xmlPassword>\n<user password=\"asdf qwert\"/>");
assertEquals("<chEEse>**********</chEEse><xmlPassword>\n ********** \n</xmlPassword>\n<user password=\"**********\"/>",
answer);
answer = formatter.format(
"{\"key\" : \"value\", \"Cheese\": \"gauda\", \"Password\":\"foo\", \"Passphrase\" : \"foo bar\", \"SecretKey\" : \"!@#$%^&*() -+[]{};:'\"}");
assertEquals(
"{\"key\" : \"value\", \"Cheese\": \"**********\", \"Password\":\"**********\", \"Passphrase\" : \"**********\", \"SecretKey\" : \"**********\"}",
answer);
}
}
| DefaultMaskingFormatterTest |
java | apache__camel | components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcGetNotFoundTest.java | {
"start": 1160,
"end": 2306
} | class ____ extends AbstractJdbcAggregationTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(JdbcGetNotFoundTest.class);
@Test
public void testGetNotFound() {
Exchange exchange = new DefaultExchange(context);
exchange.getIn().setBody("Hello World");
Exchange out = repo.get(context, exchange.getExchangeId());
assertNull(out, "Should not find exchange");
}
@Test
public void testPutAndGetNotFound() {
Exchange exchange = new DefaultExchange(context);
exchange.getIn().setBody("Hello World");
LOG.info("Created {}", exchange.getExchangeId());
repo.add(context, exchange.getExchangeId(), exchange);
Exchange out = repo.get(context, exchange.getExchangeId());
assertNotNull(out, "Should find exchange");
Exchange exchange2 = new DefaultExchange(context);
exchange2.getIn().setBody("Bye World");
LOG.info("Created {}", exchange2.getExchangeId());
Exchange out2 = repo.get(context, exchange2.getExchangeId());
assertNull(out2, "Should not find exchange");
}
}
| JdbcGetNotFoundTest |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2ClientRegistration.java | {
"start": 1481,
"end": 2304
} | class ____ extends AbstractOAuth2ClientRegistration {
@Serial
private static final long serialVersionUID = 283805553286847831L;
private OAuth2ClientRegistration(Map<String, Object> claims) {
super(claims);
}
/**
* Constructs a new {@link Builder} with empty claims.
* @return the {@link Builder}
*/
public static Builder builder() {
return new Builder();
}
/**
* Constructs a new {@link Builder} with the provided claims.
* @param claims the claims to initialize the builder
* @return the {@link Builder}
*/
public static Builder withClaims(Map<String, Object> claims) {
Assert.notEmpty(claims, "claims cannot be empty");
return new Builder().claims((c) -> c.putAll(claims));
}
/**
* Helps configure an {@link OAuth2ClientRegistration}.
*/
public static final | OAuth2ClientRegistration |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/impl/future/FailedFuture.java | {
"start": 837,
"end": 3263
} | class ____<T> extends FutureBase<T> {
private final Throwable cause;
/**
* Create a future that has already failed
* @param t the throwable
*/
public FailedFuture(Throwable t) {
this(null, t);
}
/**
* Create a future that has already failed
* @param t the throwable
*/
public FailedFuture(ContextInternal context, Throwable t) {
super(context);
this.cause = t != null ? t : new NoStackTraceThrowable(null);
}
/**
* Create a future that has already failed
* @param failureMessage the failure message
*/
public FailedFuture(String failureMessage) {
this(null, failureMessage);
}
/**
* Create a future that has already failed
* @param failureMessage the failure message
*/
public FailedFuture(ContextInternal context, String failureMessage) {
this(context, new NoStackTraceThrowable(failureMessage));
}
@Override
public boolean isComplete() {
return true;
}
@Override
public Future<T> onComplete(Handler<AsyncResult<T>> handler) {
if (handler instanceof Completable) {
emitResult(null, cause, (Completable<T>) handler);
} else if (context != null) {
context.emit(this, handler);
} else {
handler.handle(this);
}
return this;
}
@Override
public Future<T> onSuccess(Handler<? super T> handler) {
return this;
}
@Override
public Future<T> onFailure(Handler<? super Throwable> handler) {
if (context != null) {
context.emit(cause, handler);
} else {
handler.handle(cause);
}
return this;
}
@Override
public void addListener(Completable<? super T> listener) {
emitResult(null, cause, listener);
}
@Override
public void removeListener(Completable<? super T> listener) {
}
@Override
public T result() {
return null;
}
@Override
public Throwable cause() {
return cause;
}
@Override
public boolean succeeded() {
return false;
}
@Override
public boolean failed() {
return true;
}
@Override
public <U> Future<U> map(Function<? super T, U> mapper) {
return (Future<U>) this;
}
@Override
public <V> Future<V> map(V value) {
return (Future<V>) this;
}
@Override
public Future<T> otherwise(T value) {
return new SucceededFuture<>(context, value);
}
@Override
public String toString() {
return "Future{cause=" + cause.getMessage() + "}";
}
}
| FailedFuture |
java | bumptech__glide | annotation/src/main/java/com/bumptech/glide/annotation/GlideOption.java | {
"start": 2648,
"end": 3538
} | interface ____ {
/** Does not intend to override a method in a super class. */
int OVERRIDE_NONE = 0;
/** Expects to call super and then add additional functionality to an overridden method. */
int OVERRIDE_EXTEND = 1;
/** Expects to not call super and replace an overridden method. */
int OVERRIDE_REPLACE = 2;
/**
* Determines how and whether a generated method should extend a method from it's parent.
*
* <p>Must be one of {@link #OVERRIDE_NONE}, {@link #OVERRIDE_EXTEND}, {@link #OVERRIDE_REPLACE}.
*
* <p>The extended method is determined by String and argument matching against methods in the
* extended class. If {@link #OVERRIDE_NONE} is used and the method and arguments match a method
* in the extended class, a compile time error will result. Similarly if any other override type
* is used and no method/arguments in the extended | GlideOption |
java | spring-projects__spring-boot | module/spring-boot-rsocket/src/main/java/org/springframework/boot/rsocket/server/RSocketServerFactory.java | {
"start": 726,
"end": 872
} | interface ____ can be used to create a reactive {@link RSocketServer}.
*
* @author Brian Clozel
* @since 2.2.0
*/
@FunctionalInterface
public | that |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/web/servlet/client/MockMvcWebTestClient.java | {
"start": 7745,
"end": 9930
} | interface ____<B extends MockMvcServerSpec<B>> {
/**
* Add a global filter.
* <p>This is delegated to
* {@link ConfigurableMockMvcBuilder#addFilters(Filter...)}.
*/
<T extends B> T filters(Filter... filters);
/**
* Add a filter for specific URL patterns.
* <p>This is delegated to
* {@link ConfigurableMockMvcBuilder#addFilter(Filter, String...)}.
*/
<T extends B> T filter(Filter filter, String... urlPatterns);
/**
* Define default request properties that should be merged into all
* performed requests such that input from the client request override
* the default properties defined here.
* <p>This is delegated to
* {@link ConfigurableMockMvcBuilder#defaultRequest(RequestBuilder)}.
*/
<T extends B> T defaultRequest(RequestBuilder requestBuilder);
/**
* Define a global expectation that should <em>always</em> be applied to
* every response.
* <p>This is delegated to
* {@link ConfigurableMockMvcBuilder#alwaysExpect(ResultMatcher)}.
*/
<T extends B> T alwaysExpect(ResultMatcher resultMatcher);
/**
* Whether to handle HTTP OPTIONS requests.
* <p>This is delegated to
* {@link ConfigurableMockMvcBuilder#dispatchOptions(boolean)}.
*/
<T extends B> T dispatchOptions(boolean dispatchOptions);
/**
* Allow customization of {@code DispatcherServlet}.
* <p>This is delegated to
* {@link ConfigurableMockMvcBuilder#addDispatcherServletCustomizer(DispatcherServletCustomizer)}.
*/
<T extends B> T dispatcherServletCustomizer(DispatcherServletCustomizer customizer);
/**
* Add a {@code MockMvcConfigurer} that automates MockMvc setup.
* <p>This is delegated to
* {@link ConfigurableMockMvcBuilder#apply(MockMvcConfigurer)}.
*/
<T extends B> T apply(MockMvcConfigurer configurer);
/**
* Proceed to configure and build the test client.
*/
WebTestClient.Builder configureClient();
/**
* Shortcut to build the test client.
*/
WebTestClient build();
}
/**
* Specification for configuring {@link MockMvc} to test one or more
* controllers directly, and a simple facade around
* {@link StandaloneMockMvcBuilder}.
*/
| MockMvcServerSpec |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 88290,
"end": 88623
} | class ____ {
private final String name;
private final Nested nested;
NestedMultipleConstructorProperties(String name, Nested nested) {
this.name = name;
this.nested = nested;
}
String getName() {
return this.name;
}
Nested getNested() {
return this.nested;
}
static | NestedMultipleConstructorProperties |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/serializer/JSONFieldTest5.java | {
"start": 494,
"end": 675
} | class ____ {
private int id;
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
}
}
| VO |
java | spring-projects__spring-boot | module/spring-boot-cassandra/src/test/java/org/springframework/boot/cassandra/autoconfigure/CassandraPropertiesTests.java | {
"start": 1035,
"end": 2483
} | class ____ {
/**
* To let a configuration file override values, {@link CassandraProperties} can't have
* any default hardcoded. This test makes sure that the default that we moved to
* manual meta-data are accurate.
*/
@Test
void defaultValuesInManualMetadataAreConsistent() {
OptionsMap driverDefaults = OptionsMap.driverDefaults();
// spring.cassandra.connection.connect-timeout
assertThat(driverDefaults.get(TypedDriverOption.CONNECTION_CONNECT_TIMEOUT)).isEqualTo(Duration.ofSeconds(5));
// spring.cassandra.connection.init-query-timeout
assertThat(driverDefaults.get(TypedDriverOption.CONNECTION_INIT_QUERY_TIMEOUT))
.isEqualTo(Duration.ofSeconds(5));
// spring.cassandra.request.timeout
assertThat(driverDefaults.get(TypedDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofSeconds(2));
// spring.cassandra.request.page-size
assertThat(driverDefaults.get(TypedDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(5000);
// spring.cassandra.request.throttler.type
assertThat(driverDefaults.get(TypedDriverOption.REQUEST_THROTTLER_CLASS))
.isEqualTo("PassThroughRequestThrottler"); // "none"
// spring.cassandra.pool.heartbeat-interval
assertThat(driverDefaults.get(TypedDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(Duration.ofSeconds(30));
// spring.cassandra.pool.idle-timeout
assertThat(driverDefaults.get(TypedDriverOption.HEARTBEAT_TIMEOUT)).isEqualTo(Duration.ofSeconds(5));
}
}
| CassandraPropertiesTests |
java | apache__camel | components/camel-mustache/src/test/java/org/apache/camel/component/mustache/MustacheRefTest.java | {
"start": 1123,
"end": 2064
} | class ____ extends CamelTestSupport {
private static final String TEMP = "Dear {{headers.lastName}}, {{headers.firstName}}";
@Test
public void testRef() {
Exchange exchange = template.request("direct:a", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setBody("Hello");
exchange.getIn().setHeader("firstName", "Jack");
exchange.getIn().setHeader("lastName", "Sparrow");
}
});
assertEquals("Dear Sparrow, Jack", exchange.getMessage().getBody());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
context.getRegistry().bind("mytemp", TEMP);
from("direct:a").to(
"mustache:ref:mytemp");
}
};
}
}
| MustacheRefTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StEnvelopeFromWKBEvaluator.java | {
"start": 4694,
"end": 5290
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory wkb;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory wkb) {
this.source = source;
this.wkb = wkb;
}
@Override
public StEnvelopeFromWKBEvaluator get(DriverContext context) {
return new StEnvelopeFromWKBEvaluator(source, wkb.get(context), context);
}
@Override
public String toString() {
return "StEnvelopeFromWKBEvaluator[" + "wkb=" + wkb + "]";
}
}
}
| Factory |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/issues/AdviceWithTransactionIssueIT.java | {
"start": 1281,
"end": 2885
} | class ____ extends SpringJMSBasic {
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"org/apache/camel/component/jms/integration/spring/issues/AdviceWithTransactionIssueIT.xml");
}
@Override
public boolean isUseAdviceWith() {
return true;
}
@Test
void testAdviceWithWeaveById() throws Exception {
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
weaveById("mock-b*").after().to("mock:last");
}
});
context.start();
MockEndpoint mockLast = getMockEndpoint("mock:last");
mockLast.expectedBodiesReceived("bar");
mockLast.setExpectedMessageCount(1);
template.sendBody("jms:queue:start", "bar");
MockEndpoint.assertIsSatisfied(context);
}
@Test
void testAdviceWithAddLast() throws Exception {
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
weaveAddLast().to("mock:last");
}
});
context.start();
MockEndpoint mockLast = getMockEndpoint("mock:last");
mockLast.expectedBodiesReceived("bar");
mockLast.setExpectedMessageCount(1);
template.sendBody("jms:queue:start", "bar");
MockEndpoint.assertIsSatisfied(context);
}
}
| AdviceWithTransactionIssueIT |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/support/DelegatedAuthorizationSettings.java | {
"start": 636,
"end": 1147
} | class ____ {
public static final String AUTHZ_REALMS_SUFFIX = "authorization_realms";
public static final Function<String, Setting.AffixSetting<List<String>>> AUTHZ_REALMS = RealmSettings.affixSetting(
AUTHZ_REALMS_SUFFIX,
key -> Setting.stringListSetting(key, Setting.Property.NodeScope)
);
public static Collection<Setting.AffixSetting<?>> getSettings(String realmType) {
return Collections.singleton(AUTHZ_REALMS.apply(realmType));
}
}
| DelegatedAuthorizationSettings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.