language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/JUnit4SetUpNotRunTest.java | {
"start": 7735,
"end": 7887
} | class ____ extends SetUpAnnotatedBaseClass {
public void setUp() {}
}\
""")
.doTest();
}
public abstract static | J4SetUpExtendsAnnotatedMethod |
java | elastic__elasticsearch | distribution/tools/server-cli/src/main/java/org/elasticsearch/server/cli/ServerCli.java | {
"start": 2170,
"end": 12429
} | class ____ configuring logging
versionOption = parser.acceptsAll(Arrays.asList("V", "version"), "Prints Elasticsearch version information and exits");
daemonizeOption = parser.acceptsAll(Arrays.asList("d", "daemonize"), "Starts Elasticsearch in the background")
.availableUnless(versionOption);
pidfileOption = parser.acceptsAll(Arrays.asList("p", "pidfile"), "Creates a pid file in the specified path on start")
.availableUnless(versionOption)
.withRequiredArg()
.withValuesConvertedBy(new PathConverter());
quietOption = parser.acceptsAll(Arrays.asList("q", "quiet"), "Turns off standard output/error streams logging in console")
.availableUnless(versionOption)
.availableUnless(daemonizeOption);
enrollmentTokenOption = parser.accepts("enrollment-token", "An existing enrollment token for securely joining a cluster")
.availableUnless(versionOption)
.withRequiredArg();
}
@Override
public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws Exception {
if (options.nonOptionArguments().isEmpty() == false) {
throw new UserException(ExitCodes.USAGE, "Positional arguments not allowed, found " + options.nonOptionArguments());
}
if (options.has(versionOption)) {
printVersion(terminal);
return;
}
validateConfig(options, env);
var secureSettingsLoader = secureSettingsLoader(env);
try (
var loadedSecrets = secureSettingsLoader.load(env, terminal);
var password = (loadedSecrets.password().isPresent()) ? loadedSecrets.password().get() : new SecureString(new char[0]);
) {
SecureSettings secrets = loadedSecrets.secrets();
if (secureSettingsLoader.supportsSecurityAutoConfiguration()) {
env = autoConfigureSecurity(terminal, options, processInfo, env, password);
// reload or create the secrets
secrets = secureSettingsLoader.bootstrap(env, password);
}
// we should have a loaded or bootstrapped secure settings at this point
if (secrets == null) {
throw new UserException(ExitCodes.CONFIG, "Elasticsearch secure settings not configured");
}
// install/remove plugins from elasticsearch-plugins.yml
syncPlugins(terminal, env, processInfo);
ServerArgs args = createArgs(options, env, secrets, processInfo);
synchronized (shuttingDown) {
// if we are shutting down there is no reason to start the server
if (shuttingDown.get()) {
terminal.println("CLI is shutting down, skipping starting server process");
return;
}
this.server = startServer(terminal, processInfo, args);
}
}
if (options.has(daemonizeOption)) {
server.detach();
return;
}
// we are running in the foreground, so wait for the server to exit
int exitCode = server.waitFor();
onExit(exitCode);
}
/**
* A post-exit hook to perform additional processing before the command terminates
* @param exitCode the server process exit code
*/
protected void onExit(int exitCode) throws UserException {
if (exitCode != ExitCodes.OK) {
throw new UserException(exitCode, "Elasticsearch exited unexpectedly");
}
}
private static void printVersion(Terminal terminal) {
final String versionOutput = String.format(
Locale.ROOT,
"Version: %s, Build: %s/%s/%s, JVM: %s",
Build.current().qualifiedVersion(),
Build.current().type().displayName(),
Build.current().hash(),
Build.current().date(),
JvmInfo.jvmInfo().version()
);
terminal.println(versionOutput);
}
private void validateConfig(OptionSet options, Environment env) throws UserException {
if (options.valuesOf(enrollmentTokenOption).size() > 1) {
throw new UserException(ExitCodes.USAGE, "Multiple --enrollment-token parameters are not allowed");
}
Path log4jConfig = env.configDir().resolve("log4j2.properties");
if (Files.exists(log4jConfig) == false) {
throw new UserException(ExitCodes.CONFIG, "Missing logging config file at " + log4jConfig);
}
}
// Autoconfiguration of SecureSettings is currently only supported for KeyStore based secure settings
// package private for testing
Environment autoConfigureSecurity(
Terminal terminal,
OptionSet options,
ProcessInfo processInfo,
Environment env,
SecureString keystorePassword
) throws Exception {
assert secureSettingsLoader(env) instanceof KeyStoreLoader;
String autoConfigLibs = "modules/x-pack-core,modules/x-pack-security,lib/tools/security-cli";
Command cmd = loadTool(processInfo.sysprops(), "auto-configure-node", autoConfigLibs);
assert cmd instanceof EnvironmentAwareCommand;
@SuppressWarnings("raw")
var autoConfigNode = (EnvironmentAwareCommand) cmd;
final String[] autoConfigArgs;
if (options.has(enrollmentTokenOption)) {
autoConfigArgs = new String[] { "--enrollment-token", options.valueOf(enrollmentTokenOption) };
} else {
autoConfigArgs = new String[0];
}
OptionSet autoConfigOptions = autoConfigNode.parseOptions(autoConfigArgs);
boolean changed = true;
try (var autoConfigTerminal = new KeystorePasswordTerminal(terminal, keystorePassword.clone())) {
autoConfigNode.execute(autoConfigTerminal, autoConfigOptions, env, processInfo);
} catch (UserException e) {
boolean okCode = switch (e.exitCode) {
// these exit codes cover the cases where auto-conf cannot run but the node should NOT be prevented from starting as usual
// e.g. the node is restarted, is already configured in an incompatible way, or the file system permissions do not allow it
case ExitCodes.CANT_CREATE, ExitCodes.CONFIG, ExitCodes.NOOP -> true;
default -> false;
};
if (options.has(enrollmentTokenOption) == false && okCode) {
// we still want to print the error, just don't fail startup
if (e.getMessage() != null) {
terminal.errorPrintln(e.getMessage());
}
changed = false;
} else {
throw e;
}
}
if (changed) {
// reload settings since auto security changed them
env = createEnv(options, processInfo);
}
return env;
}
// package private for testing
void syncPlugins(Terminal terminal, Environment env, ProcessInfo processInfo) throws Exception {
String pluginCliLibs = "lib/tools/plugin-cli";
Command cmd = loadTool(processInfo.sysprops(), "sync-plugins", pluginCliLibs);
assert cmd instanceof EnvironmentAwareCommand;
@SuppressWarnings("raw")
var syncPlugins = (EnvironmentAwareCommand) cmd;
syncPlugins.execute(terminal, syncPlugins.parseOptions(new String[0]), env, processInfo);
}
private static void validatePidFile(Path pidFile) throws UserException {
Path parent = pidFile.getParent();
if (parent != null && Files.exists(parent) && Files.isDirectory(parent) == false) {
throw new UserException(ExitCodes.USAGE, "pid file parent [" + parent + "] exists but is not a directory");
}
if (Files.exists(pidFile) && Files.isRegularFile(pidFile) == false) {
throw new UserException(ExitCodes.USAGE, pidFile + " exists but is not a regular file");
}
}
private ServerArgs createArgs(OptionSet options, Environment env, SecureSettings secrets, ProcessInfo processInfo)
throws UserException {
boolean daemonize = options.has(daemonizeOption);
boolean quiet = options.has(quietOption);
Path pidFile = null;
if (options.has(pidfileOption)) {
pidFile = options.valueOf(pidfileOption);
if (pidFile.isAbsolute() == false) {
pidFile = processInfo.workingDir().resolve(pidFile.toString()).toAbsolutePath();
}
validatePidFile(pidFile);
}
return new ServerArgs(daemonize, quiet, pidFile, secrets, env.settings(), env.configDir(), env.logsDir());
}
@Override
public void close() throws IOException {
synchronized (shuttingDown) {
shuttingDown.set(true);
if (server != null) {
server.stop();
}
}
}
// allow subclasses to access the started process
protected ServerProcess getServer() {
return server;
}
// protected to allow tests to override
protected Command loadTool(Map<String, String> sysprops, String toolname, String libs) {
return CliToolProvider.load(sysprops, toolname, libs).create();
}
// protected to allow tests to override
protected ServerProcess startServer(Terminal terminal, ProcessInfo processInfo, ServerArgs args) throws Exception {
var tempDir = ServerProcessUtils.setupTempDir(processInfo);
var jvmOptions = JvmOptionsParser.determineJvmOptions(args, processInfo, tempDir, new MachineDependentHeap());
var serverProcessBuilder = new ServerProcessBuilder().withTerminal(terminal)
.withProcessInfo(processInfo)
.withServerArgs(args)
.withTempDir(tempDir)
.withJvmOptions(jvmOptions);
return serverProcessBuilder.start();
}
// protected to allow tests to override
protected SecureSettingsLoader secureSettingsLoader(Environment env) {
// TODO: Use the environment configuration to decide what kind of secrets store to load
return new KeyStoreLoader();
}
}
| from |
java | apache__camel | components/camel-dataformat/src/main/java/org/apache/camel/component/dataformat/DataFormatEndpoint.java | {
"start": 1911,
"end": 4725
} | class ____ extends DefaultEndpoint {
private AsyncProcessor processor;
private DataFormat dataFormat;
@UriPath(description = "Name of data format")
@Metadata(required = true)
private String name;
@UriPath(enums = "marshal,unmarshal")
@Metadata(required = true)
private String operation;
public DataFormatEndpoint() {
}
public DataFormatEndpoint(String endpointUri, Component component, DataFormat dataFormat) {
super(endpointUri, component);
this.dataFormat = dataFormat;
}
@Override
public boolean isRemote() {
return false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DataFormat getDataFormat() {
return dataFormat;
}
public void setDataFormat(DataFormat dataFormat) {
this.dataFormat = dataFormat;
}
public String getOperation() {
return operation;
}
/**
* Operation to use either marshal or unmarshal
*/
public void setOperation(String operation) {
this.operation = operation;
}
@Override
public Producer createProducer() throws Exception {
return new DefaultAsyncProducer(this) {
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
return processor.process(exchange, callback);
}
@Override
public String toString() {
return "DataFormatProducer[" + dataFormat + "]";
}
};
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Cannot consume from data format");
}
@Override
public boolean isLenientProperties() {
return true;
}
@Override
protected void doInit() throws Exception {
super.doInit();
if (dataFormat == null && name != null) {
dataFormat = getCamelContext().resolveDataFormat(name);
}
if (operation.equals("marshal")) {
MarshalProcessor marshal = new MarshalProcessor(dataFormat);
marshal.setCamelContext(getCamelContext());
processor = marshal;
} else {
UnmarshalProcessor unmarshal = new UnmarshalProcessor(dataFormat);
unmarshal.setCamelContext(getCamelContext());
processor = unmarshal;
}
}
@Override
protected void doStart() throws Exception {
ServiceHelper.startService(dataFormat, processor);
super.doStart();
}
@Override
protected void doStop() throws Exception {
ServiceHelper.stopService(processor, dataFormat);
super.doStop();
}
}
| DataFormatEndpoint |
java | hibernate__hibernate-orm | local-build-plugins/src/main/java/org/hibernate/orm/post/LoggingReportTask.java | {
"start": 7595,
"end": 8753
} | class ____ {
private final String name;
private final String description;
private final String loggingClassName;
private final String anchorName;
private IdRange idRange;
public SubSystem(String name, String description, String loggingClassName) {
this.name = name;
this.description = description;
this.loggingClassName = loggingClassName;
this.anchorName = determineAnchorName( name );
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getLoggingClassName() {
return loggingClassName;
}
public String getAnchorName() {
return anchorName;
}
public IdRange getIdRange() {
return idRange;
}
private static String determineAnchorName(final String name) {
final String baseName;
if ( name.startsWith( "org.hibernate.orm." ) ) {
baseName = name.substring( "org.hibernate.orm.".length() );
}
else if ( name.startsWith( "org.hibernate." ) ) {
baseName = name.substring( "org.hibernate.".length() );
}
else {
baseName = name;
}
return baseName.replace( '.', '_' );
}
}
private static | SubSystem |
java | quarkusio__quarkus | integration-tests/jaxb/src/test/java/io/quarkus/it/jaxb/JaxbAWTTest.java | {
"start": 356,
"end": 733
} | class ____ {
@Test
public void book() {
RestAssured.given()
.when()
.header("Content-Type", CONTENT_TYPE)
.body(BOOK_WITH_IMAGE)
.when()
.post("/jaxb/book")
.then()
.statusCode(HttpStatus.SC_ACCEPTED)
.body(is("10"));
}
}
| JaxbAWTTest |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/scheduler/RejectedExecutionTest.java | {
"start": 16127,
"end": 16883
} | class ____ extends BaseSubscriber<Long> {
private final CountDownLatch latch;
private final boolean unbounded;
public TestSub(CountDownLatch latch) {
this(latch, false);
}
public TestSub(CountDownLatch latch, boolean unbounded) {
this.latch = latch;
this.unbounded = unbounded;
}
@Override
protected void hookOnSubscribe(Subscription subscription) {
if(unbounded)
requestUnbounded();
else
request(1);
}
@Override
protected void hookOnNext(Long value) {
onNexts.add(value);
if(!unbounded)
request(1);
}
@Override
protected void hookOnError(Throwable throwable) {
onErrors.add(throwable);
}
@Override
protected void hookFinally(SignalType type) {
latch.countDown();
}
}
}
| TestSub |
java | apache__maven | impl/maven-impl/src/main/java/org/apache/maven/impl/model/DefaultProfileActivationContext.java | {
"start": 2156,
"end": 2410
} | class ____ track of information that are used during profile activation.
* This allows to cache the activated parent and check if the result of the
* activation will be the same by verifying that the used keys are the same.
*/
static | keeps |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/records/RecordTypeInfo3342Test.java | {
"start": 612,
"end": 674
} | enum ____ {
LOW,
HIGH
}
public | SpiceLevel |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/AnalyzeIndexDiskUsageResponse.java | {
"start": 870,
"end": 2077
} | class ____ extends BroadcastResponse {
private final Map<String, IndexDiskUsageStats> stats;
AnalyzeIndexDiskUsageResponse(
int totalShards,
int successfulShards,
int failedShards,
List<DefaultShardOperationFailedException> shardFailures,
Map<String, IndexDiskUsageStats> stats
) {
super(totalShards, successfulShards, failedShards, shardFailures);
this.stats = stats;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeMap(stats, StreamOutput::writeWriteable);
}
Map<String, IndexDiskUsageStats> getStats() {
return stats;
}
@Override
protected void addCustomXContentFields(XContentBuilder builder, Params params) throws IOException {
final List<Map.Entry<String, IndexDiskUsageStats>> entries = stats.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList();
for (Map.Entry<String, IndexDiskUsageStats> entry : entries) {
builder.startObject(entry.getKey());
entry.getValue().toXContent(builder, params);
builder.endObject();
}
}
}
| AnalyzeIndexDiskUsageResponse |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/DeleteCalendarEventActionRequestTests.java | {
"start": 507,
"end": 1047
} | class ____ extends AbstractWireSerializingTestCase<Request> {
@Override
protected Request createTestInstance() {
return new Request(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20));
}
@Override
protected Request mutateInstance(Request instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Writeable.Reader<Request> instanceReader() {
return Request::new;
}
}
| DeleteCalendarEventActionRequestTests |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java | {
"start": 35662,
"end": 35793
} | class ____ {
@EventListener
public void hear(TestEvent e) {
throw new AssertionError();
}
}
public static | MyEventListener |
java | apache__maven | compat/maven-compat/src/main/java/org/apache/maven/plugin/PluginManager.java | {
"start": 1718,
"end": 3858
} | interface ____ {
String ROLE = PluginManager.class.getName();
void executeMojo(MavenProject project, MojoExecution execution, MavenSession session)
throws MojoExecutionException, ArtifactResolutionException, MojoFailureException, ArtifactNotFoundException,
InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException;
PluginDescriptor getPluginDescriptorForPrefix(String prefix);
Plugin getPluginDefinitionForPrefix(String prefix, MavenSession session, MavenProject project);
PluginDescriptor verifyPlugin(
Plugin plugin, MavenProject project, Settings settings, ArtifactRepository localRepository)
throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException,
InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException,
PluginNotFoundException, PluginVersionNotFoundException;
Object getPluginComponent(Plugin plugin, String role, String roleHint)
throws PluginManagerException, ComponentLookupException;
Map<String, Object> getPluginComponents(Plugin plugin, String role)
throws ComponentLookupException, PluginManagerException;
/**
* @since 2.2.1
*/
PluginDescriptor loadPluginDescriptor(Plugin plugin, MavenProject project, MavenSession session)
throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException,
InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException,
PluginNotFoundException, PluginVersionNotFoundException;
/**
* @since 2.2.1
*/
PluginDescriptor loadPluginFully(Plugin plugin, MavenProject project, MavenSession session)
throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException,
InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException,
PluginNotFoundException, PluginVersionNotFoundException;
}
| PluginManager |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java | {
"start": 26173,
"end": 26285
} | class ____ {
@Bean
public Object prodBean() {
return new Object();
}
}
@Configuration
static | ProdConfig |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/EmbeddedIdTest.java | {
"start": 1691,
"end": 1856
} | class ____ {
@EmbeddedId
private FooId id;
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "bar_id")
private Bar bar;
}
}
| Foo |
java | apache__camel | components/camel-ehcache/src/generated/java/org/apache/camel/component/ehcache/processor/idempotent/EhcacheIdempotentRepositoryConfigurer.java | {
"start": 773,
"end": 2270
} | class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.component.ehcache.processor.idempotent.EhcacheIdempotentRepository target = (org.apache.camel.component.ehcache.processor.idempotent.EhcacheIdempotentRepository) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "cachename":
case "cacheName": target.setCacheName(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "cachename":
case "cacheName": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.component.ehcache.processor.idempotent.EhcacheIdempotentRepository target = (org.apache.camel.component.ehcache.processor.idempotent.EhcacheIdempotentRepository) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "cachename":
case "cacheName": return target.getCacheName();
default: return null;
}
}
}
| EhcacheIdempotentRepositoryConfigurer |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/processor/internals/namedtopology/RemoveNamedTopologyResult.java | {
"start": 1192,
"end": 3005
} | class ____ {
private final KafkaFutureImpl<Void> removeTopologyFuture;
private final KafkaFutureImpl<Void> resetOffsetsFuture;
public RemoveNamedTopologyResult(final KafkaFutureImpl<Void> removeTopologyFuture) {
Objects.requireNonNull(removeTopologyFuture);
this.removeTopologyFuture = removeTopologyFuture;
this.resetOffsetsFuture = null;
}
public RemoveNamedTopologyResult(final KafkaFutureImpl<Void> removeTopologyFuture,
final String removedTopology,
final Runnable resetOffsets) {
Objects.requireNonNull(removeTopologyFuture);
this.removeTopologyFuture = removeTopologyFuture;
resetOffsetsFuture = new ResetOffsetsFuture(removedTopology, removeTopologyFuture, resetOffsets);
}
public KafkaFuture<Void> removeTopologyFuture() {
return removeTopologyFuture;
}
public KafkaFuture<Void> resetOffsetsFuture() {
return resetOffsetsFuture;
}
/**
* @return a {@link KafkaFuture} that completes successfully when all threads on this client have removed the
* corresponding {@link NamedTopology} and all source topic offsets have been deleted (if applicable). At this
* point no more of its tasks will be processed by the current client, but there may still be other clients which
* do. It is only guaranteed that this {@link NamedTopology} has fully stopped processing when all clients have
* successfully completed their corresponding {@link KafkaFuture}.
*/
public final KafkaFuture<Void> all() {
if (resetOffsetsFuture == null) {
return removeTopologyFuture;
} else {
return resetOffsetsFuture;
}
}
private static | RemoveNamedTopologyResult |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ext/javatime/ser/InstantSerTest.java | {
"start": 6762,
"end": 7244
} | class ____ {
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
public Instant t1 = Instant.parse("2022-04-27T12:00:00Z");
public Instant t2 = t1;
}
@Test
public void testShapeInt() throws Exception {
String json1 = MAPPER.writer()
.with(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS)
.writeValueAsString(new Pojo1());
assertEquals("{\"t1\":1651060800000,\"t2\":1651060800.000000000}", json1);
}
}
| Pojo1 |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/ErrorInfoTest.java | {
"start": 1831,
"end": 2225
} | class ____ extends Exception {
private static final long serialVersionUID = 42L;
@SuppressWarnings("unused")
private final Serializable outOfClassLoader =
ClassLoaderUtils.createSerializableObjectFromNewClassLoader().getObject();
public ExceptionWithCustomClassLoader() {
super("tada");
}
}
}
| ExceptionWithCustomClassLoader |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/migrationsupport/rules/ExternalResourceSupportForMixedMethodAndFieldRulesTests.java | {
"start": 966,
"end": 2703
} | class ____ {
private static List<String> initEvents = new ArrayList<>();
private static List<String> beforeEvents = new ArrayList<>();
private static List<String> afterEvents = new ArrayList<>();
@BeforeAll
static void clear() {
initEvents.clear();
beforeEvents.clear();
afterEvents.clear();
}
@Rule
public ExternalResource fieldRule1 = new MyExternalResource("fieldRule1");
@Rule
public ExternalResource fieldRule2 = new MyExternalResource("fieldRule2");
@SuppressWarnings("JUnitMalformedDeclaration")
@Rule
ExternalResource methodRule1() {
return new MyExternalResource("methodRule1");
}
@SuppressWarnings("JUnitMalformedDeclaration")
@Rule
ExternalResource methodRule2() {
return new MyExternalResource("methodRule2");
}
@Test
void constructorsAndBeforeEachMethodsOfAllRulesWereExecuted() {
assertThat(initEvents).hasSize(4);
// the order of fields and methods is not stable, but fields are initialized before methods are called
assertThat(initEvents.subList(0, 2)).allMatch(item -> item.startsWith("fieldRule"));
assertThat(initEvents.subList(2, 4)).allMatch(item -> item.startsWith("methodRule"));
// beforeEach methods of rules from fields are run before those from methods but in reverse order of instantiation
assertEquals(asList(initEvents.get(1), initEvents.get(0), initEvents.get(3), initEvents.get(2)), beforeEvents);
}
@AfterAll
static void afterMethodsOfAllRulesWereExecuted() {
// beforeEach methods of rules from methods are run before those from fields but in reverse order
if (!asList(initEvents.get(2), initEvents.get(3), initEvents.get(0), initEvents.get(1)).equals(afterEvents)) {
fail();
}
}
static | ExternalResourceSupportForMixedMethodAndFieldRulesTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/strategy/SchedulingExecutionVertex.java | {
"start": 1197,
"end": 1767
} | interface ____
extends Vertex<
ExecutionVertexID,
IntermediateResultPartitionID,
SchedulingExecutionVertex,
SchedulingResultPartition> {
/**
* Gets the state of the execution vertex.
*
* @return state of the execution vertex
*/
ExecutionState getState();
/**
* Gets the {@link ConsumedPartitionGroup}s.
*
* @return list of {@link ConsumedPartitionGroup}s
*/
List<ConsumedPartitionGroup> getConsumedPartitionGroups();
}
| SchedulingExecutionVertex |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_210_union.java | {
"start": 931,
"end": 3400
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT count(*)\n" +
"FROM (\n" +
" (SELECT user_id\n" +
" FROM user_info_offline\n" +
" WHERE create_time > '2018-01-01 00:00:00'\n" +
" EXCEPT\n" +
" SELECT user_id FROM user_info_online\n" +
" )\n" +
"\n" +
" UNION\n" +
"\n" +
" SELECT coalesce(a.user_id, b.user_id) AS user_id\n" +
" FROM user_info_online a LEFT JOIN user_info_offline b ON (a.user_id = b.user_id)\n" +
" WHERE ((a.create_time > '2018-01-01 00:00:00') OR\n" +
" (a.create_time IS NULL AND b.create_time > '2018-01-01 00:00:00')\n" +
" )\n" +
")";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("SELECT count(*)\n" +
"FROM (\n" +
"\t(SELECT user_id\n" +
"\tFROM user_info_offline\n" +
"\tWHERE create_time > '2018-01-01 00:00:00'\n" +
"\tEXCEPT\n" +
"\tSELECT user_id\n" +
"\tFROM user_info_online)\n" +
"\tUNION\n" +
"\tSELECT coalesce(a.user_id, b.user_id) AS user_id\n" +
"\tFROM user_info_online a\n" +
"\t\tLEFT JOIN user_info_offline b ON (a.user_id = b.user_id)\n" +
"\tWHERE ((a.create_time > '2018-01-01 00:00:00')\n" +
"\t\tOR (a.create_time IS NULL\n" +
"\t\t\tAND b.create_time > '2018-01-01 00:00:00'))\n" +
")", //
stmt.toString());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
assertEquals(2, visitor.getTables().size());
assertEquals(4, visitor.getColumns().size());
assertEquals(5, visitor.getConditions().size());
assertEquals(0, visitor.getOrderByColumns().size());
}
}
| MySqlSelectTest_210_union |
java | apache__maven | its/core-it-suite/src/test/resources/mng-3693/projects/app/src/main/java/tests/app/App.java | {
"start": 885,
"end": 1013
} | class ____ {
public static void main(String[] args) {
new Dep();
System.out.println("Hello World!");
}
}
| App |
java | apache__kafka | group-coordinator/src/test/java/org/apache/kafka/coordinator/group/OffsetAndMetadataTest.java | {
"start": 1435,
"end": 6466
} | class ____ {
@Test
public void testAttributes() {
Uuid topicId = Uuid.randomUuid();
OffsetAndMetadata offsetAndMetadata = new OffsetAndMetadata(
100L,
OptionalInt.of(10),
"metadata",
1234L,
OptionalLong.of(5678L),
topicId
);
assertEquals(100L, offsetAndMetadata.committedOffset);
assertEquals(OptionalInt.of(10), offsetAndMetadata.leaderEpoch);
assertEquals("metadata", offsetAndMetadata.metadata);
assertEquals(1234L, offsetAndMetadata.commitTimestampMs);
assertEquals(OptionalLong.of(5678L), offsetAndMetadata.expireTimestampMs);
assertEquals(topicId, offsetAndMetadata.topicId);
}
private static Stream<Uuid> uuids() {
return Stream.of(
Uuid.ZERO_UUID,
Uuid.randomUuid()
);
}
@ParameterizedTest
@MethodSource("uuids")
public void testFromRecord(Uuid uuid) {
OffsetCommitValue record = new OffsetCommitValue()
.setOffset(100L)
.setLeaderEpoch(-1)
.setMetadata("metadata")
.setCommitTimestamp(1234L)
.setExpireTimestamp(-1L)
.setTopicId(uuid);
assertEquals(new OffsetAndMetadata(
10L,
100L,
OptionalInt.empty(),
"metadata",
1234L,
OptionalLong.empty(),
uuid
), OffsetAndMetadata.fromRecord(10L, record));
record
.setLeaderEpoch(12)
.setExpireTimestamp(5678L);
assertEquals(new OffsetAndMetadata(
11L,
100L,
OptionalInt.of(12),
"metadata",
1234L,
OptionalLong.of(5678L),
uuid
), OffsetAndMetadata.fromRecord(11L, record));
}
@ParameterizedTest
@MethodSource("uuids")
public void testFromRequest(Uuid uuid) {
MockTime time = new MockTime();
OffsetCommitRequestData.OffsetCommitRequestPartition partition =
new OffsetCommitRequestData.OffsetCommitRequestPartition()
.setPartitionIndex(0)
.setCommittedOffset(100L)
.setCommittedLeaderEpoch(-1)
.setCommittedMetadata(null);
assertEquals(
new OffsetAndMetadata(
100L,
OptionalInt.empty(),
"",
time.milliseconds(),
OptionalLong.empty(),
uuid
), OffsetAndMetadata.fromRequest(
uuid,
partition,
time.milliseconds(),
OptionalLong.empty()
)
);
partition
.setCommittedLeaderEpoch(10)
.setCommittedMetadata("hello");
assertEquals(
new OffsetAndMetadata(
100L,
OptionalInt.of(10),
"hello",
time.milliseconds(),
OptionalLong.empty(),
uuid
), OffsetAndMetadata.fromRequest(
uuid,
partition,
time.milliseconds(),
OptionalLong.empty()
)
);
assertEquals(
new OffsetAndMetadata(
100L,
OptionalInt.of(10),
"hello",
time.milliseconds(),
OptionalLong.of(5678L),
uuid
), OffsetAndMetadata.fromRequest(
uuid,
partition,
time.milliseconds(),
OptionalLong.of(5678L)
)
);
}
@Test
public void testFromTransactionalRequest() {
MockTime time = new MockTime();
TxnOffsetCommitRequestData.TxnOffsetCommitRequestPartition partition =
new TxnOffsetCommitRequestData.TxnOffsetCommitRequestPartition()
.setPartitionIndex(0)
.setCommittedOffset(100L)
.setCommittedLeaderEpoch(-1)
.setCommittedMetadata(null);
assertEquals(
new OffsetAndMetadata(
100L,
OptionalInt.empty(),
"",
time.milliseconds(),
OptionalLong.empty(),
Uuid.ZERO_UUID
), OffsetAndMetadata.fromRequest(
partition,
time.milliseconds()
)
);
partition
.setCommittedLeaderEpoch(10)
.setCommittedMetadata("hello");
assertEquals(
new OffsetAndMetadata(
100L,
OptionalInt.of(10),
"hello",
time.milliseconds(),
OptionalLong.empty(),
Uuid.ZERO_UUID
), OffsetAndMetadata.fromRequest(
partition,
time.milliseconds()
)
);
}
}
| OffsetAndMetadataTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/recursive/comparison/VisitedDualValuesTest.java | {
"start": 903,
"end": 2988
} | class ____ {
@Test
void should_return_the_registered_differences() {
// GIVEN
VisitedDualValues visitedDualValues = new VisitedDualValues();
DualValue dualValue = new DualValue(list(""), "abc", "abc");
visitedDualValues.registerVisitedDualValue(dualValue);
ComparisonDifference comparisonDifference1 = new ComparisonDifference(dualValue);
visitedDualValues.registerComparisonDifference(dualValue, comparisonDifference1);
ComparisonDifference comparisonDifference2 = new ComparisonDifference(dualValue);
visitedDualValues.registerComparisonDifference(dualValue, comparisonDifference2);
// WHEN
Optional<List<ComparisonDifference>> optionalComparisonDifferences = visitedDualValues.registeredComparisonDifferencesOf(dualValue);
// THEN
then(optionalComparisonDifferences).isPresent();
BDDAssertions.then(optionalComparisonDifferences.get()).containsExactlyInAnyOrder(comparisonDifference1,
comparisonDifference2);
}
@Test
void should_return_no_differences_when_none_have_been_registered() {
// GIVEN
VisitedDualValues visitedDualValues = new VisitedDualValues();
DualValue dualValue = new DualValue(list(""), "abc", "abc");
visitedDualValues.registerVisitedDualValue(dualValue);
// WHEN
Optional<List<ComparisonDifference>> optionalComparisonDifferences = visitedDualValues.registeredComparisonDifferencesOf(dualValue);
// THEN
then(optionalComparisonDifferences).isPresent();
BDDAssertions.then(optionalComparisonDifferences.get()).isEmpty();
}
@Test
void should_return_empty_optional_for_unknown_dual_values() {
// GIVEN
VisitedDualValues visitedDualValues = new VisitedDualValues();
DualValue dualValue = new DualValue(list(""), "abc", "abc");
// WHEN
Optional<List<ComparisonDifference>> optionalComparisonDifferences = visitedDualValues.registeredComparisonDifferencesOf(dualValue);
// THEN
then(optionalComparisonDifferences).isEmpty();
}
}
| VisitedDualValuesTest |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/LeaveGroupOnCloseEvent.java | {
"start": 1673,
"end": 2283
} | class ____ extends CompletableApplicationEvent<Void> {
/**
* @see org.apache.kafka.clients.consumer.CloseOptions.GroupMembershipOperation
*/
private final CloseOptions.GroupMembershipOperation membershipOperation;
public LeaveGroupOnCloseEvent(final long deadlineMs, final CloseOptions.GroupMembershipOperation membershipOperation) {
super(Type.LEAVE_GROUP_ON_CLOSE, deadlineMs);
this.membershipOperation = membershipOperation;
}
public CloseOptions.GroupMembershipOperation membershipOperation() {
return membershipOperation;
}
}
| LeaveGroupOnCloseEvent |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/strings/Strings_assertHasSizeBetween_Test.java | {
"start": 1335,
"end": 2581
} | class ____ extends StringsBaseTest {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
String actual = null;
// WHEN
var error = expectAssertionError(() -> assertThat(actual).hasSizeBetween(4, 7));
// THEN
assertThat(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_size_of_actual_is_less_to_min_expected_size() {
// GIVEN
String actual = "Han";
// WHEN
var error = expectAssertionError(() -> assertThat(actual).hasSizeBetween(4, 7));
// THEN
String errorMessage = shouldHaveSizeBetween(actual, actual.length(), 4, 7).create();
assertThat(error).hasMessage(errorMessage);
}
@Test
void should_fail_if_size_of_actual_is_greater_than_max_expected_size() {
// GIVEN
String actual = "Han";
// WHEN
var error = expectAssertionError(() -> assertThat(actual).hasSizeBetween(1, 2));
// THEN
String errorMessage = shouldHaveSizeBetween(actual, actual.length(), 1, 2).create();
assertThat(error).hasMessage(errorMessage);
}
@Test
void should_pass_if_size_of_actual_is_between_sizes() {
// GIVEN
String actual = "Han";
// THEN
strings.assertHasSizeBetween(someInfo(), actual, 2, 7);
}
}
| Strings_assertHasSizeBetween_Test |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/UnsupportedCompressionTypeException.java | {
"start": 938,
"end": 1276
} | class ____ extends ApiException {
private static final long serialVersionUID = 1L;
public UnsupportedCompressionTypeException(String message) {
super(message);
}
public UnsupportedCompressionTypeException(String message, Throwable cause) {
super(message, cause);
}
}
| UnsupportedCompressionTypeException |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/suite/engine/testsuites/LifecycleMethodsSuites.java | {
"start": 1044,
"end": 1238
} | class ____ {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Suite
@SelectClasses({ StatefulTestCase.Test1.class, StatefulTestCase.Test2.class })
private @ | LifecycleMethodsSuites |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/proxy/ConnectionTest.java | {
"start": 847,
"end": 5686
} | class ____ extends TestCase {
private static String create_url = "jdbc:wrap-jdbc:filters=default,commonLogging,log4j:name=demo:jdbc:derby:memory:connectionTestDB;create=true";
protected void setUp() throws Exception {
Class.forName("com.alibaba.druid.proxy.DruidDriver");
Connection conn = DriverManager.getConnection(create_url);
createTable();
conn.close();
}
private void createTable() throws SQLException {
Connection conn = DriverManager.getConnection(create_url);
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE T_BLOB (ID INTEGER, DATA BLOB)");
stmt.close();
conn.close();
}
private void dropTable() throws SQLException {
Connection conn = DriverManager.getConnection(create_url);
Statement stmt = conn.createStatement();
stmt.execute("DROP TABLE T_BLOB");
stmt.close();
conn.close();
}
protected void tearDown() throws Exception {
dropTable();
DruidDriver.getProxyDataSources().clear();
assertEquals(0, JdbcStatManager.getInstance().getSqlList().size());
}
@SuppressWarnings("deprecation")
public void test_connection() throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(create_url);
conn.setCatalog(conn.getCatalog());
conn.setClientInfo(conn.getClientInfo());
conn.setHoldability(conn.getHoldability());
conn.setReadOnly(conn.isReadOnly());
conn.setTransactionIsolation(conn.getTransactionIsolation());
conn.setTypeMap(conn.getTypeMap());
try {
conn.setClientInfo("name", "value");
} catch (SQLClientInfoException ex) {
}
try {
conn.createArrayOf("VARCHAR", new String[]{"A", "B"});
} catch (SQLFeatureNotSupportedException ex) {
}
try {
conn.createNClob();
} catch (SQLFeatureNotSupportedException ex) {
}
try {
conn.createSQLXML();
} catch (SQLFeatureNotSupportedException ex) {
}
try {
conn.createStruct("VARCHAR", new String[]{"A", "B"});
} catch (SQLFeatureNotSupportedException ex) {
}
conn.setAutoCommit(false);
Savepoint savePoint = conn.setSavepoint("XX");
conn.releaseSavepoint(savePoint);
pstmt = conn.prepareStatement("INSERT INTO T_BLOB (ID, DATA) VALUES (?, ?)");
Blob blob = conn.createBlob();
blob.setBytes(1, new byte[100]);
pstmt.setInt(1, 1);
pstmt.setBlob(2, blob);
int updateCount = pstmt.executeUpdate();
assertEquals(1, updateCount);
stmt = conn.createStatement();
conn.nativeSQL("SELECT ID, DATA FROM T_BLOB");
// //////
rs = stmt.executeQuery("SELECT ID, DATA FROM T_BLOB");
rs.getStatement(); // just call
while (rs.next()) {
Blob readBlob = rs.getBlob(2);
readBlob.length();
readBlob.getBinaryStream(1, 100).close();
readBlob.getBinaryStream().close();
readBlob.free();
try {
rs.getUnicodeStream(1).close();
} catch (SQLFeatureNotSupportedException ex) {
}
try {
rs.getUnicodeStream("DATA").close();
} catch (SQLFeatureNotSupportedException ex) {
}
}
JdbcUtils.close(rs);
rs = stmt.executeQuery("SELECT ID, DATA FROM T_BLOB");
while (rs.next()) {
rs.getBinaryStream(2).close();
}
JdbcUtils.close(rs);
rs = stmt.executeQuery("SELECT ID, DATA FROM T_BLOB");
while (rs.next()) {
rs.getBinaryStream("DATA").close();
}
JdbcUtils.close(rs);
rs = stmt.executeQuery("SELECT ID, DATA FROM T_BLOB");
while (rs.next()) {
rs.getBytes(2);
}
JdbcUtils.close(rs);
rs = stmt.executeQuery("SELECT ID, DATA FROM T_BLOB");
while (rs.next()) {
rs.getBytes("DATA");
}
JdbcUtils.close(rs);
conn.setAutoCommit(true);
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(stmt);
JdbcUtils.close(pstmt);
JdbcUtils.close(conn);
}
}
}
| ConnectionTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/ManyToManyTreatJoinTest.java | {
"start": 9099,
"end": 9372
} | class ____ extends JoinedBase {
private Integer subProp;
public JoinedSub1() {
}
public JoinedSub1(Integer id, Integer subProp) {
super( id );
this.subProp = subProp;
}
}
@SuppressWarnings("unused")
@Entity( name = "JoinedSub2" )
public static | JoinedSub1 |
java | apache__kafka | core/src/main/java/kafka/server/share/SharePartitionCache.java | {
"start": 1227,
"end": 4938
} | class ____ {
/**
* The map to store the share group id and the set of topic-partitions for that group.
*/
private final Map<String, Set<TopicIdPartition>> groups;
/**
* The map is used to store the SharePartition objects for each share group topic-partition.
*/
private final Map<SharePartitionKey, SharePartition> partitions;
SharePartitionCache() {
this.groups = new HashMap<>();
this.partitions = new ConcurrentHashMap<>();
}
/**
* Returns the share partition for the given key.
*
* @param partitionKey The key to get the share partition for.
* @return The share partition for the key or null if not found.
*/
public SharePartition get(SharePartitionKey partitionKey) {
return partitions.get(partitionKey);
}
/**
* Returns the set of topic-partitions for the given group id.
*
* @param groupId The group id to get the topic-partitions for.
* @return The set of topic-partitions for the group id.
*/
public synchronized Set<TopicIdPartition> topicIdPartitionsForGroup(String groupId) {
return groups.containsKey(groupId) ? Set.copyOf(groups.get(groupId)) : Set.of();
}
/**
* Removes the share partition from the cache. The method also removes the topic-partition from
* the group map.
*
* @param partitionKey The key to remove.
* @return The removed value or null if not found.
*/
public synchronized SharePartition remove(SharePartitionKey partitionKey) {
groups.computeIfPresent(partitionKey.groupId(), (k, v) -> {
v.remove(partitionKey.topicIdPartition());
return v.isEmpty() ? null : v;
});
return partitions.remove(partitionKey);
}
/**
* Computes the value for the given key if it is not already present in the cache. Method also
* updates the group map with the topic-partition for the group id.
*
* @param partitionKey The key to compute the value for.
* @param mappingFunction The function to compute the value.
* @return The computed or existing value.
*/
public synchronized SharePartition computeIfAbsent(SharePartitionKey partitionKey, Function<SharePartitionKey, SharePartition> mappingFunction) {
groups.computeIfAbsent(partitionKey.groupId(), k -> new HashSet<>()).add(partitionKey.topicIdPartition());
return partitions.computeIfAbsent(partitionKey, mappingFunction);
}
/**
* Returns the set of all share partition keys in the cache. As the cache can't be cleaned without
* marking the share partitions fenced and detaching the partition listener in the replica manager,
* hence rather providing a method to clean the cache directly, this method is provided to fetch
* all the keys in the cache.
*
* @return The set of all share partition keys.
*/
public Set<SharePartitionKey> cachedSharePartitionKeys() {
return partitions.keySet();
}
// Visible for testing. Should not be used outside the test classes.
void put(SharePartitionKey partitionKey, SharePartition sharePartition) {
partitions.put(partitionKey, sharePartition);
}
// Visible for testing.
int size() {
return partitions.size();
}
// Visible for testing.
boolean containsKey(SharePartitionKey partitionKey) {
return partitions.containsKey(partitionKey);
}
// Visible for testing.
boolean isEmpty() {
return partitions.isEmpty();
}
// Visible for testing.
synchronized Map<String, Set<TopicIdPartition>> groups() {
return Map.copyOf(groups);
}
}
| SharePartitionCache |
java | quarkusio__quarkus | test-framework/junit5/src/main/java/io/quarkus/test/junit/launcher/JarLauncherProvider.java | {
"start": 791,
"end": 2695
} | class ____ implements ArtifactLauncherProvider {
@Override
public boolean supportsArtifactType(String type, String testProfile) {
return isJar(type);
}
@Override
public JarArtifactLauncher create(CreateContext context) {
String pathStr = context.quarkusArtifactProperties().getProperty("path");
if ((pathStr != null) && !pathStr.isEmpty()) {
JarArtifactLauncher launcher;
ServiceLoader<JarArtifactLauncher> loader = ServiceLoader.load(JarArtifactLauncher.class);
Iterator<JarArtifactLauncher> iterator = loader.iterator();
if (iterator.hasNext()) {
launcher = iterator.next();
} else {
launcher = new DefaultJarLauncher();
}
SmallRyeConfig config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class);
TestConfig testConfig = config.getConfigMapping(TestConfig.class);
launcher.init(new DefaultJarInitContext(
config.getValue("quarkus.http.test-port", OptionalInt.class).orElse(DEFAULT_PORT),
config.getValue("quarkus.http.test-ssl-port", OptionalInt.class).orElse(DEFAULT_HTTPS_PORT),
testConfig.waitTime(),
testConfig.integrationTestProfile(),
TestConfigUtil.argLineValues(testConfig.argLine().orElse("")),
testConfig.env(),
context.devServicesLaunchResult(),
context.buildOutputDirectory().resolve(pathStr),
config.getOptionalValue("quarkus.package.jar.appcds.use-aot", Boolean.class)
.orElse(Boolean.FALSE)));
return launcher;
} else {
throw new IllegalStateException("The path of the native binary could not be determined");
}
}
static | JarLauncherProvider |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity2.java | {
"start": 704,
"end": 2628
} | class ____ {
@Id
@GeneratedValue
private Integer id;
private String data;
@ManyToOne
@JoinColumn(name = "some_join_column_2", insertable = false, updatable = false)
private DoubleListJoinColumnBidirectionalRefIngEntity owner;
public DoubleListJoinColumnBidirectionalRefEdEntity2() {
}
public DoubleListJoinColumnBidirectionalRefEdEntity2(
Integer id,
String data,
DoubleListJoinColumnBidirectionalRefIngEntity owner) {
this.id = id;
this.data = data;
this.owner = owner;
}
public DoubleListJoinColumnBidirectionalRefEdEntity2(
String data,
DoubleListJoinColumnBidirectionalRefIngEntity owner) {
this.data = data;
this.owner = owner;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public DoubleListJoinColumnBidirectionalRefIngEntity getOwner() {
return owner;
}
public void setOwner(DoubleListJoinColumnBidirectionalRefIngEntity owner) {
this.owner = owner;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof DoubleListJoinColumnBidirectionalRefEdEntity2) ) {
return false;
}
DoubleListJoinColumnBidirectionalRefEdEntity2 that = (DoubleListJoinColumnBidirectionalRefEdEntity2) o;
if ( data != null ? !data.equals( that.data ) : that.data != null ) {
return false;
}
//noinspection RedundantIfStatement
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (id != null ? id.hashCode() : 0);
result = 31 * result + (data != null ? data.hashCode() : 0);
return result;
}
public String toString() {
return "DoubleListJoinColumnBidirectionalRefIngEntity2(id = " + id + ", data = " + data + ")";
}
}
| DoubleListJoinColumnBidirectionalRefEdEntity2 |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/generics/JavadocUtil.java | {
"start": 1168,
"end": 6231
} | class ____ {
private JavadocUtil() {
}
/**
* @param model the model from which the information are extracted.
* @return the description of the given component with all the possible details.
*/
public static String getMainDescription(ComponentModel model) {
return getMainDescription(model, true);
}
/**
* @param model the model from which the information are extracted.
* @param withPathParameterDetails indicates whether the information about the path parameters should be added to
* the description.
* @return the description of the given component.
*/
public static String getMainDescription(ComponentModel model, boolean withPathParameterDetails) {
StringBuilder descSb = new StringBuilder(512);
descSb.append(model.getTitle()).append(" (").append(model.getArtifactId()).append(")");
descSb.append("\n").append(model.getDescription());
descSb.append("\n\nCategory: ").append(model.getLabel());
descSb.append("\nSince: ").append(model.getFirstVersionShort());
descSb.append("\nMaven coordinates: ").append(model.getGroupId()).append(":").append(model.getArtifactId());
if (withPathParameterDetails) {
// include javadoc for all path parameters and mark which are required
descSb.append("\n\nSyntax: <code>").append(model.getSyntax()).append("</code>");
for (ComponentModel.EndpointOptionModel option : model.getEndpointOptions()) {
if ("path".equals(option.getKind())) {
descSb.append("\n\nPath parameter: ").append(option.getName());
if (option.isRequired()) {
descSb.append(" (required)");
}
if (option.isDeprecated()) {
descSb.append(" <strong>deprecated</strong>");
}
descSb.append("\n").append(option.getDescription());
if (option.isSupportFileReference()) {
descSb.append(
"\nThis option can also be loaded from an existing file, by prefixing with file: or classpath: followed by the location of the file.");
}
if (option.getDefaultValue() != null) {
descSb.append("\nDefault value: ").append(option.getDefaultValue());
}
// TODO: default value note ?
if (option.getEnums() != null && !option.getEnums().isEmpty()) {
descSb.append("\nThere are ").append(option.getEnums().size())
.append(" enums and the value can be one of: ")
.append(wrapEnumValues(option.getEnums()));
}
}
}
}
return descSb.toString();
}
private static String wrapEnumValues(List<String> enumValues) {
// comma to space so we can wrap words (which uses space)
return String.join(", ", enumValues);
}
public static String pathParameterJavaDoc(ComponentModel model) {
String doc = null;
int pos = model.getSyntax().indexOf(':');
if (pos != -1) {
doc = model.getSyntax().substring(pos + 1);
} else {
doc = model.getSyntax();
}
// remove leading non alpha symbols
char ch = doc.charAt(0);
while (!Character.isAlphabetic(ch)) {
doc = doc.substring(1);
ch = doc.charAt(0);
}
return doc;
}
public static String extractJavaDoc(String sourceCode, MethodSource<?> ms) throws IOException {
// the javadoc is mangled by roaster (sadly it does not preserve newlines and original formatting)
// so we need to load it from the original source file
Object internal = ms.getJavaDoc().getInternal();
if (internal instanceof ASTNode) {
int pos = ((ASTNode) internal).getStartPosition();
int len = ((ASTNode) internal).getLength();
if (pos > 0 && len > 0) {
String doc = sourceCode.substring(pos, pos + len);
LineNumberReader ln = new LineNumberReader(new StringReader(doc));
String line;
StringBuilder sb = new StringBuilder(256);
while ((line = ln.readLine()) != null) {
line = line.trim();
if (line.startsWith("/**") || line.startsWith("*/")) {
continue;
}
if (line.startsWith("*")) {
line = line.substring(1).trim();
}
sb.append(line);
sb.append("\n");
}
doc = sb.toString();
return doc;
}
}
return null;
}
}
| JavadocUtil |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/UnexpectedFormatException.java | {
"start": 855,
"end": 1118
} | class ____ extends Exception {
/**
* Generated serial version ID.
*/
private static final long serialVersionUID = -5322323184538975579L;
public UnexpectedFormatException(final String msg) {
super(msg);
}
}
| UnexpectedFormatException |
java | google__guava | android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java | {
"start": 4912,
"end": 5091
} | interface ____
extends IntegerSupplier, Predicate<List<String>>, StringListPredicate {}
public void testGenericInterface() {
// test the 1st generic | IntegerStringFunction |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDeleteAccumulatedCount1Test.java | {
"start": 1695,
"end": 4869
} | class ____ {
private static final String CONFIG = "log4j-rolling-with-custom-delete-accum-count1.xml";
private static final String DIR = "target/rolling-with-delete-accum-count1/test";
private final LoggerContextRule loggerContextRule =
LoggerContextRule.createShutdownTimeoutLoggerContextRule(CONFIG);
@Rule
public RuleChain chain = loggerContextRule.withCleanFoldersRule(DIR);
@Test
public void testAppender() throws Exception {
final Path p1 = writeTextTo(DIR + "/my-1.log"); // glob="test-*.log"
final Path p2 = writeTextTo(DIR + "/my-2.log");
final Path p3 = writeTextTo(DIR + "/my-3.log");
final Path p4 = writeTextTo(DIR + "/my-4.log");
final Path p5 = writeTextTo(DIR + "/my-5.log");
final Logger logger = loggerContextRule.getLogger();
for (int i = 0; i < 10; ++i) {
updateLastModified(p1, p2, p3, p4, p5); // make my-*.log files most recent
// 30 chars per message: each message triggers a rollover
logger.debug("This is a test message number " + i); // 30 chars:
}
final File dir = new File(DIR);
assertTrue("Dir " + DIR + " should exist", dir.exists());
final List<String> expected = Arrays.asList("my-1.log", "my-2.log", "my-3.log", "my-4.log", "my-5.log");
waitAtMost(7, TimeUnit.SECONDS).untilAsserted(() -> {
final File[] files = Objects.requireNonNull(dir.listFiles(), "listFiles()");
assertTrue("Dir " + DIR + " should contain files", files.length > 0);
// The 5 my-*.log files must exist
for (final String name : expected) {
assertTrue("missing " + name, new File(dir, name).exists());
}
// Only allow my-*.log and test-*.log
for (final File file : files) {
final String n = file.getName();
if (!expected.contains(n) && !n.startsWith("test-")) {
fail("unexpected file " + file);
}
}
// Rolled files count should be within a reasonable band
final long rolled = Arrays.stream(files)
.map(File::getName)
.filter(n -> n.startsWith("test-"))
.count();
// Tolerate CRLF/LF differences + timing jitter
assertTrue("expected rolled count in [6, 9], got " + rolled, rolled >= 6 && rolled <= 9);
});
}
private void updateLastModified(final Path... paths) throws IOException {
for (final Path path : paths) {
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis() + 2000));
}
}
private Path writeTextTo(final String location) throws IOException {
final Path path = Paths.get(location);
Files.createDirectories(path.getParent());
try (final BufferedWriter buffy = Files.newBufferedWriter(path, Charset.defaultCharset())) {
buffy.write("some text");
buffy.newLine();
buffy.flush();
}
return path;
}
}
| RollingAppenderDeleteAccumulatedCount1Test |
java | apache__camel | components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/services/KubernetesServicesComponent.java | {
"start": 1097,
"end": 1380
} | class ____ extends AbstractKubernetesComponent {
@Override
protected KubernetesServicesEndpoint doCreateEndpoint(String uri, String remaining, KubernetesConfiguration config) {
return new KubernetesServicesEndpoint(uri, this, config);
}
}
| KubernetesServicesComponent |
java | apache__camel | dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/SourceScheme.java | {
"start": 1028,
"end": 2648
} | enum ____ {
GIST("https://gist.github", true),
GITHUB("https://github.com/", true),
RAW_GITHUB("https://raw.githubusercontent.com/", true),
FILE,
CLASSPATH,
HTTP(true),
HTTPS(true),
UNKNOWN;
private final String uri;
private final boolean remote;
SourceScheme() {
this(false);
}
SourceScheme(boolean remote) {
this(null, remote);
}
SourceScheme(String uri, boolean remote) {
this.uri = uri;
this.remote = remote;
}
public boolean isRemote() {
return remote;
}
/**
* Try to resolve source scheme from given file path URL. Checks for special GIST and GITHUB endpoint URLs. By
* default, uses unknown scheme usually leads to loading resource from file system.
*
* @param path
* @return
*/
public static SourceScheme fromUri(String path) {
return Arrays.stream(values())
.filter(scheme -> path.startsWith(scheme.name().toLowerCase(Locale.US) + ":") ||
(scheme.uri != null && path.startsWith(scheme.uri)))
.findFirst()
.orElse(UNKNOWN); // use file as default scheme
}
/**
* If any strip scheme prefix from given name.
*
* @param name
* @return
*/
public static String onlyName(String name) {
for (SourceScheme scheme : values()) {
if (name.startsWith(scheme.name().toLowerCase(Locale.US) + ":")) {
return name.substring(scheme.name().length() + 1);
}
}
return name;
}
}
| SourceScheme |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/util/MockUtilTest.java | {
"start": 1264,
"end": 3131
} | class ____.lang.String");
}
@Test
public void should_scream_when_null_passed() {
assertThatThrownBy(
() -> {
MockUtil.getMockHandler(null);
})
.isInstanceOf(NotAMockException.class)
.hasMessage("Argument should be a mock, but is null!");
}
@Test
public void should_get_mock_settings() {
List<?> mock = Mockito.mock(List.class);
assertNotNull(MockUtil.getMockSettings(mock));
}
@Test
public void should_validate_mock() {
assertFalse(MockUtil.isMock("i mock a mock"));
assertTrue(MockUtil.isMock(Mockito.mock(List.class)));
}
@Test
public void should_validate_spy() {
assertFalse(MockUtil.isSpy("i mock a mock"));
assertFalse(MockUtil.isSpy(Mockito.mock(List.class)));
assertFalse(MockUtil.isSpy(null));
assertTrue(MockUtil.isSpy(Mockito.spy(new ArrayList())));
assertTrue(MockUtil.isSpy(Mockito.spy(ArrayList.class)));
assertTrue(
MockUtil.isSpy(
Mockito.mock(
ArrayList.class,
withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS))));
}
@Test
public void should_redefine_MockName_if_default() {
List<?> mock = Mockito.mock(List.class);
MockUtil.maybeRedefineMockName(mock, "newName");
Assertions.assertThat(MockUtil.getMockName(mock).toString()).isEqualTo("newName");
}
@Test
public void should_not_redefine_MockName_if_default() {
List<?> mock = Mockito.mock(List.class, "original");
MockUtil.maybeRedefineMockName(mock, "newName");
Assertions.assertThat(MockUtil.getMockName(mock).toString()).isEqualTo("original");
}
final | java |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java | {
"start": 15386,
"end": 15589
} | class ____<T> {
void someMethod(Map<?, ?> m, Object otherArg) {
}
void someMethod(T theArg, Map<?, ?> m) {
}
abstract void someMethod(T theArg, Object otherArg);
}
public abstract static | Bar |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/AbstractGenerateMojo.java | {
"start": 1730,
"end": 9100
} | class ____ extends AbstractMojo {
private static final String INCREMENTAL_DATA = "";
private final MavenProjectHelper projectHelper;
private final BuildContext buildContext;
@Parameter(property = "project", required = true, readonly = true)
protected MavenProject project;
@Parameter(defaultValue = "${showStaleFiles}")
private boolean showStaleFiles;
@Parameter(defaultValue = "false")
private boolean skip;
protected AbstractGenerateMojo(MavenProjectHelper projectHelper, BuildContext buildContext) {
this.projectHelper = projectHelper;
this.buildContext = buildContext;
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().info("Skipping execution");
return;
}
try {
if (!isUpToDate(project)) {
doExecute();
writeIncrementalInfo(project);
}
} catch (Exception e) {
throw new MojoFailureException("Error generating data " + e, e);
}
}
protected abstract void doExecute() throws MojoFailureException, MojoExecutionException;
protected void invoke(Class<? extends AbstractGeneratorMojo> mojoClass)
throws MojoExecutionException, MojoFailureException {
invoke(mojoClass, null);
}
protected void invoke(Class<? extends AbstractGeneratorMojo> mojoClass, Map<String, Object> parameters)
throws MojoExecutionException, MojoFailureException {
try {
AbstractGeneratorMojo mojo = mojoClass.getDeclaredConstructor(MavenProjectHelper.class, BuildContext.class)
.newInstance(projectHelper, buildContext);
mojo.setLog(getLog());
mojo.setPluginContext(getPluginContext());
// set options using reflections
if (parameters != null && !parameters.isEmpty()) {
ReflectionHelper.doWithFields(mojoClass, field -> {
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
if (field.getName().equals(entry.getKey())) {
ReflectionHelper.setField(field, mojo, entry.getValue());
}
}
});
}
mojo.execute(project);
} catch (MojoExecutionException | MojoFailureException e) {
throw e;
} catch (Exception e) {
throw new MojoFailureException("Unable to create mojo", e);
}
}
private void writeIncrementalInfo(MavenProject project) throws MojoExecutionException {
try {
Path cacheData = getIncrementalDataPath(project);
Files.createDirectories(cacheData.getParent());
try (Writer w = Files.newBufferedWriter(cacheData)) {
w.append(INCREMENTAL_DATA);
}
} catch (IOException e) {
throw new MojoExecutionException("Error checking manifest uptodate status", e);
}
}
private boolean isUpToDate(MavenProject project) throws MojoExecutionException {
try {
Path cacheData = getIncrementalDataPath(project);
final String prvdata = getPreviousRunData(cacheData);
if (INCREMENTAL_DATA.equals(prvdata)) {
long lastmod = Files.getLastModifiedTime(cacheData).toMillis();
Set<String> stale = Stream.concat(Stream.concat(
project.getCompileSourceRoots().stream().map(File::new),
Stream.of(new File(project.getBuild().getOutputDirectory()))),
project.getArtifacts().stream().map(Artifact::getFile))
.flatMap(f -> newer(lastmod, f)).collect(Collectors.toSet());
if (!stale.isEmpty()) {
getLog().info("Stale files detected, re-generating.");
if (showStaleFiles) {
getLog().info("Stale files: " + String.join(", ", stale));
} else if (getLog().isDebugEnabled()) {
getLog().debug("Stale files: " + String.join(", ", stale));
}
} else {
// everything is in order, skip
getLog().info("Skipping generation, everything is up to date.");
return true;
}
} else {
if (prvdata == null) {
getLog().info("No previous run data found, generating files.");
} else {
getLog().info("Configuration changed, re-generating files.");
}
}
} catch (IOException e) {
throw new MojoExecutionException("Error checking uptodate status", e);
}
return false;
}
private String getPreviousRunData(Path cacheData) throws IOException {
if (Files.isRegularFile(cacheData)) {
return Files.readString(cacheData, StandardCharsets.UTF_8);
} else {
return null;
}
}
private Path getIncrementalDataPath(MavenProject project) {
return Paths.get(project.getBuild().getDirectory(), "camel-package-maven-plugin",
"org.apache.camel_camel-package-maven-plugin_info_xx");
}
private static long isRecentlyModifiedFile(Path p) {
try {
BasicFileAttributes fileAttributes = Files.readAttributes(p, BasicFileAttributes.class);
// if it's a directory, we don't care
if (fileAttributes.isDirectory()) {
return 0;
}
return fileAttributes.lastModifiedTime().toMillis();
} catch (IOException e) {
return 0;
}
}
private static Stream<String> newer(long lastmod, File file) {
try {
if (!file.exists()) {
return Stream.empty();
}
BasicFileAttributes fileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
if (fileAttributes.isDirectory()) {
return Files.walk(file.toPath()).filter(p -> isRecentlyModifiedFile(p) > lastmod)
.map(Path::toString);
} else if (fileAttributes.isRegularFile()) {
if (fileAttributes.lastModifiedTime().toMillis() > lastmod) {
if (file.getName().endsWith(".jar")) {
try (ZipFile zf = new ZipFile(file)) {
return zf.stream().filter(ze -> !ze.isDirectory())
.filter(ze -> ze.getLastModifiedTime().toMillis() > lastmod)
.map(ze -> file + "!" + ze.getName()).toList().stream();
} catch (IOException e) {
throw new IOException("Error reading zip file: " + file, e);
}
} else {
return Stream.of(file.toString());
}
} else {
return Stream.empty();
}
} else {
return Stream.empty();
}
} catch (IOException e) {
throw new IOError(e);
}
}
}
| AbstractGenerateMojo |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/cid/AccountId.java | {
"start": 250,
"end": 793
} | class ____ implements java.io.Serializable {
private final int id;
protected AccountId() {
this.id = 0;
}
public AccountId(int id) {
this.id = id;
}
public int intValue() {
return id;
}
@Override
public int hashCode() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccountId other = (AccountId) obj;
if (other != null && id != other.id)
return false;
return true;
}
}
| AccountId |
java | apache__camel | components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppDataSmCommandTest.java | {
"start": 2008,
"end": 14036
} | class ____ {
private static TimeZone defaultTimeZone;
private SMPPSession session;
private SmppConfiguration config;
private SmppDataSmCommand command;
@BeforeAll
public static void setUpBeforeClass() {
defaultTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
}
@AfterAll
public static void tearDownAfterClass() {
if (defaultTimeZone != null) {
TimeZone.setDefault(defaultTimeZone);
}
}
@BeforeEach
public void setUp() {
session = mock(SMPPSession.class);
config = new SmppConfiguration();
config.setServiceType("CMT");
command = new SmppDataSmCommand(session, config);
}
@Test
public void executeWithConfigurationData() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm");
when(session.dataShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"),
eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()),
eq(new RegisteredDelivery((byte) 1)), eq(DataCodings.newInstance((byte) 0))))
.thenReturn(new DataSmResult(new MessageId("1"), null));
command.execute(exchange);
assertEquals("1", exchange.getMessage().getHeader(SmppConstants.ID));
assertNull(exchange.getMessage().getHeader(SmppConstants.OPTIONAL_PARAMETERS));
}
@Test
public void execute() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm");
exchange.getIn().setHeader(SmppConstants.SERVICE_TYPE, "XXX");
exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_TON, TypeOfNumber.NATIONAL.value());
exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_NPI, NumberingPlanIndicator.NATIONAL.value());
exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR, "1818");
exchange.getIn().setHeader(SmppConstants.DEST_ADDR_TON, TypeOfNumber.INTERNATIONAL.value());
exchange.getIn().setHeader(SmppConstants.DEST_ADDR_NPI, NumberingPlanIndicator.INTERNET.value());
exchange.getIn().setHeader(SmppConstants.DEST_ADDR, "1919");
exchange.getIn().setHeader(SmppConstants.REGISTERED_DELIVERY,
new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE).value());
when(session.dataShortMessage(eq("XXX"), eq(TypeOfNumber.NATIONAL), eq(NumberingPlanIndicator.NATIONAL), eq("1818"),
eq(TypeOfNumber.INTERNATIONAL), eq(NumberingPlanIndicator.INTERNET), eq("1919"), eq(new ESMClass()),
eq(new RegisteredDelivery((byte) 2)), eq(DataCodings.newInstance((byte) 0))))
.thenReturn(new DataSmResult(new MessageId("1"), null));
command.execute(exchange);
assertEquals("1", exchange.getMessage().getHeader(SmppConstants.ID));
assertNull(exchange.getMessage().getHeader(SmppConstants.OPTIONAL_PARAMETERS));
}
@SuppressWarnings("unchecked")
@Test
public void executeWithOptionalParameter() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm");
Map<String, String> optionalParameters = new LinkedHashMap<>();
optionalParameters.put("SOURCE_SUBADDRESS", "1292");
optionalParameters.put("ADDITIONAL_STATUS_INFO_TEXT", "urgent");
optionalParameters.put("DEST_ADDR_SUBUNIT", "4");
optionalParameters.put("DEST_TELEMATICS_ID", "2");
optionalParameters.put("QOS_TIME_TO_LIVE", "3600000");
optionalParameters.put("ALERT_ON_MESSAGE_DELIVERY", null);
// fall back test for vendor specific optional parameter
optionalParameters.put("0x2150", "0815");
optionalParameters.put("0x2151", "0816");
optionalParameters.put("0x2152", "6");
optionalParameters.put("0x2153", "9");
optionalParameters.put("0x2154", "7400000");
optionalParameters.put("0x2155", null);
exchange.getIn().setHeader(SmppConstants.OPTIONAL_PARAMETERS, optionalParameters);
when(session.dataShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"),
eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()),
eq(new RegisteredDelivery((byte) 1)), eq(DataCodings.newInstance((byte) 0)),
eq(new OptionalParameter.Source_subaddress("1292".getBytes())),
eq(new OptionalParameter.Additional_status_info_text("urgent")),
eq(new OptionalParameter.Dest_addr_subunit((byte) 4)),
eq(new OptionalParameter.Dest_telematics_id((short) 2)),
eq(new OptionalParameter.Qos_time_to_live(3600000)),
eq(new OptionalParameter.Alert_on_message_delivery((byte) 0))))
.thenReturn(new DataSmResult(
new MessageId("1"),
new OptionalParameter[] {
new OptionalParameter.Source_subaddress("1292".getBytes()),
new OptionalParameter.Additional_status_info_text("urgent"),
new OptionalParameter.Dest_addr_subunit((byte) 4),
new OptionalParameter.Dest_telematics_id((short) 2),
new OptionalParameter.Qos_time_to_live(3600000),
new OptionalParameter.Alert_on_message_delivery((byte) 0) }));
command.execute(exchange);
assertEquals(3, exchange.getMessage().getHeaders().size());
assertEquals("1", exchange.getMessage().getHeader(SmppConstants.ID));
Map<String, String> optParamMap = exchange.getMessage().getHeader(SmppConstants.OPTIONAL_PARAMETERS, Map.class);
assertEquals(6, optParamMap.size());
assertEquals("1292", optParamMap.get("SOURCE_SUBADDRESS"));
assertEquals("urgent", optParamMap.get("ADDITIONAL_STATUS_INFO_TEXT"));
assertEquals("4", optParamMap.get("DEST_ADDR_SUBUNIT"));
assertEquals("2", optParamMap.get("DEST_TELEMATICS_ID"));
assertEquals("3600000", optParamMap.get("QOS_TIME_TO_LIVE"));
assertEquals("0", optParamMap.get("ALERT_ON_MESSAGE_DELIVERY"));
Map<Short, Object> optionalResultParameter
= exchange.getMessage().getHeader(SmppConstants.OPTIONAL_PARAMETER, Map.class);
assertEquals(6, optionalResultParameter.size());
assertArrayEquals("1292".getBytes("UTF-8"), (byte[]) optionalResultParameter.get((short) 0x0202));
assertEquals("urgent", optionalResultParameter.get((short) 0x001D));
assertEquals((byte) 4, optionalResultParameter.get((short) 0x0005));
assertEquals((short) 2, optionalResultParameter.get((short) 0x0008));
assertEquals(3600000, optionalResultParameter.get((short) 0x0017));
assertEquals((byte) 0, optionalResultParameter.get((short) 0x130C));
}
@SuppressWarnings("unchecked")
@Test
public void executeWithOptionalParameterNewStyle() throws Exception {
Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut);
exchange.getIn().setHeader(SmppConstants.COMMAND, "DataSm");
Map<Short, Object> optionalParameters = new LinkedHashMap<>();
// standard optional parameter
optionalParameters.put((short) 0x0202, "1292".getBytes("UTF-8"));
optionalParameters.put((short) 0x001D, "urgent");
optionalParameters.put((short) 0x0005, Byte.valueOf("4"));
optionalParameters.put((short) 0x0008, (short) 2);
optionalParameters.put((short) 0x0017, 3600000);
optionalParameters.put((short) 0x130C, null);
// vendor specific optional parameter
optionalParameters.put((short) 0x2150, "0815".getBytes("UTF-8"));
optionalParameters.put((short) 0x2151, "0816");
optionalParameters.put((short) 0x2152, Byte.valueOf("6"));
optionalParameters.put((short) 0x2153, (short) 9);
optionalParameters.put((short) 0x2154, 7400000);
optionalParameters.put((short) 0x2155, null);
exchange.getIn().setHeader(SmppConstants.OPTIONAL_PARAMETER, optionalParameters);
when(session.dataShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"),
eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()),
eq(new RegisteredDelivery((byte) 1)), eq(DataCodings.newInstance((byte) 0)),
eq(new OptionalParameter.OctetString(Tag.SOURCE_SUBADDRESS, "1292")),
eq(new OptionalParameter.COctetString(Tag.ADDITIONAL_STATUS_INFO_TEXT.code(), "urgent")),
eq(new OptionalParameter.Byte(Tag.DEST_ADDR_SUBUNIT, (byte) 4)),
eq(new OptionalParameter.Short(Tag.DEST_TELEMATICS_ID.code(), (short) 2)),
eq(new OptionalParameter.Int(Tag.QOS_TIME_TO_LIVE, 3600000)),
eq(new OptionalParameter.Null(Tag.ALERT_ON_MESSAGE_DELIVERY)),
eq(new OptionalParameter.OctetString((short) 0x2150, "1292", "UTF-8")),
eq(new OptionalParameter.COctetString((short) 0x2151, "0816")),
eq(new OptionalParameter.Byte((short) 0x2152, (byte) 6)),
eq(new OptionalParameter.Short((short) 0x2153, (short) 9)),
eq(new OptionalParameter.Int((short) 0x2154, 7400000)),
eq(new OptionalParameter.Null((short) 0x2155))))
.thenReturn(new DataSmResult(
new MessageId("1"), new OptionalParameter[] {
new OptionalParameter.Source_subaddress("1292".getBytes()),
new OptionalParameter.Additional_status_info_text("urgent"),
new OptionalParameter.Dest_addr_subunit((byte) 4),
new OptionalParameter.Dest_telematics_id((short) 2),
new OptionalParameter.Qos_time_to_live(3600000),
new OptionalParameter.Alert_on_message_delivery((byte) 0) }));
command.execute(exchange);
assertEquals(3, exchange.getMessage().getHeaders().size());
assertEquals("1", exchange.getMessage().getHeader(SmppConstants.ID));
Map<String, String> optParamMap = exchange.getMessage().getHeader(SmppConstants.OPTIONAL_PARAMETERS, Map.class);
assertEquals(6, optParamMap.size());
assertEquals("1292", optParamMap.get("SOURCE_SUBADDRESS"));
assertEquals("urgent", optParamMap.get("ADDITIONAL_STATUS_INFO_TEXT"));
assertEquals("4", optParamMap.get("DEST_ADDR_SUBUNIT"));
assertEquals("2", optParamMap.get("DEST_TELEMATICS_ID"));
assertEquals("3600000", optParamMap.get("QOS_TIME_TO_LIVE"));
assertEquals("0", optParamMap.get("ALERT_ON_MESSAGE_DELIVERY"));
Map<Short, Object> optionalResultParameter
= exchange.getMessage().getHeader(SmppConstants.OPTIONAL_PARAMETER, Map.class);
assertEquals(6, optionalResultParameter.size());
assertArrayEquals("1292".getBytes("UTF-8"), (byte[]) optionalResultParameter.get((short) 0x0202));
assertEquals("urgent", optionalResultParameter.get((short) 0x001D));
assertEquals((byte) 4, optionalResultParameter.get((short) 0x0005));
assertEquals((short) 2, optionalResultParameter.get((short) 0x0008));
assertEquals(3600000, optionalResultParameter.get((short) 0x0017));
assertEquals((byte) 0, optionalResultParameter.get((short) 0x130C));
}
}
| SmppDataSmCommandTest |
java | apache__camel | components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpGetOrderingIssueTest.java | {
"start": 1119,
"end": 3333
} | class ____ extends BaseUndertowTest {
@Test
public void testProducerGet() throws Exception {
getMockEndpoint("mock:root").expectedMessageCount(1);
String out = template.requestBody("undertow:http://localhost:{{port}}", null, String.class);
assertEquals("Route without name", out);
MockEndpoint.assertIsSatisfied(context);
MockEndpoint.resetMocks(context);
getMockEndpoint("mock:pippo").expectedMessageCount(1);
out = template.requestBody("undertow:http://localhost:{{port}}/Donald", null, String.class);
assertEquals("Route with name: Donald", out);
MockEndpoint.assertIsSatisfied(context);
MockEndpoint.resetMocks(context);
getMockEndpoint("mock:bar").expectedMessageCount(1);
out = template.requestBody("undertow:http://localhost:{{port}}/bar", null, String.class);
assertEquals("Going to the bar", out);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// configure to use undertow on localhost with the given port
restConfiguration().component("undertow").host("localhost").port(getPort());
rest().get("/bar").to("direct:bar");
from("direct:bar")
.setBody().constant("Going to the bar")
.to("mock:bar")
.setHeader("Content-Type", constant("text/plain"));
rest().get("/{pippo}").to("direct:pippo");
from("direct:pippo")
.setBody().simple("Route with name: ${header.pippo}")
.to("mock:pippo")
.setHeader("Content-Type", constant("text/plain"));
rest().get("/").to("direct:noname");
from("direct:noname")
.setBody().constant("Route without name")
.to("mock:root")
.setHeader("Content-Type", constant("text/plain"));
}
};
}
}
| RestUndertowHttpGetOrderingIssueTest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedOutputStream.java | {
"start": 4136,
"end": 5436
} | class ____<T> {
private final List<BlockingQueue<T>> queues;
MultipleBlockingQueue(int numQueue, int queueSize) {
queues = new ArrayList<>(numQueue);
for (int i = 0; i < numQueue; i++) {
queues.add(new LinkedBlockingQueue<T>(queueSize));
}
}
void offer(int i, T object) {
final boolean b = queues.get(i).offer(object);
Preconditions.checkState(b, "Failed to offer " + object
+ " to queue, i=" + i);
}
T take(int i) throws InterruptedIOException {
try {
return queues.get(i).take();
} catch(InterruptedException ie) {
throw DFSUtilClient.toInterruptedIOException("take interrupted, i=" + i, ie);
}
}
T takeWithTimeout(int i) throws InterruptedIOException {
try {
return queues.get(i).poll(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw DFSUtilClient.toInterruptedIOException("take interrupted, i=" + i, e);
}
}
T poll(int i) {
return queues.get(i).poll();
}
T peek(int i) {
return queues.get(i).peek();
}
void clear() {
for (BlockingQueue<T> q : queues) {
q.clear();
}
}
}
/** Coordinate the communication between the streamers. */
static | MultipleBlockingQueue |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java | {
"start": 1004,
"end": 2302
} | class ____ extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean5";
@Override
protected String getObjectName() {
return OBJECT_NAME;
}
@Override
protected int getExpectedOperationCount() {
return 5;
}
@Override
protected int getExpectedAttributeCount() {
return 2;
}
@Override
protected MBeanInfoAssembler getAssembler() {
MethodNameBasedMBeanInfoAssembler assembler = new MethodNameBasedMBeanInfoAssembler();
assembler.setManagedMethods("add", "myOperation", "getName", "setName", "getAge");
return assembler;
}
@Test
void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertThat(attr.isReadable()).isTrue();
assertThat(attr.isWritable()).isFalse();
}
@Test
void testSetNameParameterIsNamed() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
MBeanOperationInfo operationSetAge = info.getOperation("setName");
assertThat(operationSetAge.getSignature()[0].getName()).isEqualTo("name");
}
@Override
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodNameAssembler.xml";
}
}
| MethodNameBasedMBeanInfoAssemblerTests |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/node/InternalSettingsPreparerTests.java | {
"start": 1314,
"end": 9154
} | class ____ extends ESTestCase {
private static final Supplier<String> DEFAULT_NODE_NAME_SHOULDNT_BE_CALLED = () -> { throw new AssertionError("shouldn't be called"); };
Path homeDir;
Settings baseEnvSettings;
@Before
public void createBaseEnvSettings() {
homeDir = createTempDir();
baseEnvSettings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), homeDir).build();
}
@After
public void clearBaseEnvSettings() {
homeDir = null;
baseEnvSettings = null;
}
public void testEmptySettings() {
String defaultNodeName = randomAlphaOfLength(8);
Environment env = InternalSettingsPreparer.prepareEnvironment(baseEnvSettings, emptyMap(), null, () -> defaultNodeName);
Settings settings = env.settings();
assertEquals(defaultNodeName, settings.get("node.name"));
assertNotNull(settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey())); // a cluster name was set
String home = Environment.PATH_HOME_SETTING.get(baseEnvSettings);
String configDir = env.configDir().toString();
assertTrue(configDir, configDir.startsWith(home));
assertEquals("elasticsearch", settings.get("cluster.name"));
}
public void testExplicitClusterName() {
Settings.Builder output = Settings.builder().put(baseEnvSettings);
InternalSettingsPreparer.prepareEnvironment(output.put("cluster.name", "foobar").build(), Map.of(), null, () -> "nodename");
assertEquals("foobar", output.build().get("cluster.name"));
}
public void testGarbageIsNotSwallowed() throws IOException {
try {
InputStream garbage = getClass().getResourceAsStream("/config/garbage/garbage.yml");
Path home = createTempDir();
Path config = home.resolve("config");
Files.createDirectory(config);
Files.copy(garbage, config.resolve("elasticsearch.yml"));
InternalSettingsPreparer.prepareEnvironment(
Settings.builder().put(baseEnvSettings).build(),
emptyMap(),
null,
() -> "default_node_name"
);
} catch (SettingsException e) {
assertEquals("Failed to load settings from [elasticsearch.yml]", e.getMessage());
}
}
public void testReplacePlaceholderFailure() {
try {
InternalSettingsPreparer.prepareEnvironment(
Settings.builder().put(baseEnvSettings).put("cluster.name", "${ES_CLUSTER_NAME}").build(),
emptyMap(),
null,
() -> "default_node_name"
);
fail("Expected SettingsException");
} catch (SettingsException e) {
assertEquals("Failed to replace property placeholders from [elasticsearch.yml]", e.getMessage());
}
}
public void testSecureSettings() {
MockSecureSettings secureSettings = new MockSecureSettings();
secureSettings.setString("foo", "secret");
Settings input = Settings.builder().put(baseEnvSettings).setSecureSettings(secureSettings).build();
Environment env = InternalSettingsPreparer.prepareEnvironment(input, emptyMap(), null, () -> "default_node_name");
Setting<SecureString> fakeSetting = SecureSetting.secureString("foo", null);
assertEquals("secret", fakeSetting.get(env.settings()).toString());
}
public void testDefaultPropertiesDoNothing() throws Exception {
Map<String, String> props = Collections.singletonMap("default.setting", "foo");
Environment env = InternalSettingsPreparer.prepareEnvironment(baseEnvSettings, props, null, () -> "default_node_name");
assertEquals("foo", env.settings().get("default.setting"));
assertNull(env.settings().get("setting"));
}
private Path copyConfig(String resourceName) throws IOException {
InputStream yaml = getClass().getResourceAsStream(resourceName);
Path configDir = homeDir.resolve("config");
Files.createDirectory(configDir);
Path configFile = configDir.resolve("elasticsearch.yaml");
Files.copy(yaml, configFile);
return configFile;
}
private Settings loadConfigWithSubstitutions(Path configFile, Map<String, String> env) throws IOException {
Settings.Builder output = Settings.builder();
InternalSettingsPreparer.loadConfigWithSubstitutions(output, configFile, env::get);
return output.build();
}
public void testSubstitutionEntireLine() throws Exception {
Path config = copyConfig("subst-entire-line.yml");
Settings settings = loadConfigWithSubstitutions(config, Map.of("mysubst", "foo: bar"));
assertThat(settings.get("foo"), equalTo("bar"));
}
public void testSubstitutionFirstLine() throws Exception {
Path config = copyConfig("subst-first-line.yml");
Settings settings = loadConfigWithSubstitutions(config, Map.of("mysubst", "v1"));
assertThat(settings.get("foo"), equalTo("v1"));
assertThat(settings.get("bar"), equalTo("v2"));
assertThat(settings.get("baz"), equalTo("v3"));
}
public void testSubstitutionLastLine() throws Exception {
Path config = copyConfig("subst-last-line.yml");
Settings settings = loadConfigWithSubstitutions(config, Map.of("mysubst", "kazaam"));
assertThat(settings.get("foo.bar.baz"), equalTo("kazaam"));
}
public void testSubstitutionMultiple() throws Exception {
Path config = copyConfig("subst-multiple.yml");
Settings settings = loadConfigWithSubstitutions(config, Map.of("s1", "substituted", "s2", "line"));
assertThat(settings.get("foo"), equalTo("substituted line value"));
}
public void testSubstitutionMissingLenient() throws Exception {
Path config = copyConfig("subst-missing.yml");
Settings settings = loadConfigWithSubstitutions(config, Map.of());
assertThat(settings.get("foo"), equalTo("${dne}"));
}
public void testSubstitutionBrokenLenient() throws Exception {
Path config = copyConfig("subst-broken.yml");
Settings settings = loadConfigWithSubstitutions(config, Map.of("goodsubst", "replaced"));
assertThat(settings.get("foo"), equalTo("${no closing brace"));
assertThat(settings.get("bar"), equalTo("replaced"));
}
public void testOverridesOverride() throws Exception {
Settings.Builder output = Settings.builder().put("foo", "bar");
InternalSettingsPreparer.loadOverrides(output, Map.of("foo", "baz"));
Settings settings = output.build();
assertThat(settings.get("foo"), equalTo("baz"));
}
public void testOverridesEmpty() throws Exception {
Settings.Builder output = Settings.builder().put("foo", "bar");
InternalSettingsPreparer.loadOverrides(output, Map.of());
Settings settings = output.build();
assertThat(settings.get("foo"), equalTo("bar"));
}
public void testOverridesNew() throws Exception {
Settings.Builder output = Settings.builder().put("foo", "bar");
InternalSettingsPreparer.loadOverrides(output, Map.of("baz", "wat"));
Settings settings = output.build();
assertThat(settings.get("foo"), equalTo("bar"));
assertThat(settings.get("baz"), equalTo("wat"));
}
public void testOverridesMultiple() throws Exception {
Settings.Builder output = Settings.builder().put("foo1", "bar").put("foo2", "baz");
InternalSettingsPreparer.loadOverrides(output, Map.of("foo1", "wat", "foo2", "yas"));
Settings settings = output.build();
assertThat(settings.get("foo1"), equalTo("wat"));
assertThat(settings.get("foo2"), equalTo("yas"));
}
}
| InternalSettingsPreparerTests |
java | hibernate__hibernate-orm | hibernate-testing/src/test/java/org/hibernate/testing/annotations/methods/ServiceRegistryTesting.java | {
"start": 3215,
"end": 3455
} | class ____ implements ServiceContributor {
@Override
public void contribute(StandardServiceRegistryBuilder serviceRegistryBuilder) {
serviceRegistryBuilder.getSettings().put( "contributed", "contributed-2" );
}
}
}
| ServiceContributor2 |
java | google__error-prone | core/src/test/java/com/google/errorprone/CommandLineFlagTest.java | {
"start": 1820,
"end": 2096
} | class ____ {
@BugPattern(
altNames = "foo",
summary = "Disableable checker that flags all return statements as errors",
explanation = "Disableable checker that flags all return statements as errors",
severity = ERROR)
public static | CommandLineFlagTest |
java | spring-projects__spring-framework | spring-tx/src/main/java/org/springframework/dao/PessimisticLockingFailureException.java | {
"start": 1267,
"end": 1817
} | class ____ extends ConcurrencyFailureException {
/**
* Constructor for PessimisticLockingFailureException.
* @param msg the detail message
*/
public PessimisticLockingFailureException(@Nullable String msg) {
super(msg);
}
/**
* Constructor for PessimisticLockingFailureException.
* @param msg the detail message
* @param cause the root cause from the data access API in use
*/
public PessimisticLockingFailureException(@Nullable String msg, @Nullable Throwable cause) {
super(msg, cause);
}
}
| PessimisticLockingFailureException |
java | quarkusio__quarkus | extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/checker/AbstractNthMethodArgChecker.java | {
"start": 126,
"end": 346
} | class ____ {
protected boolean argsOk(int expected, Object arg, SecurityIdentity identity) {
return Integer.parseInt(arg.toString()) == expected && identity.hasRole("admin");
}
}
| AbstractNthMethodArgChecker |
java | micronaut-projects__micronaut-core | http-server/src/main/java/io/micronaut/http/server/exceptions/response/Error.java | {
"start": 796,
"end": 1185
} | interface ____ {
/**
* @return The optional error path
*/
default Optional<String> getPath() {
return Optional.empty();
}
/**
* @return The error message
*/
String getMessage();
/**
* @return An optional short description for the error
*/
default Optional<String> getTitle() {
return Optional.empty();
}
}
| Error |
java | spring-projects__spring-boot | loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelector.java | {
"start": 1123,
"end": 2776
} | class ____<T> implements ContentSelector<T> {
private final Layer layer;
private final List<ContentFilter<T>> includes;
private final List<ContentFilter<T>> excludes;
public IncludeExcludeContentSelector(Layer layer, @Nullable List<ContentFilter<T>> includes,
@Nullable List<ContentFilter<T>> excludes) {
this(layer, includes, excludes, Function.identity());
}
public <S> IncludeExcludeContentSelector(Layer layer, @Nullable List<S> includes, @Nullable List<S> excludes,
Function<S, ContentFilter<T>> filterFactory) {
Assert.notNull(layer, "'layer' must not be null");
Assert.notNull(filterFactory, "'filterFactory' must not be null");
this.layer = layer;
this.includes = (includes != null) ? adapt(includes, filterFactory) : Collections.emptyList();
this.excludes = (excludes != null) ? adapt(excludes, filterFactory) : Collections.emptyList();
}
private <S> List<ContentFilter<T>> adapt(List<S> list, Function<S, ContentFilter<T>> mapper) {
return list.stream().map(mapper).toList();
}
@Override
public Layer getLayer() {
return this.layer;
}
@Override
public boolean contains(T item) {
return isIncluded(item) && !isExcluded(item);
}
private boolean isIncluded(T item) {
if (this.includes.isEmpty()) {
return true;
}
for (ContentFilter<T> include : this.includes) {
if (include.matches(item)) {
return true;
}
}
return false;
}
private boolean isExcluded(T item) {
if (this.excludes.isEmpty()) {
return false;
}
for (ContentFilter<T> exclude : this.excludes) {
if (exclude.matches(item)) {
return true;
}
}
return false;
}
}
| IncludeExcludeContentSelector |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/IndexDiskUsageAnalyzer.java | {
"start": 34236,
"end": 35674
} | class ____ {
long invertedIndexTimeInNanos;
long storedFieldsTimeInNanos;
long docValuesTimeInNanos;
long pointsTimeInNanos;
long normsTimeInNanos;
long termVectorsTimeInNanos;
long knnVectorsTimeInNanos;
long totalInNanos() {
return invertedIndexTimeInNanos + storedFieldsTimeInNanos + docValuesTimeInNanos + pointsTimeInNanos + normsTimeInNanos
+ termVectorsTimeInNanos + knnVectorsTimeInNanos;
}
@Override
public String toString() {
return "total: "
+ totalInNanos() / 1000_000
+ "ms"
+ ", inverted index: "
+ invertedIndexTimeInNanos / 1000_000
+ "ms"
+ ", stored fields: "
+ storedFieldsTimeInNanos / 1000_000
+ "ms"
+ ", doc values: "
+ docValuesTimeInNanos / 1000_000
+ "ms"
+ ", points: "
+ pointsTimeInNanos / 1000_000
+ "ms"
+ ", norms: "
+ normsTimeInNanos / 1000_000
+ "ms"
+ ", term vectors: "
+ termVectorsTimeInNanos / 1000_000
+ "ms"
+ ", knn vectors: "
+ knnVectorsTimeInNanos / 1000_000
+ "ms";
}
}
}
| ExecutionTime |
java | quarkusio__quarkus | integration-tests/elasticsearch-rest-client/src/test/java/io/quarkus/it/elasticsearch/HealthDisabledResourceTest.java | {
"start": 414,
"end": 641
} | class ____ {
@Test
public void testHealth() {
RestAssured.when().get("/q/health/ready").then()
.body("status", is("UP"),
"checks", empty());
}
}
| HealthDisabledResourceTest |
java | apache__camel | core/camel-xml-jaxp/src/main/java/org/apache/camel/converter/jaxp/XmlConverter.java | {
"start": 47113,
"end": 48028
} | class ____ the classpath!"
+ " <xsl:message> output will not be redirected to the ErrorListener!");
}
}
if (messageWarner != null) {
// set net.sf.saxon.FeatureKeys.MESSAGE_EMITTER_CLASS
factory.setAttribute("http://saxon.sf.net/feature/messageEmitterClass", messageWarner.getName());
}
}
}
}
private int[] retrieveSaxonVersion(ClassLoader loader) {
try {
final Class<?> versionClass = loader.loadClass("net.sf.saxon.Version");
final Method method = versionClass.getDeclaredMethod("getStructuredVersionNumber");
final Object result = method.invoke(null);
return (int[]) result;
} catch (ClassNotFoundException e) {
LOG.warn("Error loading Saxon's net.sf.saxon.Version | from |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/placement/PlacementFactory.java | {
"start": 2621,
"end": 2947
} | class ____
*/
public static PlacementRule getPlacementRule(
Class<? extends PlacementRule> ruleClass, Object initArg) {
LOG.info("Creating PlacementRule implementation: " + ruleClass);
PlacementRule rule = ReflectionUtils.newInstance(ruleClass, null);
rule.setConfig(initArg);
return rule;
}
} | instance |
java | quarkusio__quarkus | extensions/oidc-db-token-state-manager/runtime/src/main/java/io/quarkus/oidc/db/token/state/manager/runtime/OidcDbTokenStateManagerRunTimeConfig.java | {
"start": 384,
"end": 764
} | interface ____ {
/**
* How often should Quarkus check for expired tokens.
*/
@WithDefault("8h")
Duration deleteExpiredDelay();
/**
* Whether Quarkus should attempt to create database table where the token state is going to be stored.
*/
@WithDefault("true")
boolean createDatabaseTableIfNotExists();
}
| OidcDbTokenStateManagerRunTimeConfig |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Timestream2EndpointBuilderFactory.java | {
"start": 1589,
"end": 15093
} | interface ____
extends
EndpointProducerBuilder {
default AdvancedTimestream2EndpointBuilder advanced() {
return (AdvancedTimestream2EndpointBuilder) this;
}
/**
* The operation to perform. It can be
* describeEndpoints,createBatchLoadTask,describeBatchLoadTask,
* resumeBatchLoadTask,listBatchLoadTasks,createDatabase,deleteDatabase,describeDatabase,updateDatabase, listDatabases,createTable,deleteTable,describeTable,updateTable,listTables,writeRecords, createScheduledQuery,deleteScheduledQuery,executeScheduledQuery,updateScheduledQuery, describeScheduledQuery,listScheduledQueries,prepareQuery,query,cancelQuery.
*
* The option is a:
* <code>org.apache.camel.component.aws2.timestream.Timestream2Operations</code> type.
*
* Required: true
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder operation(org.apache.camel.component.aws2.timestream.Timestream2Operations operation) {
doSetProperty("operation", operation);
return this;
}
/**
* The operation to perform. It can be
* describeEndpoints,createBatchLoadTask,describeBatchLoadTask,
* resumeBatchLoadTask,listBatchLoadTasks,createDatabase,deleteDatabase,describeDatabase,updateDatabase, listDatabases,createTable,deleteTable,describeTable,updateTable,listTables,writeRecords, createScheduledQuery,deleteScheduledQuery,executeScheduledQuery,updateScheduledQuery, describeScheduledQuery,listScheduledQueries,prepareQuery,query,cancelQuery.
*
* The option will be converted to a
* <code>org.apache.camel.component.aws2.timestream.Timestream2Operations</code> type.
*
* Required: true
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* Set the need for overriding the endpoint. This option needs to be
* used in combination with the uriEndpointOverride option.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param overrideEndpoint the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder overrideEndpoint(boolean overrideEndpoint) {
doSetProperty("overrideEndpoint", overrideEndpoint);
return this;
}
/**
* Set the need for overriding the endpoint. This option needs to be
* used in combination with the uriEndpointOverride option.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param overrideEndpoint the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder overrideEndpoint(String overrideEndpoint) {
doSetProperty("overrideEndpoint", overrideEndpoint);
return this;
}
/**
* If we want to use a POJO request as body or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param pojoRequest the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder pojoRequest(boolean pojoRequest) {
doSetProperty("pojoRequest", pojoRequest);
return this;
}
/**
* If we want to use a POJO request as body or not.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param pojoRequest the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder pojoRequest(String pojoRequest) {
doSetProperty("pojoRequest", pojoRequest);
return this;
}
/**
* If using a profile credentials provider, this parameter will set the
* profile name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param profileCredentialsName the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder profileCredentialsName(String profileCredentialsName) {
doSetProperty("profileCredentialsName", profileCredentialsName);
return this;
}
/**
* The region in which the Timestream client needs to work. When using
* this parameter, the configuration will expect the lowercase name of
* the region (for example, ap-east-1) You'll need to use the name
* Region.EU_WEST_1.id().
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param region the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder region(String region) {
doSetProperty("region", region);
return this;
}
/**
* If we want to trust all certificates in case of overriding the
* endpoint.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param trustAllCertificates the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder trustAllCertificates(boolean trustAllCertificates) {
doSetProperty("trustAllCertificates", trustAllCertificates);
return this;
}
/**
* If we want to trust all certificates in case of overriding the
* endpoint.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param trustAllCertificates the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder trustAllCertificates(String trustAllCertificates) {
doSetProperty("trustAllCertificates", trustAllCertificates);
return this;
}
/**
* Set the overriding uri endpoint. This option needs to be used in
* combination with overrideEndpoint option.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param uriEndpointOverride the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder uriEndpointOverride(String uriEndpointOverride) {
doSetProperty("uriEndpointOverride", uriEndpointOverride);
return this;
}
/**
* Set whether the Timestream client should expect to load credentials
* through a default credentials provider or to expect static
* credentials to be passed in.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useDefaultCredentialsProvider the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder useDefaultCredentialsProvider(boolean useDefaultCredentialsProvider) {
doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider);
return this;
}
/**
* Set whether the Timestream client should expect to load credentials
* through a default credentials provider or to expect static
* credentials to be passed in.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useDefaultCredentialsProvider the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder useDefaultCredentialsProvider(String useDefaultCredentialsProvider) {
doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider);
return this;
}
/**
* Set whether the Timestream client should expect to load credentials
* through a profile credentials provider.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useProfileCredentialsProvider the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder useProfileCredentialsProvider(boolean useProfileCredentialsProvider) {
doSetProperty("useProfileCredentialsProvider", useProfileCredentialsProvider);
return this;
}
/**
* Set whether the Timestream client should expect to load credentials
* through a profile credentials provider.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useProfileCredentialsProvider the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder useProfileCredentialsProvider(String useProfileCredentialsProvider) {
doSetProperty("useProfileCredentialsProvider", useProfileCredentialsProvider);
return this;
}
/**
* To define a proxy host when instantiating the Timestream client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyHost the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder proxyHost(String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* To define a proxy port when instantiating the Timestream client.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: proxy
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder proxyPort(Integer proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy port when instantiating the Timestream client.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: proxy
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder proxyPort(String proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy protocol when instantiating the Timestream client.
*
* The option is a: <code>software.amazon.awssdk.core.Protocol</code>
* type.
*
* Default: HTTPS
* Group: proxy
*
* @param proxyProtocol the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder proxyProtocol(software.amazon.awssdk.core.Protocol proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* To define a proxy protocol when instantiating the Timestream client.
*
* The option will be converted to a
* <code>software.amazon.awssdk.core.Protocol</code> type.
*
* Default: HTTPS
* Group: proxy
*
* @param proxyProtocol the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder proxyProtocol(String proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* Amazon AWS Access Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessKey the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder accessKey(String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* Amazon AWS Secret Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param secretKey the value to set
* @return the dsl builder
*/
default Timestream2EndpointBuilder secretKey(String secretKey) {
doSetProperty("secretKey", secretKey);
return this;
}
}
/**
* Advanced builder for endpoint for the AWS Timestream component.
*/
public | Timestream2EndpointBuilder |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/context/WebFilterHandler.java | {
"start": 1429,
"end": 3430
} | class ____ extends ServletComponentHandler {
WebFilterHandler() {
super(WebFilter.class);
}
@Override
public void doHandle(Map<String, @Nullable Object> attributes, AnnotatedBeanDefinition beanDefinition,
BeanDefinitionRegistry registry) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FilterRegistrationBean.class);
builder.addPropertyValue("asyncSupported", attributes.get("asyncSupported"));
builder.addPropertyValue("dispatcherTypes", extractDispatcherTypes(attributes));
builder.addPropertyValue("filter", beanDefinition);
builder.addPropertyValue("initParameters", extractInitParameters(attributes));
String name = determineName(attributes, beanDefinition);
builder.addPropertyValue("name", name);
builder.addPropertyValue("servletNames", attributes.get("servletNames"));
builder.addPropertyValue("urlPatterns", extractUrlPatterns(attributes));
registry.registerBeanDefinition(name, builder.getBeanDefinition());
}
private EnumSet<DispatcherType> extractDispatcherTypes(Map<String, @Nullable Object> attributes) {
DispatcherType[] dispatcherTypes = (DispatcherType[]) attributes.get("dispatcherTypes");
Assert.state(dispatcherTypes != null, "'dispatcherTypes' must not be null");
if (dispatcherTypes.length == 0) {
return EnumSet.noneOf(DispatcherType.class);
}
if (dispatcherTypes.length == 1) {
return EnumSet.of(dispatcherTypes[0]);
}
return EnumSet.of(dispatcherTypes[0], Arrays.copyOfRange(dispatcherTypes, 1, dispatcherTypes.length));
}
private String determineName(Map<String, @Nullable Object> attributes, BeanDefinition beanDefinition) {
String filterName = (String) attributes.get("filterName");
return (StringUtils.hasText(filterName) ? filterName : getBeanClassName(beanDefinition));
}
private String getBeanClassName(BeanDefinition beanDefinition) {
String name = beanDefinition.getBeanClassName();
Assert.state(name != null, "'name' must not be null");
return name;
}
}
| WebFilterHandler |
java | spring-projects__spring-framework | spring-jms/src/main/java/org/springframework/jms/support/converter/JacksonJsonMessageConverter.java | {
"start": 11798,
"end": 18044
} | class ____)
* into the configured type id message property.
* @param object the payload object to set a type id for
* @param message the JMS Message on which to set the type id property
* @throws JMSException if thrown by JMS methods
* @see #getJavaTypeForMessage(Message)
* @see #setTypeIdPropertyName(String)
* @see #setTypeIdMappings(Map)
*/
protected void setTypeIdOnMessage(Object object, Message message) throws JMSException {
if (this.typeIdPropertyName != null) {
String typeId = this.classIdMappings.get(object.getClass());
if (typeId == null) {
typeId = object.getClass().getName();
}
message.setStringProperty(this.typeIdPropertyName, typeId);
}
}
/**
* Convenience method to dispatch to converters for individual message types.
*/
private Object convertToObject(Message message, JavaType targetJavaType) throws JMSException, IOException {
if (message instanceof TextMessage textMessage) {
return convertFromTextMessage(textMessage, targetJavaType);
}
else if (message instanceof BytesMessage bytesMessage) {
return convertFromBytesMessage(bytesMessage, targetJavaType);
}
else {
return convertFromMessage(message, targetJavaType);
}
}
/**
* Convert a TextMessage to a Java Object with the specified type.
* @param message the input message
* @param targetJavaType the target type
* @return the message converted to an object
* @throws JMSException if thrown by JMS
* @throws IOException in case of I/O errors
*/
protected Object convertFromTextMessage(TextMessage message, JavaType targetJavaType)
throws JMSException, IOException {
String body = message.getText();
return this.mapper.readValue(body, targetJavaType);
}
/**
* Convert a BytesMessage to a Java Object with the specified type.
* @param message the input message
* @param targetJavaType the target type
* @return the message converted to an object
* @throws JMSException if thrown by JMS
* @throws IOException in case of I/O errors
*/
protected Object convertFromBytesMessage(BytesMessage message, JavaType targetJavaType)
throws JMSException, IOException {
String encoding = this.encoding;
if (this.encodingPropertyName != null && message.propertyExists(this.encodingPropertyName)) {
encoding = message.getStringProperty(this.encodingPropertyName);
}
byte[] bytes = new byte[(int) message.getBodyLength()];
message.readBytes(bytes);
if (encoding != null) {
try {
String body = new String(bytes, encoding);
return this.mapper.readValue(body, targetJavaType);
}
catch (UnsupportedEncodingException ex) {
throw new MessageConversionException("Cannot convert bytes to String", ex);
}
}
else {
// Jackson internally performs encoding detection, falling back to UTF-8.
return this.mapper.readValue(bytes, targetJavaType);
}
}
/**
* Template method that allows for custom message mapping.
* Invoked when {@link #setTargetType} is not {@link MessageType#TEXT} or
* {@link MessageType#BYTES}.
* <p>The default implementation throws an {@link IllegalArgumentException}.
* @param message the input message
* @param targetJavaType the target type
* @return the message converted to an object
* @throws JMSException if thrown by JMS
* @throws IOException in case of I/O errors
*/
protected Object convertFromMessage(Message message, JavaType targetJavaType)
throws JMSException, IOException {
throw new IllegalArgumentException("Unsupported message type [" + message.getClass() +
"]. MappingJacksonMessageConverter by default only supports TextMessages and BytesMessages.");
}
/**
* Determine a Jackson JavaType for the given JMS Message,
* typically parsing a type id message property.
* <p>The default implementation parses the configured type id property name
* and consults the configured type id mapping. This can be overridden with
* a different strategy, for example, doing some heuristics based on message origin.
* @param message the JMS Message from which to get the type id property
* @throws JMSException if thrown by JMS methods
* @see #setTypeIdOnMessage(Object, Message)
* @see #setTypeIdPropertyName(String)
* @see #setTypeIdMappings(Map)
*/
protected JavaType getJavaTypeForMessage(Message message) throws JMSException {
String typeId = message.getStringProperty(this.typeIdPropertyName);
if (typeId == null) {
throw new MessageConversionException(
"Could not find type id property [" + this.typeIdPropertyName + "] on message [" +
message.getJMSMessageID() + "] from destination [" + message.getJMSDestination() + "]");
}
Class<?> mappedClass = this.idClassMappings.get(typeId);
if (mappedClass != null) {
return this.mapper.constructType(mappedClass);
}
try {
Class<?> typeClass = ClassUtils.forName(typeId, this.beanClassLoader);
return this.mapper.constructType(typeClass);
}
catch (Throwable ex) {
throw new MessageConversionException("Failed to resolve type id [" + typeId + "]", ex);
}
}
/**
* Determine a Jackson serialization view based on the given conversion hint.
* @param conversionHint the conversion hint Object as passed into the
* converter for the current conversion attempt
* @return the serialization view class, or {@code null} if none
*/
protected @Nullable Class<?> getSerializationView(@Nullable Object conversionHint) {
if (conversionHint instanceof MethodParameter methodParam) {
JsonView annotation = methodParam.getParameterAnnotation(JsonView.class);
if (annotation == null) {
annotation = methodParam.getMethodAnnotation(JsonView.class);
if (annotation == null) {
return null;
}
}
return extractViewClass(annotation, conversionHint);
}
else if (conversionHint instanceof JsonView jsonView) {
return extractViewClass(jsonView, conversionHint);
}
else if (conversionHint instanceof Class<?> clazz) {
return clazz;
}
else {
return null;
}
}
private Class<?> extractViewClass(JsonView annotation, Object conversionHint) {
Class<?>[] classes = annotation.value();
if (classes.length != 1) {
throw new IllegalArgumentException(
"@JsonView only supported for handler methods with exactly 1 | name |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/TableCommentTest.java | {
"start": 3453,
"end": 4143
} | class ____ {
@Id
private int id;
}
private String getTableName(SessionFactoryScope factoryScope) {
final SessionFactoryImplementor sessionFactory = factoryScope.getSessionFactory();
final EntityMappingType entityMappingType = sessionFactory
.getRuntimeMetamodels()
.getEntityMappingType( TableWithComment.class );
return ( (AbstractEntityPersister) entityMappingType ).getTableName();
}
private void createSchema(DomainModelScope modelScope, File output) {
new SchemaExport()
.setOutputFile( output.getAbsolutePath() )
.setFormat( false )
.create( EnumSet.of( TargetType.DATABASE, TargetType.SCRIPT ), modelScope.getDomainModel() );
}
}
| TableWithComment |
java | apache__camel | core/camel-util/src/test/java/org/apache/camel/util/StringQuoteHelperTest.java | {
"start": 1295,
"end": 1399
} | class ____", arr[1]);
arr = StringQuoteHelper.splitSafeQuote(" String.class ${body} , String. | Mars |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/executor/loader/CglibProxyTest.java | {
"start": 1457,
"end": 3260
} | class ____ extends SerializableProxyTest {
@BeforeAll
static void createProxyFactory() {
proxyFactory = new CglibProxyFactory();
}
@Test
void shouldCreateAProxyForAPartiallyLoadedBean() throws Exception {
ResultLoaderMap loader = new ResultLoaderMap();
loader.addLoader("id", null, null);
Object proxy = proxyFactory.createProxy(author, loader, new Configuration(), new DefaultObjectFactory(),
new ArrayList<>(), new ArrayList<>());
Author author2 = (Author) deserialize(serialize((Serializable) proxy));
assertTrue(author2 instanceof Factory);
}
@Test
void shouldFailCallingAnUnloadedProperty() {
// yes, it must go in uppercase
HashMap<String, ResultLoaderMap.LoadPair> unloadedProperties = new HashMap<>();
unloadedProperties.put("ID", null);
Author author2 = (Author) ((CglibProxyFactory) proxyFactory).createDeserializationProxy(author, unloadedProperties,
new DefaultObjectFactory(), new ArrayList<>(), new ArrayList<>());
Assertions.assertThrows(ExecutorException.class, author2::getId);
}
@Test
void shouldLetCallALoadedProperty() {
Author author2 = (Author) ((CglibProxyFactory) proxyFactory).createDeserializationProxy(author, new HashMap<>(),
new DefaultObjectFactory(), new ArrayList<>(), new ArrayList<>());
assertEquals(999, author2.getId());
}
@Test
void shouldSerializeADeserializedProxy() throws Exception {
Object proxy = ((CglibProxyFactory) proxyFactory).createDeserializationProxy(author, new HashMap<>(),
new DefaultObjectFactory(), new ArrayList<>(), new ArrayList<>());
Author author2 = (Author) deserialize(serialize((Serializable) proxy));
assertEquals(author, author2);
assertNotEquals(author.getClass(), author2.getClass());
}
}
| CglibProxyTest |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/enrollment/EnrollmentBaseRestHandlerTests.java | {
"start": 909,
"end": 3247
} | class ____ extends ESTestCase {
public void testInEnrollmentMode() {
final Settings settings = Settings.builder().put(XPackSettings.ENROLLMENT_ENABLED.getKey(), true).build();
final EnrollmentBaseRestHandler handler = buildHandler(settings);
assertThat(handler.checkFeatureAvailable(new FakeRestRequest()), Matchers.nullValue());
}
public void testNotInEnrollmentMode() {
final Settings settings = Settings.builder().put(XPackSettings.ENROLLMENT_ENABLED.getKey(), false).build();
final EnrollmentBaseRestHandler handler = buildHandler(settings);
Exception ex = handler.checkFeatureAvailable(new FakeRestRequest());
assertThat(ex, instanceOf(ElasticsearchSecurityException.class));
assertThat(
ex.getMessage(),
Matchers.containsString(
"Enrollment mode is not enabled. Set [xpack.security.enrollment.enabled] " + "to true, in order to use this API."
)
);
assertThat(((ElasticsearchSecurityException) ex).status(), Matchers.equalTo(RestStatus.FORBIDDEN));
}
public void testSecurityExplicitlyDisabled() {
final Settings settings = Settings.builder()
.put(XPackSettings.SECURITY_ENABLED.getKey(), false)
.put(XPackSettings.ENROLLMENT_ENABLED.getKey(), true)
.build();
final EnrollmentBaseRestHandler handler = buildHandler(settings);
Exception ex = handler.checkFeatureAvailable(new FakeRestRequest());
assertThat(ex, instanceOf(IllegalStateException.class));
assertThat(ex.getMessage(), Matchers.containsString("Security is not enabled but a security rest handler is registered"));
}
private EnrollmentBaseRestHandler buildHandler(Settings settings) {
return new EnrollmentBaseRestHandler(settings, new XPackLicenseState(() -> 0)) {
@Override
public String getName() {
return "enrollment_test";
}
@Override
public List<Route> routes() {
return Collections.emptyList();
}
@Override
protected RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) {
return null;
}
};
}
}
| EnrollmentBaseRestHandlerTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchSubselectCollection2Test.java | {
"start": 7667,
"end": 7894
} | class ____ {
@Id
@GeneratedValue
Integer id;
@JoinColumn(name = "ENTITY_D")
@ManyToOne
EntityD entityD;
public Integer getId() {
return id;
}
public EntityD getEntityD() {
return entityD;
}
}
}
| EntityE |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/TimeSeriesRoutingHashFieldMapper.java | {
"start": 1913,
"end": 2430
} | class ____ extends MetadataFieldMapper {
public static final String NAME = "_ts_routing_hash";
public static final TimeSeriesRoutingHashFieldMapper INSTANCE = new TimeSeriesRoutingHashFieldMapper();
public static final TypeParser PARSER = new FixedTypeParser(c -> c.getIndexSettings().getMode().timeSeriesRoutingHashFieldMapper());
public static final DocValueFormat TS_ROUTING_HASH_DOC_VALUE_FORMAT = TimeSeriesRoutingHashFieldType.DOC_VALUE_FORMAT;
static final | TimeSeriesRoutingHashFieldMapper |
java | apache__camel | components/camel-aws/camel-aws2-eventbridge/src/main/java/org/apache/camel/component/aws2/eventbridge/client/EventbridgeClientFactory.java | {
"start": 1429,
"end": 2396
} | class ____ {
private EventbridgeClientFactory() {
}
/**
* Return the correct AWS Eventbridge client (based on remote vs local).
*
* @param configuration configuration
* @return EventBridgeClient
*/
public static EventbridgeInternalClient getEventbridgeClient(EventbridgeConfiguration configuration) {
if (Boolean.TRUE.equals(configuration.isUseDefaultCredentialsProvider())) {
return new EventbridgeClientIAMOptimizedImpl(configuration);
} else if (Boolean.TRUE.equals(configuration.isUseProfileCredentialsProvider())) {
return new EventbridgeClientIAMProfileOptimizedImpl(configuration);
} else if (Boolean.TRUE.equals(configuration.isUseSessionCredentials())) {
return new EventbridgeClientSessionTokenImpl(configuration);
} else {
return new EventbridgeClientStandardImpl(configuration);
}
}
}
| EventbridgeClientFactory |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java | {
"start": 3655,
"end": 3868
} | class ____ {
SuiteLauncherDiscoveryRequestBuilder builder = request();
@Test
void configurationParameter() {
@ConfigurationParameter(key = "com.example", value = "*")
| SuiteLauncherDiscoveryRequestBuilderTests |
java | google__auto | value/src/main/java/com/google/auto/value/processor/BuilderSpec.java | {
"start": 3465,
"end": 4493
} | interface ____ return a representation of it in an {@code
* Optional} if so.
*/
Optional<Builder> getBuilder() {
Optional<TypeElement> builderTypeElement = Optional.empty();
for (TypeElement containedClass : typesIn(autoValueClass.getEnclosedElements())) {
if (hasAnnotationMirror(containedClass, AUTO_VALUE_BUILDER_NAME)) {
findBuilderError(containedClass)
.ifPresent(error -> errorReporter.reportError(containedClass, "%s", error));
if (builderTypeElement.isPresent()) {
errorReporter.reportError(
containedClass,
"[AutoValueTwoBuilders] %s already has a Builder: %s",
autoValueClass,
builderTypeElement.get());
} else {
builderTypeElement = Optional.of(containedClass);
}
}
}
if (builderTypeElement.isPresent()) {
return builderFrom(builderTypeElement.get());
} else {
return Optional.empty();
}
}
/** Finds why this {@code @AutoValue.Builder} | and |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/RoundToInt1Evaluator.java | {
"start": 3959,
"end": 4625
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory field;
private final int p0;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory field, int p0) {
this.source = source;
this.field = field;
this.p0 = p0;
}
@Override
public RoundToInt1Evaluator get(DriverContext context) {
return new RoundToInt1Evaluator(source, field.get(context), p0, context);
}
@Override
public String toString() {
return "RoundToInt1Evaluator[" + "field=" + field + ", p0=" + p0 + "]";
}
}
}
| Factory |
java | resilience4j__resilience4j | resilience4j-bulkhead/src/main/java/io/github/resilience4j/bulkhead/internal/SemaphoreBulkhead.java | {
"start": 1713,
"end": 7437
} | class ____ implements Bulkhead {
private static final String CONFIG_MUST_NOT_BE_NULL = "Config must not be null";
private static final String TAGS_MUST_NOTE_BE_NULL = "Tags must not be null";
private final String name;
private final Semaphore semaphore;
private final BulkheadMetrics metrics;
private final BulkheadEventProcessor eventProcessor;
private final ReentrantLock lock = new ReentrantLock();
private final Map<String, String> tags;
@SuppressWarnings("squid:S3077")
// this object is immutable and we replace ref entirely during config change.
private volatile BulkheadConfig config;
/**
* Creates a bulkhead using a configuration supplied
*
* @param name the name of this bulkhead
* @param bulkheadConfig custom bulkhead configuration
*/
public SemaphoreBulkhead(String name, @Nullable BulkheadConfig bulkheadConfig) {
this(name, bulkheadConfig, emptyMap());
}
/**
* Creates a bulkhead using a configuration supplied
*
* @param name the name of this bulkhead
* @param bulkheadConfig custom bulkhead configuration
* @param tags the tags to add to the Bulkhead
*/
public SemaphoreBulkhead(String name, @Nullable BulkheadConfig bulkheadConfig,
Map<String, String> tags) {
this.name = name;
this.config = requireNonNull(bulkheadConfig, CONFIG_MUST_NOT_BE_NULL);
this.tags = requireNonNull(tags, TAGS_MUST_NOTE_BE_NULL);
// init semaphore
this.semaphore = new Semaphore(config.getMaxConcurrentCalls(), config.isFairCallHandlingEnabled());
this.metrics = new BulkheadMetrics();
this.eventProcessor = new BulkheadEventProcessor();
}
/**
* Creates a bulkhead with a default config.
*
* @param name the name of this bulkhead
*/
public SemaphoreBulkhead(String name) {
this(name, BulkheadConfig.ofDefaults(), emptyMap());
}
/**
* Create a bulkhead using a configuration supplier
*
* @param name the name of this bulkhead
* @param configSupplier BulkheadConfig supplier
*/
public SemaphoreBulkhead(String name, Supplier<BulkheadConfig> configSupplier) {
this(name, configSupplier.get(), emptyMap());
}
/**
* Create a bulkhead using a configuration supplier
*
* @param name the name of this bulkhead
* @param configSupplier BulkheadConfig supplier
* @param tags tags to add to the Bulkhead
*/
public SemaphoreBulkhead(String name, Supplier<BulkheadConfig> configSupplier,
Map<String, String> tags) {
this(name, configSupplier.get(), tags);
}
/**
* {@inheritDoc}
*/
@Override
public void changeConfig(final BulkheadConfig newConfig) {
lock.lock();
try {
int delta = newConfig.getMaxConcurrentCalls() - config.getMaxConcurrentCalls();
if (delta < 0) {
semaphore.acquireUninterruptibly(-delta);
} else if (delta > 0) {
semaphore.release(delta);
}
config = newConfig;
} finally {
lock.unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean tryAcquirePermission() {
boolean callPermitted = tryEnterBulkhead();
publishBulkheadEvent(
() -> callPermitted ? new BulkheadOnCallPermittedEvent(name)
: new BulkheadOnCallRejectedEvent(name)
);
return callPermitted;
}
/**
* {@inheritDoc}
*/
@Override
public void acquirePermission() {
boolean permitted = tryAcquirePermission();
if (permitted) {
return;
}
if (Thread.currentThread().isInterrupted()) {
throw new AcquirePermissionCancelledException();
}
throw BulkheadFullException.createBulkheadFullException(this);
}
/**
* {@inheritDoc}
*/
@Override
public void releasePermission() {
semaphore.release();
}
/**
* {@inheritDoc}
*/
@Override
public void onComplete() {
semaphore.release();
publishBulkheadEvent(() -> new BulkheadOnCallFinishedEvent(name));
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Override
public BulkheadConfig getBulkheadConfig() {
return config;
}
/**
* {@inheritDoc}
*/
@Override
public Metrics getMetrics() {
return metrics;
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, String> getTags() {
return tags;
}
/**
* {@inheritDoc}
*/
@Override
public EventPublisher getEventPublisher() {
return eventProcessor;
}
@Override
public String toString() {
return String.format("Bulkhead '%s'", this.name);
}
/**
* @return true if caller was able to wait for permission without {@link Thread#interrupt}
*/
boolean tryEnterBulkhead() {
long timeout = config.getMaxWaitDuration().toMillis();
try {
return semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return false;
}
}
private void publishBulkheadEvent(Supplier<BulkheadEvent> eventSupplier) {
if (eventProcessor.hasConsumers()) {
eventProcessor.consumeEvent(eventSupplier.get());
}
}
private | SemaphoreBulkhead |
java | spring-projects__spring-boot | module/spring-boot-r2dbc/src/main/java/org/springframework/boot/r2dbc/autoconfigure/ConnectionFactoryBeanCreationFailureAnalyzer.java | {
"start": 1293,
"end": 3621
} | class ____
extends AbstractFailureAnalyzer<ConnectionFactoryBeanCreationException> {
private final Environment environment;
ConnectionFactoryBeanCreationFailureAnalyzer(Environment environment) {
this.environment = environment;
}
@Override
protected FailureAnalysis analyze(Throwable rootFailure, ConnectionFactoryBeanCreationException cause) {
return getFailureAnalysis(cause);
}
private FailureAnalysis getFailureAnalysis(ConnectionFactoryBeanCreationException cause) {
String description = getDescription(cause);
String action = getAction(cause);
return new FailureAnalysis(description, action, cause);
}
private String getDescription(ConnectionFactoryBeanCreationException cause) {
StringBuilder description = new StringBuilder();
description.append("Failed to configure a ConnectionFactory: ");
if (!StringUtils.hasText(cause.getUrl())) {
description.append("'url' attribute is not specified and ");
}
description.append(String.format("no embedded database could be configured.%n"));
description.append(String.format("%nReason: %s%n", cause.getMessage()));
return description.toString();
}
private String getAction(ConnectionFactoryBeanCreationException cause) {
StringBuilder action = new StringBuilder();
action.append(String.format("Consider the following:%n"));
if (EmbeddedDatabaseConnection.NONE == cause.getEmbeddedDatabaseConnection()) {
action.append(String.format("\tIf you want an embedded database (H2), please put it on the classpath.%n"));
}
else {
action.append(String.format("\tReview the configuration of %s%n.", cause.getEmbeddedDatabaseConnection()));
}
action
.append("\tIf you have database settings to be loaded from a particular "
+ "profile you may need to activate it")
.append(getActiveProfiles());
return action.toString();
}
private String getActiveProfiles() {
StringBuilder message = new StringBuilder();
String[] profiles = this.environment.getActiveProfiles();
if (ObjectUtils.isEmpty(profiles)) {
message.append(" (no profiles are currently active).");
}
else {
message.append(" (the profiles ");
message.append(StringUtils.arrayToCommaDelimitedString(profiles));
message.append(" are currently active).");
}
return message.toString();
}
}
| ConnectionFactoryBeanCreationFailureAnalyzer |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/tm/TestInterceptor.java | {
"start": 342,
"end": 1037
} | class ____ implements Interceptor {
private static final Logger LOGGER = Logger.getLogger( TestInterceptor.class );
private static Map<TestInterceptor, Integer> interceptorInvocations = new HashMap<>();
public TestInterceptor() {
interceptorInvocations.put( this, 0 );
}
@Override
public void beforeTransactionCompletion(Transaction tx) {
interceptorInvocations.put( this, interceptorInvocations.get( this ) + 1 );
LOGGER.info( "Interceptor beforeTransactionCompletion invoked" );
}
public static Map<TestInterceptor, Integer> getBeforeCompletionCallbacks() {
return interceptorInvocations;
}
public static void reset() {
interceptorInvocations.clear();
}
}
| TestInterceptor |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestEditLog.java | {
"start": 4820,
"end": 5612
} | class ____ {
static {
GenericTestUtils.setLogLevel(FSEditLog.LOG, Level.TRACE);
}
public static Collection<Object[]> data() {
Collection<Object[]> params = new ArrayList<Object[]>();
params.add(new Object[]{ Boolean.FALSE });
params.add(new Object[]{ Boolean.TRUE });
return params;
}
private static boolean useAsyncEditLog;
public TestEditLog(Boolean async) {
useAsyncEditLog = async;
}
public static Configuration getConf() {
Configuration conf = new HdfsConfiguration();
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_EDITS_ASYNC_LOGGING,
useAsyncEditLog);
return conf;
}
/**
* A garbage mkdir op which is used for testing
* {@link EditLogFileInputStream#scanEditLog(File, long, boolean)}
*/
public static | TestEditLog |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/mllib/JavaIsotonicRegressionExample.java | {
"start": 1327,
"end": 3240
} | class ____ {
public static void main(String[] args) {
SparkConf sparkConf = new SparkConf().setAppName("JavaIsotonicRegressionExample");
JavaSparkContext jsc = new JavaSparkContext(sparkConf);
// $example on$
JavaRDD<LabeledPoint> data = MLUtils.loadLibSVMFile(
jsc.sc(), "data/mllib/sample_isotonic_regression_libsvm_data.txt").toJavaRDD();
// Create label, feature, weight tuples from input data with weight set to default value 1.0.
JavaRDD<Tuple3<Double, Double, Double>> parsedData = data.map(point ->
new Tuple3<>(point.label(), point.features().apply(0), 1.0));
// Split data into training (60%) and test (40%) sets.
JavaRDD<Tuple3<Double, Double, Double>>[] splits =
parsedData.randomSplit(new double[]{0.6, 0.4}, 11L);
JavaRDD<Tuple3<Double, Double, Double>> training = splits[0];
JavaRDD<Tuple3<Double, Double, Double>> test = splits[1];
// Create isotonic regression model from training data.
// Isotonic parameter defaults to true so it is only shown for demonstration
IsotonicRegressionModel model = new IsotonicRegression().setIsotonic(true).run(training);
// Create tuples of predicted and real labels.
JavaPairRDD<Double, Double> predictionAndLabel = test.mapToPair(point ->
new Tuple2<>(model.predict(point._2()), point._1()));
// Calculate mean squared error between predicted and real labels.
double meanSquaredError = predictionAndLabel.mapToDouble(pl -> {
double diff = pl._1() - pl._2();
return diff * diff;
}).mean();
System.out.println("Mean Squared Error = " + meanSquaredError);
// Save and load model
model.save(jsc.sc(), "target/tmp/myIsotonicRegressionModel");
IsotonicRegressionModel sameModel =
IsotonicRegressionModel.load(jsc.sc(), "target/tmp/myIsotonicRegressionModel");
// $example off$
jsc.stop();
}
}
| JavaIsotonicRegressionExample |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TryWithResourcesVariableTest.java | {
"start": 879,
"end": 1203
} | class ____ {
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(TryWithResourcesVariable.class, getClass());
@Test
public void refactoring() {
testHelper
.addInputLines(
"Test.java",
"""
| TryWithResourcesVariableTest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSEditLog.java | {
"start": 63661,
"end": 63783
} | class ____ for " + uriScheme);
}
return clazz;
}
/**
* Construct a custom journal manager.
* The | configured |
java | apache__kafka | connect/transforms/src/test/java/org/apache/kafka/connect/transforms/InsertHeaderTest.java | {
"start": 1369,
"end": 5038
} | class ____ {
private final InsertHeader<SourceRecord> xform = new InsertHeader<>();
private Map<String, ?> config(String header, String valueLiteral) {
Map<String, String> result = new HashMap<>();
result.put(InsertHeader.HEADER_FIELD, header);
result.put(InsertHeader.VALUE_LITERAL_FIELD, valueLiteral);
return result;
}
@Test
public void insertionWithExistingOtherHeader() {
xform.configure(config("inserted", "inserted-value"));
ConnectHeaders headers = new ConnectHeaders();
headers.addString("existing", "existing-value");
Headers expect = headers.duplicate().addString("inserted", "inserted-value");
SourceRecord original = sourceRecord(headers);
SourceRecord xformed = xform.apply(original);
assertNonHeaders(original, xformed);
assertEquals(expect, xformed.headers());
}
@Test
public void insertionWithExistingSameHeader() {
xform.configure(config("existing", "inserted-value"));
ConnectHeaders headers = new ConnectHeaders();
headers.addString("existing", "preexisting-value");
Headers expect = headers.duplicate().addString("existing", "inserted-value");
SourceRecord original = sourceRecord(headers);
SourceRecord xformed = xform.apply(original);
assertNonHeaders(original, xformed);
assertEquals(expect, xformed.headers());
}
@Test
public void insertionWithByteHeader() {
xform.configure(config("inserted", "1"));
ConnectHeaders headers = new ConnectHeaders();
headers.addString("existing", "existing-value");
Headers expect = headers.duplicate().addByte("inserted", (byte) 1);
SourceRecord original = sourceRecord(headers);
SourceRecord xformed = xform.apply(original);
assertNonHeaders(original, xformed);
assertEquals(expect, xformed.headers());
}
@Test
public void configRejectsNullHeaderKey() {
assertThrows(ConfigException.class, () -> xform.configure(config(null, "1")));
}
@Test
public void configRejectsNullHeaderValue() {
assertThrows(ConfigException.class, () -> xform.configure(config("inserted", null)));
}
private void assertNonHeaders(SourceRecord original, SourceRecord xformed) {
assertEquals(original.sourcePartition(), xformed.sourcePartition());
assertEquals(original.sourceOffset(), xformed.sourceOffset());
assertEquals(original.topic(), xformed.topic());
assertEquals(original.kafkaPartition(), xformed.kafkaPartition());
assertEquals(original.keySchema(), xformed.keySchema());
assertEquals(original.key(), xformed.key());
assertEquals(original.valueSchema(), xformed.valueSchema());
assertEquals(original.value(), xformed.value());
assertEquals(original.timestamp(), xformed.timestamp());
}
private SourceRecord sourceRecord(ConnectHeaders headers) {
Map<String, ?> sourcePartition = Map.of("foo", "bar");
Map<String, ?> sourceOffset = Map.of("baz", "quxx");
String topic = "topic";
Integer partition = 0;
Schema keySchema = null;
Object key = "key";
Schema valueSchema = null;
Object value = "value";
Long timestamp = 0L;
return new SourceRecord(sourcePartition, sourceOffset, topic, partition,
keySchema, key, valueSchema, value, timestamp, headers);
}
@Test
public void testInsertHeaderVersionRetrievedFromAppInfoParser() {
assertEquals(AppInfoParser.getVersion(), xform.version());
}
}
| InsertHeaderTest |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/illegal/TypeVariableInitializerInjectionPointTest.java | {
"start": 1159,
"end": 1239
} | class ____<T> {
@Inject
void setIt(T it) {
}
}
}
| Head |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/MultipartUtils.java | {
"start": 7218,
"end": 8823
} | class ____
implements RemoteIterator<MultipartUpload> {
/**
* Iterator for issuing new upload list requests from
* where the previous one ended.
*/
private ListingIterator lister;
/** Current listing: the last upload listing we fetched. */
private ListMultipartUploadsResponse listing;
/** Iterator over the current listing. */
private ListIterator<MultipartUpload> batchIterator;
/**
* Construct an iterator to list uploads under a path.
* @param storeContext store context
* @param s3 s3 client
* @param maxKeys max # of keys to list per batch
* @param prefix prefix
* @throws IOException listing failure.
*/
@Retries.RetryTranslated
public UploadIterator(
final StoreContext storeContext,
S3Client s3,
int maxKeys,
@Nullable String prefix)
throws IOException {
lister = new ListingIterator(storeContext, s3, prefix,
maxKeys);
requestNextBatch();
}
@Override
public boolean hasNext() throws IOException {
return (batchIterator.hasNext() || requestNextBatch());
}
@Override
public MultipartUpload next() throws IOException {
if (!hasNext()) {
throw new NoSuchElementException();
}
return batchIterator.next();
}
private boolean requestNextBatch() throws IOException {
if (lister.hasNext()) {
listing = lister.next();
batchIterator = listing.uploads().listIterator();
return batchIterator.hasNext();
}
return false;
}
}
}
| UploadIterator |
java | lettuce-io__lettuce-core | src/test/java/io/redis/examples/async/SetExample.java | {
"start": 467,
"end": 10798
} | class ____ {
@Test
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisAsyncCommands<String, String> asyncCommands = connection.async();
// REMOVE_START
CompletableFuture<Long> delResult = asyncCommands
.del("bikes:racing:france", "bikes:racing:usa", "bikes:racing:italy").toCompletableFuture();
// REMOVE_END
// STEP_START sadd
CompletableFuture<Void> sAdd = asyncCommands.sadd("bikes:racing:france", "bike:1").thenCompose(res1 -> {
System.out.println(res1); // >>> 1
// REMOVE_START
assertThat(res1).isEqualTo(1);
// REMOVE_END
return asyncCommands.sadd("bikes:racing:france", "bike:1");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> 0
// REMOVE_START
assertThat(res2).isEqualTo(0);
// REMOVE_END
return asyncCommands.sadd("bikes:racing:france", "bike:2", "bike:3");
}).thenCompose(res3 -> {
System.out.println(res3); // >>> 2
// REMOVE_START
assertThat(res3).isEqualTo(2);
// REMOVE_END
return asyncCommands.sadd("bikes:racing:usa", "bike:1", "bike:4");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isEqualTo(2);
return res;
})
// REMOVE_END
.thenAccept(System.out::println)
// >>> 2
.toCompletableFuture();
// STEP_END
// STEP_START sismember
CompletableFuture<Void> sIsMember = sAdd.thenCompose(r -> {
return asyncCommands.sismember("bikes:racing:usa", "bike:1");
}).thenCompose(res4 -> {
System.out.println(res4); // >>> true
// REMOVE_START
assertThat(res4).isTrue();
// REMOVE_END
return asyncCommands.sismember("bikes:racing:usa", "bike:2");
})
// REMOVE_START
.thenApply(r -> {
assertThat(r).isFalse();
return r;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> false
.toCompletableFuture();
// STEP_END
// STEP_START sinter
CompletableFuture<Void> sInter = sIsMember.thenCompose(r -> {
return asyncCommands.sinter("bikes:racing:france", "bikes:racing:usa");
})
// REMOVE_START
.thenApply(r -> {
assertThat(r.toString()).isEqualTo("[bike:1]");
return r;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> ["bike:1"]
.toCompletableFuture();
// STEP_END
// STEP_START scard
CompletableFuture<Void> sCard = sInter.thenCompose(r -> {
return asyncCommands.scard("bikes:racing:france");
})
// REMOVE_START
.thenApply(r -> {
assertThat(r).isEqualTo(3);
return r;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> 3
.toCompletableFuture();
// STEP_END
// STEP_START sadd_smembers
CompletableFuture<Void> sAddSMembers = sCard.thenCompose(r -> {
return asyncCommands.del("bikes:racing:france");
}).thenCompose(r -> {
return asyncCommands.sadd("bikes:racing:france", "bike:1", "bike:2", "bike:3");
}).thenCompose(res5 -> {
System.out.println(res5); // >>> 3
return asyncCommands.smembers("bikes:racing:france");
})
// REMOVE_START
.thenApply((Set<String> r) -> {
assertThat(r.stream().sorted().collect(toList()).toString()).isEqualTo("[bike:1, bike:2, bike:3]");
return r;
})
// REMOVE_END
.thenAccept(System.out::println)
// >>> [bike:1, bike:2, bike:3]
.toCompletableFuture();
// STEP_END
// STEP_START smismember
CompletableFuture<Void> sMIsMember = sAddSMembers.thenCompose(r -> {
return asyncCommands.sismember("bikes:racing:france", "bike:1");
}).thenCompose(res6 -> {
System.out.println(res6); // >>> True
// REMOVE_START
assertThat(res6).isTrue();
// REMOVE_END
return asyncCommands.smismember("bikes:racing:france", "bike:2", "bike:3", "bike:4");
})
// REMOVE_START
.thenApply(r -> {
assertThat(r).containsSequence(true, true, false);
return r;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> [true, true, false]
.toCompletableFuture();
// STEP_END
// STEP_START sdiff
CompletableFuture<Void> sDiff = sMIsMember.thenCompose(r -> {
return asyncCommands.sadd("bikes:racing:france", "bike:1", "bike:2", "bike:3");
}).thenCompose(r -> {
return asyncCommands.sadd("bikes:racing:usa", "bike:1", "bike:4");
}).thenCompose(r -> {
return asyncCommands.sdiff("bikes:racing:france", "bikes:racing:usa");
})
// REMOVE_START
.thenApply(r -> {
assertThat(r.stream().sorted().collect(toList()).toString()).isEqualTo("[bike:2, bike:3]");
return r;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> [bike:2, bike:3]
.toCompletableFuture();
// STEP_END
// STEP_START multisets
CompletableFuture<Void> multisets = sDiff.thenCompose(r -> {
return asyncCommands.sadd("bikes:racing:france", "bike:1", "bike:2", "bike:3");
}).thenCompose(r -> {
return asyncCommands.sadd("bikes:racing:usa", "bike:1", "bike:4");
}).thenCompose(r -> {
return asyncCommands.sadd("bikes:racing:italy", "bike:1", "bike:2", "bike:3", "bike:4");
}).thenCompose(r -> {
return asyncCommands.sinter("bikes:racing:france", "bikes:racing:usa", "bikes:racing:italy");
}).thenCompose(res7 -> {
System.out.println(res7); // >>> [bike:1]
// REMOVE_START
assertThat(res7.toString()).isEqualTo("[bike:1]");
// REMOVE_END
return asyncCommands.sunion("bikes:racing:france", "bikes:racing:usa", "bikes:racing:italy");
}).thenCompose(res8 -> {
System.out.println(res8);
// >>> [bike:1, bike:2, bike:3, bike:4]
// REMOVE_START
assertThat(res8.stream().sorted().collect(toList()).toString()).isEqualTo("[bike:1, bike:2, bike:3, bike:4]");
// REMOVE_END
return asyncCommands.sdiff("bikes:racing:france", "bikes:racing:usa", "bikes:racing:italy");
}).thenCompose(res9 -> {
System.out.println(res9); // >>> []
// REMOVE_START
assertThat(res9.toString()).isEqualTo("[]");
// REMOVE_END
return asyncCommands.sdiff("bikes:racing:usa", "bikes:racing:france");
}).thenCompose(res10 -> {
System.out.println(res10); // >>> [bike:4]
// REMOVE_START
assertThat(res10.toString()).isEqualTo("[bike:4]");
// REMOVE_END
return asyncCommands.sdiff("bikes:racing:france", "bikes:racing:usa");
})
// REMOVE_START
.thenApply(r -> {
assertThat(r.stream().sorted().collect(toList()).toString()).isEqualTo("[bike:2, bike:3]");
return r;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> [bike:2, bike:3]
.toCompletableFuture();
// STEP_END
// STEP_START srem
CompletableFuture<Void> sRem = multisets.thenCompose(r -> {
return asyncCommands.sadd("bikes:racing:france", "bike:1", "bike:2", "bike:3", "bike:4", "bike:5");
}).thenCompose(r -> {
return asyncCommands.srem("bikes:racing:france", "bike:1");
}).thenCompose(res11 -> {
System.out.println(res11); // >>> 1
// REMOVE_START
assertThat(res11).isEqualTo(1);
// REMOVE_END
return asyncCommands.spop("bikes:racing:france");
}).thenCompose(res12 -> {
System.out.println(res12); // >>> bike:3 (for example)
return asyncCommands.smembers("bikes:racing:france");
}).thenCompose(res13 -> {
System.out.println(res13); // >>> [bike:2, bike:4, bike:5]
return asyncCommands.srandmember("bikes:racing:france");
}).thenAccept(System.out::println) // >>> bike:4
.toCompletableFuture();
// STEP_END
CompletableFuture.allOf(
// REMOVE_START
delResult,
// REMOVE_END,
sRem).join();
} finally {
redisClient.shutdown();
}
}
}
| SetExample |
java | alibaba__fastjson | src/test/java/com/alibaba/fastjson/deserializer/issue3804/TestIssue3804.java | {
"start": 127,
"end": 610
} | class ____ {
@Test
public void testIssue3804() {
//String textResponse="{\"error\":false,\"code\":0}";
String textResponse="{\"error\":false,\"code";
JSONValidator validator = JSONValidator.from(textResponse);
if (validator.validate() && validator.getType() == JSONValidator.Type.Object) {
System.out.println("Yes, it is Object");
} else {
System.out.println("No, it is not Object");
}
}
}
| TestIssue3804 |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/postgresql/pl/PGGetDiagnosticsStatementTest.java | {
"start": 250,
"end": 925
} | class ____ extends PGTest {
public void test_0() throws Exception {
String sql = "DO $$\n" +
"BEGIN\n" +
" GET DIAGNOSTICS n = ROW_COUNT;\n" +
"END $$;";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.POSTGRESQL);
assertEquals(1, statementList.size());
String output = SQLUtils.toSQLString(statementList, JdbcConstants.POSTGRESQL);
assertEquals("DO $$\n" +
"BEGIN\n" +
"\tGET DIAGNOSTICS n = ROW_COUNT;\n" +
"END;\n" +
"$$;",
output);
}
}
| PGGetDiagnosticsStatementTest |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/junit/jupiter/CustomSoftAssertions.java | {
"start": 828,
"end": 1162
} | class ____ extends AbstractSoftAssertions {
public IntegerAssert expectThat(int value) {
return proxy(IntegerAssert.class, Integer.class, value);
}
@SuppressWarnings("unchecked")
public <T> ListAssert<T> expectThat(List<? extends T> actual) {
return proxy(ListAssert.class, List.class, actual);
}
}
| CustomSoftAssertions |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/math/AtanTests.java | {
"start": 807,
"end": 1583
} | class ____ extends AbstractScalarFunctionTestCase {
public AtanTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) {
this.testCase = testCaseSupplier.get();
}
@ParametersFactory
public static Iterable<Object[]> parameters() {
List<TestCaseSupplier> suppliers = TestCaseSupplier.forUnaryCastingToDouble(
"AtanEvaluator",
"val",
Math::atan,
Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY,
List.of()
);
return parameterSuppliersFromTypedDataWithDefaultChecks(true, suppliers);
}
@Override
protected Expression build(Source source, List<Expression> args) {
return new Atan(source, args.get(0));
}
}
| AtanTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/conditional/basic/ConditionalMethodForCollectionMapper.java | {
"start": 1258,
"end": 1498
} | class ____ {
private List<BookDto> books;
public List<BookDto> getBooks() {
return books;
}
public void setBooks(List<BookDto> books) {
this.books = books;
}
}
| AuthorDto |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/files/StaticFileWithoutResourcesTest.java | {
"start": 361,
"end": 1047
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource(new File("src/test/resources/lorem.txt"), "META-INF/resources/lorem.txt")
.addAsResource(new File("src/test/resources/index.html"), "META-INF/resources/index.html"));
@Test
public void test() {
RestAssured.get("/").then()
.statusCode(200)
.body(containsString("<h1>Hello</h1>"));
RestAssured.get("/lorem.txt").then()
.statusCode(200)
.body(containsString("Lorem"));
}
}
| StaticFileWithoutResourcesTest |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/dynamic/parameter/Parameters.java | {
"start": 307,
"end": 2549
} | class ____<P extends Parameter> implements Iterable<P> {
private final List<P> parameters;
private final List<P> bindableParameters;
/**
* Create new {@link Parameters} given a {@link Method}.
*
* @param method must not be {@code null}.
*/
public Parameters(Method method) {
LettuceAssert.notNull(method, "Method must not be null");
this.parameters = new ArrayList<>(method.getParameterCount());
for (int i = 0; i < method.getParameterCount(); i++) {
P parameter = createParameter(method, i);
parameters.add(parameter);
}
this.bindableParameters = createBindableParameters();
}
/**
* Create a new {@link Parameters} for given a {@link Method} at {@code parameterIndex}.
*
* @param method must not be {@code null}.
* @param parameterIndex the parameter index.
* @return the {@link Parameter}.
*/
protected abstract P createParameter(Method method, int parameterIndex);
/**
* Returns {@link Parameter} instances with effectively all special parameters removed.
*
* @return
*/
private List<P> createBindableParameters() {
List<P> bindables = new ArrayList<>(parameters.size());
for (P parameter : parameters) {
if (parameter.isBindable()) {
bindables.add(parameter);
}
}
return bindables;
}
/**
* @return
*/
public List<P> getParameters() {
return parameters;
}
/**
* Get the bindable parameter according it's logical position in the command. Declarative position may differ because of
* special parameters interleaved.
*
* @param index
* @return the {@link Parameter}.
*/
public Parameter getBindableParameter(int index) {
return getBindableParameters().get(index);
}
/**
* Returns {@link Parameter} instances with effectively all special parameters removed.
*
* @return
*/
public List<P> getBindableParameters() {
return bindableParameters;
}
@Override
public Iterator<P> iterator() {
return getBindableParameters().iterator();
}
}
| Parameters |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/restriction/WorkflowServiceTests.java | {
"start": 2624,
"end": 3174
} | class ____ extends BaseRestHandler {
private final String name;
public TestBaseRestHandler(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public List<Route> routes() {
return List.of();
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
return channel -> {};
}
}
}
| TestBaseRestHandler |
java | apache__rocketmq | proxy/src/test/java/org/apache/rocketmq/proxy/service/mqclient/MQClientAPIExtTest.java | {
"start": 4659,
"end": 17748
} | class ____ {
private static final String BROKER_ADDR = "127.0.0.1:10911";
private static final String BROKER_NAME = "brokerName";
private static final long TIMEOUT = 3000;
private static final String CONSUMER_GROUP = "group";
private static final String TOPIC = "topic";
@Spy
private final MQClientAPIExt mqClientAPI = new MQClientAPIExt(new ClientConfig(), new NettyClientConfig(), new DoNothingClientRemotingProcessor(null), null);
@Mock
private RemotingClient remotingClient;
@Before
public void init() throws Exception {
Field field = MQClientAPIImpl.class.getDeclaredField("remotingClient");
field.setAccessible(true);
field.set(mqClientAPI, remotingClient);
}
@Test
public void testSendHeartbeatAsync() throws Exception {
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
future.complete(RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, ""));
doReturn(future).when(remotingClient).invoke(anyString(), any(RemotingCommand.class), anyLong());
assertNotNull(mqClientAPI.sendHeartbeatAsync(BROKER_ADDR, new HeartbeatData(), TIMEOUT).get());
}
@Test
public void testSendMessageAsync() throws Exception {
AtomicReference<String> msgIdRef = new AtomicReference<>();
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
SendMessageResponseHeader sendMessageResponseHeader = (SendMessageResponseHeader) response.readCustomHeader();
sendMessageResponseHeader.setMsgId(msgIdRef.get());
sendMessageResponseHeader.setQueueId(0);
sendMessageResponseHeader.setQueueOffset(1L);
response.setCode(ResponseCode.SUCCESS);
response.makeCustomHeaderToNet();
future.complete(response);
doReturn(future).when(remotingClient).invoke(anyString(), any(RemotingCommand.class), anyLong());
MessageExt messageExt = createMessage();
msgIdRef.set(MessageClientIDSetter.getUniqID(messageExt));
SendResult sendResult = mqClientAPI.sendMessageAsync(BROKER_ADDR, BROKER_NAME, messageExt, new SendMessageRequestHeader(), TIMEOUT)
.get();
assertNotNull(sendResult);
assertEquals(msgIdRef.get(), sendResult.getMsgId());
assertEquals(SendStatus.SEND_OK, sendResult.getSendStatus());
}
@Test
public void testSendMessageListAsync() throws Exception {
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
RemotingCommand response = RemotingCommand.createResponseCommand(SendMessageResponseHeader.class);
SendMessageResponseHeader sendMessageResponseHeader = (SendMessageResponseHeader) response.readCustomHeader();
sendMessageResponseHeader.setMsgId("");
sendMessageResponseHeader.setQueueId(0);
sendMessageResponseHeader.setQueueOffset(1L);
response.setCode(ResponseCode.SUCCESS);
response.makeCustomHeaderToNet();
future.complete(response);
doReturn(future).when(remotingClient).invoke(anyString(), any(RemotingCommand.class), anyLong());
List<MessageExt> messageExtList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
MessageExt messageExt = createMessage();
sb.append(sb.length() == 0 ? "" : ",").append(MessageClientIDSetter.getUniqID(messageExt));
messageExtList.add(messageExt);
}
SendResult sendResult = mqClientAPI.sendMessageAsync(BROKER_ADDR, BROKER_NAME, messageExtList, new SendMessageRequestHeader(), TIMEOUT)
.get();
assertNotNull(sendResult);
assertEquals(sb.toString(), sendResult.getMsgId());
assertEquals(SendStatus.SEND_OK, sendResult.getSendStatus());
}
@Test
public void testSendMessageBackAsync() throws Exception {
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
future.complete(RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, ""));
doReturn(future).when(remotingClient).invoke(anyString(), any(RemotingCommand.class), anyLong());
RemotingCommand remotingCommand = mqClientAPI.sendMessageBackAsync(BROKER_ADDR, new ConsumerSendMsgBackRequestHeader(), TIMEOUT)
.get();
assertNotNull(remotingCommand);
assertEquals(ResponseCode.SUCCESS, remotingCommand.getCode());
}
@Test
public void testPopMessageAsync() throws Exception {
PopResult popResult = new PopResult(PopStatus.POLLING_NOT_FOUND, null);
doAnswer((Answer<Void>) mock -> {
PopCallback popCallback = mock.getArgument(4);
popCallback.onSuccess(popResult);
return null;
}).when(mqClientAPI).popMessageAsync(anyString(), anyString(), any(), anyLong(), any());
assertSame(popResult, mqClientAPI.popMessageAsync(BROKER_ADDR, BROKER_NAME, new PopMessageRequestHeader(), TIMEOUT).get());
}
@Test
public void testAckMessageAsync() throws Exception {
AckResult ackResult = new AckResult();
doAnswer((Answer<Void>) mock -> {
AckCallback ackCallback = mock.getArgument(2);
ackCallback.onSuccess(ackResult);
return null;
}).when(mqClientAPI).ackMessageAsync(anyString(), anyLong(), any(AckCallback.class), any());
assertSame(ackResult, mqClientAPI.ackMessageAsync(BROKER_ADDR, new AckMessageRequestHeader(), TIMEOUT).get());
}
@Test
public void testBatchAckMessageAsync() throws Exception {
AckResult ackResult = new AckResult();
doAnswer((Answer<Void>) mock -> {
AckCallback ackCallback = mock.getArgument(2);
ackCallback.onSuccess(ackResult);
return null;
}).when(mqClientAPI).batchAckMessageAsync(anyString(), anyLong(), any(AckCallback.class), any());
assertSame(ackResult, mqClientAPI.batchAckMessageAsync(BROKER_ADDR, TOPIC, CONSUMER_GROUP, new ArrayList<>(), TIMEOUT).get());
}
@Test
public void testChangeInvisibleTimeAsync() throws Exception {
AckResult ackResult = new AckResult();
doAnswer((Answer<Void>) mock -> {
AckCallback ackCallback = mock.getArgument(4);
ackCallback.onSuccess(ackResult);
return null;
}).when(mqClientAPI).changeInvisibleTimeAsync(anyString(), anyString(), any(), anyLong(), any(AckCallback.class));
assertSame(ackResult, mqClientAPI.changeInvisibleTimeAsync(BROKER_ADDR, BROKER_NAME, new ChangeInvisibleTimeRequestHeader(), TIMEOUT).get());
}
@Test
public void testPullMessageAsync() throws Exception {
MessageExt msg1 = createMessage();
byte[] msg1Byte = MessageDecoder.encode(msg1, false);
MessageExt msg2 = createMessage();
byte[] msg2Byte = MessageDecoder.encode(msg2, false);
ByteBuffer byteBuffer = ByteBuffer.allocate(msg1Byte.length + msg2Byte.length);
byteBuffer.put(msg1Byte);
byteBuffer.put(msg2Byte);
PullResultExt pullResultExt = new PullResultExt(PullStatus.FOUND, 0, 0, 1, null, 0,
byteBuffer.array());
doAnswer((Answer<Void>) mock -> {
PullCallback pullCallback = mock.getArgument(4);
pullCallback.onSuccess(pullResultExt);
return null;
}).when(mqClientAPI).pullMessage(anyString(), any(), anyLong(), any(CommunicationMode.class), any(PullCallback.class));
PullResult pullResult = mqClientAPI.pullMessageAsync(BROKER_ADDR, new PullMessageRequestHeader(), TIMEOUT).get();
assertNotNull(pullResult);
assertEquals(2, pullResult.getMsgFoundList().size());
Set<String> msgIdSet = pullResult.getMsgFoundList().stream().map(MessageClientIDSetter::getUniqID).collect(Collectors.toSet());
assertTrue(msgIdSet.contains(MessageClientIDSetter.getUniqID(msg1)));
assertTrue(msgIdSet.contains(MessageClientIDSetter.getUniqID(msg2)));
}
@Test
public void testGetConsumerListByGroupAsync() throws Exception {
List<String> clientIds = Lists.newArrayList("clientIds");
doAnswer((Answer<Void>) mock -> {
InvokeCallback invokeCallback = mock.getArgument(3);
ResponseFuture responseFuture = new ResponseFuture(null, 0, 3000, invokeCallback, null);
RemotingCommand response = RemotingCommand.createResponseCommand(GetConsumerListByGroupResponseHeader.class);
response.setCode(ResponseCode.SUCCESS);
response.makeCustomHeaderToNet();
GetConsumerListByGroupResponseBody body = new GetConsumerListByGroupResponseBody();
body.setConsumerIdList(clientIds);
response.setBody(body.encode());
responseFuture.putResponse(response);
invokeCallback.operationSucceed(responseFuture.getResponseCommand());
return null;
}).when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any());
List<String> res = mqClientAPI.getConsumerListByGroupAsync(BROKER_ADDR, new GetConsumerListByGroupRequestHeader(), TIMEOUT).get();
assertEquals(clientIds, res);
}
@Test
public void testGetEmptyConsumerListByGroupAsync() throws Exception {
doAnswer((Answer<Void>) mock -> {
InvokeCallback invokeCallback = mock.getArgument(3);
ResponseFuture responseFuture = new ResponseFuture(null, 0, 3000, invokeCallback, null);
RemotingCommand response = RemotingCommand.createResponseCommand(GetConsumerListByGroupRequestHeader.class);
response.setCode(ResponseCode.SYSTEM_ERROR);
response.makeCustomHeaderToNet();
responseFuture.putResponse(response);
invokeCallback.operationSucceed(responseFuture.getResponseCommand());
return null;
}).when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any());
List<String> res = mqClientAPI.getConsumerListByGroupAsync(BROKER_ADDR, new GetConsumerListByGroupRequestHeader(), TIMEOUT).get();
assertTrue(res.isEmpty());
}
@Test
public void testGetMaxOffsetAsync() throws Exception {
long offset = ThreadLocalRandom.current().nextLong();
doAnswer((Answer<Void>) mock -> {
InvokeCallback invokeCallback = mock.getArgument(3);
ResponseFuture responseFuture = new ResponseFuture(null, 0, 3000, invokeCallback, null);
RemotingCommand response = RemotingCommand.createResponseCommand(GetMaxOffsetResponseHeader.class);
GetMaxOffsetResponseHeader responseHeader = (GetMaxOffsetResponseHeader) response.readCustomHeader();
responseHeader.setOffset(offset);
response.setCode(ResponseCode.SUCCESS);
response.makeCustomHeaderToNet();
responseFuture.putResponse(response);
invokeCallback.operationSucceed(responseFuture.getResponseCommand());
return null;
}).when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any());
GetMaxOffsetRequestHeader requestHeader = new GetMaxOffsetRequestHeader();
requestHeader.setTopic(TOPIC);
requestHeader.setQueueId(0);
assertEquals(offset, mqClientAPI.getMaxOffset(BROKER_ADDR, requestHeader, TIMEOUT).get().longValue());
}
@Test
public void testSearchOffsetAsync() throws Exception {
long offset = ThreadLocalRandom.current().nextLong();
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
RemotingCommand response = RemotingCommand.createResponseCommand(SearchOffsetResponseHeader.class);
SearchOffsetResponseHeader responseHeader = (SearchOffsetResponseHeader) response.readCustomHeader();
responseHeader.setOffset(offset);
response.setCode(ResponseCode.SUCCESS);
response.makeCustomHeaderToNet();
future.complete(response);
doReturn(future).when(remotingClient).invoke(anyString(), any(RemotingCommand.class), anyLong());
SearchOffsetRequestHeader requestHeader = new SearchOffsetRequestHeader();
requestHeader.setTopic(TOPIC);
requestHeader.setQueueId(0);
requestHeader.setTimestamp(System.currentTimeMillis());
assertEquals(offset, mqClientAPI.searchOffset(BROKER_ADDR, requestHeader, TIMEOUT).get().longValue());
}
protected MessageExt createMessage() {
MessageExt messageExt = new MessageExt();
messageExt.setTopic("topic");
messageExt.setBornHost(NetworkUtil.string2SocketAddress("127.0.0.2:8888"));
messageExt.setStoreHost(NetworkUtil.string2SocketAddress("127.0.0.1:10911"));
messageExt.setBody(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
MessageClientIDSetter.setUniqID(messageExt);
return messageExt;
}
}
| MQClientAPIExtTest |
java | elastic__elasticsearch | x-pack/plugin/mapper-constant-keyword/src/main/java/org/elasticsearch/xpack/constantkeyword/ConstantKeywordMapperPlugin.java | {
"start": 602,
"end": 862
} | class ____ extends Plugin implements MapperPlugin {
@Override
public Map<String, Mapper.TypeParser> getMappers() {
return singletonMap(ConstantKeywordFieldMapper.CONTENT_TYPE, ConstantKeywordFieldMapper.PARSER);
}
}
| ConstantKeywordMapperPlugin |
java | elastic__elasticsearch | test/external-modules/delayed-aggs/src/internalClusterTest/java/org/elasticsearch/search/aggregations/DelayedShardAggregationIT.java | {
"start": 1274,
"end": 2608
} | class ____ extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Arrays.asList(DelayedShardAggregationPlugin.class);
}
public void testSimple() throws Exception {
assertAcked(client().admin().indices().prepareCreate("index"));
float expectedMax = Float.MIN_VALUE;
List<IndexRequestBuilder> reqs = new ArrayList<>();
for (int i = 0; i < 5; i++) {
float rand = randomFloat();
expectedMax = Math.max(rand, expectedMax);
reqs.add(client().prepareIndex("index").setSource("number", rand));
}
indexRandom(true, reqs);
SearchResponse response = client().prepareSearch("index")
.addAggregation(
new DelayedShardAggregationBuilder("delay", TimeValue.timeValueMillis(10)).subAggregation(
new MaxAggregationBuilder("max").field("number")
)
)
.get();
Aggregations aggs = response.getAggregations();
assertThat(aggs.get("delay"), instanceOf(InternalFilter.class));
InternalFilter filter = aggs.get("delay");
InternalMax max = filter.getAggregations().get("max");
assertThat((float) max.getValue(), equalTo(expectedMax));
}
}
| DelayedShardAggregationIT |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/IRDecorations.java | {
"start": 13083,
"end": 13228
} | interface ____ extends IRCondition {
}
/** describes the type of value stored in an assignment operation */
public static | IRCCaptureBox |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/util/DefaultShutdownCallbackRegistry.java | {
"start": 3665,
"end": 7287
} | class ____ implements Cancellable {
private Runnable callback;
private Collection<Reference<Cancellable>> registered;
RegisteredCancellable(final Runnable callback, final Collection<Reference<Cancellable>> registered) {
this.callback = callback;
this.registered = registered;
}
@Override
public void cancel() {
callback = null;
final Collection<Reference<Cancellable>> references = registered;
if (references != null) {
registered = null;
references.removeIf(ref -> {
final Cancellable value = ref.get();
return value == null || value == RegisteredCancellable.this;
});
}
}
@Override
public void run() {
final Runnable runnableHook = callback;
if (runnableHook != null) {
runnableHook.run();
callback = null;
}
}
@Override
public String toString() {
return String.valueOf(callback);
}
}
@Override
public Cancellable addShutdownCallback(final Runnable callback) {
if (isStarted()) {
final Cancellable receipt = new RegisteredCancellable(callback, hooks);
hooks.add(new SoftReference<>(receipt));
return receipt;
}
throw new IllegalStateException("Cannot add new shutdown hook as this is not started. Current state: "
+ state.get().name());
}
@Override
public void initialize() {}
/**
* Registers the shutdown thread only if this is initialized.
*/
@Override
public void start() {
if (state.compareAndSet(State.INITIALIZED, State.STARTING)) {
try {
addShutdownHook(threadFactory.newThread(this));
state.set(State.STARTED);
} catch (final IllegalStateException ex) {
state.set(State.STOPPED);
throw ex;
} catch (final Exception e) {
LOGGER.catching(e);
state.set(State.STOPPED);
}
}
}
private void addShutdownHook(final Thread thread) {
shutdownHookRef = new WeakReference<>(thread);
Runtime.getRuntime().addShutdownHook(thread);
}
@Override
public void stop() {
stop(AbstractLifeCycle.DEFAULT_STOP_TIMEOUT, AbstractLifeCycle.DEFAULT_STOP_TIMEUNIT);
}
/**
* Cancels the shutdown thread only if this is started.
*/
@Override
public boolean stop(final long timeout, final TimeUnit timeUnit) {
if (state.compareAndSet(State.STARTED, State.STOPPING)) {
try {
removeShutdownHook();
} finally {
state.set(State.STOPPED);
}
}
return true;
}
private void removeShutdownHook() {
final Thread shutdownThread = shutdownHookRef.get();
if (shutdownThread != null) {
Runtime.getRuntime().removeShutdownHook(shutdownThread);
shutdownHookRef.enqueue();
}
}
@Override
public State getState() {
return state.get();
}
/**
* Indicates if this can accept shutdown hooks.
*
* @return true if this can accept shutdown hooks
*/
@Override
public boolean isStarted() {
return state.get() == State.STARTED;
}
@Override
public boolean isStopped() {
return state.get() == State.STOPPED;
}
}
| RegisteredCancellable |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/form/ClientFormParamFromPropertyTest.java | {
"start": 2424,
"end": 2760
} | class ____ {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public String returnFormParamValue(@FormParam("my-param") String param) {
return param;
}
}
@ClientFormParam(name = "my-param", value = "${my.property-value}")
public | Resource |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/plain/SortedNumericIndexFieldData.java | {
"start": 2045,
"end": 6648
} | class ____ implements IndexFieldData.Builder {
private final String name;
private final NumericType numericType;
private final ValuesSourceType valuesSourceType;
protected final ToScriptFieldFactory<SortedNumericLongValues> toScriptFieldFactory;
private final IndexType indexType;
public Builder(
String name,
NumericType numericType,
ToScriptFieldFactory<SortedNumericLongValues> toScriptFieldFactory,
IndexType indexType
) {
this(name, numericType, numericType.getValuesSourceType(), toScriptFieldFactory, indexType);
}
public Builder(
String name,
NumericType numericType,
ValuesSourceType valuesSourceType,
ToScriptFieldFactory<SortedNumericLongValues> toScriptFieldFactory,
IndexType indexType
) {
this.name = name;
this.numericType = numericType;
this.valuesSourceType = valuesSourceType;
this.toScriptFieldFactory = toScriptFieldFactory;
this.indexType = indexType;
}
@Override
public SortedNumericIndexFieldData build(IndexFieldDataCache cache, CircuitBreakerService breakerService) {
return new SortedNumericIndexFieldData(name, numericType, valuesSourceType, toScriptFieldFactory, indexType);
}
}
private final NumericType numericType;
protected final String fieldName;
protected final ValuesSourceType valuesSourceType;
protected final ToScriptFieldFactory<SortedNumericLongValues> toScriptFieldFactory;
protected final IndexType indexType;
public SortedNumericIndexFieldData(
String fieldName,
NumericType numericType,
ValuesSourceType valuesSourceType,
ToScriptFieldFactory<SortedNumericLongValues> toScriptFieldFactory,
IndexType indexType
) {
this.fieldName = fieldName;
this.numericType = Objects.requireNonNull(numericType);
assert this.numericType.isFloatingPoint() == false;
this.valuesSourceType = valuesSourceType;
this.toScriptFieldFactory = toScriptFieldFactory;
this.indexType = indexType;
}
@Override
public final String getFieldName() {
return fieldName;
}
@Override
public ValuesSourceType getValuesSourceType() {
return valuesSourceType;
}
@Override
protected boolean sortRequiresCustomComparator() {
return false;
}
@Override
public IndexType indexType() {
return indexType;
}
@Override
protected XFieldComparatorSource dateComparatorSource(Object missingValue, MultiValueMode sortMode, Nested nested) {
if (numericType == NumericType.DATE_NANOSECONDS) {
// converts date_nanos values to millisecond resolution
return new LongValuesComparatorSource(
this,
missingValue,
sortMode,
nested,
dvs -> convertNumeric(dvs, DateUtils::toMilliSeconds),
NumericType.DATE
);
}
return new LongValuesComparatorSource(this, missingValue, sortMode, nested, NumericType.DATE);
}
@Override
protected XFieldComparatorSource dateNanosComparatorSource(Object missingValue, MultiValueMode sortMode, Nested nested) {
if (numericType == NumericType.DATE) {
// converts date values to nanosecond resolution
return new LongValuesComparatorSource(
this,
missingValue,
sortMode,
nested,
dvs -> convertNumeric(dvs, DateUtils::toNanoSeconds),
NumericType.DATE_NANOSECONDS
);
}
return new LongValuesComparatorSource(this, missingValue, sortMode, nested, NumericType.DATE_NANOSECONDS);
}
@Override
public NumericType getNumericType() {
return numericType;
}
@Override
public LeafNumericFieldData loadDirect(LeafReaderContext context) {
return load(context);
}
@Override
public LeafNumericFieldData load(LeafReaderContext context) {
final LeafReader reader = context.reader();
final String field = fieldName;
if (numericType == NumericType.DATE_NANOSECONDS) {
return new NanoSecondFieldData(reader, field, toScriptFieldFactory);
}
return new SortedNumericLongFieldData(reader, field, toScriptFieldFactory);
}
/**
* A small helper | Builder |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestUncachedThreadName.java | {
"start": 1589,
"end": 3186
} | class ____ {
@BeforeAll
static void beforeClass() {
System.setProperty("AsyncLogger.ThreadNameStrategy", "UNCACHED");
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName());
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerTest.xml");
}
@AfterAll
static void afterClass() {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY);
}
@Test
void testAsyncLogUsesCurrentThreadName() throws Exception {
final File file = new File("target", "AsyncLoggerTest.log");
// System.out.println(f.getAbsolutePath());
file.delete();
final Logger log = LogManager.getLogger("com.foo.Bar");
final String msg = "Async logger msg";
log.info(msg);
Thread.currentThread().setName("MODIFIED-THREADNAME");
log.info(msg);
CoreLoggerContexts.stopLoggerContext(file); // stop async thread
final BufferedReader reader = new BufferedReader(new FileReader(file));
final String line1 = reader.readLine();
final String line2 = reader.readLine();
// System.out.println(line1);
// System.out.println(line2);
reader.close();
file.delete();
assertNotNull(line1, "line1");
assertNotNull(line2, "line2");
assertTrue(line1.endsWith(" INFO c.f.Bar [main] Async logger msg "), "line1");
assertTrue(line2.endsWith(" INFO c.f.Bar [MODIFIED-THREADNAME] Async logger msg "), "line2");
}
}
| AsyncLoggerTestUncachedThreadName |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/UniVocityHeader.java | {
"start": 1410,
"end": 2192
} | class ____ implements CopyableDefinition<UniVocityHeader> {
@XmlValue
private String name;
@XmlAttribute
private String length;
public UniVocityHeader() {
}
protected UniVocityHeader(UniVocityHeader source) {
this.name = source.name;
this.length = source.length;
}
@Override
public UniVocityHeader copyDefinition() {
return new UniVocityHeader(this);
}
public String getName() {
return name;
}
/**
* Header name
*/
public void setName(String name) {
this.name = name;
}
public String getLength() {
return length;
}
/**
* Header length
*/
public void setLength(String length) {
this.length = length;
}
}
| UniVocityHeader |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.