language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/resolver/FederationNamenodeContext.java | {
"start": 949,
"end": 2480
} | interface ____ {
/**
* Get the RPC server address of the namenode.
*
* @return RPC server address in the form of host:port.
*/
String getRpcAddress();
/**
* Get the Service RPC server address of the namenode.
*
* @return Service RPC server address in the form of host:port.
*/
String getServiceAddress();
/**
* Get the Lifeline RPC server address of the namenode.
*
* @return Lifeline RPC server address in the form of host:port.
*/
String getLifelineAddress();
/**
* Get the Scheme of web address of the namenode.
*
* @return Scheme of web address (HTTP/HTTPS).
*/
String getWebScheme();
/**
* Get the HTTP(s) server address of the namenode.
*
* @return HTTP(s) address in the form of host:port.
*/
String getWebAddress();
/**
* Get the unique key representing the namenode.
*
* @return Combination of the nameservice and the namenode IDs.
*/
String getNamenodeKey();
/**
* Identifier for the nameservice/namespace.
*
* @return Namenode nameservice identifier.
*/
String getNameserviceId();
/**
* Identifier for the namenode.
*
* @return String
*/
String getNamenodeId();
/**
* The current state of the namenode (active, standby, etc).
*
* @return FederationNamenodeServiceState State of the namenode.
*/
FederationNamenodeServiceState getState();
/**
* The update date.
*
* @return Long with the update date.
*/
long getDateModified();
}
| FederationNamenodeContext |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/where/hbm/LazyToManyWhereUseClassWhereTest.java | {
"start": 909,
"end": 5346
} | class ____ {
@AfterEach
void dropTestData(SessionFactoryScope factoryScope) {
factoryScope.dropData();
}
@Test
@JiraKey( "HHH-13011" )
public void testAssociatedWhereClause(SessionFactoryScope factoryScope) {
Product product = new Product();
Category flowers = new Category();
flowers.setId( 1 );
flowers.setName( "flowers" );
flowers.setDescription( "FLOWERS" );
product.getCategoriesOneToMany().add( flowers );
product.getCategoriesWithDescOneToMany().add( flowers );
product.getCategoriesManyToMany().add( flowers );
product.getCategoriesWithDescManyToMany().add( flowers );
product.getCategoriesWithDescIdLt4ManyToMany().add( flowers );
Category vegetables = new Category();
vegetables.setId( 2 );
vegetables.setName( "vegetables" );
vegetables.setDescription( "VEGETABLES" );
product.getCategoriesOneToMany().add( vegetables );
product.getCategoriesWithDescOneToMany().add( vegetables );
product.getCategoriesManyToMany().add( vegetables );
product.getCategoriesWithDescManyToMany().add( vegetables );
product.getCategoriesWithDescIdLt4ManyToMany().add( vegetables );
Category dogs = new Category();
dogs.setId( 3 );
dogs.setName( "dogs" );
dogs.setDescription( null );
product.getCategoriesOneToMany().add( dogs );
product.getCategoriesWithDescOneToMany().add( dogs );
product.getCategoriesManyToMany().add( dogs );
product.getCategoriesWithDescManyToMany().add( dogs );
product.getCategoriesWithDescIdLt4ManyToMany().add( dogs );
Category building = new Category();
building.setId( 4 );
building.setName( "building" );
building.setDescription( "BUILDING" );
product.getCategoriesOneToMany().add( building );
product.getCategoriesWithDescOneToMany().add( building );
product.getCategoriesManyToMany().add( building );
product.getCategoriesWithDescManyToMany().add( building );
product.getCategoriesWithDescIdLt4ManyToMany().add( building );
factoryScope.inTransaction( (session) -> {
session.persist( flowers );
session.persist( vegetables );
session.persist( dogs );
session.persist( building );
session.persist( product );
} );
factoryScope.inTransaction( (session) -> {
Product p = session.find( Product.class, product.getId() );
assertNotNull( p );
assertEquals( 4, p.getCategoriesOneToMany().size() );
checkIds( p.getCategoriesOneToMany(), new Integer[] { 1, 2, 3, 4 } );
assertEquals( 3, p.getCategoriesWithDescOneToMany().size() );
checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 1, 2, 4 } );
assertEquals( 4, p.getCategoriesManyToMany().size() );
checkIds( p.getCategoriesManyToMany(), new Integer[] { 1, 2, 3, 4 } );
assertEquals( 3, p.getCategoriesWithDescManyToMany().size() );
checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 1, 2, 4 } );
assertEquals( 2, p.getCategoriesWithDescIdLt4ManyToMany().size() );
checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 1, 2 } );
} );
factoryScope.inTransaction( (session) -> {
Category c = session.find( Category.class, flowers.getId() );
assertNotNull( c );
c.setInactive( 1 );
} );
factoryScope.inTransaction( (session) -> {
Category c = session.find( Category.class, flowers.getId() );
assertNull( c );
} );
factoryScope.inTransaction( (session) -> {
Product p = session.find( Product.class, product.getId() );
assertNotNull( p );
assertEquals( 3, p.getCategoriesOneToMany().size() );
checkIds( p.getCategoriesOneToMany(), new Integer[] { 2, 3, 4 } );
assertEquals( 2, p.getCategoriesWithDescOneToMany().size() );
checkIds( p.getCategoriesWithDescOneToMany(), new Integer[] { 2, 4 } );
assertEquals( 3, p.getCategoriesManyToMany().size() );
checkIds( p.getCategoriesManyToMany(), new Integer[] { 2, 3, 4 } );
assertEquals( 2, p.getCategoriesWithDescManyToMany().size() );
checkIds( p.getCategoriesWithDescManyToMany(), new Integer[] { 2, 4 } );
assertEquals( 1, p.getCategoriesWithDescIdLt4ManyToMany().size() );
checkIds( p.getCategoriesWithDescIdLt4ManyToMany(), new Integer[] { 2 } );
} );
}
private void checkIds(Set<Category> categories, Integer[] expectedIds) {
final Set<Integer> expectedIdSet = new HashSet<>( Arrays.asList( expectedIds ) );
for ( Category category : categories ) {
expectedIdSet.remove( category.getId() );
}
assertTrue( expectedIdSet.isEmpty() );
}
}
| LazyToManyWhereUseClassWhereTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DebeziumMongodbEndpointBuilderFactory.java | {
"start": 90146,
"end": 93554
} | class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final DebeziumMongodbHeaderNameBuilder INSTANCE = new DebeziumMongodbHeaderNameBuilder();
/**
* The metadata about the source event, for example table name, database
* name, log position, etc, please refer to the Debezium documentation
* for more info.
*
* The option is a: {@code Map<String, Object>} type.
*
* Group: consumer
*
* @return the name of the header {@code DebeziumSourceMetadata}.
*/
public String debeziumSourceMetadata() {
return "CamelDebeziumSourceMetadata";
}
/**
* The identifier of the connector, normally is this format
* {server-name}.{database-name}.{table-name}.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code DebeziumIdentifier}.
*/
public String debeziumIdentifier() {
return "CamelDebeziumIdentifier";
}
/**
* The key of the event, normally is the table Primary Key.
*
* The option is a: {@code Struct} type.
*
* Group: consumer
*
* @return the name of the header {@code DebeziumKey}.
*/
public String debeziumKey() {
return "CamelDebeziumKey";
}
/**
* If presents, the type of event operation. Values for the connector
* are c for create (or insert), u for update, d for delete or r for
* read (in the case of a initial sync) or in case of a snapshot event.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code DebeziumOperation}.
*/
public String debeziumOperation() {
return "CamelDebeziumOperation";
}
/**
* If presents, the time (using the system clock in the JVM) at which
* the connector processed the event.
*
* The option is a: {@code Long} type.
*
* Group: consumer
*
* @return the name of the header {@code DebeziumTimestamp}.
*/
public String debeziumTimestamp() {
return "CamelDebeziumTimestamp";
}
/**
* If presents, contains the state of the row before the event occurred.
*
* The option is a: {@code Struct} type.
*
* Group: consumer
*
* @return the name of the header {@code DebeziumBefore}.
*/
public String debeziumBefore() {
return "CamelDebeziumBefore";
}
/**
* If presents, the ddl sql text of the event.
*
* The option is a: {@code String} type.
*
* Group: consumer
*
* @return the name of the header {@code DebeziumDdlSQL}.
*/
public String debeziumDdlSQL() {
return "CamelDebeziumDdlSQL";
}
}
static DebeziumMongodbEndpointBuilder endpointBuilder(String componentName, String path) {
| DebeziumMongodbHeaderNameBuilder |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/asyncprocessing/operators/AsyncIntervalJoinOperatorTest.java | {
"start": 28299,
"end": 32769
} | class ____ {
private AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
operator;
private TestHarness testHarness;
public JoinTestBuilder(
TestHarness t,
AsyncIntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
operator)
throws Exception {
this.testHarness = t;
this.operator = operator;
t.open();
t.setup();
}
public TestHarness get() {
return testHarness;
}
public JoinTestBuilder processElement1(int ts) throws Exception {
testHarness.processElement1(createStreamRecord(ts, "lhs"));
return this;
}
public JoinTestBuilder processElement2(int ts) throws Exception {
testHarness.processElement2(createStreamRecord(ts, "rhs"));
return this;
}
public JoinTestBuilder processWatermark1(int ts) throws Exception {
testHarness.processWatermark1(new Watermark(ts));
return this;
}
public JoinTestBuilder processWatermark2(int ts) throws Exception {
testHarness.processWatermark2(new Watermark(ts));
return this;
}
public JoinTestBuilder processElementsAndWatermarks(int from, int to) throws Exception {
if (lhsFasterThanRhs) {
// add to lhs
for (int i = from; i <= to; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
// add to rhs
for (int i = from; i <= to; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
} else {
// add to rhs
for (int i = from; i <= to; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
// add to lhs
for (int i = from; i <= to; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
}
return this;
}
@SafeVarargs
public final JoinTestBuilder andExpect(StreamRecord<Tuple2<TestElem, TestElem>>... elems) {
assertOutput(Lists.newArrayList(elems), testHarness.getOutput());
return this;
}
public JoinTestBuilder assertLeftBufferContainsOnly(long... timestamps) {
try {
assertContainsOnly(operator.getLeftBuffer(), timestamps);
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertRightBufferContainsOnly(long... timestamps) {
try {
assertContainsOnly(operator.getRightBuffer(), timestamps);
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertLeftBufferEmpty() {
try {
assertEmpty(operator.getLeftBuffer());
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertRightBufferEmpty() {
try {
assertEmpty(operator.getRightBuffer());
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
@SafeVarargs
public final JoinTestBuilder expectLateRecords(
OutputTag<TestElem> tag, StreamRecord<TestElem>... elems) {
assertOutput(Lists.newArrayList(elems), testHarness.getSideOutput(tag));
return this;
}
public JoinTestBuilder noLateRecords() {
TestHarnessUtil.assertNoLateRecords(this.testHarness.getOutput());
return this;
}
public void close() throws Exception {
testHarness.close();
}
}
private static | JoinTestBuilder |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng5760ResumeFeatureTest.java | {
"start": 1379,
"end": 9589
} | class ____ extends AbstractMavenIntegrationTestCase {
private final File parentDependentTestDir;
private final File parentIndependentTestDir;
private final File noProjectTestDir;
private final File fourModulesTestDir;
public MavenITmng5760ResumeFeatureTest() throws IOException {
super();
this.parentDependentTestDir = extractResources("/mng-5760-resume-feature/parent-dependent");
this.parentIndependentTestDir = extractResources("/mng-5760-resume-feature/parent-independent");
this.noProjectTestDir = extractResources("/mng-5760-resume-feature/no-project");
this.fourModulesTestDir = extractResources("/mng-5760-resume-feature/four-modules");
}
/**
* Tests that the hint at the end of a failed build mentions <code>--resume</code> instead of <code>--resume-from</code>.
*
* @throws Exception in case of failure
*/
@Test
public void testShouldSuggestToResumeWithoutArgs() throws Exception {
Verifier verifier = newVerifier(parentDependentTestDir.getAbsolutePath());
verifier.addCliArgument("-Dmodule-b.fail=true");
try {
verifier.addCliArgument("test");
verifier.execute();
fail("Expected this invocation to fail");
} catch (final VerificationException ve) {
verifier.verifyTextInLog("mvn [args] -r");
verifier.verifyTextNotInLog("mvn [args] -rf :module-b");
}
// New build with -r should resume the build from module-b, skipping module-a since it has succeeded already.
verifier = newVerifier(parentDependentTestDir.getAbsolutePath());
verifier.addCliArgument("-r");
verifier.addCliArgument("test");
verifier.execute();
verifier.verifyTextNotInLog("Building module-a 1.0");
verifier.verifyTextInLog("Building module-b 1.0");
verifier.verifyTextInLog("Building module-c 1.0");
}
@Test
public void testShouldSkipSuccessfulProjects() throws Exception {
Verifier verifier = newVerifier(parentDependentTestDir.getAbsolutePath());
verifier.addCliArgument("-Dmodule-a.fail=true");
verifier.addCliArgument("--fail-at-end");
try {
verifier.addCliArgument("test");
verifier.execute();
fail("Expected this invocation to fail");
} catch (final VerificationException ve) {
// Expected to fail.
}
// Let module-b and module-c fail, if they would have been built...
verifier = newVerifier(parentDependentTestDir.getAbsolutePath());
verifier.addCliArgument("-Dmodule-b.fail=true");
verifier.addCliArgument("-Dmodule-c.fail=true");
// ... but adding -r should exclude those two from the build because the previous Maven invocation
// marked them as successfully built.
verifier.addCliArgument("-r");
verifier.addCliArgument("test");
verifier.execute();
}
@Test
public void testShouldSkipSuccessfulModulesWhenTheFirstModuleFailed() throws Exception {
// In this multi-module project, the submodules are not dependent on the parent.
// This results in the parent to be built last, and module-a to be built first.
// This enables us to let the first module in the reactor (module-a) fail.
Verifier verifier = newVerifier(parentIndependentTestDir.getAbsolutePath());
verifier.addCliArgument("-Dmodule-a.fail=true");
verifier.addCliArgument("--fail-at-end");
try {
verifier.addCliArgument("test");
verifier.execute();
fail("Expected this invocation to fail");
} catch (final VerificationException ve) {
verifier.verifyTextInLog("mvn [args] -r");
}
verifier = newVerifier(parentIndependentTestDir.getAbsolutePath());
verifier.addCliArgument("-r");
verifier.addCliArgument("test");
verifier.execute();
verifier.verifyTextInLog("Building module-a 1.0");
verifier.verifyTextNotInLog("Building module-b 1.0");
}
@Test
public void testShouldNotCrashWithoutProject() throws Exception {
// There is no Maven project available in the test directory.
// As reported in JIRA this would previously break with a NullPointerException.
// (see
// https://issues.apache.org/jira/browse/MNG-5760?focusedCommentId=17143795&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-17143795)
final Verifier verifier = newVerifier(noProjectTestDir.getAbsolutePath());
try {
verifier.addCliArgument("org.apache.maven.plugins:maven-resources-plugin:resources");
verifier.execute();
} catch (final VerificationException ve) {
verifier.verifyTextInLog("Goal requires a project to execute but there is no POM in this directory");
}
}
@Test
public void testFailureWithParallelBuild() throws Exception {
// four modules: a, b, c, d
// c depends on b, d depends on a
// Let's do a first pass with a and c failing. The build is parallel,
// so we have a first thread with a and d, and the second one with b and c
// The result should be:
// a : failure (slow, so b and c will be built in the meantime)
// b : success
// c : failure
// d : skipped
Verifier verifier = newVerifier(fourModulesTestDir.getAbsolutePath());
verifier.addCliArgument("-T2");
verifier.addCliArgument("-Dmodule-a.delay=1000");
verifier.addCliArgument("-Dmodule-a.fail=true");
verifier.addCliArgument("-Dmodule-c.fail=true");
try {
verifier.addCliArgument("verify");
verifier.execute();
fail("Expected this invocation to fail");
} catch (final VerificationException ve) {
// Expected to fail.
}
// Let module-b fail, if it would have been built...
verifier = newVerifier(fourModulesTestDir.getAbsolutePath());
verifier.addCliArgument("-T2");
verifier.addCliArgument("-Dmodule-b.fail=true");
// ... but adding -r should exclude it from the build because the previous Maven invocation
// marked it as successfully built.
verifier.addCliArgument("-r");
// The result should be:
// a : success
// c : success
// d : success
verifier.addCliArgument("verify");
verifier.execute();
}
@Test
public void testFailureAfterSkipWithParallelBuild() throws Exception {
// four modules: a, b, c, d
// c depends on b, d depends on a
// Let's do a first pass with a and c failing. The build is parallel,
// so we have a first thread with a and d, and the second one with b and c
// The result should be:
// a : success
// b : success, slow
// c : skipped
// d : failure
Verifier verifier = newVerifier(fourModulesTestDir.getAbsolutePath());
verifier.addCliArgument("-T2");
verifier.addCliArgument("-Dmodule-b.delay=2000");
verifier.addCliArgument("-Dmodule-d.fail=true");
try {
verifier.addCliArgument("verify");
verifier.execute();
fail("Expected this invocation to fail");
} catch (final VerificationException ve) {
// Expected to fail.
}
// Let module-a and module-b fail, if they would have been built...
verifier = newVerifier(fourModulesTestDir.getAbsolutePath());
verifier.addCliArgument("-T2");
verifier.addCliArgument("-Dmodule-a.fail=true");
verifier.addCliArgument("-Dmodule-b.fail=true");
// ... but adding -r should exclude those two from the build because the previous Maven invocation
// marked them as successfully built.
verifier.addCliArgument("-r");
// The result should be:
// c : success
// d : success
verifier.addCliArgument("verify");
verifier.execute();
}
}
| MavenITmng5760ResumeFeatureTest |
java | spring-projects__spring-boot | module/spring-boot-tomcat/src/test/java/org/springframework/boot/tomcat/autoconfigure/reactive/TomcatReactiveWebServerAutoConfigurationTests.java | {
"start": 2134,
"end": 6598
} | class ____ extends AbstractReactiveWebServerAutoConfigurationTests {
TomcatReactiveWebServerAutoConfigurationTests() {
super(TomcatReactiveWebServerAutoConfiguration.class);
}
@Test
void tomcatConnectorCustomizerBeanIsAddedToFactory() {
this.serverRunner.withUserConfiguration(TomcatConnectorCustomizerConfiguration.class).run((context) -> {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer",
TomcatConnectorCustomizer.class);
assertThat(factory.getConnectorCustomizers()).contains(customizer);
then(customizer).should().customize(any(Connector.class));
});
}
@Test
void tomcatConnectorCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() {
this.serverRunner.withUserConfiguration(DoubleRegistrationTomcatConnectorCustomizerConfiguration.class)
.run((context) -> {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer",
TomcatConnectorCustomizer.class);
assertThat(factory.getConnectorCustomizers()).contains(customizer);
then(customizer).should().customize(any(Connector.class));
});
}
@Test
void tomcatContextCustomizerBeanIsAddedToFactory() {
this.serverRunner.withUserConfiguration(TomcatContextCustomizerConfiguration.class).run((context) -> {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class);
assertThat(factory.getContextCustomizers()).contains(customizer);
then(customizer).should().customize(any(Context.class));
});
}
@Test
void tomcatContextCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() {
this.serverRunner.withUserConfiguration(DoubleRegistrationTomcatContextCustomizerConfiguration.class)
.run((context) -> {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatContextCustomizer customizer = context.getBean("contextCustomizer",
TomcatContextCustomizer.class);
assertThat(factory.getContextCustomizers()).contains(customizer);
then(customizer).should().customize(any(Context.class));
});
}
@Test
void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() {
this.serverRunner.withUserConfiguration(TomcatProtocolHandlerCustomizerConfiguration.class).run((context) -> {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer",
TomcatProtocolHandlerCustomizer.class);
assertThat(factory.getProtocolHandlerCustomizers()).contains(customizer);
then(customizer).should().customize(any());
});
}
@Test
void tomcatProtocolHandlerCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() {
this.serverRunner.withUserConfiguration(DoubleRegistrationTomcatProtocolHandlerCustomizerConfiguration.class)
.run((context) -> {
TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class);
TomcatProtocolHandlerCustomizer<?> customizer = context.getBean("protocolHandlerCustomizer",
TomcatProtocolHandlerCustomizer.class);
assertThat(factory.getProtocolHandlerCustomizers()).contains(customizer);
then(customizer).should().customize(any());
});
}
@Test
void webSocketServerContainerIsAvailableFromServletContext() {
this.serverRunner.run((context) -> {
WebServer webServer = ((ReactiveWebServerApplicationContext) context.getSourceApplicationContext())
.getWebServer();
assertThat(webServer).isNotNull();
ServletContext servletContext = findContext(((TomcatWebServer) webServer).getTomcat()).getServletContext();
Object serverContainer = servletContext.getAttribute("jakarta.websocket.server.ServerContainer");
assertThat(serverContainer).isInstanceOf(ServerContainer.class);
});
}
private static Context findContext(Tomcat tomcat) {
for (Container child : tomcat.getHost().findChildren()) {
if (child instanceof Context context) {
return context;
}
}
throw new IllegalStateException("The Host does not contain a Context");
}
@Configuration(proxyBeanMethods = false)
static | TomcatReactiveWebServerAutoConfigurationTests |
java | apache__maven | api/maven-api-core/src/main/java/org/apache/maven/api/services/ToolchainFactory.java | {
"start": 1138,
"end": 1420
} | interface ____ creating toolchain instances from configuration models.
*
* <p>This factory is responsible for instantiating concrete toolchain implementations
* based on toolchain model configurations or default settings.</p>
*
* @since 4.0.0
*/
@Experimental
@Consumer
public | for |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/IbmCosComponentBuilderFactory.java | {
"start": 19027,
"end": 24008
} | class ____
extends AbstractComponentBuilder<IBMCOSComponent>
implements IbmCosComponentBuilder {
@Override
protected IBMCOSComponent buildConcreteComponent() {
return new IBMCOSComponent();
}
private org.apache.camel.component.ibm.cos.IBMCOSConfiguration getOrCreateConfiguration(IBMCOSComponent component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.ibm.cos.IBMCOSConfiguration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "autoCreateBucket": getOrCreateConfiguration((IBMCOSComponent) component).setAutoCreateBucket((boolean) value); return true;
case "configuration": ((IBMCOSComponent) component).setConfiguration((org.apache.camel.component.ibm.cos.IBMCOSConfiguration) value); return true;
case "delimiter": getOrCreateConfiguration((IBMCOSComponent) component).setDelimiter((java.lang.String) value); return true;
case "endpointUrl": getOrCreateConfiguration((IBMCOSComponent) component).setEndpointUrl((java.lang.String) value); return true;
case "location": getOrCreateConfiguration((IBMCOSComponent) component).setLocation((java.lang.String) value); return true;
case "prefix": getOrCreateConfiguration((IBMCOSComponent) component).setPrefix((java.lang.String) value); return true;
case "bridgeErrorHandler": ((IBMCOSComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "deleteAfterRead": getOrCreateConfiguration((IBMCOSComponent) component).setDeleteAfterRead((boolean) value); return true;
case "destinationBucket": getOrCreateConfiguration((IBMCOSComponent) component).setDestinationBucket((java.lang.String) value); return true;
case "destinationBucketPrefix": getOrCreateConfiguration((IBMCOSComponent) component).setDestinationBucketPrefix((java.lang.String) value); return true;
case "destinationBucketSuffix": getOrCreateConfiguration((IBMCOSComponent) component).setDestinationBucketSuffix((java.lang.String) value); return true;
case "fileName": getOrCreateConfiguration((IBMCOSComponent) component).setFileName((java.lang.String) value); return true;
case "includeBody": getOrCreateConfiguration((IBMCOSComponent) component).setIncludeBody((boolean) value); return true;
case "includeFolders": getOrCreateConfiguration((IBMCOSComponent) component).setIncludeFolders((boolean) value); return true;
case "moveAfterRead": getOrCreateConfiguration((IBMCOSComponent) component).setMoveAfterRead((boolean) value); return true;
case "autocloseBody": getOrCreateConfiguration((IBMCOSComponent) component).setAutocloseBody((boolean) value); return true;
case "deleteAfterWrite": getOrCreateConfiguration((IBMCOSComponent) component).setDeleteAfterWrite((boolean) value); return true;
case "keyName": getOrCreateConfiguration((IBMCOSComponent) component).setKeyName((java.lang.String) value); return true;
case "lazyStartProducer": ((IBMCOSComponent) component).setLazyStartProducer((boolean) value); return true;
case "multiPartUpload": getOrCreateConfiguration((IBMCOSComponent) component).setMultiPartUpload((boolean) value); return true;
case "operation": getOrCreateConfiguration((IBMCOSComponent) component).setOperation((org.apache.camel.component.ibm.cos.IBMCOSOperations) value); return true;
case "partSize": getOrCreateConfiguration((IBMCOSComponent) component).setPartSize((long) value); return true;
case "storageClass": getOrCreateConfiguration((IBMCOSComponent) component).setStorageClass((java.lang.String) value); return true;
case "autowiredEnabled": ((IBMCOSComponent) component).setAutowiredEnabled((boolean) value); return true;
case "cosClient": getOrCreateConfiguration((IBMCOSComponent) component).setCosClient((com.ibm.cloud.objectstorage.services.s3.AmazonS3) value); return true;
case "healthCheckConsumerEnabled": ((IBMCOSComponent) component).setHealthCheckConsumerEnabled((boolean) value); return true;
case "healthCheckProducerEnabled": ((IBMCOSComponent) component).setHealthCheckProducerEnabled((boolean) value); return true;
case "apiKey": getOrCreateConfiguration((IBMCOSComponent) component).setApiKey((java.lang.String) value); return true;
case "serviceInstanceId": getOrCreateConfiguration((IBMCOSComponent) component).setServiceInstanceId((java.lang.String) value); return true;
default: return false;
}
}
}
} | IbmCosComponentBuilderImpl |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/arraymapping/ArrayMapping_long_stream.java | {
"start": 239,
"end": 642
} | class ____ extends TestCase {
public void test_for_error() throws Exception {
JSONReader reader = new JSONReader(new StringReader("[1001,\"wenshao\"]"), Feature.SupportArrayToBean);
Model model = reader.readObject(Model.class);
Assert.assertEquals(1001, model.id);
Assert.assertEquals("wenshao", model.name);
}
public static | ArrayMapping_long_stream |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortComparatorTest.java | {
"start": 1828,
"end": 2100
} | class ____ {
@Id
@GeneratedValue
private long id;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
@SortComparator(CatNicknameComparator.class)
private SortedSet<Cat> cats = new TreeSet<>();
}
@Entity(name = "Cat")
@Table(name = "Cat")
static | Owner |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/orm/domain/library/Book.java | {
"start": 526,
"end": 1987
} | class ____ {
@Id
private Integer id;
private String name;
private String isbn;
@ManyToMany
@JoinTable( name = "book_authors",
joinColumns = @JoinColumn(name = "book_fk"),
inverseJoinColumns = @JoinColumn(name = "author_fk")
)
@Cache( usage = CacheConcurrencyStrategy.READ_WRITE)
Set<Person> authors;
@ManyToMany
@JoinTable( name = "book_editors",
joinColumns = @JoinColumn(name = "book_fk"),
inverseJoinColumns = @JoinColumn(name = "editor_fk")
)
@Cache( usage = CacheConcurrencyStrategy.READ_WRITE)
Set<Person> editors;
protected Book() {
// for Hibernate use
}
public Book(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Set<Person> getAuthors() {
return authors;
}
public void setAuthors(Set<Person> authors) {
this.authors = authors;
}
public void addAuthor(Person author) {
if ( authors == null ) {
authors = new HashSet<>();
}
authors.add( author );
}
public Set<Person> getEditors() {
return editors;
}
public void setEditors(Set<Person> editors) {
this.editors = editors;
}
public void addEditor(Person editor) {
if ( editors == null ) {
editors = new HashSet<>();
}
editors.add( editor );
}
}
| Book |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AbstractYarnScheduler.java | {
"start": 70087,
"end": 71917
} | class ____ extends Object {
private final long allocationId;
private final Priority priority;
private final ExecutionType executionType;
private final Resource resource;
public ContainerObjectType(long allocationId, Priority priority,
ExecutionType executionType, Resource resource) {
this.allocationId = allocationId;
this.priority = priority;
this.executionType = executionType;
this.resource = resource;
}
public long getAllocationId() {
return allocationId;
}
public Priority getPriority() {
return priority;
}
public ExecutionType getExecutionType() {
return executionType;
}
public Resource getResource() {
return resource;
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(allocationId)
.append(priority)
.append(executionType)
.append(resource)
.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
ContainerObjectType other = (ContainerObjectType) obj;
return new EqualsBuilder()
.append(allocationId, other.getAllocationId())
.append(priority, other.getPriority())
.append(executionType, other.getExecutionType())
.append(resource, other.getResource())
.isEquals();
}
@Override
public String toString() {
return "{ContainerObjectType: "
+ ", Priority: " + getPriority()
+ ", Allocation Id: " + getAllocationId()
+ ", Execution Type: " + getExecutionType()
+ ", Resource: " + getResource()
+ "}";
}
}
}
| ContainerObjectType |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/DisplayConnector.java | {
"start": 403,
"end": 776
} | class ____ {
private int number;
private Display display;
@Min(1)
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@ManyToOne(cascade = CascadeType.PERSIST)
@Valid
public Display getDisplay() {
return display;
}
public void setDisplay(Display display) {
this.display = display;
}
}
| DisplayConnector |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/blockhash/IntBlockHash.java | {
"start": 1226,
"end": 6575
} | class ____ extends BlockHash {
private final int channel;
final LongHash hash;
/**
* Have we seen any {@code null} values?
* <p>
* We reserve the 0 ordinal for the {@code null} key so methods like
* {@link #nonEmpty} need to skip 0 if we haven't seen any null values.
* </p>
*/
private boolean seenNull;
IntBlockHash(int channel, BlockFactory blockFactory) {
super(blockFactory);
this.channel = channel;
this.hash = new LongHash(1, blockFactory.bigArrays());
}
@Override
public void add(Page page, GroupingAggregatorFunction.AddInput addInput) {
// TODO track raw counts and which implementation we pick for the profiler - #114008
var block = page.getBlock(channel);
if (block.areAllValuesNull()) {
seenNull = true;
try (IntVector groupIds = blockFactory.newConstantIntVector(0, block.getPositionCount())) {
addInput.add(0, groupIds);
}
return;
}
IntBlock castBlock = (IntBlock) block;
IntVector vector = castBlock.asVector();
if (vector == null) {
try (IntBlock groupIds = add(castBlock)) {
addInput.add(0, groupIds);
}
return;
}
try (IntVector groupIds = add(vector)) {
addInput.add(0, groupIds);
}
}
/**
* Adds the vector values to the hash, and returns a new vector with the group IDs for those positions.
*/
IntVector add(IntVector vector) {
int positions = vector.getPositionCount();
try (var builder = blockFactory.newIntVectorFixedBuilder(positions)) {
for (int i = 0; i < positions; i++) {
int v = vector.getInt(i);
builder.appendInt(Math.toIntExact(hashOrdToGroupNullReserved(hash.add(v))));
}
return builder.build();
}
}
/**
* Adds the block values to the hash, and returns a new vector with the group IDs for those positions.
* <p>
* For nulls, a 0 group ID is used. For multivalues, a multivalue is used with all the group IDs.
* </p>
*/
IntBlock add(IntBlock block) {
MultivalueDedupe.HashResult result = new MultivalueDedupeInt(block).hashAdd(blockFactory, hash);
seenNull |= result.sawNull();
return result.ords();
}
@Override
public ReleasableIterator<IntBlock> lookup(Page page, ByteSizeValue targetBlockSize) {
var block = page.getBlock(channel);
if (block.areAllValuesNull()) {
return ReleasableIterator.single(blockFactory.newConstantIntVector(0, block.getPositionCount()).asBlock());
}
IntBlock castBlock = (IntBlock) block;
IntVector vector = castBlock.asVector();
// TODO honor targetBlockSize and chunk the pages if requested.
if (vector == null) {
return ReleasableIterator.single(lookup(castBlock));
}
return ReleasableIterator.single(lookup(vector));
}
private IntBlock lookup(IntVector vector) {
int positions = vector.getPositionCount();
try (var builder = blockFactory.newIntBlockBuilder(positions)) {
for (int i = 0; i < positions; i++) {
int v = vector.getInt(i);
long found = hash.find(v);
if (found < 0) {
builder.appendNull();
} else {
builder.appendInt(Math.toIntExact(hashOrdToGroupNullReserved(found)));
}
}
return builder.build();
}
}
private IntBlock lookup(IntBlock block) {
return new MultivalueDedupeInt(block).hashLookup(blockFactory, hash);
}
@Override
public IntBlock[] getKeys() {
if (seenNull) {
final int size = Math.toIntExact(hash.size() + 1);
final int[] keys = new int[size];
for (int i = 1; i < size; i++) {
keys[i] = (int) hash.get(i - 1);
}
BitSet nulls = new BitSet(1);
nulls.set(0);
return new IntBlock[] {
blockFactory.newIntArrayBlock(keys, keys.length, null, nulls, Block.MvOrdering.DEDUPLICATED_AND_SORTED_ASCENDING) };
}
final int size = Math.toIntExact(hash.size());
final int[] keys = new int[size];
for (int i = 0; i < size; i++) {
keys[i] = (int) hash.get(i);
}
return new IntBlock[] { blockFactory.newIntArrayVector(keys, keys.length).asBlock() };
}
@Override
public IntVector nonEmpty() {
return IntVector.range(seenNull ? 0 : 1, Math.toIntExact(hash.size() + 1), blockFactory);
}
@Override
public BitArray seenGroupIds(BigArrays bigArrays) {
return new SeenGroupIds.Range(seenNull ? 0 : 1, Math.toIntExact(hash.size() + 1)).seenGroupIds(bigArrays);
}
@Override
public void close() {
hash.close();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("IntBlockHash{channel=").append(channel);
b.append(", entries=").append(hash.size());
b.append(", seenNull=").append(seenNull);
return b.append('}').toString();
}
}
| IntBlockHash |
java | elastic__elasticsearch | modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/DerivativePipelineAggregator.java | {
"start": 1343,
"end": 3997
} | class ____ extends PipelineAggregator {
private final DocValueFormat formatter;
private final GapPolicy gapPolicy;
private final Double xAxisUnits;
DerivativePipelineAggregator(
String name,
String[] bucketsPaths,
DocValueFormat formatter,
GapPolicy gapPolicy,
Long xAxisUnits,
Map<String, Object> metadata
) {
super(name, bucketsPaths, metadata);
this.formatter = formatter;
this.gapPolicy = gapPolicy;
this.xAxisUnits = xAxisUnits == null ? null : (double) xAxisUnits;
}
@Override
public InternalAggregation reduce(InternalAggregation aggregation, AggregationReduceContext reduceContext) {
@SuppressWarnings("rawtypes")
InternalMultiBucketAggregation<
? extends InternalMultiBucketAggregation,
? extends InternalMultiBucketAggregation.InternalBucket> histo = (InternalMultiBucketAggregation<
? extends InternalMultiBucketAggregation,
? extends InternalMultiBucketAggregation.InternalBucket>) aggregation;
List<? extends InternalMultiBucketAggregation.InternalBucket> buckets = histo.getBuckets();
HistogramFactory factory = (HistogramFactory) histo;
List<Bucket> newBuckets = new ArrayList<>();
Number lastBucketKey = null;
Double lastBucketValue = null;
for (InternalMultiBucketAggregation.InternalBucket bucket : buckets) {
Number thisBucketKey = factory.getKey(bucket);
Double thisBucketValue = resolveBucketValue(histo, bucket, bucketsPaths()[0], gapPolicy);
if (lastBucketValue != null && thisBucketValue != null) {
double gradient = thisBucketValue - lastBucketValue;
double xDiff = -1;
if (xAxisUnits != null) {
xDiff = (thisBucketKey.doubleValue() - lastBucketKey.doubleValue()) / xAxisUnits;
}
newBuckets.add(
factory.createBucket(
factory.getKey(bucket),
bucket.getDocCount(),
InternalAggregations.append(
bucket.getAggregations(),
new Derivative(name(), gradient, xDiff, formatter, metadata())
)
)
);
} else {
newBuckets.add(bucket);
}
lastBucketKey = thisBucketKey;
lastBucketValue = thisBucketValue;
}
return factory.createAggregation(newBuckets);
}
}
| DerivativePipelineAggregator |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/convert/ConversionException.java | {
"start": 881,
"end": 1316
} | class ____ extends NestedRuntimeException {
/**
* Construct a new conversion exception.
* @param message the exception message
*/
public ConversionException(String message) {
super(message);
}
/**
* Construct a new conversion exception.
* @param message the exception message
* @param cause the cause
*/
public ConversionException(String message, Throwable cause) {
super(message, cause);
}
}
| ConversionException |
java | dropwizard__dropwizard | dropwizard-auth/src/main/java/io/dropwizard/auth/JSONUnauthorizedHandler.java | {
"start": 198,
"end": 866
} | class ____ implements UnauthorizedHandler {
private static final String CHALLENGE_FORMAT = "%s realm=\"%s\"";
@Override
public Response buildResponse(String prefix, String realm) {
ErrorMessage errorMessage = new ErrorMessage(
Response.Status.UNAUTHORIZED.getStatusCode(),
"Credentials are required to access this resource."
);
return Response.status(errorMessage.getCode())
.header(HttpHeaders.WWW_AUTHENTICATE, String.format(CHALLENGE_FORMAT, prefix, realm))
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(errorMessage)
.build();
}
}
| JSONUnauthorizedHandler |
java | apache__logging-log4j2 | log4j-1.2-api/src/main/java/org/apache/log4j/Hierarchy.java | {
"start": 3905,
"end": 18631
} | class ____ private, no confusion can arise.")
public static org.apache.logging.log4j.Logger getLogger(final String name) {
return getLogger(FQCN, name);
}
}
private static final PrivateLoggerAdapter LOGGER_ADAPTER = new PrivateLoggerAdapter();
private static final WeakHashMap<LoggerContext, ConcurrentMap<String, Logger>> CONTEXT_MAP = new WeakHashMap<>();
static LoggerContext getContext() {
return PrivateLogManager.getContext();
}
private Logger getInstance(final LoggerContext context, final String name) {
return getInstance(context, name, LOGGER_ADAPTER);
}
private Logger getInstance(final LoggerContext context, final String name, final LoggerFactory factory) {
return getLoggersMap(context).computeIfAbsent(name, k -> {
final Logger logger = factory.makeNewLoggerInstance(name);
logger.setHierarchy(this);
return logger;
});
}
private Logger getInstance(final LoggerContext context, final String name, final PrivateLoggerAdapter factory) {
return getLoggersMap(context).computeIfAbsent(name, k -> {
final Logger logger = factory.newLogger(name, context);
logger.setHierarchy(this);
return logger;
});
}
static ConcurrentMap<String, Logger> getLoggersMap(final LoggerContext context) {
synchronized (CONTEXT_MAP) {
return CONTEXT_MAP.computeIfAbsent(context, k -> new ConcurrentHashMap<>());
}
}
private final LoggerFactory defaultFactory;
private final Vector listeners;
Hashtable ht;
Logger root;
RendererMap rendererMap;
int thresholdInt;
Level threshold;
boolean emittedNoAppenderWarning;
boolean emittedNoResourceBundleWarning;
private ThrowableRenderer throwableRenderer;
/**
* Creates a new logger hierarchy.
*
* @param root The root of the new hierarchy.
*
*/
public Hierarchy(final Logger root) {
ht = new Hashtable();
listeners = new Vector(1);
this.root = root;
// Enable all level levels by default.
setThreshold(Level.ALL);
this.root.setHierarchy(this);
rendererMap = new RendererMap();
defaultFactory = new DefaultCategoryFactory();
}
@Override
public void addHierarchyEventListener(final HierarchyEventListener listener) {
if (listeners.contains(listener)) {
LogLog.warn("Ignoring attempt to add an existent listener.");
} else {
listeners.addElement(listener);
}
}
/**
* Adds an object renderer for a specific class.
*/
public void addRenderer(final Class classToRender, final ObjectRenderer or) {
rendererMap.put(classToRender, or);
}
/**
* This call will clear all logger definitions from the internal hashtable. Invoking this method will irrevocably mess
* up the logger hierarchy.
*
* <p>
* You should <em>really</em> know what you are doing before invoking this method.
* </p>
*
* @since 0.9.0
*/
public void clear() {
// System.out.println("\n\nAbout to clear internal hash table.");
ht.clear();
getLoggersMap(getContext()).clear();
}
@Override
public void emitNoAppenderWarning(final Category cat) {
// No appenders in hierarchy, warn user only once.
if (!this.emittedNoAppenderWarning) {
LogLog.warn("No appenders could be found for logger (" + cat.getName() + ").");
LogLog.warn("Please initialize the log4j system properly.");
LogLog.warn("See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.");
this.emittedNoAppenderWarning = true;
}
}
/**
* Tests if the named logger exists in the hierarchy. If so return its reference, otherwise returns <code>null</code>.
*
* @param name The name of the logger to search for.
*
*/
@Override
public Logger exists(final String name) {
return exists(name, getContext());
}
Logger exists(final String name, final ClassLoader classLoader) {
return exists(name, getContext(classLoader));
}
Logger exists(final String name, final LoggerContext loggerContext) {
if (!loggerContext.hasLogger(name)) {
return null;
}
return Logger.getLogger(name);
}
@Override
public void fireAddAppenderEvent(final Category logger, final Appender appender) {
if (listeners != null) {
final int size = listeners.size();
HierarchyEventListener listener;
for (int i = 0; i < size; i++) {
listener = (HierarchyEventListener) listeners.elementAt(i);
listener.addAppenderEvent(logger, appender);
}
}
}
void fireRemoveAppenderEvent(final Category logger, final Appender appender) {
if (listeners != null) {
final int size = listeners.size();
HierarchyEventListener listener;
for (int i = 0; i < size; i++) {
listener = (HierarchyEventListener) listeners.elementAt(i);
listener.removeAppenderEvent(logger, appender);
}
}
}
LoggerContext getContext(final ClassLoader classLoader) {
return LogManager.getContext(classLoader);
}
/**
* @deprecated Please use {@link #getCurrentLoggers} instead.
*/
@Deprecated
@Override
public Enumeration getCurrentCategories() {
return getCurrentLoggers();
}
/**
* Gets all the currently defined categories in this hierarchy as an {@link java.util.Enumeration Enumeration}.
*
* <p>
* The root logger is <em>not</em> included in the returned {@link Enumeration}.
* </p>
*/
@Override
public Enumeration getCurrentLoggers() {
// The accumlation in v is necessary because not all elements in
// ht are Logger objects as there might be some ProvisionNodes
// as well.
// final Vector v = new Vector(ht.size());
//
// final Enumeration elems = ht.elements();
// while (elems.hasMoreElements()) {
// final Object o = elems.nextElement();
// if (o instanceof Logger) {
// v.addElement(o);
// }
// }
// return v.elements();
return LogManager.getCurrentLoggers(StackLocatorUtil.getCallerClassLoader(2));
}
/**
* Gets a new logger instance named as the first parameter using the default factory.
*
* <p>
* If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated and
* then linked with its existing ancestors as well as children.
* </p>
*
* @param name The name of the logger to retrieve.
*
*/
@Override
public Logger getLogger(final String name) {
return getInstance(getContext(), name);
}
Logger getLogger(final String name, final ClassLoader classLoader) {
return getInstance(getContext(classLoader), name);
}
/**
* Gets a new logger instance named as the first parameter using <code>factory</code>.
*
* <p>
* If a logger of that name already exists, then it will be returned. Otherwise, a new logger will be instantiated by
* the <code>factory</code> parameter and linked with its existing ancestors as well as children.
* </p>
*
* @param name The name of the logger to retrieve.
* @param factory The factory that will make the new logger instance.
*
*/
@Override
public Logger getLogger(final String name, final LoggerFactory factory) {
return getInstance(getContext(), name, factory);
}
Logger getLogger(final String name, final LoggerFactory factory, final ClassLoader classLoader) {
return getInstance(getContext(classLoader), name, factory);
}
/**
* Gets the renderer map for this hierarchy.
*/
@Override
public RendererMap getRendererMap() {
return rendererMap;
}
/**
* Gets the root of this hierarchy.
*
* @since 0.9.0
*/
@Override
public Logger getRootLogger() {
return getInstance(getContext(), org.apache.logging.log4j.LogManager.ROOT_LOGGER_NAME);
}
Logger getRootLogger(final ClassLoader classLoader) {
return getInstance(getContext(classLoader), org.apache.logging.log4j.LogManager.ROOT_LOGGER_NAME);
}
/**
* Gets a {@link Level} representation of the <code>enable</code> state.
*
* @since 1.2
*/
@Override
public Level getThreshold() {
return threshold;
}
/**
* {@inheritDoc}
*/
@Override
public ThrowableRenderer getThrowableRenderer() {
return throwableRenderer;
}
/**
* This method will return <code>true</code> if this repository is disabled for <code>level</code> object passed as
* parameter and <code>false</code> otherwise. See also the {@link #setThreshold(Level) threshold} emthod.
*/
@Override
public boolean isDisabled(final int level) {
return thresholdInt > level;
}
/**
* @deprecated Deprecated with no replacement.
*/
@Deprecated
public void overrideAsNeeded(final String override) {
LogLog.warn("The Hiearchy.overrideAsNeeded method has been deprecated.");
}
/**
* Resets all values contained in this hierarchy instance to their default. This removes all appenders from all
* categories, sets the level of all non-root categories to <code>null</code>, sets their additivity flag to
* <code>true</code> and sets the level of the root logger to {@link Level#DEBUG DEBUG}. Moreover, message disabling is
* set its default "off" value.
*
* <p>
* Existing categories are not removed. They are just reset.
* </p>
*
* <p>
* This method should be used sparingly and with care as it will block all logging until it is completed.
* </p>
*
* @since 0.8.5
*/
@Override
public void resetConfiguration() {
resetConfiguration(getContext());
}
void resetConfiguration(final ClassLoader classLoader) {
resetConfiguration(getContext(classLoader));
}
void resetConfiguration(final LoggerContext loggerContext) {
getLoggersMap(loggerContext).clear();
getRootLogger().setLevel(Level.DEBUG);
root.setResourceBundle(null);
setThreshold(Level.ALL);
// the synchronization is needed to prevent JDK 1.2.x hashtable
// surprises
synchronized (ht) {
shutdown(); // nested locks are OK
final Enumeration cats = getCurrentLoggers();
while (cats.hasMoreElements()) {
final Logger c = (Logger) cats.nextElement();
c.setLevel(null);
c.setAdditivity(true);
c.setResourceBundle(null);
}
}
rendererMap.clear();
throwableRenderer = null;
}
/**
* Does nothing.
*
* @deprecated Deprecated with no replacement.
*/
@Deprecated
public void setDisableOverride(final String override) {
LogLog.warn("The Hiearchy.setDisableOverride method has been deprecated.");
}
/**
* Used by subclasses to add a renderer to the hierarchy passed as parameter.
*/
@Override
public void setRenderer(final Class renderedClass, final ObjectRenderer renderer) {
rendererMap.put(renderedClass, renderer);
}
/**
* Enable logging for logging requests with level <code>l</code> or higher. By default all levels are enabled.
*
* @param level The minimum level for which logging requests are sent to their appenders.
*/
@Override
public void setThreshold(final Level level) {
if (level != null) {
thresholdInt = level.level;
threshold = level;
}
}
/**
* The string form of {@link #setThreshold(Level)}.
*/
@Override
public void setThreshold(final String levelStr) {
final Level level = OptionConverter.toLevel(levelStr, null);
if (level != null) {
setThreshold(level);
} else {
LogLog.warn("Could not convert [" + levelStr + "] to Level.");
}
}
/**
* {@inheritDoc}
*/
@Override
public void setThrowableRenderer(final ThrowableRenderer throwableRenderer) {
this.throwableRenderer = throwableRenderer;
}
/**
* Shutting down a hierarchy will <em>safely</em> close and remove all appenders in all categories including the root
* logger.
*
* <p>
* Some appenders such as {@link org.apache.log4j.net.SocketAppender} and {@link AsyncAppender} need to be closed before
* the application exists. Otherwise, pending logging events might be lost.
* </p>
* <p>
* The <code>shutdown</code> method is careful to close nested appenders before closing regular appenders. This is
* allows configurations where a regular appender is attached to a logger and again to a nested appender.
* </p>
*
* @since 1.0
*/
@Override
public void shutdown() {
shutdown(getContext());
}
public void shutdown(final ClassLoader classLoader) {
shutdown(org.apache.logging.log4j.LogManager.getContext(classLoader, false));
}
void shutdown(final LoggerContext context) {
// final Logger root = getRootLogger();
// // begin by closing nested appenders
// root.closeNestedAppenders();
//
// synchronized (ht) {
// Enumeration cats = this.getCurrentLoggers();
// while (cats.hasMoreElements()) {
// final Logger c = (Logger) cats.nextElement();
// c.closeNestedAppenders();
// }
//
// // then, remove all appenders
// root.removeAllAppenders();
// cats = this.getCurrentLoggers();
// while (cats.hasMoreElements()) {
// final Logger c = (Logger) cats.nextElement();
// c.removeAllAppenders();
// }
// }
getLoggersMap(context).clear();
if (LogManager.isLog4jCorePresent()) {
ContextUtil.shutdown(context);
}
}
}
| is |
java | netty__netty | transport/src/test/java/io/netty/nativeimage/ChannelHandlerMetadataUtil.java | {
"start": 8125,
"end": 9206
} | class ____ {
final String name;
final Condition condition;
final boolean queryAllPublicMethods;
HandlerMetadata(String name, Condition condition, boolean queryAllPublicMethods) {
this.name = name;
this.condition = condition;
this.queryAllPublicMethods = queryAllPublicMethods;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HandlerMetadata that = (HandlerMetadata) o;
return queryAllPublicMethods == that.queryAllPublicMethods
&& (name != null && name.equals(that.name))
&& (condition != null && condition.equals(that.condition));
}
@Override
public int hashCode() {
return name.hashCode();
}
}
}
| HandlerMetadata |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/opensaml5Main/java/org/springframework/security/saml2/provider/service/authentication/logout/OpenSaml5LogoutRequestValidator.java | {
"start": 858,
"end": 1254
} | class ____ implements Saml2LogoutRequestValidator {
@SuppressWarnings("deprecation")
private final Saml2LogoutRequestValidator delegate = new BaseOpenSamlLogoutRequestValidator(
new OpenSaml5Template());
@Override
public Saml2LogoutValidatorResult validate(Saml2LogoutRequestValidatorParameters parameters) {
return this.delegate.validate(parameters);
}
}
| OpenSaml5LogoutRequestValidator |
java | elastic__elasticsearch | x-pack/plugin/slm/src/internalClusterTest/java/org/elasticsearch/xpack/slm/SLMHealthBlockedSnapshotIT.java | {
"start": 6091,
"end": 15213
} | class ____ extends FsRepository {
private static final String TYPE = "delayed";
private final Runnable delayFn;
protected TestDelayedRepo(
ProjectId projectId,
RepositoryMetadata metadata,
Environment env,
NamedXContentRegistry namedXContentRegistry,
ClusterService clusterService,
BigArrays bigArrays,
RecoverySettings recoverySettings,
Runnable delayFn
) {
super(projectId, metadata, env, namedXContentRegistry, clusterService, bigArrays, recoverySettings);
this.delayFn = delayFn;
}
@Override
protected void snapshotFile(SnapshotShardContext context, BlobStoreIndexShardSnapshot.FileInfo fileInfo) throws IOException {
delayFn.run();
super.snapshotFile(context, fileInfo);
}
}
public void testSlmHealthYellowWithBlockedSnapshot() throws Exception {
final String repoName = "test-repo";
internalCluster().startMasterOnlyNodes(1);
final String masterNode = internalCluster().getMasterName();
final String dataNode = internalCluster().startDataOnlyNode();
ensureStableCluster(2);
createRepository(repoName, TestDelayedRepo.TYPE);
String idxName = "test-index";
String policyHealthy = "policy-health";
String policyHealthyBelowThreshold = "policy-health-below-threshold";
String policyUnhealthy = "policy-unhealthy";
List<String> policyNames = List.of(policyHealthy, policyHealthyBelowThreshold, policyUnhealthy);
List<String> policyNamesUnhealthy = List.of(policyUnhealthy);
createRandomIndex(idxName);
putSnapshotPolicy(policyHealthy, "snap", NEVER_EXECUTE_CRON_SCHEDULE, repoName, idxName, null);
// 1hr unhealthyIfNoSnapshotWithin should not be exceeded during test period, so policy is healthy
putSnapshotPolicy(policyHealthyBelowThreshold, "snap", NEVER_EXECUTE_CRON_SCHEDULE, repoName, idxName, TimeValue.ONE_HOUR);
// zero unhealthyIfNoSnapshotWithin will always be exceeded, so policy is always unhealthy
putSnapshotPolicy(policyUnhealthy, "snap", NEVER_EXECUTE_CRON_SCHEDULE, repoName, idxName, TimeValue.ZERO);
ensureGreen();
// allow snapshots to run
TestDelayedRepoPlugin.disable();
// create a successful snapshot, so there's baseline time to check against missing snapshot threshold
List<String> firstSnapshots = executePolicies(masterNode, policyNames);
waitForSnapshotsAndClusterState(repoName, firstSnapshots);
// block snapshot execution, create second set of snapshots, assert YELLOW health
TestDelayedRepoPlugin.enable();
List<String> secondSnapshots = executePolicies(masterNode, policyNames);
assertSlmYellowMissingSnapshot(policyNamesUnhealthy);
// resume snapshot execution
TestDelayedRepoPlugin.removeDelay();
waitForSnapshotsAndClusterState(repoName, secondSnapshots);
// increase policy unhealthy threshold, assert GREEN health
putSnapshotPolicy(policyUnhealthy, "snap", NEVER_EXECUTE_CRON_SCHEDULE, repoName, idxName, TimeValue.ONE_HOUR);
assertBusy(() -> {
GetHealthAction.Request getHealthRequest = new GetHealthAction.Request(true, 1000);
GetHealthAction.Response health = admin().cluster().execute(GetHealthAction.INSTANCE, getHealthRequest).get();
assertThat(health.getStatus(), equalTo(HealthStatus.GREEN));
});
}
private void createRandomIndex(String idxName) throws InterruptedException {
createIndex(idxName);
logger.info("--> indexing some data");
final int numdocs = randomIntBetween(10, 100);
IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs];
for (int i = 0; i < builders.length; i++) {
builders[i] = prepareIndex(idxName).setId(Integer.toString(i)).setSource("field1", "bar " + i);
}
indexRandom(true, builders);
indicesAdmin().refresh(new RefreshRequest(idxName)).actionGet();
}
private void putSnapshotPolicy(
String policyName,
String snapshotNamePattern,
String schedule,
String repoId,
String indexPattern,
TimeValue unhealthyIfNoSnapshotWithin
) throws ExecutionException, InterruptedException {
Map<String, Object> snapConfig = new HashMap<>();
snapConfig.put("indices", Collections.singletonList(indexPattern));
snapConfig.put("ignore_unavailable", false);
snapConfig.put("partial", true);
SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy(
policyName,
snapshotNamePattern,
schedule,
repoId,
snapConfig,
SnapshotRetentionConfiguration.EMPTY,
unhealthyIfNoSnapshotWithin
);
PutSnapshotLifecycleAction.Request putLifecycle = new PutSnapshotLifecycleAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
policyName,
policy
);
client().execute(PutSnapshotLifecycleAction.INSTANCE, putLifecycle).get();
}
private void assertSlmYellowMissingSnapshot(List<String> unhealthyPolicies) throws Exception {
assertBusy(() -> {
GetHealthAction.Request getHealthRequest = new GetHealthAction.Request(true, 1000);
GetHealthAction.Response health = admin().cluster().execute(GetHealthAction.INSTANCE, getHealthRequest).get();
assertThat(health.getStatus(), equalTo(HealthStatus.YELLOW));
HealthIndicatorResult slmIndicator = health.findIndicator(SlmHealthIndicatorService.NAME);
assertThat(slmIndicator.status(), equalTo(HealthStatus.YELLOW));
assertThat(slmIndicator.impacts().size(), equalTo(1));
assertThat(slmIndicator.impacts().getFirst().id(), equalTo(SlmHealthIndicatorService.MISSING_SNAPSHOT_IMPACT_ID));
List<HealthIndicatorImpact> missingSnapshotPolicies = slmIndicator.impacts()
.stream()
.filter(impact -> SlmHealthIndicatorService.MISSING_SNAPSHOT_IMPACT_ID.equals(impact.id()))
.toList();
assertThat(missingSnapshotPolicies.size(), equalTo(unhealthyPolicies.size()));
// validate affected policy names
assertThat(slmIndicator.diagnosisList().size(), equalTo(1));
Diagnosis diagnosis = slmIndicator.diagnosisList().getFirst();
List<Diagnosis.Resource> resources = diagnosis.affectedResources();
assertThat(resources, notNullValue());
assertThat(resources.size(), equalTo(1));
assertThat(resources.getFirst().getValues(), equalTo(unhealthyPolicies));
});
}
private List<String> executePolicies(String node, List<String> policies) throws Exception {
List<String> snapshots = new ArrayList<>();
for (String policyName : policies) {
snapshots.add(executePolicy(node, policyName));
}
return snapshots;
}
/**
* Execute the given policy and return the generated snapshot name
*/
private String executePolicy(String node, String policyId) throws ExecutionException, InterruptedException {
ExecuteSnapshotLifecycleAction.Request executeReq = new ExecuteSnapshotLifecycleAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
policyId
);
ExecuteSnapshotLifecycleAction.Response resp = client(node).execute(ExecuteSnapshotLifecycleAction.INSTANCE, executeReq).get();
return resp.getSnapshotName();
}
private void waitForSnapshotsAndClusterState(String repo, List<String> snapshots) throws Exception {
for (String snapshot : snapshots) {
waitForSnapshot(repo, snapshot);
}
assertBusy(() -> assertTrue(SnapshotsInProgress.get(internalCluster().clusterService().state()).isEmpty()));
}
private void waitForSnapshot(String repo, String snapshotName) throws Exception {
assertBusy(() -> {
try {
SnapshotsStatusResponse s = getSnapshotStatus(repo, snapshotName);
assertThat("expected a snapshot but none were returned", s.getSnapshots().size(), equalTo(1));
SnapshotStatus status = s.getSnapshots().get(0);
logger.info("--> waiting for snapshot {} to be completed, got: {}", snapshotName, status.getState());
assertThat(status.getState(), equalTo(SnapshotsInProgress.State.SUCCESS));
} catch (SnapshotMissingException e) {
fail("expected a snapshot with name " + snapshotName + " but it does not exist");
}
});
}
private SnapshotsStatusResponse getSnapshotStatus(String repo, String snapshotName) {
return clusterAdmin().prepareSnapshotStatus(TEST_REQUEST_TIMEOUT, repo).setSnapshots(snapshotName).get();
}
}
| TestDelayedRepo |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/util/FailureMessages.java | {
"start": 691,
"end": 961
} | class ____ {
public static String actualIsEmpty() {
return "%nExpecting actual not to be empty".formatted();
}
public static String actualIsNull() {
return "%nExpecting actual not to be null".formatted();
}
private FailureMessages() {}
}
| FailureMessages |
java | apache__kafka | metadata/src/main/java/org/apache/kafka/metadata/util/SnapshotFileReader.java | {
"start": 7201,
"end": 7738
} | class ____ implements EventQueue.Event {
@Override
public void run() throws Exception {
if (fileRecords != null) {
fileRecords.close();
fileRecords = null;
}
batchIterator = null;
}
@Override
public void handleException(Throwable e) {
log.error("shutdown error", e);
}
}
@Override
public void close() throws Exception {
beginShutdown("closing");
queue.close();
}
}
| ShutdownEvent |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_1482/Source2.java | {
"start": 228,
"end": 662
} | class ____ {
private Enum<SourceEnum> test;
private ValueWrapper<BigDecimal> wrapper;
public Enum<SourceEnum> getTest() {
return test;
}
public void setTest(Enum<SourceEnum> test) {
this.test = test;
}
public ValueWrapper<BigDecimal> getWrapper() {
return wrapper;
}
public void setWrapper(ValueWrapper<BigDecimal> wrapper) {
this.wrapper = wrapper;
}
}
| Source2 |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/qualifiers/RepeatingQualifierClassTest.java | {
"start": 516,
"end": 2119
} | class ____ {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(Location.class, Locations.class, SomePlace.class, Home.class,
FarAway.class, Work.class, NotAQualifier.class, InjectingBean.class);
@Test
public void testRepeatingQualifiers() {
ArcContainer container = Arc.container();
// simple resolution with just one instance of repeatable qualifier
InstanceHandle<SomePlace> home = container.instance(SomePlace.class, new Location.Literal("home"));
Assertions.assertTrue(home.isAvailable());
// resolution when we select a bean having two repeatable qualifiers but only using one
InstanceHandle<SomePlace> farAway = container.instance(SomePlace.class, new Location.Literal("farAway"));
Assertions.assertTrue(farAway.isAvailable());
// resolution where we select a bean having two repeatable qualifiers using both
InstanceHandle<SomePlace> work = container.instance(SomePlace.class, new Location.Literal("work"),
new Location.Literal("office"));
Assertions.assertTrue(work.isAvailable());
InjectingBean injectingBean = container.instance(InjectingBean.class).get();
Assertions.assertNotNull(injectingBean.getFarAway());
Assertions.assertNotNull(injectingBean.getHome());
Assertions.assertNotNull(injectingBean.getWork());
Assertions.assertNotNull(injectingBean.getLocationFromInitializer());
}
@Singleton
@Location("home")
@NotAQualifier("ignored")
public static | RepeatingQualifierClassTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/Endpoint2MustBeStartedBeforeSendProcessorTest.java | {
"start": 5158,
"end": 5518
} | class ____ extends DefaultConsumer {
MyConsumer(Endpoint endpoint, Processor processor) {
super(endpoint, processor);
}
@Override
protected void doStart() {
order += "Consumer";
}
@Override
protected void doStop() {
order += "StopConsumer";
}
}
}
| MyConsumer |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceOrderIntegrationTests.java | {
"start": 1402,
"end": 1582
} | class ____ {
@Nested
@SpringJUnitConfig(locations = "AopNamespaceHandlerAdviceOrderIntegrationTests-afterFirst.xml")
@DirtiesContext
| AopNamespaceHandlerAdviceOrderIntegrationTests |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/schedulers/ScheduledRunnableTest.java | {
"start": 1196,
"end": 13455
} | class ____ extends RxJavaTest {
@Test
public void dispose() {
CompositeDisposable set = new CompositeDisposable();
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
assertFalse(run.isDisposed());
set.dispose();
assertTrue(run.isDisposed());
}
@Test
public void disposeRun() {
CompositeDisposable set = new CompositeDisposable();
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
assertFalse(run.isDisposed());
run.dispose();
run.dispose();
assertTrue(run.isDisposed());
}
@Test
public void setFutureCancelRace() {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
CompositeDisposable set = new CompositeDisposable();
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
final FutureTask<Object> ft = new FutureTask<>(Functions.EMPTY_RUNNABLE, 0);
Runnable r1 = new Runnable() {
@Override
public void run() {
run.setFuture(ft);
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
run.dispose();
}
};
TestHelper.race(r1, r2);
assertEquals(0, set.size());
}
}
@Test
public void setFutureRunRace() {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
CompositeDisposable set = new CompositeDisposable();
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
final FutureTask<Object> ft = new FutureTask<>(Functions.EMPTY_RUNNABLE, 0);
Runnable r1 = new Runnable() {
@Override
public void run() {
run.setFuture(ft);
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
run.run();
}
};
TestHelper.race(r1, r2);
assertEquals(0, set.size());
}
}
@Test
public void disposeRace() {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
CompositeDisposable set = new CompositeDisposable();
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
Runnable r1 = new Runnable() {
@Override
public void run() {
run.dispose();
}
};
TestHelper.race(r1, r1);
assertEquals(0, set.size());
}
}
@Test
public void runDispose() {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
CompositeDisposable set = new CompositeDisposable();
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
Runnable r1 = new Runnable() {
@Override
public void run() {
run.call();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
run.dispose();
}
};
TestHelper.race(r1, r2);
assertEquals(0, set.size());
}
}
@Test
public void pluginCrash() {
Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
throw new TestException("Second");
}
});
CompositeDisposable set = new CompositeDisposable();
final ScheduledRunnable run = new ScheduledRunnable(new Runnable() {
@Override
public void run() {
throw new TestException("First");
}
}, set);
set.add(run);
try {
run.run();
fail("Should have thrown!");
} catch (TestException ex) {
assertEquals("Second", ex.getMessage());
} finally {
Thread.currentThread().setUncaughtExceptionHandler(null);
}
assertTrue(run.isDisposed());
assertEquals(0, set.size());
}
@Test
public void crashReported() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
CompositeDisposable set = new CompositeDisposable();
final ScheduledRunnable run = new ScheduledRunnable(new Runnable() {
@Override
public void run() {
throw new TestException("First");
}
}, set);
set.add(run);
try {
run.run();
fail("Should have thrown!");
} catch (TestException expected) {
// expected
}
assertTrue(run.isDisposed());
assertEquals(0, set.size());
TestHelper.assertUndeliverable(errors, 0, TestException.class, "First");
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void withoutParentDisposed() {
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
run.dispose();
run.call();
}
@Test
public void withParentDisposed() {
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, new CompositeDisposable());
run.dispose();
run.call();
}
@Test
public void withFutureDisposed() {
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
run.setFuture(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null));
run.dispose();
run.call();
}
@Test
public void withFutureDisposed2() {
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
run.dispose();
run.setFuture(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null));
run.call();
}
@Test
public void withFutureDisposed3() {
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
run.dispose();
run.set(2, Thread.currentThread());
run.setFuture(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null));
run.call();
}
@Test
public void runFuture() {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
CompositeDisposable set = new CompositeDisposable();
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
final FutureTask<Void> ft = new FutureTask<>(Functions.EMPTY_RUNNABLE, null);
Runnable r1 = new Runnable() {
@Override
public void run() {
run.call();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
run.setFuture(ft);
}
};
TestHelper.race(r1, r2);
}
}
@Test
public void syncWorkerCancelRace() {
for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
final CompositeDisposable set = new CompositeDisposable();
final AtomicBoolean interrupted = new AtomicBoolean();
final AtomicInteger sync = new AtomicInteger(2);
final AtomicInteger syncb = new AtomicInteger(2);
Runnable r0 = new Runnable() {
@Override
public void run() {
set.dispose();
if (sync.decrementAndGet() != 0) {
while (sync.get() != 0) { }
}
if (syncb.decrementAndGet() != 0) {
while (syncb.get() != 0) { }
}
for (int j = 0; j < 1000; j++) {
if (Thread.currentThread().isInterrupted()) {
interrupted.set(true);
break;
}
}
}
};
final ScheduledRunnable run = new ScheduledRunnable(r0, set);
set.add(run);
final FutureTask<Void> ft = new FutureTask<>(run, null);
Runnable r2 = new Runnable() {
@Override
public void run() {
if (sync.decrementAndGet() != 0) {
while (sync.get() != 0) { }
}
run.setFuture(ft);
if (syncb.decrementAndGet() != 0) {
while (syncb.get() != 0) { }
}
}
};
TestHelper.race(ft, r2);
assertFalse("The task was interrupted", interrupted.get());
}
}
@Test
public void disposeAfterRun() {
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
run.run();
assertEquals(ScheduledRunnable.DONE, run.get(ScheduledRunnable.FUTURE_INDEX));
run.dispose();
assertEquals(ScheduledRunnable.DONE, run.get(ScheduledRunnable.FUTURE_INDEX));
}
@Test
public void syncDisposeIdempotent() {
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
run.set(ScheduledRunnable.THREAD_INDEX, Thread.currentThread());
run.dispose();
assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX));
run.dispose();
assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX));
run.run();
assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX));
}
@Test
public void asyncDisposeIdempotent() {
final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
run.dispose();
assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX));
run.dispose();
assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX));
run.run();
assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX));
}
@Test
public void noParentIsDisposed() {
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null);
assertFalse(run.isDisposed());
run.run();
assertTrue(run.isDisposed());
}
@Test
public void withParentIsDisposed() {
CompositeDisposable set = new CompositeDisposable();
ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
set.add(run);
assertFalse(run.isDisposed());
run.run();
assertTrue(run.isDisposed());
assertFalse(set.remove(run));
}
@Test
public void toStringStates() {
CompositeDisposable set = new CompositeDisposable();
ScheduledRunnable task = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
assertEquals("ScheduledRunnable[Waiting]", task.toString());
task.set(ScheduledRunnable.THREAD_INDEX, Thread.currentThread());
assertEquals("ScheduledRunnable[Running on " + Thread.currentThread() + "]", task.toString());
task.dispose();
assertEquals("ScheduledRunnable[Disposed(Sync)]", task.toString());
task.set(ScheduledRunnable.FUTURE_INDEX, ScheduledRunnable.DONE);
assertEquals("ScheduledRunnable[Finished]", task.toString());
task = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set);
task.dispose();
assertEquals("ScheduledRunnable[Disposed(Async)]", task.toString());
}
}
| ScheduledRunnableTest |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindyRecordFieldStartingWithSeperatorCharTest.java | {
"start": 1373,
"end": 3545
} | class ____ extends CamelTestSupport {
@EndpointInject("mock:result")
private MockEndpoint mockEndPoint;
@Test
public void testUnmarshallCsvRecordFieldStartingWithSeparatorChar() throws Exception {
mockEndPoint.expectedMessageCount(4);
template.sendBody("direct:start", "'val1',',val2',1");
template.sendBody("direct:start", "',',',val2',2");
template.sendBody("direct:start", "',','val2,',3");
template.sendBody("direct:start", "'',',val2,',4");
mockEndPoint.assertIsSatisfied();
BindyCsvRowFormat row = mockEndPoint.getExchanges().get(0).getIn().getBody(BindyCsvRowFormat.class);
assertEquals("val1", row.getFirstField());
assertEquals(",val2", row.getSecondField());
assertEquals(BigDecimal.valueOf(1), row.getNumber());
row = mockEndPoint.getExchanges().get(1).getIn().getBody(BindyCsvRowFormat.class);
assertEquals(",", row.getFirstField());
assertEquals(",val2", row.getSecondField());
assertEquals(BigDecimal.valueOf(2), row.getNumber());
row = mockEndPoint.getExchanges().get(2).getIn().getBody(BindyCsvRowFormat.class);
assertEquals(",", row.getFirstField());
assertEquals("val2,", row.getSecondField());
assertEquals(BigDecimal.valueOf(3), row.getNumber());
row = mockEndPoint.getExchanges().get(3).getIn().getBody(BindyCsvRowFormat.class);
assertEquals("", row.getFirstField());
assertEquals(",val2,", row.getSecondField());
assertEquals(BigDecimal.valueOf(4), row.getNumber());
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
BindyCsvDataFormat camelDataFormat = new BindyCsvDataFormat(BindyCsvRowFormat.class);
from("direct:start").unmarshal(camelDataFormat).to("mock:result");
}
};
}
//from https://issues.apache.org/jira/browse/CAMEL-11065
@SuppressWarnings("serial")
@CsvRecord(separator = ",", quote = "'")
public static | BindyRecordFieldStartingWithSeperatorCharTest |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/params/provider/EnumArgumentsProviderTests.java | {
"start": 2471,
"end": 2701
} | enum ____ name(s) found");
}
@Test
void invalidConstantNameIsDetected() {
assertPreconditionViolationFor(() -> provideArguments(EnumWithFourConstants.class, "FO0", "B4R").findAny())//
.withMessageContaining("Invalid | constant |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextScheduledExecutorService.java | {
"start": 1293,
"end": 3367
} | class ____ extends DelegatingSecurityContextExecutorService
implements ScheduledExecutorService {
/**
* Creates a new {@link DelegatingSecurityContextScheduledExecutorService} that uses
* the specified {@link SecurityContext}.
* @param delegateScheduledExecutorService the {@link ScheduledExecutorService} to
* delegate to. Cannot be null.
* @param securityContext the {@link SecurityContext} to use for each
* {@link DelegatingSecurityContextRunnable} and each
* {@link DelegatingSecurityContextCallable}.
*/
public DelegatingSecurityContextScheduledExecutorService(ScheduledExecutorService delegateScheduledExecutorService,
@Nullable SecurityContext securityContext) {
super(delegateScheduledExecutorService, securityContext);
}
/**
* Creates a new {@link DelegatingSecurityContextScheduledExecutorService} that uses
* the current {@link SecurityContext} from the {@link SecurityContextHolder}.
* @param delegate the {@link ScheduledExecutorService} to delegate to. Cannot be
* null.
*/
public DelegatingSecurityContextScheduledExecutorService(ScheduledExecutorService delegate) {
this(delegate, null);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return getDelegate().schedule(wrap(command), delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return getDelegate().schedule(wrap(callable), delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return getDelegate().scheduleAtFixedRate(wrap(command), initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return getDelegate().scheduleWithFixedDelay(wrap(command), initialDelay, delay, unit);
}
private ScheduledExecutorService getDelegate() {
return (ScheduledExecutorService) getDelegateExecutor();
}
}
| DelegatingSecurityContextScheduledExecutorService |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/StreamCachingStrategy.java | {
"start": 4753,
"end": 9463
} | class ____ can be separated by comma.
*/
void setDenyClasses(String names);
/**
* To filter stream caching of a given set of allowed/denied classes. By default, all classes that are
* {@link java.io.InputStream} is allowed.
*/
Collection<Class<?>> getDenyClasses();
/**
* Enables spooling to disk.
* <p/>
* <b>Notice:</b> This cannot be changed at runtime.
*
* Default is disabled.
*/
void setSpoolEnabled(boolean spoolEnabled);
/**
* Is spooling to disk enabled.
*/
boolean isSpoolEnabled();
/**
* Sets the spool (temporary) directory to use for overflow and spooling to disk.
* <p/>
* If no spool directory has been explicit configured, then a temporary directory is created in the
* <tt>java.io.tmpdir</tt> directory.
*/
void setSpoolDirectory(File path);
File getSpoolDirectory();
void setSpoolDirectory(String path);
/**
* Threshold in bytes when overflow to disk is activated.
* <p/>
* The default threshold is {@link org.apache.camel.StreamCache#DEFAULT_SPOOL_THRESHOLD} bytes (eg 128kb). Use
* <tt>-1</tt> to disable overflow to disk.
*/
void setSpoolThreshold(long threshold);
long getSpoolThreshold();
/**
* Sets a percentage (1-99) of used heap memory threshold to activate spooling to disk.
*
* @param percentage percentage of used heap memory.
*/
void setSpoolUsedHeapMemoryThreshold(int percentage);
int getSpoolUsedHeapMemoryThreshold();
/**
* Sets what the upper bounds should be when {@link #setSpoolUsedHeapMemoryThreshold(int)} is in use.
*
* @param bounds the bounds
*/
void setSpoolUsedHeapMemoryLimit(SpoolUsedHeapMemoryLimit bounds);
SpoolUsedHeapMemoryLimit getSpoolUsedHeapMemoryLimit();
/**
* Sets the buffer size to use when allocating in-memory buffers used for in-memory stream caches.
* <p/>
* The default size is {@link org.apache.camel.util.IOHelper#DEFAULT_BUFFER_SIZE}
*/
void setBufferSize(int bufferSize);
int getBufferSize();
/**
* Sets a cipher name to use when spooling to disk to write with encryption.
* <p/>
* By default the data is not encrypted.
*/
void setSpoolCipher(String cipher);
String getSpoolCipher();
/**
* Whether to remove the temporary directory when stopping.
* <p/>
* This option is default <tt>true</tt>
*/
void setRemoveSpoolDirectoryWhenStopping(boolean remove);
boolean isRemoveSpoolDirectoryWhenStopping();
/**
* Sets whether if just any of the {@link org.apache.camel.spi.StreamCachingStrategy.SpoolRule} rules returns
* <tt>true</tt> then {@link #shouldSpoolCache(long)} returns <tt>true</tt>. If this option is <tt>false</tt>, then
* <b>all</b> the {@link org.apache.camel.spi.StreamCachingStrategy.SpoolRule} must return <tt>true</tt>.
* <p/>
* The default value is <tt>false</tt> which means that all the rules must return <tt>true</tt>.
*/
void setAnySpoolRules(boolean any);
boolean isAnySpoolRules();
/**
* Gets the utilization statistics.
*/
Statistics getStatistics();
/**
* Adds the {@link org.apache.camel.spi.StreamCachingStrategy.SpoolRule} rule to be used.
*/
void addSpoolRule(SpoolRule rule);
/**
* Determines if the stream should be spooled or not. For example if the stream length is over a threshold.
* <p/>
* This allows implementations to use custom strategies to determine if spooling is needed or not.
*
* @param length the length of the stream
* @return <tt>true</tt> to spool the cache, or <tt>false</tt> to keep the cache in-memory
*/
boolean shouldSpoolCache(long length);
/**
* Caches the body aas a {@link StreamCache}.
*
* @param exchange the exchange
* @return the body cached as a {@link StreamCache}, or <tt>null</tt> if not possible or no need to cache
* the body
*/
StreamCache cache(Exchange exchange);
/**
* Caches the body aas a {@link StreamCache}.
*
* @param message the message
* @return the body cached as a {@link StreamCache}, or <tt>null</tt> if not possible or no need to cache
* the body
*/
StreamCache cache(Message message);
/**
* Caches the value aas a {@link StreamCache}.
*
* @param value the value
* @return the value cached as a {@link StreamCache}, or <tt>null</tt> if not possible or no need to cache
*/
StreamCache cache(Object value);
}
| names |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/resettable/SpillingResettableMutableObjectIterator.java | {
"start": 1946,
"end": 8428
} | class ____<T>
implements ResettableMutableObjectIterator<T> {
private static final Logger LOG =
LoggerFactory.getLogger(SpillingResettableMutableObjectIterator.class);
// ------------------------------------------------------------------------
protected DataInputView inView;
protected final TypeSerializer<T> serializer;
private long elementCount;
private long currentElementNum;
protected final SpillingBuffer buffer;
protected final MutableObjectIterator<T> input;
protected final MemoryManager memoryManager;
private final List<MemorySegment> memorySegments;
private final boolean releaseMemoryOnClose;
// ------------------------------------------------------------------------
public SpillingResettableMutableObjectIterator(
MutableObjectIterator<T> input,
TypeSerializer<T> serializer,
MemoryManager memoryManager,
IOManager ioManager,
int numPages,
AbstractInvokable parentTask)
throws MemoryAllocationException {
this(
input,
serializer,
memoryManager,
ioManager,
memoryManager.allocatePages(parentTask, numPages),
true);
}
public SpillingResettableMutableObjectIterator(
MutableObjectIterator<T> input,
TypeSerializer<T> serializer,
MemoryManager memoryManager,
IOManager ioManager,
List<MemorySegment> memory) {
this(input, serializer, memoryManager, ioManager, memory, false);
}
private SpillingResettableMutableObjectIterator(
MutableObjectIterator<T> input,
TypeSerializer<T> serializer,
MemoryManager memoryManager,
IOManager ioManager,
List<MemorySegment> memory,
boolean releaseMemOnClose) {
this.memoryManager = memoryManager;
this.input = input;
this.serializer = serializer;
this.memorySegments = memory;
this.releaseMemoryOnClose = releaseMemOnClose;
if (LOG.isDebugEnabled()) {
LOG.debug(
"Creating spilling resettable iterator with "
+ memory.size()
+ " pages of memory.");
}
this.buffer =
new SpillingBuffer(
ioManager,
new ListMemorySegmentSource(memory),
memoryManager.getPageSize());
}
public void open() {}
@Override
public void reset() throws IOException {
this.inView = this.buffer.flip();
this.currentElementNum = 0;
}
public List<MemorySegment> close() throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Spilling Resettable Iterator closing. Stored "
+ this.elementCount
+ " records.");
}
this.inView = null;
final List<MemorySegment> memory = this.buffer.close();
memory.addAll(this.memorySegments);
this.memorySegments.clear();
if (this.releaseMemoryOnClose) {
this.memoryManager.release(memory);
return Collections.emptyList();
} else {
return memory;
}
}
@Override
public T next(T reuse) throws IOException {
if (this.inView != null) {
// reading, any subsequent pass
if (this.currentElementNum < this.elementCount) {
try {
reuse = this.serializer.deserialize(reuse, this.inView);
} catch (IOException e) {
throw new RuntimeException(
"SpillingIterator: Error reading element from buffer.", e);
}
this.currentElementNum++;
return reuse;
} else {
return null;
}
} else {
// writing pass (first)
if ((reuse = this.input.next(reuse)) != null) {
try {
this.serializer.serialize(reuse, this.buffer);
} catch (IOException e) {
throw new RuntimeException(
"SpillingIterator: Error writing element to buffer.", e);
}
this.elementCount++;
return reuse;
} else {
return null;
}
}
}
@Override
public T next() throws IOException {
T result = null;
if (this.inView != null) {
// reading, any subsequent pass
if (this.currentElementNum < this.elementCount) {
try {
result = this.serializer.deserialize(this.inView);
} catch (IOException e) {
throw new RuntimeException(
"SpillingIterator: Error reading element from buffer.", e);
}
this.currentElementNum++;
return result;
} else {
return null;
}
} else {
// writing pass (first)
if ((result = this.input.next()) != null) {
try {
this.serializer.serialize(result, this.buffer);
} catch (IOException e) {
throw new RuntimeException(
"SpillingIterator: Error writing element to buffer.", e);
}
this.elementCount++;
return result;
} else {
return null;
}
}
}
public void consumeAndCacheRemainingData() throws IOException {
// check that we are in the first pass and that more input data is left
if (this.inView == null) {
T holder = this.serializer.createInstance();
while ((holder = this.input.next(holder)) != null) {
try {
this.serializer.serialize(holder, this.buffer);
} catch (IOException e) {
throw new RuntimeException(
"SpillingIterator: Error writing element to buffer.", e);
}
this.elementCount++;
}
}
}
}
| SpillingResettableMutableObjectIterator |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/volume/csi/exception/VolumeException.java | {
"start": 989,
"end": 1189
} | class ____ extends YarnException {
public VolumeException(String message) {
super(message);
}
public VolumeException(String message, Exception e) {
super(message, e);
}
}
| VolumeException |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/sql/RouterStoreTokenHandler.java | {
"start": 1423,
"end": 3365
} | class ____ implements ResultSetHandler<RouterStoreToken> {
private final static String TOKENIDENT_OUT = "tokenIdent_OUT";
private final static String TOKEN_OUT = "token_OUT";
private final static String RENEWDATE_OUT = "renewDate_OUT";
@Override
public RouterStoreToken handle(Object... params) throws SQLException {
RouterStoreToken storeToken = Records.newRecord(RouterStoreToken.class);
for (Object param : params) {
if (param instanceof FederationSQLOutParameter) {
FederationSQLOutParameter parameter = (FederationSQLOutParameter) param;
String paramName = parameter.getParamName();
Object parmaValue = parameter.getValue();
if (StringUtils.equalsIgnoreCase(paramName, TOKENIDENT_OUT)) {
YARNDelegationTokenIdentifier identifier = getYARNDelegationTokenIdentifier(parmaValue);
storeToken.setIdentifier(identifier);
} else if (StringUtils.equalsIgnoreCase(paramName, TOKEN_OUT)) {
String tokenInfo = getTokenInfo(parmaValue);
storeToken.setTokenInfo(tokenInfo);
} else if(StringUtils.equalsIgnoreCase(paramName, RENEWDATE_OUT)){
Long renewDate = getRenewDate(parmaValue);
storeToken.setRenewDate(renewDate);
}
}
}
return storeToken;
}
private YARNDelegationTokenIdentifier getYARNDelegationTokenIdentifier(Object tokenIdent)
throws SQLException {
try {
YARNDelegationTokenIdentifier resultIdentifier =
Records.newRecord(YARNDelegationTokenIdentifier.class);
decodeWritable(resultIdentifier, String.valueOf(tokenIdent));
return resultIdentifier;
} catch (IOException e) {
throw new SQLException(e);
}
}
private String getTokenInfo(Object tokenInfo) {
return String.valueOf(tokenInfo);
}
private Long getRenewDate(Object renewDate) {
return Long.parseLong(String.valueOf(renewDate));
}
}
| RouterStoreTokenHandler |
java | spring-projects__spring-boot | module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/autoconfigure/RabbitStreamConfigurationTests.java | {
"start": 2549,
"end": 11921
} | class ____ {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class));
@Test
@SuppressWarnings("unchecked")
void whenListenerTypeIsStreamThenStreamListenerContainerAndEnvironmentAreAutoConfigured() {
this.contextRunner.withUserConfiguration(TestConfiguration.class)
.withPropertyValues("spring.rabbitmq.listener.type:stream")
.run((context) -> {
RabbitListenerEndpointRegistry registry = context.getBean(RabbitListenerEndpointRegistry.class);
MessageListenerContainer listenerContainer = registry.getListenerContainer("test");
assertThat(listenerContainer).isInstanceOf(StreamListenerContainer.class);
assertThat(listenerContainer).extracting("consumerCustomizer").isNotNull();
assertThat(context.getBean(StreamRabbitListenerContainerFactory.class))
.extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN)
.isFalse();
then(context.getBean(ContainerCustomizer.class)).should().configure(listenerContainer);
assertThat(context).hasSingleBean(Environment.class);
});
}
@Test
void whenNativeListenerIsEnabledThenContainerFactoryIsConfiguredToUseNativeListeners() {
this.contextRunner
.withPropertyValues("spring.rabbitmq.listener.type:stream",
"spring.rabbitmq.listener.stream.native-listener:true")
.run((context) -> assertThat(context.getBean(StreamRabbitListenerContainerFactory.class))
.extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN)
.isTrue());
}
@Test
void shouldConfigureObservations() {
this.contextRunner
.withPropertyValues("spring.rabbitmq.listener.type:stream",
"spring.rabbitmq.listener.stream.observation-enabled:true")
.run((context) -> assertThat(context.getBean(StreamRabbitListenerContainerFactory.class))
.extracting("observationEnabled", InstanceOfAssertFactories.BOOLEAN)
.isTrue());
}
@Test
void environmentIsAutoConfiguredByDefault() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Environment.class));
}
@Test
void whenCustomEnvironmentIsDefinedThenAutoConfiguredEnvironmentBacksOff() {
this.contextRunner.withUserConfiguration(CustomEnvironmentConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(Environment.class);
assertThat(context.getBean(Environment.class))
.isSameAs(context.getBean(CustomEnvironmentConfiguration.class).environment);
});
}
@Test
void whenCustomMessageListenerContainerFactoryIsDefinedThenAutoConfiguredContainerFactoryBacksOff() {
this.contextRunner.withUserConfiguration(CustomMessageListenerContainerFactoryConfiguration.class)
.run((context) -> {
assertThat(context).hasSingleBean(RabbitListenerContainerFactory.class);
assertThat(context.getBean(RabbitListenerContainerFactory.class)).isSameAs(context
.getBean(CustomMessageListenerContainerFactoryConfiguration.class).listenerContainerFactory);
});
}
@Test
void environmentUsesConnectionDetailsByDefault() {
EnvironmentBuilder builder = mock(EnvironmentBuilder.class);
RabbitProperties properties = new RabbitProperties();
RabbitStreamConfiguration.configure(builder, properties,
new TestRabbitConnectionDetails("guest", "guest", "vhost"));
then(builder).should().port(5552);
then(builder).should().host("localhost");
then(builder).should().virtualHost("vhost");
then(builder).should().lazyInitialization(true);
then(builder).should().username("guest");
then(builder).should().password("guest");
then(builder).shouldHaveNoMoreInteractions();
}
@Test
void whenStreamPortIsSetThenEnvironmentUsesCustomPort() {
EnvironmentBuilder builder = mock(EnvironmentBuilder.class);
RabbitProperties properties = new RabbitProperties();
properties.getStream().setPort(5553);
RabbitStreamConfiguration.configure(builder, properties,
new TestRabbitConnectionDetails("guest", "guest", "vhost"));
then(builder).should().port(5553);
}
@Test
void whenStreamHostIsSetThenEnvironmentUsesCustomHost() {
EnvironmentBuilder builder = mock(EnvironmentBuilder.class);
RabbitProperties properties = new RabbitProperties();
properties.getStream().setHost("stream.rabbit.example.com");
RabbitStreamConfiguration.configure(builder, properties,
new TestRabbitConnectionDetails("guest", "guest", "vhost"));
then(builder).should().host("stream.rabbit.example.com");
}
@Test
void whenStreamVirtualHostIsSetThenEnvironmentUsesCustomVirtualHost() {
EnvironmentBuilder builder = mock(EnvironmentBuilder.class);
RabbitProperties properties = new RabbitProperties();
properties.getStream().setVirtualHost("stream-virtual-host");
RabbitStreamConfiguration.configure(builder, properties,
new TestRabbitConnectionDetails("guest", "guest", "vhost"));
then(builder).should().virtualHost("stream-virtual-host");
}
@Test
void whenStreamVirtualHostIsNotSetButDefaultVirtualHostIsSetThenEnvironmentUsesDefaultVirtualHost() {
EnvironmentBuilder builder = mock(EnvironmentBuilder.class);
RabbitProperties properties = new RabbitProperties();
properties.setVirtualHost("properties-virtual-host");
RabbitStreamConfiguration.configure(builder, properties,
new TestRabbitConnectionDetails("guest", "guest", "default-virtual-host"));
then(builder).should().virtualHost("default-virtual-host");
}
@Test
void whenStreamCredentialsAreNotSetThenEnvironmentUsesConnectionDetailsCredentials() {
EnvironmentBuilder builder = mock(EnvironmentBuilder.class);
RabbitProperties properties = new RabbitProperties();
properties.setUsername("alice");
properties.setPassword("secret");
RabbitStreamConfiguration.configure(builder, properties,
new TestRabbitConnectionDetails("bob", "password", "vhost"));
then(builder).should().username("bob");
then(builder).should().password("password");
}
@Test
void whenStreamCredentialsAreSetThenEnvironmentUsesStreamCredentials() {
EnvironmentBuilder builder = mock(EnvironmentBuilder.class);
RabbitProperties properties = new RabbitProperties();
properties.setUsername("alice");
properties.setPassword("secret");
properties.getStream().setUsername("bob");
properties.getStream().setPassword("confidential");
RabbitStreamConfiguration.configure(builder, properties,
new TestRabbitConnectionDetails("charlotte", "hidden", "vhost"));
then(builder).should().username("bob");
then(builder).should().password("confidential");
}
@Test
void testDefaultRabbitStreamTemplateConfiguration() {
this.contextRunner.withPropertyValues("spring.rabbitmq.stream.name:stream-test").run((context) -> {
assertThat(context).hasSingleBean(RabbitStreamTemplate.class);
assertThat(context.getBean(RabbitStreamTemplate.class)).hasFieldOrPropertyWithValue("streamName",
"stream-test");
});
}
@Test
void testDefaultRabbitStreamTemplateConfigurationWithoutStreamName() {
this.contextRunner.withPropertyValues("spring.rabbitmq.listener.type:stream")
.run((context) -> assertThat(context).doesNotHaveBean(RabbitStreamTemplate.class));
}
@Test
void testRabbitStreamTemplateConfigurationWithCustomMessageConverter() {
this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class)
.withPropertyValues("spring.rabbitmq.stream.name:stream-test")
.run((context) -> {
assertThat(context).hasSingleBean(RabbitStreamTemplate.class);
RabbitStreamTemplate streamTemplate = context.getBean(RabbitStreamTemplate.class);
assertThat(streamTemplate).hasFieldOrPropertyWithValue("streamName", "stream-test");
assertThat(streamTemplate).extracting("messageConverter")
.isSameAs(context.getBean(MessageConverter.class));
});
}
@Test
void testRabbitStreamTemplateConfigurationWithCustomStreamMessageConverter() {
this.contextRunner
.withBean("myStreamMessageConverter", StreamMessageConverter.class,
() -> mock(StreamMessageConverter.class))
.withPropertyValues("spring.rabbitmq.stream.name:stream-test")
.run((context) -> {
assertThat(context).hasSingleBean(RabbitStreamTemplate.class);
assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("messageConverter")
.isSameAs(context.getBean("myStreamMessageConverter"));
});
}
@Test
void testRabbitStreamTemplateConfigurationWithCustomProducerCustomizer() {
this.contextRunner
.withBean("myProducerCustomizer", ProducerCustomizer.class, () -> mock(ProducerCustomizer.class))
.withPropertyValues("spring.rabbitmq.stream.name:stream-test")
.run((context) -> {
assertThat(context).hasSingleBean(RabbitStreamTemplate.class);
assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("producerCustomizer")
.isSameAs(context.getBean("myProducerCustomizer"));
});
}
@Test
void environmentCreatedByBuilderCanBeCustomized() {
this.contextRunner.withUserConfiguration(EnvironmentBuilderCustomizers.class).run((context) -> {
Environment environment = context.getBean(Environment.class);
assertThat(environment).extracting("codec")
.isEqualTo(context.getBean(EnvironmentBuilderCustomizers.class).codec);
assertThat(environment).extracting("recoveryBackOffDelayPolicy")
.isEqualTo(context.getBean(EnvironmentBuilderCustomizers.class).recoveryBackOffDelayPolicy);
});
}
@Configuration(proxyBeanMethods = false)
static | RabbitStreamConfigurationTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/joinfetch/JoinFetchNestedAssociationsTest.java | {
"start": 3706,
"end": 4270
} | class ____ {
@Id
@GeneratedValue
private Long id;
@Column( name = "b_id" )
private Long bEntityId;
@ManyToOne
@JoinColumn( name = "b_id", updatable = false, insertable = false )
private B1Entity b_entity;
private String name;
public Long getbEntityId() {
return bEntityId;
}
public void setbEntityId(Long bEntityId) {
this.bEntityId = bEntityId;
}
public B1Entity getB_entity() {
return b_entity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| CEntity |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/annotation/ConfigurationProperties.java | {
"start": 1300,
"end": 1797
} | class ____ define properties or fields which will have the configuration properties to them at runtime.
* </p>
*
* <p>Complex nested properties are supported via classes that are public static inner classes and are also annotated
* with {@link ConfigurationProperties}.</p>
*
* @author Graeme Rocher
* @since 1.0
*/
@Singleton
@Documented
@Retention(RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR})
@ConfigurationReader
public @ | can |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/characters/Characters_assertNotEqual_Test.java | {
"start": 1427,
"end": 3382
} | class ____ extends CharactersBaseTest {
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> characters.assertNotEqual(someInfo(), null, 'a'))
.withMessage(actualIsNull());
}
@Test
void should_pass_if_characters_are_not_equal() {
characters.assertNotEqual(someInfo(), 'a', 'b');
}
@Test
void should_fail_if_characters_are_equal() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> characters.assertNotEqual(info, 'b', 'b'));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeEqual('b', 'b'));
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> charactersWithCaseInsensitiveComparisonStrategy.assertNotEqual(someInfo(),
null,
'a'))
.withMessage(actualIsNull());
}
@Test
void should_pass_if_characters_are_not_equal_according_to_custom_comparison_strategy() {
charactersWithCaseInsensitiveComparisonStrategy.assertNotEqual(someInfo(), 'a', 'b');
}
@Test
void should_fail_if_characters_are_equal_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> charactersWithCaseInsensitiveComparisonStrategy.assertNotEqual(info, 'b', 'B'));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeEqual('b', 'B', caseInsensitiveComparisonStrategy));
}
}
| Characters_assertNotEqual_Test |
java | elastic__elasticsearch | x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/AbstractPausableIntegTestCase.java | {
"start": 1161,
"end": 4201
} | class ____ extends AbstractEsqlIntegTestCase {
protected static final Semaphore scriptPermits = new Semaphore(0);
// Incremented onWait. Can be used to check if the onWait process has been reached.
protected static final Semaphore scriptWaits = new Semaphore(0);
protected int pageSize = -1;
protected int numberOfDocs = -1;
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return CollectionUtils.appendToCopy(super.nodePlugins(), pausableFieldPluginClass());
}
protected Class<? extends Plugin> pausableFieldPluginClass() {
return PausableFieldPlugin.class;
}
protected int pageSize() {
if (pageSize == -1) {
pageSize = between(10, 100);
}
return pageSize;
}
protected int numberOfDocs() {
if (numberOfDocs == -1) {
numberOfDocs = between(4 * pageSize(), 5 * pageSize());
}
return numberOfDocs;
}
protected int shardCount() {
return 1;
}
@Before
public void setupIndex() throws IOException {
assumeTrue("requires query pragmas", canUseQueryPragmas());
XContentBuilder mapping = JsonXContent.contentBuilder().startObject();
mapping.startObject("runtime");
{
mapping.startObject("pause_me");
{
mapping.field("type", "long");
mapping.startObject("script").field("source", "").field("lang", "pause").endObject();
}
mapping.endObject();
}
mapping.endObject();
client().admin().indices().prepareCreate("test").setSettings(indexSettings(shardCount(), 0)).setMapping(mapping.endObject()).get();
BulkRequestBuilder bulk = client().prepareBulk().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
for (int i = 0; i < numberOfDocs(); i++) {
bulk.add(prepareIndex("test").setId(Integer.toString(i)).setSource("foo", i));
}
bulk.get();
/*
* forceMerge so we can be sure that we don't bump into tiny
* segments that finish super quickly and cause us to report strange
* statuses when we expect "starting".
*/
client().admin().indices().prepareForceMerge("test").setMaxNumSegments(1).get();
/*
* Double super extra paranoid check that force merge worked. It's
* failed to reduce the index to a single segment and caused this test
* to fail in very difficult to debug ways. If it fails again, it'll
* trip here. Or maybe it won't! And we'll learn something. Maybe
* it's ghosts. Extending classes can override the shardCount method if
* more than a single segment is expected.
*/
SegmentsStats stats = client().admin().indices().prepareStats("test").get().getPrimaries().getSegments();
if (stats.getCount() != shardCount()) {
fail(Strings.toString(stats));
}
}
public static | AbstractPausableIntegTestCase |
java | elastic__elasticsearch | x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/predicate/operator/comparison/InsensitiveNotEquals.java | {
"start": 586,
"end": 1686
} | class ____ extends InsensitiveBinaryComparison implements Negatable<InsensitiveBinaryComparison> {
public InsensitiveNotEquals(Source source, Expression left, Expression right, ZoneId zoneId) {
super(source, left, right, InsensitiveBinaryComparisonProcessor.InsensitiveBinaryComparisonOperation.SNEQ, zoneId);
}
@Override
protected NodeInfo<InsensitiveNotEquals> info() {
return NodeInfo.create(this, InsensitiveNotEquals::new, left(), right(), zoneId());
}
@Override
protected InsensitiveNotEquals replaceChildren(Expression newLeft, Expression newRight) {
return new InsensitiveNotEquals(source(), newLeft, newRight, zoneId());
}
@Override
public InsensitiveNotEquals swapLeftAndRight() {
return new InsensitiveNotEquals(source(), right(), left(), zoneId());
}
@Override
public InsensitiveBinaryComparison negate() {
return new InsensitiveEquals(source(), left(), right(), zoneId());
}
@Override
protected String regularOperatorSymbol() {
return "not in";
}
}
| InsensitiveNotEquals |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/DiskValidator.java | {
"start": 1053,
"end": 1230
} | interface ____ disk validators.
*
* The {@link #checkStatus(File)} operation checks status of a file/dir.
*
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public | for |
java | apache__camel | dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java | {
"start": 510894,
"end": 511803
} | enum ____ com.fasterxml.jackson.databind.SerializationFeature, com.fasterxml.jackson.databind.DeserializationFeature, or com.fasterxml.jackson.databind.MapperFeature Multiple features can be separated by comma", displayName = "Enable Features"),
@YamlProperty(name = "id", type = "string", description = "The id of this node", displayName = "Id"),
@YamlProperty(name = "include", type = "string", description = "If you want to marshal a pojo to JSON, and the pojo has some fields with null values. And you want to skip these null values, you can set this option to NON_NULL", displayName = "Include"),
@YamlProperty(name = "jsonView", type = "string", description = "When marshalling a POJO to JSON you might want to exclude certain fields from the JSON output. With Jackson you can use JSON views to accomplish this. This option is to refer to the | from |
java | spring-projects__spring-boot | module/spring-boot-data-elasticsearch/src/main/java/org/springframework/boot/data/elasticsearch/autoconfigure/DataElasticsearchConfiguration.java | {
"start": 2335,
"end": 2477
} | class ____ guarantee
* their order of execution.
*
* @author Brian Clozel
* @author Scott Frederick
* @author Stephane Nicoll
*/
abstract | to |
java | quarkusio__quarkus | extensions/kafka-streams/runtime/src/test/java/io/quarkus/kafka/streams/runtime/health/KafkaStreamsHealthCheckTest.java | {
"start": 481,
"end": 1487
} | class ____ {
@InjectMocks
KafkaStreamsStateHealthCheck healthCheck;
@Mock
private KafkaStreams streams;
@Test
public void shouldBeUpIfStateRunning() {
Mockito.when(streams.state()).thenReturn(KafkaStreams.State.RUNNING);
HealthCheckResponse response = healthCheck.call();
assertThat(response.getStatus()).isEqualTo(HealthCheckResponse.Status.UP);
}
@Test
public void shouldBeUpIfStateRebalancing() {
Mockito.when(streams.state()).thenReturn(KafkaStreams.State.REBALANCING);
HealthCheckResponse response = healthCheck.call();
assertThat(response.getStatus()).isEqualTo(HealthCheckResponse.Status.UP);
}
@Test
public void shouldBeDownIfStateCreated() {
Mockito.when(streams.state()).thenReturn(KafkaStreams.State.CREATED);
HealthCheckResponse response = healthCheck.call();
assertThat(response.getStatus()).isEqualTo(HealthCheckResponse.Status.DOWN);
}
}
| KafkaStreamsHealthCheckTest |
java | quarkusio__quarkus | extensions/narayana-jta/deployment/src/test/java/io/quarkus/narayana/interceptor/TxAssertionData.java | {
"start": 173,
"end": 734
} | class ____ {
private AtomicInteger commitNumber = new AtomicInteger();
private AtomicInteger rollbackNumber = new AtomicInteger();
public void reset() {
commitNumber.set(0);
rollbackNumber.set(0);
}
public int addCommit() {
return commitNumber.incrementAndGet();
}
public int addRollback() {
return rollbackNumber.incrementAndGet();
}
public int getCommit() {
return commitNumber.get();
}
public int getRollback() {
return rollbackNumber.get();
}
}
| TxAssertionData |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_3300/Issue3373.java | {
"start": 222,
"end": 684
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
RefBeforeFilterTest refAfterFilterTest = new RefBeforeFilterTest();
List<Item> items = new ArrayList<Item>(2);
Category category = new Category("category");
items.add(new Item("item1",category));
items.add(new Item("item2",category));
System.out.println(JSON.toJSONString(items,refAfterFilterTest));
}
public static | Issue3373 |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSImageSerialization.java | {
"start": 3524,
"end": 27135
} | class ____ {
final DeprecatedUTF8 U_STR = new DeprecatedUTF8();
final ShortWritable U_SHORT = new ShortWritable();
final IntWritable U_INT = new IntWritable();
final LongWritable U_LONG = new LongWritable();
final FsPermission FILE_PERM = new FsPermission((short) 0);
final BooleanWritable U_BOOLEAN = new BooleanWritable();
}
private static void writePermissionStatus(INodeAttributes inode,
DataOutput out) throws IOException {
final FsPermission p = TL_DATA.get().FILE_PERM;
p.fromShort(inode.getFsPermissionShort());
PermissionStatus.write(out, inode.getUserName(), inode.getGroupName(), p);
}
private static void writeBlocks(final Block[] blocks,
final DataOutput out) throws IOException {
if (blocks == null) {
out.writeInt(0);
} else {
out.writeInt(blocks.length);
for (Block blk : blocks) {
blk.write(out);
}
}
}
// Helper function that reads in an INodeUnderConstruction
// from the input stream
//
static INodeFile readINodeUnderConstruction(
DataInput in, FSNamesystem fsNamesys, int imgVersion)
throws IOException {
byte[] name = readBytes(in);
long inodeId = NameNodeLayoutVersion.supports(
LayoutVersion.Feature.ADD_INODE_ID, imgVersion) ? in.readLong()
: fsNamesys.dir.allocateNewInodeId();
short blockReplication = in.readShort();
long modificationTime = in.readLong();
long preferredBlockSize = in.readLong();
int numBlocks = in.readInt();
final BlockInfoContiguous[] blocksContiguous =
new BlockInfoContiguous[numBlocks];
Block blk = new Block();
int i = 0;
for (; i < numBlocks - 1; i++) {
blk.readFields(in);
blocksContiguous[i] = new BlockInfoContiguous(blk, blockReplication);
}
// last block is UNDER_CONSTRUCTION
if(numBlocks > 0) {
blk.readFields(in);
blocksContiguous[i] = new BlockInfoContiguous(blk, blockReplication);
blocksContiguous[i].convertToBlockUnderConstruction(
BlockUCState.UNDER_CONSTRUCTION, null);
}
PermissionStatus perm = PermissionStatus.read(in);
String clientName = readString(in);
String clientMachine = readString(in);
// We previously stored locations for the last block, now we
// just record that there are none
int numLocs = in.readInt();
assert numLocs == 0 : "Unexpected block locations";
// Images in the pre-protobuf format will not have the lazyPersist flag,
// so it is safe to pass false always.
INodeFile file = new INodeFile(inodeId, name, perm, modificationTime,
modificationTime, blocksContiguous, blockReplication, preferredBlockSize);
file.toUnderConstruction(clientName, clientMachine);
return file;
}
// Helper function that writes an INodeUnderConstruction
// into the output stream
//
static void writeINodeUnderConstruction(DataOutputStream out, INodeFile cons,
String path) throws IOException {
writeString(path, out);
out.writeLong(cons.getId());
out.writeShort(cons.getFileReplication());
out.writeLong(cons.getModificationTime());
out.writeLong(cons.getPreferredBlockSize());
writeBlocks(cons.getBlocks(), out);
cons.getPermissionStatus().write(out);
FileUnderConstructionFeature uc = cons.getFileUnderConstructionFeature();
writeString(uc.getClientName(), out);
writeString(uc.getClientMachine(), out);
out.writeInt(0); // do not store locations of last block
}
/**
* Serialize a {@link INodeFile} node
* @param file The INodeFile to write
* @param out The {@link DataOutputStream} where the fields are written
* @param writeUnderConstruction Whether to write under construction information
*/
public static void writeINodeFile(INodeFile file, DataOutput out,
boolean writeUnderConstruction) throws IOException {
writeLocalName(file, out);
out.writeLong(file.getId());
out.writeShort(file.getFileReplication());
out.writeLong(file.getModificationTime());
out.writeLong(file.getAccessTime());
out.writeLong(file.getPreferredBlockSize());
writeBlocks(file.getBlocks(), out);
SnapshotFSImageFormat.saveFileDiffList(file, out);
if (writeUnderConstruction) {
if (file.isUnderConstruction()) {
out.writeBoolean(true);
final FileUnderConstructionFeature uc = file.getFileUnderConstructionFeature();
writeString(uc.getClientName(), out);
writeString(uc.getClientMachine(), out);
} else {
out.writeBoolean(false);
}
}
writePermissionStatus(file, out);
}
/** Serialize an {@link INodeFileAttributes}. */
public static void writeINodeFileAttributes(INodeFileAttributes file,
DataOutput out) throws IOException {
writeLocalName(file, out);
writePermissionStatus(file, out);
out.writeLong(file.getModificationTime());
out.writeLong(file.getAccessTime());
out.writeShort(file.getFileReplication());
out.writeLong(file.getPreferredBlockSize());
}
private static void writeQuota(QuotaCounts quota, DataOutput out)
throws IOException {
out.writeLong(quota.getNameSpace());
out.writeLong(quota.getStorageSpace());
}
/**
* Serialize a {@link INodeDirectory}
* @param node The node to write
* @param out The {@link DataOutput} where the fields are written
*/
public static void writeINodeDirectory(INodeDirectory node, DataOutput out)
throws IOException {
writeLocalName(node, out);
out.writeLong(node.getId());
out.writeShort(0); // replication
out.writeLong(node.getModificationTime());
out.writeLong(0); // access time
out.writeLong(0); // preferred block size
out.writeInt(-1); // # of blocks
writeQuota(node.getQuotaCounts(), out);
if (node.isSnapshottable()) {
out.writeBoolean(true);
} else {
out.writeBoolean(false);
out.writeBoolean(node.isWithSnapshot());
}
writePermissionStatus(node, out);
}
/**
* Serialize a {@link INodeDirectory}
* @param a The node to write
* @param out The {@link DataOutput} where the fields are written
*/
public static void writeINodeDirectoryAttributes(
INodeDirectoryAttributes a, DataOutput out) throws IOException {
writeLocalName(a, out);
writePermissionStatus(a, out);
out.writeLong(a.getModificationTime());
writeQuota(a.getQuotaCounts(), out);
}
/**
* Serialize a {@link INodeSymlink} node
* @param node The node to write
* @param out The {@link DataOutput} where the fields are written
*/
private static void writeINodeSymlink(INodeSymlink node, DataOutput out)
throws IOException {
writeLocalName(node, out);
out.writeLong(node.getId());
out.writeShort(0); // replication
out.writeLong(0); // modification time
out.writeLong(0); // access time
out.writeLong(0); // preferred block size
out.writeInt(-2); // # of blocks
Text.writeString(out, node.getSymlinkString());
writePermissionStatus(node, out);
}
/** Serialize a {@link INodeReference} node */
private static void writeINodeReference(INodeReference ref, DataOutput out,
boolean writeUnderConstruction, ReferenceMap referenceMap
) throws IOException {
writeLocalName(ref, out);
out.writeLong(ref.getId());
out.writeShort(0); // replication
out.writeLong(0); // modification time
out.writeLong(0); // access time
out.writeLong(0); // preferred block size
out.writeInt(-3); // # of blocks
final boolean isWithName = ref instanceof INodeReference.WithName;
out.writeBoolean(isWithName);
if (!isWithName) {
Preconditions.checkState(ref instanceof INodeReference.DstReference);
// dst snapshot id
out.writeInt(ref.getDstSnapshotId());
} else {
out.writeInt(((INodeReference.WithName) ref).getLastSnapshotId());
}
final INodeReference.WithCount withCount
= (INodeReference.WithCount)ref.getReferredINode();
referenceMap.writeINodeReferenceWithCount(withCount, out,
writeUnderConstruction);
}
/**
* Save one inode's attributes to the image.
*/
public static void saveINode2Image(INode node, DataOutput out,
boolean writeUnderConstruction, ReferenceMap referenceMap)
throws IOException {
if (node.isReference()) {
writeINodeReference(node.asReference(), out, writeUnderConstruction,
referenceMap);
} else if (node.isDirectory()) {
writeINodeDirectory(node.asDirectory(), out);
} else if (node.isSymlink()) {
writeINodeSymlink(node.asSymlink(), out);
} else if (node.isFile()) {
writeINodeFile(node.asFile(), out, writeUnderConstruction);
}
}
// This should be reverted to package private once the ImageLoader
// code is moved into this package. This method should not be called
// by other code.
@SuppressWarnings("deprecation")
public static String readString(DataInput in) throws IOException {
DeprecatedUTF8 ustr = TL_DATA.get().U_STR;
ustr.readFields(in);
return ustr.toStringChecked();
}
static String readString_EmptyAsNull(DataInput in) throws IOException {
final String s = readString(in);
return s.isEmpty()? null: s;
}
@SuppressWarnings("deprecation")
public static void writeString(String str, DataOutput out) throws IOException {
DeprecatedUTF8 ustr = TL_DATA.get().U_STR;
ustr.set(str);
ustr.write(out);
}
/** read the long value */
static long readLong(DataInput in) throws IOException {
LongWritable uLong = TL_DATA.get().U_LONG;
uLong.readFields(in);
return uLong.get();
}
/** write the long value */
static void writeLong(long value, DataOutputStream out) throws IOException {
LongWritable uLong = TL_DATA.get().U_LONG;
uLong.set(value);
uLong.write(out);
}
/** read the boolean value */
static boolean readBoolean(DataInput in) throws IOException {
BooleanWritable uBoolean = TL_DATA.get().U_BOOLEAN;
uBoolean.readFields(in);
return uBoolean.get();
}
/** write the boolean value */
static void writeBoolean(boolean value, DataOutputStream out)
throws IOException {
BooleanWritable uBoolean = TL_DATA.get().U_BOOLEAN;
uBoolean.set(value);
uBoolean.write(out);
}
/** write the byte value */
static void writeByte(byte value, DataOutputStream out)
throws IOException {
out.write(value);
}
/** read the int value */
static int readInt(DataInput in) throws IOException {
IntWritable uInt = TL_DATA.get().U_INT;
uInt.readFields(in);
return uInt.get();
}
/** write the int value */
static void writeInt(int value, DataOutputStream out) throws IOException {
IntWritable uInt = TL_DATA.get().U_INT;
uInt.set(value);
uInt.write(out);
}
/** read short value */
static short readShort(DataInput in) throws IOException {
ShortWritable uShort = TL_DATA.get().U_SHORT;
uShort.readFields(in);
return uShort.get();
}
/** write short value */
static void writeShort(short value, DataOutputStream out) throws IOException {
ShortWritable uShort = TL_DATA.get().U_SHORT;
uShort.set(value);
uShort.write(out);
}
// Same comments apply for this method as for readString()
@SuppressWarnings("deprecation")
public static byte[] readBytes(DataInput in) throws IOException {
DeprecatedUTF8 ustr = TL_DATA.get().U_STR;
ustr.readFields(in);
int len = ustr.getLength();
byte[] bytes = new byte[len];
System.arraycopy(ustr.getBytes(), 0, bytes, 0, len);
return bytes;
}
public static byte readByte(DataInput in) throws IOException {
return in.readByte();
}
/**
* Reading the path from the image and converting it to byte[][] directly
* this saves us an array copy and conversions to and from String
* @param in input to read from
* @return the array each element of which is a byte[] representation
* of a path component
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static byte[][] readPathComponents(DataInput in)
throws IOException {
DeprecatedUTF8 ustr = TL_DATA.get().U_STR;
ustr.readFields(in);
return DFSUtil.bytes2byteArray(ustr.getBytes(),
ustr.getLength(), (byte) Path.SEPARATOR_CHAR);
}
public static byte[] readLocalName(DataInput in) throws IOException {
byte[] createdNodeName = new byte[in.readShort()];
in.readFully(createdNodeName);
return createdNodeName;
}
private static void writeLocalName(INodeAttributes inode, DataOutput out)
throws IOException {
final byte[] name = inode.getLocalNameBytes();
writeBytes(name, out);
}
public static void writeBytes(byte[] data, DataOutput out)
throws IOException {
out.writeShort(data.length);
out.write(data);
}
/**
* Write an array of blocks as compactly as possible. This uses
* delta-encoding for the generation stamp and size, following
* the principle that genstamp increases relatively slowly,
* and size is equal for all but the last block of a file.
*/
public static void writeCompactBlockArray(
Block[] blocks, DataOutputStream out) throws IOException {
WritableUtils.writeVInt(out, blocks.length);
Block prev = null;
for (Block b : blocks) {
long szDelta = b.getNumBytes() -
(prev != null ? prev.getNumBytes() : 0);
long gsDelta = b.getGenerationStamp() -
(prev != null ? prev.getGenerationStamp() : 0);
out.writeLong(b.getBlockId()); // blockid is random
WritableUtils.writeVLong(out, szDelta);
WritableUtils.writeVLong(out, gsDelta);
prev = b;
}
}
public static Block[] readCompactBlockArray(
DataInput in, int logVersion) throws IOException {
int num = WritableUtils.readVInt(in);
if (num < 0) {
throw new IOException("Invalid block array length: " + num);
}
Block prev = null;
Block[] ret = new Block[num];
for (int i = 0; i < num; i++) {
long id = in.readLong();
long sz = WritableUtils.readVLong(in) +
((prev != null) ? prev.getNumBytes() : 0);
long gs = WritableUtils.readVLong(in) +
((prev != null) ? prev.getGenerationStamp() : 0);
ret[i] = new Block(id, sz, gs);
prev = ret[i];
}
return ret;
}
public static void writeCacheDirectiveInfo(DataOutputStream out,
CacheDirectiveInfo directive) throws IOException {
writeLong(directive.getId(), out);
int flags =
((directive.getPath() != null) ? 0x1 : 0) |
((directive.getReplication() != null) ? 0x2 : 0) |
((directive.getPool() != null) ? 0x4 : 0) |
((directive.getExpiration() != null) ? 0x8 : 0);
out.writeInt(flags);
if (directive.getPath() != null) {
writeString(directive.getPath().toUri().getPath(), out);
}
if (directive.getReplication() != null) {
writeShort(directive.getReplication(), out);
}
if (directive.getPool() != null) {
writeString(directive.getPool(), out);
}
if (directive.getExpiration() != null) {
writeLong(directive.getExpiration().getAbsoluteMillis(), out);
}
}
public static CacheDirectiveInfo readCacheDirectiveInfo(DataInput in)
throws IOException {
CacheDirectiveInfo.Builder builder =
new CacheDirectiveInfo.Builder();
builder.setId(readLong(in));
int flags = in.readInt();
if ((flags & 0x1) != 0) {
builder.setPath(new Path(readString(in)));
}
if ((flags & 0x2) != 0) {
builder.setReplication(readShort(in));
}
if ((flags & 0x4) != 0) {
builder.setPool(readString(in));
}
if ((flags & 0x8) != 0) {
builder.setExpiration(
CacheDirectiveInfo.Expiration.newAbsolute(readLong(in)));
}
if ((flags & ~0xF) != 0) {
throw new IOException("unknown flags set in " +
"ModifyCacheDirectiveInfoOp: " + flags);
}
return builder.build();
}
public static CacheDirectiveInfo readCacheDirectiveInfo(Stanza st)
throws InvalidXmlException {
CacheDirectiveInfo.Builder builder =
new CacheDirectiveInfo.Builder();
builder.setId(Long.parseLong(st.getValue("ID")));
String path = st.getValueOrNull("PATH");
if (path != null) {
builder.setPath(new Path(path));
}
String replicationString = st.getValueOrNull("REPLICATION");
if (replicationString != null) {
builder.setReplication(Short.parseShort(replicationString));
}
String pool = st.getValueOrNull("POOL");
if (pool != null) {
builder.setPool(pool);
}
String expiryTime = st.getValueOrNull("EXPIRATION");
if (expiryTime != null) {
builder.setExpiration(CacheDirectiveInfo.Expiration.newAbsolute(
Long.parseLong(expiryTime)));
}
return builder.build();
}
public static void writeCacheDirectiveInfo(ContentHandler contentHandler,
CacheDirectiveInfo directive) throws SAXException {
XMLUtils.addSaxString(contentHandler, "ID",
Long.toString(directive.getId()));
if (directive.getPath() != null) {
XMLUtils.addSaxString(contentHandler, "PATH",
directive.getPath().toUri().getPath());
}
if (directive.getReplication() != null) {
XMLUtils.addSaxString(contentHandler, "REPLICATION",
Short.toString(directive.getReplication()));
}
if (directive.getPool() != null) {
XMLUtils.addSaxString(contentHandler, "POOL", directive.getPool());
}
if (directive.getExpiration() != null) {
XMLUtils.addSaxString(contentHandler, "EXPIRATION",
"" + directive.getExpiration().getAbsoluteMillis());
}
}
public static void writeCachePoolInfo(DataOutputStream out, CachePoolInfo info)
throws IOException {
writeString(info.getPoolName(), out);
final String ownerName = info.getOwnerName();
final String groupName = info.getGroupName();
final Long limit = info.getLimit();
final FsPermission mode = info.getMode();
final Long maxRelativeExpiry = info.getMaxRelativeExpiryMs();
final Short defaultReplication = info.getDefaultReplication();
boolean hasOwner, hasGroup, hasMode, hasLimit,
hasMaxRelativeExpiry, hasDefaultReplication;
hasOwner = ownerName != null;
hasGroup = groupName != null;
hasMode = mode != null;
hasLimit = limit != null;
hasMaxRelativeExpiry = maxRelativeExpiry != null;
hasDefaultReplication = defaultReplication != null;
int flags =
(hasOwner ? 0x1 : 0) |
(hasGroup ? 0x2 : 0) |
(hasMode ? 0x4 : 0) |
(hasLimit ? 0x8 : 0) |
(hasMaxRelativeExpiry ? 0x10 : 0) |
(hasDefaultReplication ? 0x20 : 0);
writeInt(flags, out);
if (hasOwner) {
writeString(ownerName, out);
}
if (hasGroup) {
writeString(groupName, out);
}
if (hasMode) {
mode.write(out);
}
if (hasLimit) {
writeLong(limit, out);
}
if (hasMaxRelativeExpiry) {
writeLong(maxRelativeExpiry, out);
}
if (hasDefaultReplication) {
writeShort(defaultReplication, out);
}
}
public static CachePoolInfo readCachePoolInfo(DataInput in)
throws IOException {
String poolName = readString(in);
CachePoolInfo info = new CachePoolInfo(poolName);
int flags = readInt(in);
if ((flags & 0x1) != 0) {
info.setOwnerName(readString(in));
}
if ((flags & 0x2) != 0) {
info.setGroupName(readString(in));
}
if ((flags & 0x4) != 0) {
info.setMode(FsPermission.read(in));
}
if ((flags & 0x8) != 0) {
info.setLimit(readLong(in));
}
if ((flags & 0x10) != 0) {
info.setMaxRelativeExpiryMs(readLong(in));
}
if ((flags & 0x20) != 0) {
info.setDefaultReplication(readShort(in));
}
if ((flags & ~0x3F) != 0) {
throw new IOException("Unknown flag in CachePoolInfo: " + flags);
}
return info;
}
public static void writeCachePoolInfo(ContentHandler contentHandler,
CachePoolInfo info) throws SAXException {
XMLUtils.addSaxString(contentHandler, "POOLNAME", info.getPoolName());
final String ownerName = info.getOwnerName();
final String groupName = info.getGroupName();
final Long limit = info.getLimit();
final FsPermission mode = info.getMode();
final Long maxRelativeExpiry = info.getMaxRelativeExpiryMs();
final Short defaultReplication = info.getDefaultReplication();
if (ownerName != null) {
XMLUtils.addSaxString(contentHandler, "OWNERNAME", ownerName);
}
if (groupName != null) {
XMLUtils.addSaxString(contentHandler, "GROUPNAME", groupName);
}
if (mode != null) {
FSEditLogOp.fsPermissionToXml(contentHandler, mode);
}
if (limit != null) {
XMLUtils.addSaxString(contentHandler, "LIMIT",
Long.toString(limit));
}
if (maxRelativeExpiry != null) {
XMLUtils.addSaxString(contentHandler, "MAXRELATIVEEXPIRY",
Long.toString(maxRelativeExpiry));
}
if (defaultReplication != null) {
XMLUtils.addSaxString(contentHandler, "DEFAULTREPLICATION",
Short.toString(defaultReplication));
}
}
public static CachePoolInfo readCachePoolInfo(Stanza st)
throws InvalidXmlException {
String poolName = st.getValue("POOLNAME");
CachePoolInfo info = new CachePoolInfo(poolName);
if (st.hasChildren("OWNERNAME")) {
info.setOwnerName(st.getValue("OWNERNAME"));
}
if (st.hasChildren("GROUPNAME")) {
info.setGroupName(st.getValue("GROUPNAME"));
}
if (st.hasChildren("MODE")) {
info.setMode(FSEditLogOp.fsPermissionFromXml(st));
}
if (st.hasChildren("LIMIT")) {
info.setLimit(Long.parseLong(st.getValue("LIMIT")));
}
if (st.hasChildren("MAXRELATIVEEXPIRY")) {
info.setMaxRelativeExpiryMs(
Long.parseLong(st.getValue("MAXRELATIVEEXPIRY")));
}
if (st.hasChildren("DEFAULTREPLICATION")) {
info.setDefaultReplication(Short.parseShort(st
.getValue("DEFAULTREPLICATION")));
}
return info;
}
public static void writeErasureCodingPolicy(DataOutputStream out,
ErasureCodingPolicy ecPolicy) throws IOException {
writeString(ecPolicy.getSchema().getCodecName(), out);
writeInt(ecPolicy.getNumDataUnits(), out);
writeInt(ecPolicy.getNumParityUnits(), out);
writeInt(ecPolicy.getCellSize(), out);
Map<String, String> extraOptions = ecPolicy.getSchema().getExtraOptions();
if (extraOptions == null || extraOptions.isEmpty()) {
writeInt(0, out);
return;
}
writeInt(extraOptions.size(), out);
for (Map.Entry<String, String> entry : extraOptions.entrySet()) {
writeString(entry.getKey(), out);
writeString(entry.getValue(), out);
}
}
public static ErasureCodingPolicy readErasureCodingPolicy(DataInput in)
throws IOException {
String codecName = readString(in);
int numDataUnits = readInt(in);
int numParityUnits = readInt(in);
int cellSize = readInt(in);
int size = readInt(in);
Map<String, String> extraOptions = new HashMap<>(size);
if (size != 0) {
for (int i = 0; i < size; i++) {
String key = readString(in);
String value = readString(in);
extraOptions.put(key, value);
}
}
ECSchema ecSchema = new ECSchema(codecName, numDataUnits,
numParityUnits, extraOptions);
return new ErasureCodingPolicy(ecSchema, cellSize);
}
}
| TLData |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjector.java | {
"start": 2507,
"end": 2997
} | class ____ {
private static final Logger LOGGER = StatusLogger.getLogger();
/**
* ContextDataProviders loaded via OSGi.
*/
public static Collection<ContextDataProvider> contextDataProviders = new ConcurrentLinkedDeque<>();
private static final List<ContextDataProvider> SERVICE_PROVIDERS = getServiceProviders();
/**
* Previously this method allowed ContextDataProviders to be loaded eagerly, now they
* are loaded when this | ThreadContextDataInjector |
java | qos-ch__slf4j | log4j-over-slf4j/src/test/java/org/apache/log4j/test/NDCTest.java | {
"start": 1431,
"end": 2017
} | class ____ {
@Before
public void setUp() {
assertEquals(0, NDC.getDepth());
}
@After
public void tearDown() {
NDC.clear();
}
@Test
public void testSmoke() {
NDC.push("a");
String back = NDC.pop();
assertEquals("a", back);
}
@Test
public void testPop() {
NDC.push("peek");
String back = NDC.peek();
assertEquals("peek", back);
}
@Test
public void testClear() {
NDC.push("clear");
NDC.clear();
assertEquals(0, NDC.getDepth());
}
}
| NDCTest |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/network/SaslChannelBuilderTest.java | {
"start": 2764,
"end": 10045
} | class ____ {
@AfterEach
public void tearDown() {
System.clearProperty(SaslChannelBuilder.GSS_NATIVE_PROP);
}
@Test
public void testCloseBeforeConfigureIsIdempotent() {
SaslChannelBuilder builder = createChannelBuilder(SecurityProtocol.SASL_PLAINTEXT, "PLAIN");
builder.close();
assertTrue(builder.loginManagers().isEmpty());
builder.close();
assertTrue(builder.loginManagers().isEmpty());
}
@Test
public void testCloseAfterConfigIsIdempotent() {
SaslChannelBuilder builder = createChannelBuilder(SecurityProtocol.SASL_PLAINTEXT, "PLAIN");
builder.configure(new HashMap<>());
assertNotNull(builder.loginManagers().get("PLAIN"));
builder.close();
assertTrue(builder.loginManagers().isEmpty());
builder.close();
assertTrue(builder.loginManagers().isEmpty());
}
@Test
public void testLoginManagerReleasedIfConfigureThrowsException() {
SaslChannelBuilder builder = createChannelBuilder(SecurityProtocol.SASL_SSL, "PLAIN");
try {
// Use invalid config so that an exception is thrown
builder.configure(Collections.singletonMap(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, "1"));
fail("Exception should have been thrown");
} catch (KafkaException e) {
assertTrue(builder.loginManagers().isEmpty());
}
builder.close();
assertTrue(builder.loginManagers().isEmpty());
}
@Test
public void testNativeGssapiCredentials() throws Exception {
System.setProperty(SaslChannelBuilder.GSS_NATIVE_PROP, "true");
TestJaasConfig jaasConfig = new TestJaasConfig();
jaasConfig.addEntry("jaasContext", TestGssapiLoginModule.class.getName(), new HashMap<>());
JaasContext jaasContext = new JaasContext("jaasContext", JaasContext.Type.SERVER, jaasConfig, null);
Map<String, JaasContext> jaasContexts = Collections.singletonMap("GSSAPI", jaasContext);
GSSManager gssManager = Mockito.mock(GSSManager.class);
GSSName gssName = Mockito.mock(GSSName.class);
Mockito.when(gssManager.createName(Mockito.anyString(), Mockito.any()))
.thenAnswer(unused -> gssName);
Oid oid = new Oid("1.2.840.113554.1.2.2");
Mockito.when(gssManager.createCredential(gssName, GSSContext.INDEFINITE_LIFETIME, oid, GSSCredential.ACCEPT_ONLY))
.thenAnswer(unused -> Mockito.mock(GSSCredential.class));
SaslChannelBuilder channelBuilder1 = createGssapiChannelBuilder(jaasContexts, gssManager);
assertEquals(1, channelBuilder1.subject("GSSAPI").getPrincipals().size());
assertEquals(1, channelBuilder1.subject("GSSAPI").getPrivateCredentials().size());
SaslChannelBuilder channelBuilder2 = createGssapiChannelBuilder(jaasContexts, gssManager);
assertEquals(1, channelBuilder2.subject("GSSAPI").getPrincipals().size());
assertEquals(1, channelBuilder2.subject("GSSAPI").getPrivateCredentials().size());
assertSame(channelBuilder1.subject("GSSAPI"), channelBuilder2.subject("GSSAPI"));
Mockito.verify(gssManager, Mockito.times(1))
.createCredential(gssName, GSSContext.INDEFINITE_LIFETIME, oid, GSSCredential.ACCEPT_ONLY);
}
/**
* Verify that unparsed broker configs don't break clients. This is to ensure that clients
* created by brokers are not broken if broker configs are passed to clients.
*/
@Test
public void testClientChannelBuilderWithBrokerConfigs() throws Exception {
CertStores certStores = new CertStores(false, "client", "localhost");
Map<String, Object> configs = new HashMap<>(certStores.getTrustingConfig(certStores));
configs.put(SaslConfigs.SASL_KERBEROS_SERVICE_NAME, "kafka");
configs.putAll(new ConfigDef().withClientSaslSupport().parse(configs));
for (Field field : BrokerSecurityConfigs.class.getFields()) {
if (field.getName().endsWith("_CONFIG"))
configs.put(field.get(BrokerSecurityConfigs.class).toString(), "somevalue");
}
SaslChannelBuilder plainBuilder = createChannelBuilder(SecurityProtocol.SASL_PLAINTEXT, "PLAIN");
plainBuilder.configure(configs);
SaslChannelBuilder gssapiBuilder = createChannelBuilder(SecurityProtocol.SASL_PLAINTEXT, "GSSAPI");
gssapiBuilder.configure(configs);
SaslChannelBuilder oauthBearerBuilder = createChannelBuilder(SecurityProtocol.SASL_PLAINTEXT, "OAUTHBEARER");
oauthBearerBuilder.configure(configs);
SaslChannelBuilder scramBuilder = createChannelBuilder(SecurityProtocol.SASL_PLAINTEXT, "SCRAM-SHA-256");
scramBuilder.configure(configs);
SaslChannelBuilder saslSslBuilder = createChannelBuilder(SecurityProtocol.SASL_SSL, "PLAIN");
saslSslBuilder.configure(configs);
}
private SaslChannelBuilder createGssapiChannelBuilder(Map<String, JaasContext> jaasContexts, GSSManager gssManager) {
SaslChannelBuilder channelBuilder = new SaslChannelBuilder(ConnectionMode.SERVER, jaasContexts,
SecurityProtocol.SASL_PLAINTEXT, new ListenerName("GSSAPI"), false, "GSSAPI",
null, null, null, Time.SYSTEM, new LogContext(), defaultApiVersionsSupplier()) {
@Override
protected GSSManager gssManager() {
return gssManager;
}
};
Map<String, Object> props = Collections.singletonMap(SaslConfigs.SASL_KERBEROS_SERVICE_NAME, "kafka");
channelBuilder.configure(new TestSecurityConfig(props).values());
return channelBuilder;
}
private Function<Short, ApiVersionsResponse> defaultApiVersionsSupplier() {
return version -> TestUtils.defaultApiVersionsResponse(ApiMessageType.ListenerType.BROKER);
}
private SaslChannelBuilder createChannelBuilder(SecurityProtocol securityProtocol, String saslMechanism) {
Class<?> loginModule;
switch (saslMechanism) {
case "PLAIN":
loginModule = PlainLoginModule.class;
break;
case "SCRAM-SHA-256":
loginModule = ScramLoginModule.class;
break;
case "OAUTHBEARER":
loginModule = OAuthBearerLoginModule.class;
break;
case "GSSAPI":
loginModule = TestGssapiLoginModule.class;
break;
default:
throw new IllegalArgumentException("Unsupported SASL mechanism " + saslMechanism);
}
TestJaasConfig jaasConfig = new TestJaasConfig();
jaasConfig.addEntry("jaasContext", loginModule.getName(), new HashMap<>());
JaasContext jaasContext = new JaasContext("jaasContext", JaasContext.Type.SERVER, jaasConfig, null);
Map<String, JaasContext> jaasContexts = Collections.singletonMap(saslMechanism, jaasContext);
return new SaslChannelBuilder(ConnectionMode.CLIENT, jaasContexts, securityProtocol, new ListenerName(saslMechanism),
false, saslMechanism, null,
null, null, Time.SYSTEM, new LogContext(), defaultApiVersionsSupplier());
}
public static final | SaslChannelBuilderTest |
java | apache__camel | components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppGroupChatProducer.java | {
"start": 1605,
"end": 6918
} | class ____ extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(XmppGroupChatProducer.class);
private final XmppEndpoint endpoint;
private XMPPTCPConnection connection;
private MultiUserChat chat;
private String room;
public XmppGroupChatProducer(XmppEndpoint endpoint) {
super(endpoint);
this.endpoint = endpoint;
}
@Override
public void process(Exchange exchange) {
if (connection == null) {
try {
connection = endpoint.createConnection();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeExchangeException("Interrupted while connecting to XMPP server.", exchange, e);
} catch (Exception e) {
throw new RuntimeExchangeException("Could not connect to XMPP server.", exchange, e);
}
}
if (chat == null) {
try {
initializeChat();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeExchangeException("Interrupted while initializing XMPP chat.", exchange, e);
} catch (Exception e) {
throw new RuntimeExchangeException("Could not initialize XMPP chat.", exchange, e);
}
}
Message message = chat.createMessage();
try {
message.setTo(JidCreate.from(room));
message.setFrom(JidCreate.from(endpoint.getUser()));
endpoint.getBinding().populateXmppMessage(message, exchange);
// make sure we are connected
if (!connection.isConnected()) {
this.reconnect();
}
if (LOG.isDebugEnabled()) {
LOG.debug("Sending XMPP message: {}", message.getBody());
}
chat.sendMessage(message);
// must invoke nextMessage to consume the response from the server
// otherwise the client local queue will fill up (CAMEL-1467)
chat.pollMessage();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeExchangeException("Interrupted while sending XMPP message: " + message, exchange, e);
} catch (Exception e) {
throw new RuntimeExchangeException("Could not send XMPP message: " + message, exchange, e);
}
}
private void reconnect() throws InterruptedException, IOException, SmackException, XMPPException {
lock.lock();
try {
if (!connection.isConnected()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Reconnecting to: {}", XmppEndpoint.getConnectionMessage(connection));
}
connection.connect();
}
} finally {
lock.unlock();
}
}
@Override
protected void doStart() throws Exception {
if (connection == null) {
try {
connection = endpoint.createConnection();
} catch (SmackException e) {
if (endpoint.isTestConnectionOnStartup()) {
throw new RuntimeCamelException(
"Could not connect to XMPP server: " + endpoint.getConnectionDescription(), e);
} else {
LOG.warn("Could not connect to XMPP server. {} Producer will attempt lazy connection when needed.",
e.getMessage());
}
}
}
if (chat == null && connection != null) {
initializeChat();
}
super.doStart();
}
protected void initializeChat()
throws InterruptedException, SmackException, XMPPException, XmppStringprepException {
lock.lock();
try {
if (chat == null) {
room = endpoint.resolveRoom(connection);
String roomPassword = endpoint.getRoomPassword();
MultiUserChatManager chatManager = MultiUserChatManager.getInstanceFor(connection);
chat = chatManager.getMultiUserChat(JidCreate.entityBareFrom(room));
MucEnterConfiguration.Builder mucc
= chat.getEnterConfigurationBuilder(Resourcepart.from(endpoint.getNickname()))
.requestNoHistory();
if (roomPassword != null) {
mucc.withPassword(roomPassword);
}
chat.join(mucc.build());
LOG.info("Joined room: {} as: {}", room, endpoint.getNickname());
}
} finally {
lock.unlock();
}
}
@Override
protected void doStop() throws Exception {
if (chat != null) {
LOG.info("Leaving room: {}", room);
chat.leave();
}
chat = null;
if (connection != null && connection.isConnected()) {
connection.disconnect();
}
connection = null;
super.doStop();
}
// Properties
// -------------------------------------------------------------------------
public String getRoom() {
return room;
}
}
| XmppGroupChatProducer |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/component/validator/SpringValidatorRouteTest.java | {
"start": 988,
"end": 1243
} | class ____ extends ValidatorRouteTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/component/validator/camelContext.xml");
}
}
| SpringValidatorRouteTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/regression/Huber.java | {
"start": 5736,
"end": 7164
} | class ____ implements EvaluationMetricResult {
private static final String VALUE = "value";
private final double value;
public Result(double value) {
this.value = value;
}
public Result(StreamInput in) throws IOException {
this.value = in.readDouble();
}
@Override
public String getWriteableName() {
return registeredMetricName(Regression.NAME, NAME);
}
@Override
public String getMetricName() {
return NAME.getPreferredName();
}
public double getValue() {
return value;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeDouble(value);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(VALUE, value);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Result other = (Result) o;
return value == other.value;
}
@Override
public int hashCode() {
return Double.hashCode(value);
}
}
}
| Result |
java | quarkusio__quarkus | extensions/vertx/runtime/src/main/java/io/quarkus/vertx/core/runtime/graal/JdkSubstitutions.java | {
"start": 888,
"end": 1787
} | class ____ {
@Substitute
private Target_URLClassPath$Loader getLoader(final URL url) throws IOException {
String file = url.getFile();
if (file != null && file.endsWith("/")) {
if ("file".equals(url.getProtocol())) {
return (Target_URLClassPath$Loader) (Object) new Target_URLClassPath$FileLoader(
url);
} else {
return new Target_URLClassPath$Loader(url);
}
} else {
// that must be wrong, but JarLoader is deleted by SVM
return (Target_URLClassPath$Loader) (Object) new Target_URLClassPath$FileLoader(
url);
}
}
}
@Substitute
@TargetClass(className = "sun.nio.ch.WindowsAsynchronousFileChannelImpl", innerClass = "DefaultIocpHolder")
@Platforms({ Platform.WINDOWS.class })
final | Target_jdk_internal_loader_URLClassPath |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/sql/syncSpace/NativeQuerySyncSpaceCachingTest.java | {
"start": 4670,
"end": 5124
} | class ____ {
@Id
private int id;
private String name;
public Customer() {
}
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity(name = "Address")
@Table(name = "Address")
public static | Customer |
java | grpc__grpc-java | services/src/main/java/io/grpc/protobuf/services/BinlogHelper.java | {
"start": 10720,
"end": 13322
} | class ____ {
/**
* Logs the client header. This method logs the appropriate number of bytes
* as determined by the binary logging configuration.
*/
abstract void logClientHeader(
long seq,
String methodName,
// not all transports have the concept of authority
@Nullable String authority,
@Nullable Duration timeout,
Metadata metadata,
GrpcLogEntry.Logger logger,
long callId,
// null on client side
@Nullable SocketAddress peerAddress);
/**
* Logs the server header. This method logs the appropriate number of bytes
* as determined by the binary logging configuration.
*/
abstract void logServerHeader(
long seq,
Metadata metadata,
GrpcLogEntry.Logger logger,
long callId,
// null on server
@Nullable SocketAddress peerAddress);
/**
* Logs the server trailer. This method logs the appropriate number of bytes
* as determined by the binary logging configuration.
*/
abstract void logTrailer(
long seq,
Status status,
Metadata metadata,
GrpcLogEntry.Logger logger,
long callId,
// null on server, can be non null on client if this is a trailer-only response
@Nullable SocketAddress peerAddress);
/**
* Logs the message message. The number of bytes logged is determined by the binary
* logging configuration.
*/
abstract <T> void logRpcMessage(
long seq,
EventType eventType,
Marshaller<T> marshaller,
T message,
GrpcLogEntry.Logger logger,
long callId);
abstract void logHalfClose(long seq, GrpcLogEntry.Logger logger, long callId);
/**
* Logs the cancellation.
*/
abstract void logCancel(long seq, GrpcLogEntry.Logger logger, long callId);
/**
* Returns the number bytes of the header this writer will log, according to configuration.
*/
abstract int getMaxHeaderBytes();
/**
* Returns the number bytes of the message this writer will log, according to configuration.
*/
abstract int getMaxMessageBytes();
}
static SocketAddress getPeerSocket(Attributes streamAttributes) {
return streamAttributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
}
private static Deadline min(@Nullable Deadline deadline0, @Nullable Deadline deadline1) {
if (deadline0 == null) {
return deadline1;
}
if (deadline1 == null) {
return deadline0;
}
return deadline0.minimum(deadline1);
}
| SinkWriter |
java | grpc__grpc-java | api/src/main/java/io/grpc/NameResolver.java | {
"start": 26150,
"end": 29422
} | class ____ {
private final StatusOr<List<EquivalentAddressGroup>> addressesOrError;
@ResolutionResultAttr
private final Attributes attributes;
@Nullable
private final ConfigOrError serviceConfig;
ResolutionResult(
StatusOr<List<EquivalentAddressGroup>> addressesOrError,
@ResolutionResultAttr Attributes attributes,
ConfigOrError serviceConfig) {
this.addressesOrError = addressesOrError;
this.attributes = checkNotNull(attributes, "attributes");
this.serviceConfig = serviceConfig;
}
/**
* Constructs a new builder of a name resolution result.
*
* @since 1.21.0
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* Converts these results back to a builder.
*
* @since 1.21.0
*/
public Builder toBuilder() {
return newBuilder()
.setAddressesOrError(addressesOrError)
.setAttributes(attributes)
.setServiceConfig(serviceConfig);
}
/**
* Gets the addresses resolved by name resolution.
*
* @since 1.21.0
* @deprecated Will be superseded by getAddressesOrError
*/
@Deprecated
public List<EquivalentAddressGroup> getAddresses() {
return addressesOrError.getValue();
}
/**
* Gets the addresses resolved by name resolution or the error in doing so.
*
* @since 1.65.0
*/
public StatusOr<List<EquivalentAddressGroup>> getAddressesOrError() {
return addressesOrError;
}
/**
* Gets the attributes associated with the addresses resolved by name resolution. If there are
* no attributes, {@link Attributes#EMPTY} will be returned.
*
* @since 1.21.0
*/
@ResolutionResultAttr
public Attributes getAttributes() {
return attributes;
}
/**
* Gets the Service Config parsed by {@link Args#getServiceConfigParser}.
*
* @since 1.21.0
*/
@Nullable
public ConfigOrError getServiceConfig() {
return serviceConfig;
}
@Override
public String toString() {
ToStringHelper stringHelper = MoreObjects.toStringHelper(this);
stringHelper.add("addressesOrError", addressesOrError.toString());
stringHelper.add("attributes", attributes);
stringHelper.add("serviceConfigOrError", serviceConfig);
return stringHelper.toString();
}
/**
* Useful for testing. May be slow to calculate.
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ResolutionResult)) {
return false;
}
ResolutionResult that = (ResolutionResult) obj;
return Objects.equal(this.addressesOrError, that.addressesOrError)
&& Objects.equal(this.attributes, that.attributes)
&& Objects.equal(this.serviceConfig, that.serviceConfig);
}
/**
* Useful for testing. May be slow to calculate.
*/
@Override
public int hashCode() {
return Objects.hashCode(addressesOrError, attributes, serviceConfig);
}
/**
* A builder for {@link ResolutionResult}.
*
* @since 1.21.0
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1770")
public static final | ResolutionResult |
java | apache__camel | components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/IncomingPhoneNumberEndpointConfiguration.java | {
"start": 2190,
"end": 3723
} | class ____ extends TwilioConfiguration {
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private String areaCode;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator"), @ApiMethod(methodName = "deleter"), @ApiMethod(methodName = "fetcher"), @ApiMethod(methodName = "reader"), @ApiMethod(methodName = "updater")})
private String pathAccountSid;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "deleter"), @ApiMethod(methodName = "fetcher"), @ApiMethod(methodName = "updater")})
private String pathSid;
@UriParam
@ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "creator")})
private com.twilio.type.PhoneNumber phoneNumber;
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getPathAccountSid() {
return pathAccountSid;
}
public void setPathAccountSid(String pathAccountSid) {
this.pathAccountSid = pathAccountSid;
}
public String getPathSid() {
return pathSid;
}
public void setPathSid(String pathSid) {
this.pathSid = pathSid;
}
public com.twilio.type.PhoneNumber getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(com.twilio.type.PhoneNumber phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
| IncomingPhoneNumberEndpointConfiguration |
java | netty__netty | example/src/main/java/io/netty/example/securechat/SecureChatServer.java | {
"start": 1303,
"end": 2264
} | class ____ {
static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));
public static void main(String[] args) throws Exception {
X509Bundle ssc = new CertificateBuilder()
.subject("cn=localhost")
.setIsCertificateAuthority(true)
.buildSelfSigned();
SslContext sslCtx = SslContextBuilder.forServer(ssc.toKeyManagerFactory())
.build();
EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new SecureChatServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
| SecureChatServer |
java | quarkusio__quarkus | extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/StreamCommandsTest.java | {
"start": 1507,
"end": 33745
} | class ____ extends DatasourceTestBase {
private RedisDataSource ds;
private StreamCommands<String, String, Integer> stream;
@BeforeEach
void initialize() {
ds = new BlockingRedisDataSourceImpl(vertx, redis, api, Duration.ofSeconds(1));
stream = ds.stream(Integer.class);
}
@AfterEach
void clear() {
ds.flushall();
}
@Test
void getDataSource() {
assertThat(ds).isEqualTo(stream.getDataSource());
}
@Test
void xreadTest() {
stream.xadd("my-stream", Map.of("duration", 1532, "event-id", 5, "user-id", 77788));
stream.xadd("my-stream", Map.of("duration", 1533, "event-id", 6, "user-id", 77788));
stream.xadd("my-stream", Map.of("duration", 1534, "event-id", 7, "user-id", 77788));
List<StreamMessage<String, String, Integer>> messages = stream.xread("my-stream", "0-0");
assertThat(messages).hasSize(3)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo("my-stream");
assertThat(m.id()).isNotEmpty().contains("-");
assertThat(m.payload()).contains(entry("user-id", 77788)).containsKey("event-id").containsKey("duration");
});
}
@Test
void xAdd() {
assertThat(stream.xadd("mystream", Map.of("sensor-id", 1234, "temperature", 19)))
.isNotBlank().contains("-");
long now = System.currentTimeMillis();
assertThat(stream.xadd("mystream", new XAddArgs().id(now + 1000 + "-0"),
Map.of("sensor-id", 1234, "temperature", 19))).isEqualTo(now + 1000 + "-0");
for (int i = 0; i < 10; i++) {
assertThat(stream.xadd("my-second-stream", new XAddArgs().maxlen(5L),
Map.of("sensor-id", 1234, "temperature", 19))).isNotBlank();
}
assertThat(stream.xlen("my-second-stream")).isEqualTo(5);
}
@Test
@RequiresRedis7OrHigher
void xAddWithRedis7() {
assertThat(stream.xadd("mystream", Map.of("sensor-id", 1234, "temperature", 19)))
.isNotBlank().contains("-");
long now = System.currentTimeMillis();
assertThat(stream.xadd("mystream", new XAddArgs().id(now + 1000 + "-0"),
Map.of("sensor-id", 1234, "temperature", 19))).isEqualTo(now + 1000 + "-0");
for (int i = 0; i < 10; i++) {
assertThat(stream.xadd("my-second-stream", new XAddArgs().maxlen(5L),
Map.of("sensor-id", 1234, "temperature", 19))).isNotBlank();
}
assertThat(stream.xlen("my-second-stream")).isEqualTo(5);
for (int i = 0; i < 10; i++) {
assertThat(stream.xadd("my-third-stream", new XAddArgs().minid("12345-0").nearlyExactTrimming()
.limit(3).id("12346-" + i),
Map.of("sensor-id", 1234, "temperature", 19))).isNotBlank();
}
assertThat(stream.xlen("my-third-stream")).isEqualTo(10);
assertThat(stream.xadd("another", new XAddArgs().nomkstream(), Map.of("foo", 12))).isNull();
}
@Test
void xLen() {
assertThat(stream.xlen("missing")).isEqualTo(0);
assertThat(stream.xadd("mystream", Map.of("sensor-id", 1234, "temperature", 19)))
.isNotBlank().contains("-");
assertThat(stream.xlen("mystream")).isEqualTo(1);
}
@Test
void xRangeAndxRevRange() {
List<String> ids = new ArrayList<>();
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 3; i++) {
ids.add(stream.xadd(key, payload));
}
assertThat(stream.xlen(key)).isEqualTo(3);
assertThat(stream.xrange(key, StreamRange.of("-", "+")))
.hasSize(3)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.id()).isNotBlank();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xrange(key, StreamRange.of(ids.get(1), ids.get(2))))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.id()).isNotBlank();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xrange(key, StreamRange.of("-", "+"), 2))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.id()).isNotBlank();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xrevrange(key, StreamRange.of("+", "-")))
.hasSize(3)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.id()).isNotBlank();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xrevrange(key, StreamRange.of(ids.get(2), ids.get(1))))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.id()).isNotBlank();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xrevrange(key, StreamRange.of("+", "-"), 2))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.id()).isNotBlank();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
}
@Test
void xReadWithAndWithoutCount() {
List<String> ids1 = new ArrayList<>();
List<String> ids2 = new ArrayList<>();
String key2 = key + "2";
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 3; i++) {
ids1.add(stream.xadd(key, payload));
ids2.add(stream.xadd(key2, payload));
}
assertThat(stream.xlen(key)).isEqualTo(3);
assertThat(stream.xlen(key2)).isEqualTo(3);
assertThat(stream.xread(key, "0", new XReadArgs().count(2)))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(ids1).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xread(key2, "0"))
.hasSize(3)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key2);
assertThat(ids2).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
}
@Test
void xReadMultipleStreams() {
List<String> ids = new ArrayList<>();
String key2 = key + "2";
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 3; i++) {
ids.add(stream.xadd(key, payload));
ids.add(stream.xadd(key2, payload));
}
assertThat(stream.xlen(key)).isEqualTo(3);
assertThat(stream.xlen(key2)).isEqualTo(3);
assertThat(stream.xread(Map.of(key2, "0", key, "0")))
.hasSize(6)
.allSatisfy(m -> {
assertThat(m.key().equals(key) || m.key().equals(key2)).isTrue();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xread(Map.of(key2, "0", key, "0"), new XReadArgs().count(2)))
.hasSize(4) // the count is per stream
.allSatisfy(m -> {
assertThat(m.key().equals(key) || m.key().equals(key2)).isTrue();
assertThat(ids).contains(m.id());
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
}
@Test
void xReadBlocking() throws InterruptedException {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
assertThat(stream.xread(key, "$", new XReadArgs().block(Duration.ofSeconds(10))))
.isNotEmpty()
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
latch.countDown();
}).start();
await()
.pollDelay(10, TimeUnit.MILLISECONDS)
.until(() -> {
stream.xadd(key, payload);
return latch.getCount() == 0;
});
}
@Test
void xReadBlockingMultipleStreams() {
String key2 = key + "2";
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
assertThat(stream.xread(Map.of(key, "$", key2, "$"), new XReadArgs().block(Duration.ofSeconds(10))))
.isNotEmpty()
.allSatisfy(m -> {
assertThat(m.key().equals(key) || m.key().equals(key2)).isTrue();
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
latch.countDown();
}).start();
await()
.pollDelay(10, TimeUnit.MILLISECONDS)
.until(() -> {
stream.xadd(key2, payload);
stream.xadd(key, payload);
return latch.getCount() == 0;
});
}
@Test
void consumerGroupTests() {
String g1 = "my-group";
stream.xgroupCreate(key, g1, "$", new XGroupCreateArgs().mkstream());
String g2 = "my-group-2";
stream.xgroupCreate(key, g2, "$");
String g3 = "my-group-3";
String key2 = key + "2";
stream.xgroupCreate(key, g3, "$");
stream.xgroupCreate(key2, g3, "$", new XGroupCreateArgs().mkstream());
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 5; i++) {
stream.xadd(key, payload);
stream.xadd(key2, payload);
}
assertThat(stream.xreadgroup(g1, "c1", key, ">", new XReadGroupArgs().count(1)))
.hasSize(1)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
assertThat(stream.xreadgroup(g1, "c2", key, ">"))
.hasSize(4)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
assertThat(stream.xack(m.key(), g1, m.id())).isEqualTo(1);
});
assertThat(stream.xreadgroup(g2, "c2", key, ">"))
.hasSize(5)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
assertThat(stream.xack(m.key(), g2, m.id())).isEqualTo(1);
});
assertThat(stream.xreadgroup(g2, "c2", key, ">"))
.hasSize(0);
assertThat(stream.xreadgroup(g3, "c1", Map.of(key, ">", key2, ">"), new XReadGroupArgs().count(1)))
.hasSize(2); // 1 per stream
assertThat(stream.xreadgroup(g3, "c1", Map.of(key, ">", key2, ">"),
new XReadGroupArgs().block(Duration.ofSeconds(1)).noack()))
.hasSize(8);
assertThat(stream.xreadgroup(g3, "c1", Map.of(key, ">", key2, ">")))
.hasSize(0);
}
@Test
void consumerGroupTestsBlocking() {
String g1 = "my-group";
stream.xgroupCreate(key, g1, "$", new XGroupCreateArgs().mkstream());
String g3 = "my-group-3";
String key2 = key + "2";
stream.xgroupCreate(key, g3, "$");
stream.xgroupCreate(key2, g3, "$", new XGroupCreateArgs().mkstream());
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
assertThat(stream.xreadgroup(g1, "c1", key, ">", new XReadGroupArgs().block(Duration.ofSeconds(10)).count(1)))
.isNotEmpty()
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
});
latch.countDown();
}).start();
stream.xadd(key, payload);
await()
.pollDelay(10, TimeUnit.MILLISECONDS)
.until(() -> {
stream.xadd(key, payload);
return latch.getCount() == 0;
});
CountDownLatch latch2 = new CountDownLatch(1);
new Thread(() -> {
assertThat(stream.xreadgroup(g3, "c1", Map.of(key, ">", key2, ">"),
new XReadGroupArgs().block(Duration.ofSeconds(10))))
.isNotEmpty();
latch2.countDown();
}).start();
stream.xadd(key2, payload);
await()
.pollDelay(10, TimeUnit.MILLISECONDS)
.until(() -> {
stream.xadd(key2, payload);
return latch.getCount() == 0;
});
}
@Test
void xClaim() throws InterruptedException {
String g1 = "my-group";
stream.xgroupCreate(key, g1, "$", new XGroupCreateArgs().mkstream());
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 5; i++) {
stream.xadd(key, payload);
}
List<String> pending = new ArrayList<>();
assertThat(stream.xreadgroup(g1, "c1", key, ">", new XReadGroupArgs().count(2)))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
// Do not ack
pending.add(m.id());
});
List<String> read = new ArrayList<>();
assertThat(stream.xreadgroup(g1, "c2", key, ">", new XReadGroupArgs().count(2)))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
read.add(m.id());
});
assertThat(stream.xack(key, g1, read.toArray(new String[0]))).isEqualTo(2);
// Make sure that the message are pending for a bit of time before claiming the ownership
Thread.sleep(5);
assertThat(stream.xclaim(key, g1, "c2", Duration.ofMillis(1), pending.toArray(new String[0])))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
stream.xack(key, g1, m.id());
});
assertThat(stream.xreadgroup(g1, "c1", key, ">")).hasSize(1);
assertThat(stream.xreadgroup(g1, "c2", key, ">")).hasSize(0);
}
@Test
void xClaimWithArgs() throws InterruptedException {
String g1 = "my-group";
stream.xgroupCreate(key, g1, "$", new XGroupCreateArgs().mkstream());
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 5; i++) {
stream.xadd(key, payload);
}
List<String> pending = new ArrayList<>();
assertThat(stream.xreadgroup(g1, "c1", key, ">", new XReadGroupArgs().count(2)))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
// Do not ack
pending.add(m.id());
});
List<String> read = new ArrayList<>();
assertThat(stream.xreadgroup(g1, "c2", key, ">", new XReadGroupArgs().count(2)))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
read.add(m.id());
});
assertThat(stream.xack(key, g1, read.toArray(new String[0]))).isEqualTo(2);
// Make sure that the message are pending for a bit of time before claiming the ownership
Thread.sleep(5);
assertThat(stream.xclaim(key, g1, "c2", Duration.ofMillis(1), new XClaimArgs()
.force().retryCount(5).idle(Duration.ofMillis(1)).justId(), pending.toArray(new String[0])))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).isEmpty(); // Justid
stream.xack(key, g1, m.id());
});
assertThat(stream.xreadgroup(g1, "c1", key, ">")).hasSize(1);
assertThat(stream.xreadgroup(g1, "c2", key, ">")).hasSize(0);
}
@Test
@RequiresRedis6OrHigher
void xAutoClaim() throws InterruptedException {
String g1 = "my-group";
stream.xgroupCreate(key, g1, "$", new XGroupCreateArgs().mkstream());
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 10; i++) {
stream.xadd(key, payload);
}
assertThat(stream.xreadgroup(g1, "c1", key, ">", new XReadGroupArgs().count(4)))
.hasSize(4)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
// Do not ack
});
List<String> read = new ArrayList<>();
assertThat(stream.xreadgroup(g1, "c2", key, ">", new XReadGroupArgs().count(2)))
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
read.add(m.id());
});
assertThat(stream.xack(key, g1, read.toArray(new String[0]))).isEqualTo(2);
// Make sure that the message are pending for a bit of time before claiming the ownership
Thread.sleep(5);
var claimed = stream.xautoclaim(key, g1, "c2", Duration.ofMillis(1), "0", 1);
assertThat(claimed.getMessages())
.hasSize(1)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
stream.xack(key, g1, m.id());
});
claimed = stream.xautoclaim(key, g1, "c2", Duration.ofMillis(1), "0", 2, true);
assertThat(claimed.getMessages())
.hasSize(2)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).isEmpty();
stream.xack(key, g1, m.id());
});
claimed = stream.xautoclaim(key, g1, "c2", Duration.ofMillis(1), claimed.getId());
assertThat(claimed.getMessages())
.hasSize(1)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo(key);
assertThat(m.payload()).containsExactlyInAnyOrderEntriesOf(payload);
stream.xack(key, g1, m.id());
});
}
@Test
@RequiresRedis6OrHigher
void xTrim() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
var l = stream.xtrim(key, new XTrimArgs().maxlen(50));
assertThat(l).isEqualTo(50);
assertThat(stream.xlen(key)).isEqualTo(50);
var list = stream.xrange(key, StreamRange.of("-", "+"));
var id = list.get(10).id();
l = stream.xtrim(key, id);
assertThat(l).isEqualTo(10);
assertThat(stream.xlen(key)).isEqualTo(40);
}
@Test
void xDel() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
var list = stream.xrange(key, StreamRange.of("-", "+"));
assertThat(stream.xdel(key, list.get(0).id(), list.get(3).id(), "12345-01")).isEqualTo(2);
assertThat(stream.xlen(key)).isEqualTo(98);
}
@Test
@RequiresRedis6OrHigher
void xGroupCreateAndDeleteConsumer() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
stream.xgroupCreate(key, "g1", "0");
assertThat(stream.xgroupCreateConsumer(key, "g1", "c1")).isTrue();
assertThat(stream.xgroupCreateConsumer(key, "g1", "c2")).isTrue();
assertThat(stream.xgroupCreateConsumer(key, "g1", "c1")).isFalse();
assertThatThrownBy(() -> stream.xgroupCreateConsumer(key, "missing", "c3"))
.hasMessageContaining("missing");
assertThat(stream.xgroupDelConsumer(key, "g1", "c1")).isEqualTo(0);
assertThat(stream.xreadgroup("g1", "c2", key, ">", new XReadGroupArgs().count(10))).hasSize(10);
assertThat(stream.xgroupDelConsumer(key, "g1", "c2")).isEqualTo(10);
assertThat(stream.xgroupDestroy(key, "g1")).isTrue();
}
@Test
void xGroupSetId() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
List<String> ids = new ArrayList<>();
for (int i = 0; i < 100; i++) {
ids.add(stream.xadd(key, payload));
}
stream.xgroupCreate(key, "g1", "0");
assertThat(stream.xreadgroup("g1", "c2", key, ">", new XReadGroupArgs().count(10))).hasSize(10);
stream.xgroupSetId(key, "g1", ids.get(50));
assertThat(stream.xreadgroup("g1", "c2", key, ">")).hasSize(49);
}
@Test
@RequiresRedis7OrHigher
void xGroupSetIdWithArgs() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
List<String> ids = new ArrayList<>();
for (int i = 0; i < 100; i++) {
ids.add(stream.xadd(key, payload));
}
stream.xgroupCreate(key, "g1", "0");
assertThat(stream.xreadgroup("g1", "c2", key, ">", new XReadGroupArgs().count(10))).hasSize(10);
stream.xgroupSetId(key, "g1", ids.get(50), new XGroupSetIdArgs().entriesRead(1234));
assertThat(stream.xreadgroup("g1", "c2", key, ">")).hasSize(49);
}
@Test
void xPendingSummaryTest() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
stream.xadd(key, payload);
stream.xtrim(key, new XTrimArgs().maxlen(0));
stream.xgroupCreate(key, "my-group", "0-0");
XPendingSummary summaryEmpty = stream.xpending(key, "my-group");
assertThat(summaryEmpty.getPendingCount()).isEqualTo(0);
assertThat(summaryEmpty.getHighestId()).isNull();
assertThat(summaryEmpty.getLowestId()).isNull();
assertThat(summaryEmpty.getConsumers()).isEmpty();
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
List<StreamMessage<String, String, Integer>> messages = stream.xreadgroup("my-group", "consumer-123", key, ">");
assertThat(messages).hasSize(100);
XPendingSummary summary = stream.xpending(key, "my-group");
assertThat(summary.getPendingCount()).isEqualTo(100L);
assertThat(summary.getHighestId()).isNotNull();
assertThat(summary.getLowestId()).isNotNull();
assertThat(summary.getConsumers()).containsExactly(entry("consumer-123", 100L));
}
@Test
void xPendingSummaryTestWithTwoConsumers() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
stream.xgroupCreate(key, "my-group", "0-0");
List<StreamMessage<String, String, Integer>> m1 = stream.xreadgroup("my-group", "consumer-1", key, ">");
List<StreamMessage<String, String, Integer>> m2 = stream.xreadgroup("my-group", "consumer-2", key, ">");
assertThat(m1.size() + m2.size()).isEqualTo(100);
XPendingSummary summary = stream.xpending(key, "my-group");
assertThat(summary.getPendingCount()).isEqualTo(100L);
assertThat(summary.getHighestId()).isNotNull();
assertThat(summary.getLowestId()).isNotNull();
assertThat(summary.getConsumers()).containsOnlyKeys("consumer-1"); // The second didn't have the chance to poll
}
@Test
void xPendingExtendedTest() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
stream.xgroupCreate(key, "my-group", "0-0");
List<StreamMessage<String, String, Integer>> messages = stream.xreadgroup("my-group", "consumer-123", key, ">");
assertThat(messages).hasSize(100);
List<PendingMessage> pending = stream.xpending(key, "my-group", StreamRange.of("-", "+"), 10);
assertThat(pending).hasSize(10);
assertThat(pending).allSatisfy(msg -> {
assertThat(msg.getMessageId()).isNotNull();
assertThat(msg.getDeliveryCount()).isEqualTo(1);
assertThat(msg.getDurationSinceLastDelivery()).isNotNull();
assertThat(msg.getConsumer()).isEqualTo("consumer-123");
});
}
@Test
void xPendingExtendedWithConsumerTest() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
stream.xgroupCreate(key, "my-group", "0-0");
stream.xreadgroup("my-group", "consumer-123", key, ">");
stream.xreadgroup("my-group", "consumer-456", key, ">");
List<PendingMessage> pending = stream.xpending(key, "my-group", StreamRange.of("-", "+"), 10,
new XPendingArgs().consumer("consumer-123"));
assertThat(pending).hasSize(10);
assertThat(pending).allSatisfy(msg -> {
assertThat(msg.getMessageId()).isNotNull();
assertThat(msg.getDeliveryCount()).isEqualTo(1);
assertThat(msg.getDurationSinceLastDelivery()).isNotNull();
assertThat(msg.getConsumer()).isEqualTo("consumer-123");
});
pending = stream.xpending(key, "my-group", StreamRange.of("-", "+"), 10, new XPendingArgs().consumer("consumer-456"));
assertThat(pending).isEmpty();
pending = stream.xpending(key, "my-group", StreamRange.of("-", "+"), 10,
new XPendingArgs().consumer("consumer-missing"));
assertThat(pending).isEmpty();
}
@Test
void xPendingExtendedTestWithConsumerAndIdle() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
stream.xgroupCreate(key, "my-group", "0-0");
stream.xreadgroup("my-group", "consumer-123", key, ">");
stream.xreadgroup("my-group", "consumer-456", key, ">");
}
@Test
@RequiresRedis6OrHigher
void xPendingExtendedTestWithConsumerAndIdleWithRedis6() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
stream.xgroupCreate(key, "my-group", "0-0");
stream.xreadgroup("my-group", "consumer-123", key, ">");
stream.xreadgroup("my-group", "consumer-456", key, ">");
AtomicReference<List<PendingMessage>> reference = new AtomicReference<>();
await().untilAsserted(() -> {
List<PendingMessage> pending = stream.xpending(key, "my-group", StreamRange.of("-", "+"), 10, new XPendingArgs()
.idle(Duration.ofSeconds(1))
.consumer("consumer-123"));
assertThat(pending).hasSize(10);
reference.set(pending);
});
assertThat(reference.get()).allSatisfy(msg -> {
assertThat(msg.getMessageId()).isNotNull();
assertThat(msg.getDeliveryCount()).isEqualTo(1);
assertThat(msg.getDurationSinceLastDelivery()).isNotNull();
assertThat(msg.getConsumer()).isEqualTo("consumer-123");
});
}
@Test
@RequiresRedis6OrHigher
void xPendingExtendedTestWithIdle() {
Map<String, Integer> payload = Map.of("sensor-id", 1234, "temperature", 19);
for (int i = 0; i < 100; i++) {
stream.xadd(key, payload);
}
stream.xgroupCreate(key, "my-group", "0-0");
stream.xreadgroup("my-group", "consumer-123", key, ">");
AtomicReference<List<PendingMessage>> reference = new AtomicReference<>();
await().untilAsserted(() -> {
List<PendingMessage> pending = stream.xpending(key, "my-group", StreamRange.of("-", "+"), 10, new XPendingArgs()
.idle(Duration.ofSeconds(1)));
assertThat(pending).hasSize(10);
reference.set(pending);
});
assertThat(reference.get()).allSatisfy(msg -> {
assertThat(msg.getMessageId()).isNotNull();
assertThat(msg.getDeliveryCount()).isEqualTo(1);
assertThat(msg.getDurationSinceLastDelivery()).isNotNull();
assertThat(msg.getConsumer()).isEqualTo("consumer-123");
});
}
@Test
void streamWithTypeReference() {
var stream = ds.stream(new TypeReference<List<Integer>>() {
// Empty on purpose
});
stream.xadd("my-stream", Map.of("duration", List.of(1532), "event-id", List.of(5), "user-id", List.of(77788)));
stream.xadd("my-stream", Map.of("duration", List.of(1533), "event-id", List.of(6), "user-id", List.of(77788)));
stream.xadd("my-stream", Map.of("duration", List.of(1534), "event-id", List.of(7), "user-id", List.of(77788)));
List<StreamMessage<String, String, List<Integer>>> messages = stream.xread("my-stream", "0-0");
assertThat(messages).hasSize(3)
.allSatisfy(m -> {
assertThat(m.key()).isEqualTo("my-stream");
assertThat(m.id()).isNotEmpty().contains("-");
assertThat(m.payload()).contains(entry("user-id", List.of(77788))).containsKey("event-id")
.containsKey("duration");
});
}
}
| StreamCommandsTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_3238/Issue3238Test.java | {
"start": 653,
"end": 1250
} | class ____ {
@ProcessorTest
@ExpectedCompilationOutcome(
value = CompilationResult.FAILED,
diagnostics = @Diagnostic( type = ErroneousIssue3238Mapper.class,
kind = javax.tools.Diagnostic.Kind.ERROR,
line = 14,
message = "Using @Mapping( target = \".\", ignore = true ) is not allowed." +
" You need to use @BeanMapping( ignoreByDefault = true ) if you would like to ignore" +
" all non explicitly mapped target properties."
)
)
void shouldGenerateValidCompileError() {
}
}
| Issue3238Test |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/ListMultimapTestSuiteBuilder.java | {
"start": 1753,
"end": 2159
} | class ____<K, V>
extends MultimapTestSuiteBuilder<K, V, ListMultimap<K, V>> {
public static <K, V> ListMultimapTestSuiteBuilder<K, V> using(
TestListMultimapGenerator<K, V> generator) {
ListMultimapTestSuiteBuilder<K, V> result = new ListMultimapTestSuiteBuilder<>();
result.usingGenerator(generator);
return result;
}
@SuppressWarnings("rawtypes") // | ListMultimapTestSuiteBuilder |
java | quarkusio__quarkus | extensions/flyway/runtime-dev/src/main/java/io/quarkus/flyway/runtime/dev/ui/FlywayJsonRpcService.java | {
"start": 832,
"end": 10133
} | class ____ {
private Map<String, Supplier<String>> initialSqlSuppliers;
private Map<String, Supplier<String>> updateSqlSuppliers;
private String artifactId;
private Map<String, FlywayDatasource> datasources;
@ConfigProperty(name = "quarkus.flyway.locations")
private List<String> locations;
@ConfigProperty(name = "quarkus.flyway.clean-disabled")
private boolean cleanDisabled;
public void setInitialSqlSuppliers(Map<String, Supplier<String>> initialSqlSuppliers) {
this.initialSqlSuppliers = initialSqlSuppliers;
}
public void setUpdateSqlSuppliers(Map<String, Supplier<String>> updateSqlSuppliers) {
this.updateSqlSuppliers = updateSqlSuppliers;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public Collection<FlywayDatasource> getDatasources() {
if (datasources == null) {
datasources = new HashMap<>();
Collection<FlywayContainer> flywayContainers = new FlywayContainersSupplier().get();
for (FlywayContainer fc : flywayContainers) {
datasources.put(fc.getDataSourceName(),
new FlywayDatasource(fc.getDataSourceName(), fc.isHasMigrations(), fc.isCreatePossible()));
}
}
return datasources.values();
}
public boolean isCleanDisabled() {
return this.cleanDisabled;
}
public FlywayActionResponse clean(String ds) {
Flyway flyway = getFlyway(ds);
if (flyway != null) {
CleanResult cleanResult = flyway.clean();
if (cleanResult.warnings != null && cleanResult.warnings.size() > 0) {
return new FlywayActionResponse("warning",
"Cleaning failed",
cleanResult.warnings.size(),
null,
cleanResult.database, cleanResult.warnings);
} else {
return new FlywayActionResponse("success",
"Cleaned",
cleanResult.schemasCleaned.size(),
null,
cleanResult.database);
}
}
return errorNoDatasource(ds);
}
public FlywayActionResponse migrate(String ds) {
Flyway flyway = getFlyway(ds);
if (flyway != null) {
MigrateResult migrateResult = flyway.migrate();
if (migrateResult.success) {
return new FlywayActionResponse("success",
"Migration executed",
migrateResult.migrationsExecuted,
migrateResult.schemaName,
migrateResult.database);
} else {
return new FlywayActionResponse("warning",
"Migration failed",
migrateResult.warnings.size(),
migrateResult.schemaName,
migrateResult.database,
migrateResult.warnings);
}
}
return errorNoDatasource(ds);
}
public FlywayActionResponse create(String ds) {
this.getDatasources(); // Make sure we populated the datasources
Supplier<String> found = initialSqlSuppliers.get(ds);
if (found == null) {
return new FlywayActionResponse("error", "Unable to find SQL generator");
}
String script = found.get();
Flyway flyway = getFlyway(ds);
if (flyway != null) {
if (script != null) {
Map<String, String> params = Map.of("ds", ds, "script", script, "artifactId", artifactId);
try {
if (locations.isEmpty()) {
return new FlywayActionResponse("error", "Datasource has no locations configured");
}
List<Path> resourcesDir = DevConsoleManager.getHotReplacementContext().getResourcesDir();
if (resourcesDir.isEmpty()) {
return new FlywayActionResponse("error", "No resource directory found");
}
// In the current project only
Path path = resourcesDir.get(0);
Path migrationDir = path.resolve(locations.get(0));
Files.createDirectories(migrationDir);
Path file = migrationDir.resolve(
"V1.0.0__" + artifactId + ".sql");
Files.writeString(file, script);
FlywayDatasource flywayDatasource = datasources.get(ds);
flywayDatasource.hasMigrations = true;
flywayDatasource.createPossible = false;
Map<String, String> newConfig = new HashMap<>();
boolean isBaselineOnMigrateConfigured = ConfigUtils
.isPropertyPresent("quarkus.flyway.baseline-on-migrate");
boolean isMigrateAtStartConfigured = ConfigUtils.isPropertyPresent("quarkus.flyway.migrate-at-start");
boolean isCleanAtStartConfigured = ConfigUtils.isPropertyPresent("quarkus.flyway.clean-at-start");
if (!isBaselineOnMigrateConfigured) {
newConfig.put("quarkus.flyway.baseline-on-migrate", "true");
}
if (!isMigrateAtStartConfigured) {
newConfig.put("quarkus.flyway.migrate-at-start", "true");
}
for (var profile : of("test", "dev")) {
if (!isCleanAtStartConfigured) {
newConfig.put("%" + profile + ".quarkus.flyway.clean-at-start", "true");
}
}
CurrentConfig.EDITOR.accept(newConfig);
//force a scan, to make sure everything is up-to-date
DevConsoleManager.getHotReplacementContext().doScan(true);
return new FlywayActionResponse("success",
"Initial migration created, Flyway will now manage this datasource");
} catch (Throwable t) {
return new FlywayActionResponse("error", t.getMessage());
}
}
return errorNoScript(ds);
}
return errorNoDatasource(ds);
}
public FlywayActionResponse update(String ds) {
try {
Supplier<String> found = updateSqlSuppliers.get(ds);
if (found == null) {
return new FlywayActionResponse("error", "Unable to find SQL Update generator");
}
String script = found.get();
if (script == null) {
return new FlywayActionResponse("error", "Missing Flyway update script for [" + ds + "]");
}
Flyway flyway = getFlyway(ds);
if (flyway == null) {
return errorNoDatasource(ds);
}
if (locations.isEmpty()) {
return new FlywayActionResponse("error", "Datasource has no locations configured");
}
List<Path> resourcesDir = DevConsoleManager.getHotReplacementContext().getResourcesDir();
if (resourcesDir.isEmpty()) {
return new FlywayActionResponse("error", "No resource directory found");
}
// In the current project only
Path path = resourcesDir.get(0);
Path migrationDir = path.resolve(locations.get(0));
Files.createDirectories(migrationDir);
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy.MM.dd.HHmmss");
String timestamp = LocalDateTime.now().format(format);
BigInteger major = flyway.info().current().isVersioned() ? flyway.info().current().getVersion().getMajor()
: BigInteger.ONE;
Path file = migrationDir.resolve(
"V" + major + "." + timestamp + "__" + artifactId + ".sql");
Files.writeString(file, script);
return new FlywayActionResponse("success",
"migration created");
} catch (Throwable t) {
return new FlywayActionResponse("error", t.getMessage());
}
}
public int getNumberOfDatasources() {
Collection<FlywayContainer> flywayContainers = new FlywayContainersSupplier().get();
return flywayContainers.size();
}
private FlywayActionResponse errorNoDatasource(String ds) {
return new FlywayActionResponse("error", "Flyway datasource not found [" + ds + "]");
}
private FlywayActionResponse errorNoScript(String ds) {
return new FlywayActionResponse("error", "Missing Flyway initial script for [" + ds + "]");
}
private Flyway getFlyway(String ds) {
Collection<FlywayContainer> flywayContainers = new FlywayContainersSupplier().get();
for (FlywayContainer flywayContainer : flywayContainers) {
if (flywayContainer.getDataSourceName().equals(ds)) {
return flywayContainer.getFlyway();
}
}
return null;
}
public static | FlywayJsonRpcService |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/CommentsTest.java | {
"start": 9690,
"end": 10374
} | class ____ {
abstract void target(Object param1, Object param2);
private void test(Object param1, Object param2) {
// BUG: Diagnostic contains: [[] param1 [1], [] param2 []]
target(
param1, // 1
param2);
}
}
""")
.doTest();
}
@Test
@SuppressWarnings("MisformattedTestData")
public void findCommentsForArguments_assignToFirstParameter_withBlockAfterComma() {
CompilationTestHelper.newInstance(PrintCommentsForArguments.class, getClass())
.addSourceLines(
"Test.java",
"""
abstract | Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/ondeletecascade/OnDeleteManyToManyTest.java | {
"start": 2599,
"end": 2738
} | class ____ {
@Id
long id;
@ManyToMany(mappedBy = "bs")
@OnDelete(action = OnDeleteAction.CASCADE)
Set<A> as = new HashSet<>();
}
}
| B |
java | spring-projects__spring-boot | core/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java | {
"start": 5347,
"end": 5415
} | class ____ {
}
@SecondMetaImport
static | FirstMetaAnnotatedTestClass |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/operations/converters/SqlShowFunctionsConverter.java | {
"start": 1280,
"end": 2593
} | class ____ extends AbstractSqlShowConverter<SqlShowFunctions> {
@Override
public Operation getOperationWithoutPrep(
SqlShowFunctions sqlShowFunctions,
@Nullable String catalogName,
@Nullable String databaseName,
@Nullable ShowLikeOperator likeOp) {
final FunctionScope functionScope = getFunctionScope(sqlShowFunctions);
return new ShowFunctionsOperation(functionScope, catalogName, databaseName, likeOp);
}
@Override
public Operation getOperation(
SqlShowFunctions sqlShowFunctions,
@Nullable String catalogName,
@Nullable String databaseName,
String prep,
@Nullable ShowLikeOperator likeOp) {
final FunctionScope functionScope = getFunctionScope(sqlShowFunctions);
return new ShowFunctionsOperation(functionScope, prep, catalogName, databaseName, likeOp);
}
@Override
public Operation convertSqlNode(SqlShowFunctions sqlShowFunctions, ConvertContext context) {
return convertShowOperation(sqlShowFunctions, context);
}
private static FunctionScope getFunctionScope(SqlShowFunctions sqlShowFunctions) {
return sqlShowFunctions.requireUser() ? FunctionScope.USER : FunctionScope.ALL;
}
}
| SqlShowFunctionsConverter |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/HierarchicalMessageSource.java | {
"start": 718,
"end": 883
} | interface ____ MessageSource to be implemented by objects that
* can resolve messages hierarchically.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public | of |
java | apache__flink | flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/WebSubmissionExtensionTest.java | {
"start": 4976,
"end": 5549
} | class ____ implements ApplicationRunner {
private final Set<Thread> threads = Collections.newSetFromMap(new IdentityHashMap<>());
@Override
public List<JobID> run(
DispatcherGateway dispatcherGateway,
PackagedProgram program,
Configuration configuration) {
threads.add(Thread.currentThread());
return Collections.singletonList(new JobID());
}
public Collection<Thread> getThreads() {
return threads;
}
}
}
| ThreadCapturingApplicationRunner |
java | playframework__playframework | core/play/src/main/java/play/mvc/Action.java | {
"start": 415,
"end": 1707
} | class ____<T> extends Results {
/** @deprecated Deprecated as of 2.8.0. Method does nothing. */
@Deprecated
public void setContextComponents(JavaContextComponents contextComponents) {}
/** The action configuration - typically the annotation used to decorate the action method. */
public T configuration;
/** Where an action was defined. */
public AnnotatedElement annotatedElement;
/**
* The precursor action.
*
* <p>If this action was called in a chain then this will contain the value of the action that is
* called before this action. If no action was called first, then this value will be null.
*/
public Action<?> precursor;
/**
* The wrapped action.
*
* <p>If this action was called in a chain then this will contain the value of the action that is
* called after this action. If there is no action left to be called, then this value will be
* null.
*/
public Action<?> delegate;
/**
* Executes this action with the given HTTP request and returns the result.
*
* @param req the http request with which to execute this action
* @return a promise to the action's result
*/
public abstract CompletionStage<Result> call(Request req);
/** A simple action with no configuration. */
public abstract static | Action |
java | elastic__elasticsearch | x-pack/plugin/autoscaling/src/internalClusterTest/java/org/elasticsearch/xpack/autoscaling/existence/FrozenExistenceDeciderIT.java | {
"start": 2521,
"end": 7713
} | class ____ extends AbstractFrozenAutoscalingIntegTestCase {
private static final String INDEX_NAME = "index";
private static final String PARTIAL_INDEX_NAME = "partial-index";
@Override
protected String deciderName() {
return FrozenExistenceDeciderService.NAME;
}
@Override
protected Settings.Builder addDeciderSettings(Settings.Builder builder) {
return builder;
}
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
Settings.Builder settings = Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings));
settings.put(LifecycleSettings.LIFECYCLE_POLL_INTERVAL, "1s");
settings.put(LifecycleSettings.LIFECYCLE_HISTORY_INDEX_ENABLED, false);
settings.put(LifecycleSettings.SLM_HISTORY_INDEX_ENABLED_SETTING.getKey(), false);
return settings.build();
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return List.of(
BlobCachePlugin.class,
LocalStateAutoscalingAndSearchableSnapshotsAndIndexLifecycle.class,
SnapshotLifecycle.class,
Ccr.class
);
}
public void testZeroToOne() throws Exception {
internalCluster().startMasterOnlyNode();
setupRepoAndPolicy();
logger.info("starting 2 content data nodes");
internalCluster().startNode(NodeRoles.onlyRole(DiscoveryNodeRole.DATA_CONTENT_NODE_ROLE));
internalCluster().startNode(NodeRoles.onlyRole(DiscoveryNodeRole.DATA_CONTENT_NODE_ROLE));
// create an ignored snapshot to initialize the latest-N file.
createFullSnapshot(fsRepoName, snapshotName);
Phase hotPhase = new Phase("hot", TimeValue.ZERO, Collections.emptyMap());
Phase frozenPhase = new Phase(
"frozen",
TimeValue.ZERO,
singletonMap(SearchableSnapshotAction.NAME, new SearchableSnapshotAction(fsRepoName, randomBoolean()))
);
LifecyclePolicy lifecyclePolicy = new LifecyclePolicy("policy", Map.of("hot", hotPhase, "frozen", frozenPhase));
PutLifecycleRequest putLifecycleRequest = new PutLifecycleRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, lifecyclePolicy);
assertAcked(client().execute(ILMActions.PUT, putLifecycleRequest).get());
Settings settings = Settings.builder()
.put(indexSettings())
.put(SETTING_NUMBER_OF_SHARDS, 1)
.put(SETTING_NUMBER_OF_REPLICAS, 1)
.put(LifecycleSettings.LIFECYCLE_NAME, "policy")
.build();
CreateIndexResponse res = indicesAdmin().prepareCreate(INDEX_NAME).setSettings(settings).get();
assertTrue(res.isAcknowledged());
logger.info("-> created index");
assertBusy(() -> assertMinimumCapacity(capacity().results().get("frozen").requiredCapacity().total()));
assertMinimumCapacity(capacity().results().get("frozen").requiredCapacity().node());
assertThat(
clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT).get().getStatus(),
anyOf(equalTo(ClusterHealthStatus.YELLOW), equalTo(ClusterHealthStatus.GREEN))
);
assertBusy(() -> {
ExplainLifecycleResponse response = client().execute(
ExplainLifecycleAction.INSTANCE,
new ExplainLifecycleRequest(TEST_REQUEST_TIMEOUT).indices(INDEX_NAME)
).actionGet();
IndexLifecycleExplainResponse indexResponse = response.getIndexResponses().get(INDEX_NAME);
assertNotNull(indexResponse);
assertThat(indexResponse.getStep(), equalTo(WaitForDataTierStep.NAME));
});
// verify that SearchableSnapshotAction uses WaitForDataTierStep and that it waits.
assertThat(indices(), not(arrayContaining(PARTIAL_INDEX_NAME)));
logger.info("-> starting dedicated frozen node");
internalCluster().startNode(NodeRoles.onlyRole(DiscoveryNodeRole.DATA_FROZEN_NODE_ROLE));
// we've seen a case where bootstrapping a node took just over 60 seconds in the test environment, so using an (excessive) 90
// seconds max wait time to avoid flakiness
assertBusy(() -> {
// cause a bit of cluster activity using an empty reroute call in case the `wait-for-index-colour` ILM step missed the
// notification that partial-index is now GREEN.
ClusterRerouteUtils.reroute(client());
String[] indices = indices();
assertThat(indices, arrayContaining(PARTIAL_INDEX_NAME));
assertThat(indices, not(arrayContaining(INDEX_NAME)));
}, 90, TimeUnit.SECONDS);
ensureGreen();
}
private String[] indices() {
return indicesAdmin().prepareGetIndex(TEST_REQUEST_TIMEOUT).addIndices("index").get().indices();
}
private void assertMinimumCapacity(AutoscalingCapacity.AutoscalingResources resources) {
assertThat(resources.memory(), equalTo(FrozenExistenceDeciderService.MINIMUM_FROZEN_MEMORY));
assertThat(resources.storage(), equalTo(FrozenExistenceDeciderService.MINIMUM_FROZEN_STORAGE));
}
}
| FrozenExistenceDeciderIT |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/inheritance/deep/DeepInheritanceTest.java | {
"start": 788,
"end": 1289
} | class ____ {
@Test
@TestForIssue(jiraKey = "METAGEN-69")
@WithClasses({ JetPlane.class, PersistenceBase.class, Plane.class })
void testDeepInheritance() throws Exception {
assertMetamodelClassGeneratedFor( Plane.class );
assertMetamodelClassGeneratedFor( JetPlane.class );
assertPresenceOfFieldInMetamodelFor( JetPlane.class, "jets" );
assertAttributeTypeInMetaModelFor(
JetPlane.class,
"jets",
Integer.class,
"jets should be defined in JetPlane_"
);
}
}
| DeepInheritanceTest |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/matchers/AnnotationDoesNotHaveArgument.java | {
"start": 919,
"end": 1378
} | class ____ implements Matcher<AnnotationTree> {
private final String name;
/**
* Creates a new matcher.
*
* @param name the name of the argument to search for
*/
public AnnotationDoesNotHaveArgument(String name) {
this.name = name;
}
@Override
public boolean matches(AnnotationTree annotationTree, VisitorState state) {
return AnnotationMatcherUtils.getArgument(annotationTree, name) == null;
}
}
| AnnotationDoesNotHaveArgument |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Address.java | {
"start": 309,
"end": 595
} | class ____ {
private Integer id;
private String city;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| Address |
java | netty__netty | common/src/main/java/io/netty/util/ResourceLeakException.java | {
"start": 711,
"end": 779
} | class ____ be removed in the future version.
*/
@Deprecated
public | will |
java | apache__kafka | connect/api/src/main/java/org/apache/kafka/connect/storage/StringConverterConfig.java | {
"start": 1205,
"end": 2227
} | class ____ extends ConverterConfig {
public static final String ENCODING_CONFIG = "converter.encoding";
public static final String ENCODING_DEFAULT = StandardCharsets.UTF_8.name();
private static final String ENCODING_DOC = "The name of the Java character set to use for encoding strings as byte arrays.";
private static final String ENCODING_DISPLAY = "Encoding";
private static final ConfigDef CONFIG;
static {
CONFIG = ConverterConfig.newConfigDef();
CONFIG.define(ENCODING_CONFIG, Type.STRING, ENCODING_DEFAULT, Importance.HIGH, ENCODING_DOC, null, -1, Width.MEDIUM,
ENCODING_DISPLAY);
}
public static ConfigDef configDef() {
return CONFIG;
}
public StringConverterConfig(Map<String, ?> props) {
super(CONFIG, props);
}
/**
* Get the string encoding.
*
* @return the encoding; never null
*/
public String encoding() {
return getString(ENCODING_CONFIG);
}
}
| StringConverterConfig |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/jmx/access/MBeanProxyFactoryBean.java | {
"start": 2035,
"end": 2358
} | class ____ extends MBeanClientInterceptor
implements FactoryBean<Object>, BeanClassLoaderAware, InitializingBean {
private @Nullable Class<?> proxyInterface;
private @Nullable ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
private @Nullable Object mbeanProxy;
/**
* Set the | MBeanProxyFactoryBean |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/SpringJmsRoutingSlipInOutIT.java | {
"start": 1922,
"end": 2538
} | class ____ {
public void createSlip(@Headers Map<String, Object> headers) {
headers.put("mySlip",
"activemq:queue:SpringJmsRoutingSlipInOutTest.a,activemq:queue:SpringJmsRoutingSlipInOutTest.b");
}
public String backFromSlip(String body) {
return "Done-" + body;
}
public String doA(String body) {
return "A-" + body;
}
public String doB(String body) {
return "B-" + body;
}
public String doResult(String body) {
return "Result-" + body;
}
}
}
| MyBean |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/DefaultNameMapper.java | {
"start": 686,
"end": 896
} | class ____ implements NameMapper {
@Override
public String map(String name) {
return name;
}
@Override
public String unmap(String name) {
return name;
}
}
| DefaultNameMapper |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestRedundancyMonitor.java | {
"start": 1661,
"end": 4141
} | class ____ {
private static final String FILENAME = "/dummyfile.txt";
/**
* RedundancyMonitor invoke choose target out of global lock when
* #computeDatanodeWork. However it may result in NN terminate when choose
* target meet runtime exception(ArithmeticException) since we stop all
* DataNodes during that time.
* Verify that NN should not terminate even stop all datanodes.
*/
@Test
public void testChooseTargetWhenAllDataNodesStop() throws Throwable {
HdfsConfiguration conf = new HdfsConfiguration();
String[] hosts = new String[]{"host1", "host2"};
String[] racks = new String[]{"/d1/r1", "/d1/r1"};
try (MiniDFSCluster miniCluster = new MiniDFSCluster.Builder(conf)
.racks(racks).hosts(hosts).numDataNodes(hosts.length).build()) {
miniCluster.waitActive();
FSNamesystem fsn = miniCluster.getNamesystem();
BlockManager blockManager = fsn.getBlockManager();
BlockPlacementPolicyDefault replicator
= (BlockPlacementPolicyDefault) blockManager
.getBlockPlacementPolicy();
Set<DatanodeDescriptor> dns = blockManager.getDatanodeManager()
.getDatanodes();
DelayAnswer delayer = new DelayAnswer(BlockPlacementPolicyDefault.LOG);
NetworkTopology clusterMap = replicator.clusterMap;
NetworkTopology spyClusterMap = spy(clusterMap);
replicator.clusterMap = spyClusterMap;
doAnswer(delayer).when(spyClusterMap).getNumOfNonEmptyRacks();
ExecutorService pool = Executors.newFixedThreadPool(2);
// Trigger chooseTarget
Future<Void> chooseTargetFuture = pool.submit(() -> {
replicator.chooseTarget(FILENAME, 2, dns.iterator().next(),
new ArrayList<DatanodeStorageInfo>(), false, null, BLOCK_SIZE,
TestBlockStoragePolicy.DEFAULT_STORAGE_POLICY, null);
return null;
});
// Wait until chooseTarget calls NetworkTopology#getNumOfRacks
delayer.waitForCall();
// Remove all DataNodes
Future<Void> stopDatanodesFuture = pool.submit(() -> {
for (DatanodeDescriptor dn : dns) {
spyClusterMap.remove(dn);
}
return null;
});
// Wait stopDatanodesFuture run finish
stopDatanodesFuture.get();
// Allow chooseTarget to proceed
delayer.proceed();
try {
chooseTargetFuture.get();
} catch (ExecutionException ee) {
throw ee.getCause();
}
}
}
}
| TestRedundancyMonitor |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/model/source/selector/JakartaXmlElementDeclSelector.java | {
"start": 666,
"end": 1423
} | class ____ extends XmlElementDeclSelector {
JakartaXmlElementDeclSelector(TypeUtils typeUtils) {
super( typeUtils );
}
@Override
XmlElementDeclInfo getXmlElementDeclInfo(Element element) {
XmlElementDeclGem gem = XmlElementDeclGem.instanceOn( element );
if (gem == null) {
return null;
}
return new XmlElementDeclInfo( gem.name().get(), gem.scope().get() );
}
@Override
XmlElementRefInfo getXmlElementRefInfo(Element element) {
XmlElementRefGem gem = XmlElementRefGem.instanceOn( element );
if (gem == null) {
return null;
}
return new XmlElementRefInfo( gem.name().get(), gem.type().get() );
}
}
| JakartaXmlElementDeclSelector |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java | {
"start": 12180,
"end": 13846
} | class ____ proxy");
}
setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
}
// Initialize the shared singleton instance.
super.setFrozen(this.freezeProxy);
this.singletonInstance = getProxy(createAopProxy());
}
return this.singletonInstance;
}
/**
* Create a new prototype instance of this class's created proxy object,
* backed by an independent AdvisedSupport configuration.
* @return a totally independent proxy, whose advice we may manipulate in isolation
*/
private synchronized Object newPrototypeInstance() {
// In the case of a prototype, we need to give the proxy
// an independent instance of the configuration.
// In this case, no proxy will have an instance of this object's configuration,
// but will have an independent copy.
ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory());
// The copy needs a fresh advisor chain, and a fresh TargetSource.
TargetSource targetSource = freshTargetSource();
copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain());
if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
// Rely on AOP infrastructure to tell us what interfaces to proxy.
Class<?> targetClass = targetSource.getTargetClass();
if (targetClass != null) {
copy.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
}
}
copy.setFrozen(this.freezeProxy);
return getProxy(copy.createAopProxy());
}
/**
* Return the proxy object to expose.
* <p>The default implementation uses a {@code getProxy} call with
* the factory's bean | for |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/type/PgJdbcHelper.java | {
"start": 694,
"end": 807
} | class ____, where they have access to the JDBC driver classes.
*
* @author Christian Beikov
*/
public final | loader |
java | apache__camel | components/camel-quartz/src/main/java/org/apache/camel/routepolicy/quartz/CronScheduledRoutePolicy.java | {
"start": 1513,
"end": 6505
} | class ____ extends ScheduledRoutePolicy implements ScheduledRoutePolicyConstants {
@Metadata(description = "Cron expression for when the route should be started")
private String routeStartTime;
@Metadata(description = "Cron expression for when the route should be stopped")
private String routeStopTime;
@Metadata(label = "advanced", description = "Cron expression for when the route should be suspended")
private String routeSuspendTime;
@Metadata(label = "advanced", description = "Cron expression for when the route should be resumed")
private String routeResumeTime;
@Metadata(description = "To use a specific timezone (ID such as CET)")
private String timeZoneString;
private TimeZone timeZone;
@Override
public void onInit(Route route) {
try {
doOnInit(route);
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
protected void doOnInit(Route route) {
QuartzComponent quartz = route.getCamelContext().getComponent("quartz", QuartzComponent.class);
quartz.addScheduleInitTask(scheduler -> {
setScheduler(scheduler);
// Important: do not start scheduler as QuartzComponent does that automatic
// when CamelContext has been fully initialized and started
if (getRouteStopGracePeriod() == 0) {
setRouteStopGracePeriod(10000);
}
if (getTimeUnit() == null) {
setTimeUnit(TimeUnit.MILLISECONDS);
}
// validate time options has been configured
if (getRouteStartTime() == null && getRouteStopTime() == null && getRouteSuspendTime() == null
&& getRouteResumeTime() == null) {
throw new IllegalArgumentException(
"Scheduled Route Policy for route " + route.getId()
+ " has no start/stop/suspend/resume times specified");
}
registerRouteToScheduledRouteDetails(route);
if (getRouteStartTime() != null) {
scheduleRoute(Action.START, route);
}
if (getRouteStopTime() != null) {
scheduleRoute(Action.STOP, route);
}
if (getRouteSuspendTime() != null) {
scheduleRoute(Action.SUSPEND, route);
}
if (getRouteResumeTime() != null) {
scheduleRoute(Action.RESUME, route);
}
});
}
@Override
protected Trigger createTrigger(Action action, Route route) throws Exception {
Trigger trigger = null;
CronScheduleBuilder scheduleBuilder = null;
String triggerPrefix = null;
if (action == Action.START) {
scheduleBuilder = CronScheduleBuilder.cronSchedule(getRouteStartTime());
triggerPrefix = TRIGGER_START;
} else if (action == Action.STOP) {
scheduleBuilder = CronScheduleBuilder.cronSchedule(getRouteStopTime());
triggerPrefix = TRIGGER_STOP;
} else if (action == Action.SUSPEND) {
scheduleBuilder = CronScheduleBuilder.cronSchedule(getRouteSuspendTime());
triggerPrefix = TRIGGER_SUSPEND;
} else if (action == Action.RESUME) {
scheduleBuilder = CronScheduleBuilder.cronSchedule(getRouteResumeTime());
triggerPrefix = TRIGGER_RESUME;
}
if (scheduleBuilder != null) {
if (timeZone != null) {
scheduleBuilder.inTimeZone(timeZone);
}
TriggerKey triggerKey = new TriggerKey(triggerPrefix + route.getId(), TRIGGER_GROUP + route.getId());
trigger = TriggerBuilder.newTrigger()
.withIdentity(triggerKey)
.withSchedule(scheduleBuilder)
.build();
}
return trigger;
}
public void setRouteStartTime(String routeStartTime) {
this.routeStartTime = routeStartTime;
}
public String getRouteStartTime() {
return routeStartTime;
}
public void setRouteStopTime(String routeStopTime) {
this.routeStopTime = routeStopTime;
}
public String getRouteStopTime() {
return routeStopTime;
}
public void setRouteSuspendTime(String routeSuspendTime) {
this.routeSuspendTime = routeSuspendTime;
}
public String getRouteSuspendTime() {
return routeSuspendTime;
}
public void setRouteResumeTime(String routeResumeTime) {
this.routeResumeTime = routeResumeTime;
}
public String getRouteResumeTime() {
return routeResumeTime;
}
public String getTimeZone() {
return timeZoneString;
}
public void setTimeZone(String timeZone) {
this.timeZoneString = timeZone;
this.timeZone = TimeZone.getTimeZone(timeZone);
}
}
| CronScheduledRoutePolicy |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvMarshallPositionModifiedTest.java | {
"start": 1420,
"end": 2714
} | class ____ extends CommonBindyTest {
private List<Map<String, Object>> models = new ArrayList<>();
private String expected;
@Test
@DirtiesContext
public void testReverseMessage() throws Exception {
expected = "08-01-2009,EUR,400.25,Share,BUY,BE12345678,ISIN,Knightley,Keira,B2,1\r\n";
result.expectedBodiesReceived(expected);
template.sendBody(generateModel());
result.assertIsSatisfied();
}
public List<Map<String, Object>> generateModel() {
Map<String, Object> model = new HashMap<>();
Order order = new Order();
order.setOrderNr(1);
order.setOrderType("BUY");
order.setClientNr("B2");
order.setFirstName("Keira");
order.setLastName("Knightley");
order.setAmount(new BigDecimal("400.25"));
order.setInstrumentCode("ISIN");
order.setInstrumentNumber("BE12345678");
order.setInstrumentType("Share");
order.setCurrency("EUR");
Calendar calendar = new GregorianCalendar();
calendar.set(2009, 0, 8);
order.setOrderDate(calendar.getTime());
model.put(order.getClass().getName(), order);
models.add(model);
return models;
}
public static | BindySimpleCsvMarshallPositionModifiedTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/PropertyAccessException.java | {
"start": 763,
"end": 1247
} | class ____ extends HibernateException {
private final Class<?> persistentClass;
private final String propertyName;
private final boolean wasSetter;
/**
* Constructs a {@code PropertyAccessException} using the specified information.
*
* @param cause The underlying cause
* @param message A message explaining the exception condition
* @param wasSetter Was the attempting to access the setter the cause of the exception?
* @param persistentClass The | PropertyAccessException |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLBlockStatement.java | {
"start": 919,
"end": 4771
} | class ____ extends SQLStatementImpl {
private boolean isDollarQuoted;
private String dollarQuoteTagName;
private String labelName;
private String endLabel;
private List<SQLParameter> parameters = new ArrayList<SQLParameter>();
private List<SQLStatement> statementList = new ArrayList<SQLStatement>();
public SQLStatement exception;
private boolean endOfCommit;
private boolean haveBeginEnd;
private String language;
public SQLBlockStatement() {
haveBeginEnd = true;
}
public List<SQLStatement> getStatementList() {
return statementList;
}
public void setStatementList(List<SQLStatement> statementList) {
this.statementList = statementList;
}
public boolean isDollarQuoted() {
return isDollarQuoted;
}
public void setIsDollarQuoted(boolean isDollarQuoted) {
this.isDollarQuoted = isDollarQuoted;
}
public String getDollarQuoteTagName() {
return dollarQuoteTagName;
}
public void setDollarQuoteTagName(String dollarQuoteTagName) {
this.dollarQuoteTagName = dollarQuoteTagName;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public boolean isHaveBeginEnd() {
return haveBeginEnd;
}
public void setHaveBeginEnd(boolean haveBeginEnd) {
this.haveBeginEnd = haveBeginEnd;
}
@Override
public void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, parameters);
acceptChild(visitor, statementList);
acceptChild(visitor, exception);
}
visitor.endVisit(this);
}
public List<SQLParameter> getParameters() {
return parameters;
}
public void setParameters(List<SQLParameter> parameters) {
this.parameters = parameters;
}
public SQLStatement getException() {
return exception;
}
public void setException(SQLStatement exception) {
if (exception != null) {
exception.setParent(this);
}
this.exception = exception;
}
public String getEndLabel() {
return endLabel;
}
public void setEndLabel(String endLabel) {
this.endLabel = endLabel;
}
public SQLBlockStatement clone() {
SQLBlockStatement x = new SQLBlockStatement();
x.labelName = labelName;
x.endLabel = endLabel;
for (SQLParameter p : parameters) {
SQLParameter p2 = p.clone();
p2.setParent(x);
x.parameters.add(p2);
}
for (SQLStatement stmt : statementList) {
SQLStatement stmt2 = stmt.clone();
stmt2.setParent(x);
x.statementList.add(stmt2);
}
if (exception != null) {
x.setException(exception.clone());
}
return x;
}
public SQLParameter findParameter(long hash) {
for (SQLParameter param : this.parameters) {
if (param.getName().nameHashCode64() == hash) {
return param;
}
}
return null;
}
public boolean isEndOfCommit() {
return endOfCommit;
}
public void setEndOfCommit(boolean value) {
this.endOfCommit = value;
}
public boolean replace(SQLStatement cmp, SQLStatement target) {
for (int i = 0; i < statementList.size(); i++) {
if (statementList.get(i) == cmp) {
statementList.set(i, target);
return true;
}
}
return false;
}
}
| SQLBlockStatement |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/module/SimpleModuleTest.java | {
"start": 2485,
"end": 2756
} | class ____ extends ValueDeserializer<SimpleEnum>
{
@Override
public SimpleEnum deserialize(JsonParser p, DeserializationContext ctxt)
{
return SimpleEnum.valueOf(p.getString().toUpperCase());
}
}
| SimpleEnumDeserializer |
java | apache__flink | flink-connectors/flink-hadoop-compatibility/src/test/java/org/apache/flink/test/hadoopcompatibility/mapred/example/HadoopMapredCompatWordCount.java | {
"start": 5305,
"end": 5938
} | class ____ implements Reducer<Text, LongWritable, Text, LongWritable> {
@Override
public void reduce(
Text k,
Iterator<LongWritable> vs,
OutputCollector<Text, LongWritable> out,
Reporter rep)
throws IOException {
long cnt = 0;
while (vs.hasNext()) {
cnt += vs.next().get();
}
out.collect(k, new LongWritable(cnt));
}
@Override
public void configure(JobConf arg0) {}
@Override
public void close() throws IOException {}
}
}
| Counter |
java | google__guava | guava-tests/test/com/google/common/collect/ImmutableMapTest.java | {
"start": 33467,
"end": 33915
} | class ____ {}
Map<NonSerializableClass, String> map =
RegularImmutableMap.fromEntries(ImmutableMap.entryOf(new NonSerializableClass(), "value"));
Collection<String> collection = map.values();
LenientSerializableTester.reserializeAndAssertElementsEqual(collection);
}
@J2ktIncompatible
@GwtIncompatible // SerializableTester
public void testValuesCollectionIsSerializable_jdkBackedImmutableMap() {
| NonSerializableClass |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/oauthbearer/ClientCredentialsJwtRetriever.java | {
"start": 3104,
"end": 5101
} | class ____ in the <code>sasl.oauthbearer.jwt.retriever.class</code>
* configuration like so:
*
* <pre>
* sasl.oauthbearer.jwt.retriever.class=org.apache.kafka.common.security.oauthbearer.ClientCredentialsJwtRetriever
* </pre>
*
* <p/>
*
* If using this {@code JwtRetriever} on the broker side (for inter-broker communication), the configuration
* should be specified with a listener-based property:
*
* <pre>
* listener.name.<listener name>.oauthbearer.sasl.oauthbearer.jwt.retriever.class=org.apache.kafka.common.security.oauthbearer.ClientCredentialsJwtRetriever
* </pre>
*
* <p/>
*
* The {@code ClientCredentialsJwtRetriever} also uses the following configuration:
*
* <ul>
* <li><code>sasl.oauthbearer.client.credentials.client.id</code></li>
* <li><code>sasl.oauthbearer.client.credentials.client.secret</code></li>
* <li><code>sasl.oauthbearer.scope</code></li>
* <li><code>sasl.oauthbearer.token.endpoint.url</code></li>
* </ul>
*
* Please refer to the official Apache Kafka documentation for more information on these, and related configuration.
*
* <p/>
*
* Previous versions of this implementation used <code>sasl.jaas.config</code> to specify attributes such
* as <code>clientId</code>, <code>clientSecret</code>, and <code>scope</code>. These will still work, but
* if the configuration for each of these is specified, it will be used instead of the JAAS option.
*
* <p/>
*
* Here's an example of the JAAS configuration for a Kafka client:
*
* <pre>
* sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required ;
*
* sasl.oauthbearer.client.credentials.client.id=jdoe
* sasl.oauthbearer.client.credentials.client.secret=$3cr3+
* sasl.oauthbearer.jwt.retriever.class=org.apache.kafka.common.security.oauthbearer.ClientCredentialsJwtRetriever
* sasl.oauthbearer.scope=my-application-scope
* sasl.oauthbearer.token.endpoint.url=https://example.com/oauth2/v1/token
* </pre>
*/
public | name |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java | {
"start": 38208,
"end": 38594
} | class ____ {
void foo(Lib l) {
var unused = l.makeBarOrThrow();
}
}
""")
.doTest();
}
@Test
public void suggestsVarUnusedForConstructor() {
refactoringHelper
.addInputLines(
"Test.java",
"""
@com.google.errorprone.annotations.CheckReturnValue
| Test |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/test/MemoryUtils.java | {
"start": 1202,
"end": 1347
} | class ____ check that some tracked object are finalized, by way of tracking
* them through a {@link PhantomReference}.
*/
public static final | to |
java | elastic__elasticsearch | modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/SortProcessorFactoryTests.java | {
"start": 763,
"end": 4374
} | class ____ extends ESTestCase {
public void testCreate() throws Exception {
String processorTag = randomAlphaOfLength(10);
String fieldName = RandomDocumentPicks.randomFieldName(random());
Map<String, Object> config = new HashMap<>();
config.put("field", fieldName);
SortProcessor.Factory factory = new SortProcessor.Factory();
SortProcessor processor = factory.create(null, processorTag, null, config, null);
assertThat(processor.getTag(), equalTo(processorTag));
assertThat(processor.getField(), equalTo(fieldName));
assertThat(processor.getOrder(), equalTo(SortProcessor.SortOrder.ASCENDING));
assertThat(processor.getTargetField(), equalTo(fieldName));
}
public void testCreateWithOrder() throws Exception {
String processorTag = randomAlphaOfLength(10);
String fieldName = RandomDocumentPicks.randomFieldName(random());
Map<String, Object> config = new HashMap<>();
config.put("field", fieldName);
config.put("order", "desc");
SortProcessor.Factory factory = new SortProcessor.Factory();
SortProcessor processor = factory.create(null, processorTag, null, config, null);
assertThat(processor.getTag(), equalTo(processorTag));
assertThat(processor.getField(), equalTo(fieldName));
assertThat(processor.getOrder(), equalTo(SortProcessor.SortOrder.DESCENDING));
assertThat(processor.getTargetField(), equalTo(fieldName));
}
public void testCreateWithTargetField() throws Exception {
String processorTag = randomAlphaOfLength(10);
String fieldName = RandomDocumentPicks.randomFieldName(random());
String targetFieldName = RandomDocumentPicks.randomFieldName(random());
Map<String, Object> config = new HashMap<>();
config.put("field", fieldName);
config.put("target_field", targetFieldName);
SortProcessor.Factory factory = new SortProcessor.Factory();
SortProcessor processor = factory.create(null, processorTag, null, config, null);
assertThat(processor.getTag(), equalTo(processorTag));
assertThat(processor.getField(), equalTo(fieldName));
assertThat(processor.getOrder(), equalTo(SortProcessor.SortOrder.ASCENDING));
assertThat(processor.getTargetField(), equalTo(targetFieldName));
}
public void testCreateWithInvalidOrder() throws Exception {
String processorTag = randomAlphaOfLength(10);
String fieldName = RandomDocumentPicks.randomFieldName(random());
Map<String, Object> config = new HashMap<>();
config.put("field", fieldName);
config.put("order", "invalid");
SortProcessor.Factory factory = new SortProcessor.Factory();
try {
factory.create(null, processorTag, null, config, null);
fail("factory create should have failed");
} catch (ElasticsearchParseException e) {
assertThat(e.getMessage(), equalTo("[order] Sort direction [invalid] not recognized. Valid values are: [asc, desc]"));
}
}
public void testCreateMissingField() throws Exception {
SortProcessor.Factory factory = new SortProcessor.Factory();
Map<String, Object> config = new HashMap<>();
try {
factory.create(null, null, null, config, null);
fail("factory create should have failed");
} catch (ElasticsearchParseException e) {
assertThat(e.getMessage(), equalTo("[field] required property is missing"));
}
}
}
| SortProcessorFactoryTests |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/QueueDrainSubscriber.java | {
"start": 9676,
"end": 10847
} | class ____ extends QueueDrainSubscriberPad3 {
byte pad000,pad001,pad002,pad003,pad004,pad005,pad006,pad007;// 8b
byte pad010,pad011,pad012,pad013,pad014,pad015,pad016,pad017;// 16b
byte pad020,pad021,pad022,pad023,pad024,pad025,pad026,pad027;// 24b
byte pad030,pad031,pad032,pad033,pad034,pad035,pad036,pad037;// 32b
byte pad040,pad041,pad042,pad043,pad044,pad045,pad046,pad047;// 40b
byte pad050,pad051,pad052,pad053,pad054,pad055,pad056,pad057;// 48b
byte pad060,pad061,pad062,pad063,pad064,pad065,pad066,pad067;// 56b
byte pad070,pad071,pad072,pad073,pad074,pad075,pad076,pad077;// 64b
byte pad100,pad101,pad102,pad103,pad104,pad105,pad106,pad107;// 72b
byte pad110,pad111,pad112,pad113,pad114,pad115,pad116,pad117;// 80b
byte pad120,pad121,pad122,pad123,pad124,pad125,pad126,pad127;// 88b
byte pad130,pad131,pad132,pad133,pad134,pad135,pad136,pad137;// 96b
byte pad140,pad141,pad142,pad143,pad144,pad145,pad146,pad147;//104b
byte pad150,pad151,pad152,pad153,pad154,pad155,pad156,pad157;//112b
byte pad160,pad161,pad162,pad163,pad164,pad165,pad166,pad167;//120b
byte pad170,pad171,pad172,pad173,pad174,pad175,pad176,pad177;//128b
} | QueueDrainSubscriberPad4 |
java | google__guice | core/test/com/google/inject/ScopesTest.java | {
"start": 17907,
"end": 18013
} | class ____ {
static int nextInstanceId;
final int instanceId = nextInstanceId++;
}
| EagerSingleton |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/creators/ArrayDelegatorCreatorForCollectionTest.java | {
"start": 668,
"end": 1423
} | class ____ {
@JsonCreator
public UnmodifiableSetMixin(Set<?> s) {}
}
@Test
public void testUnmodifiable() throws Exception
{
Class<?> unmodSetType = Collections.unmodifiableSet(Collections.<String>emptySet()).getClass();
ObjectMapper mapper = jsonMapperBuilder()
.activateDefaultTyping(NoCheckSubTypeValidator.instance,
DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY)
.addMixIn(unmodSetType, UnmodifiableSetMixin.class)
.build();
final String EXPECTED_JSON = "[\""+unmodSetType.getName()+"\",[]]";
Set<?> foo = mapper.readValue(EXPECTED_JSON, Set.class);
assertTrue(foo.isEmpty());
}
}
| UnmodifiableSetMixin |
java | google__dagger | javatests/dagger/internal/codegen/MissingBindingValidationTest.java | {
"start": 56859,
"end": 57199
} | interface ____ {",
" Object getObject();",
"}");
Source sub2 =
CompilerTests.javaSource(
"bar.Sub",
"package bar;",
"",
"import dagger.Subcomponent;",
"",
"@Subcomponent(modules = test.RepeatedSubModule.class)",
"public | Sub |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringStreamResequencerTest.java | {
"start": 1042,
"end": 1305
} | class ____ extends StreamResequencerTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/streamResequencer.xml");
}
}
| SpringStreamResequencerTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.