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
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/cluster/ClusterScanSupport.java
|
{
"start": 557,
"end": 8001
}
|
class ____ {
/**
* Map a {@link RedisFuture} of {@link KeyScanCursor} to a {@link RedisFuture} of {@link ClusterKeyScanCursor}.
*/
static final ScanCursorMapper<RedisFuture<KeyScanCursor<?>>> futureKeyScanCursorMapper = new ScanCursorMapper<RedisFuture<KeyScanCursor<?>>>() {
@Override
public RedisFuture<KeyScanCursor<?>> map(List<String> nodeIds, String currentNodeId,
RedisFuture<KeyScanCursor<?>> cursor) {
return new PipelinedRedisFuture<>(cursor, new Function<KeyScanCursor<?>, KeyScanCursor<?>>() {
@Override
public KeyScanCursor<?> apply(KeyScanCursor<?> result) {
return new ClusterKeyScanCursor<>(nodeIds, currentNodeId, result);
}
});
}
};
/**
* Map a {@link RedisFuture} of {@link StreamScanCursor} to a {@link RedisFuture} of {@link ClusterStreamScanCursor}.
*/
static final ScanCursorMapper<RedisFuture<StreamScanCursor>> futureStreamScanCursorMapper = new ScanCursorMapper<RedisFuture<StreamScanCursor>>() {
@Override
public RedisFuture<StreamScanCursor> map(List<String> nodeIds, String currentNodeId,
RedisFuture<StreamScanCursor> cursor) {
return new PipelinedRedisFuture<>(cursor, new Function<StreamScanCursor, StreamScanCursor>() {
@Override
public StreamScanCursor apply(StreamScanCursor result) {
return new ClusterStreamScanCursor(nodeIds, currentNodeId, result);
}
});
}
};
/**
* Map a {@link Mono} of {@link KeyScanCursor} to a {@link Mono} of {@link ClusterKeyScanCursor}.
*/
static final ScanCursorMapper<Mono<KeyScanCursor<?>>> reactiveKeyScanCursorMapper = (nodeIds, currentNodeId,
cursor) -> cursor.map(keyScanCursor -> new ClusterKeyScanCursor<>(nodeIds, currentNodeId, keyScanCursor));
/**
* Map a {@link Mono} of {@link StreamScanCursor} to a {@link Mono} of {@link ClusterStreamScanCursor}.
*/
static final ScanCursorMapper<Mono<StreamScanCursor>> reactiveStreamScanCursorMapper = (nodeIds, currentNodeId,
cursor) -> cursor.map(new Function<StreamScanCursor, StreamScanCursor>() {
@Override
public StreamScanCursor apply(StreamScanCursor streamScanCursor) {
return new ClusterStreamScanCursor(nodeIds, currentNodeId, streamScanCursor);
}
});
/**
* Retrieve the cursor to continue the scan.
*
* @param scanCursor can be {@code null}.
* @return
*/
static ScanCursor getContinuationCursor(ScanCursor scanCursor) {
if (ScanCursor.INITIAL.equals(scanCursor)) {
return scanCursor;
}
assertClusterScanCursor(scanCursor);
ClusterScanCursor clusterScanCursor = (ClusterScanCursor) scanCursor;
if (clusterScanCursor.isScanOnCurrentNodeFinished()) {
return ScanCursor.INITIAL;
}
return scanCursor;
}
static <K, V> List<String> getNodeIds(StatefulRedisClusterConnection<K, V> connection, ScanCursor cursor) {
if (ScanCursor.INITIAL.equals(cursor)) {
List<String> nodeIds = getNodeIds(connection);
assertHasNodes(nodeIds);
return nodeIds;
}
assertClusterScanCursor(cursor);
ClusterScanCursor clusterScanCursor = (ClusterScanCursor) cursor;
return clusterScanCursor.getNodeIds();
}
static String getCurrentNodeId(ScanCursor cursor, List<String> nodeIds) {
if (ScanCursor.INITIAL.equals(cursor)) {
assertHasNodes(nodeIds);
return nodeIds.get(0);
}
assertClusterScanCursor(cursor);
return getNodeIdForNextScanIteration(nodeIds, (ClusterScanCursor) cursor);
}
/**
* Retrieve a list of node Ids to use for the SCAN operation.
*
* @param connection
* @return
*/
private static List<String> getNodeIds(StatefulRedisClusterConnection<?, ?> connection) {
List<String> nodeIds = new ArrayList<>();
PartitionAccessor partitionAccessor = new PartitionAccessor(connection.getPartitions());
for (RedisClusterNode redisClusterNode : partitionAccessor.getUpstream()) {
if (connection.getReadFrom() != null) {
List<RedisNodeDescription> readCandidates = (List) partitionAccessor.getReadCandidates(redisClusterNode);
List<RedisNodeDescription> selection = connection.getReadFrom().select(new ReadFrom.Nodes() {
@Override
public List<RedisNodeDescription> getNodes() {
return readCandidates;
}
@Override
public Iterator<RedisNodeDescription> iterator() {
return readCandidates.iterator();
}
});
if (!selection.isEmpty()) {
int indexToUse = 0;
if (!OrderingReadFromAccessor.isOrderSensitive(connection.getReadFrom())) {
indexToUse = ThreadLocalRandom.current().nextInt(selection.size());
}
RedisClusterNode selectedNode = (RedisClusterNode) selection.get(indexToUse);
nodeIds.add(selectedNode.getNodeId());
continue;
}
}
nodeIds.add(redisClusterNode.getNodeId());
}
return nodeIds;
}
private static String getNodeIdForNextScanIteration(List<String> nodeIds, ClusterScanCursor clusterKeyScanCursor) {
if (clusterKeyScanCursor.isScanOnCurrentNodeFinished()) {
if (clusterKeyScanCursor.isFinished()) {
throw new IllegalStateException("Cluster scan is finished");
}
int nodeIndex = nodeIds.indexOf(clusterKeyScanCursor.getCurrentNodeId());
return nodeIds.get(nodeIndex + 1);
}
return clusterKeyScanCursor.getCurrentNodeId();
}
private static void assertClusterScanCursor(ScanCursor cursor) {
if (!(cursor instanceof ClusterScanCursor)) {
throw new IllegalArgumentException(
"A scan in Redis Cluster mode requires to reuse the resulting cursor from the previous scan invocation");
}
}
private static void assertHasNodes(List<String> nodeIds) {
if (nodeIds.isEmpty()) {
throw new RedisException("No available nodes for a scan");
}
}
static <K> ScanCursorMapper<RedisFuture<KeyScanCursor<K>>> asyncClusterKeyScanCursorMapper() {
return (ScanCursorMapper) futureKeyScanCursorMapper;
}
static ScanCursorMapper<RedisFuture<StreamScanCursor>> asyncClusterStreamScanCursorMapper() {
return futureStreamScanCursorMapper;
}
static <K> ScanCursorMapper<Mono<KeyScanCursor<K>>> reactiveClusterKeyScanCursorMapper() {
return (ScanCursorMapper) reactiveKeyScanCursorMapper;
}
static ScanCursorMapper<Mono<StreamScanCursor>> reactiveClusterStreamScanCursorMapper() {
return reactiveStreamScanCursorMapper;
}
/**
* Mapper between the node operation cursor and the cluster scan cursor.
*
* @param <T>
*/
|
ClusterScanSupport
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/support/ConfigurationService.java
|
{
"start": 5736,
"end": 6471
}
|
class ____<T> extends AbstractBuilder<T, InstanceBuilder<T>> {
private final T instance;
public InstanceBuilder(ConfigurationService service, T instance) {
super(service);
this.instance = instance;
}
@Override
protected InstanceBuilder<T> getThis() {
return this;
}
@Override
protected void validate() {
Objects.requireNonNull(this.instance, "instance may not be null");
}
@Override
protected T doBind() {
T toBind = getTargetObject(this.instance);
Bindable<T> bindable = Bindable.ofInstance(toBind);
return bindOrCreate(bindable, this.normalizedProperties, this.name, this.service.validator.get(),
this.service.conversionService.get());
}
}
public static abstract
|
InstanceBuilder
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/nationalized/NationalizedLobFieldTest.java
|
{
"start": 1188,
"end": 1889
}
|
class ____ {
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
MyEntity e = new MyEntity( 1L );
e.setState( "UK" );
session.persist( e );
}
);
}
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void testNationalization(SessionFactoryScope scope) {
scope.inSession(
session -> {
MyEntity myEntity = session.get( MyEntity.class, 1L );
assertNotNull( myEntity );
assertThat( myEntity.getState(), is( "UK" ) );
}
);
}
@Entity(name = "MyEntity")
@Table(name = "my_entity")
public static
|
NationalizedLobFieldTest
|
java
|
apache__flink
|
flink-docs/src/test/java/org/apache/flink/docs/rest/data/TestAdditionalFieldsMessageHeaders.java
|
{
"start": 2017,
"end": 3719
}
|
class ____ implements RequestBody {}
private static final String URL = "/test/additional-fields";
private static final String DESCRIPTION = "This is an testing REST API with additional fields.";
private final String url;
private final String description;
private final String operationId;
public TestAdditionalFieldsMessageHeaders(String operationId) {
this(URL, DESCRIPTION, operationId);
}
private TestAdditionalFieldsMessageHeaders(String url, String description, String operationId) {
this.url = url;
this.description = description;
this.operationId = operationId;
}
@Override
public Class<AdditionalFieldsRequestBody> getRequestClass() {
return AdditionalFieldsRequestBody.class;
}
@Override
public Class<EmptyResponseBody> getResponseClass() {
return EmptyResponseBody.class;
}
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.PUT;
}
@Override
public HttpResponseStatus getResponseStatusCode() {
return HttpResponseStatus.OK;
}
@Override
public String operationId() {
return operationId;
}
@Override
public String getDescription() {
return description;
}
@Override
public EmptyMessageParameters getUnresolvedMessageParameters() {
return EmptyMessageParameters.getInstance();
}
@Override
public String getTargetRestEndpointURL() {
return url;
}
@Override
public Collection<RuntimeRestAPIVersion> getSupportedAPIVersions() {
return Collections.singleton(RuntimeRestAPIVersion.V0);
}
}
|
AdditionalFieldsRequestBody
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/error/ShouldBeAssignableTo.java
|
{
"start": 861,
"end": 1985
}
|
class ____ extends BasicErrorMessageFactory {
private static final String SHOULD_BE_ASSIGNABLE_TO = new StringJoiner("%n", "%n", "").add("Expecting")
.add(" %s")
.add("to be assignable to:")
.add(" %s")
.toString();
/**
* Creates a new <code>{@link ShouldBeAssignableTo}</code>.
*
* @param actual the actual value in the failed assertion.
* @param other the type {@code actual} should be assignable to.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldBeAssignableTo(Class<?> actual, Class<?> other) {
return new ShouldBeAssignableTo(actual, other);
}
private ShouldBeAssignableTo(Class<?> actual, Class<?> other) {
super(SHOULD_BE_ASSIGNABLE_TO, actual, other);
}
}
|
ShouldBeAssignableTo
|
java
|
apache__hadoop
|
hadoop-cloud-storage-project/hadoop-huaweicloud/src/main/java/org/apache/hadoop/fs/obs/RenameFailedException.java
|
{
"start": 1071,
"end": 1727
}
|
class ____ extends PathIOException {
/**
* Exit code to be returned.
*/
private boolean exitCode = false;
RenameFailedException(final Path src, final Path optionalDest,
final String error) {
super(src.toString(), error);
setOperation("rename");
if (optionalDest != null) {
setTargetPath(optionalDest.toString());
}
}
public boolean getExitCode() {
return exitCode;
}
/**
* Set the exit code.
*
* @param code exit code to raise
* @return the exception
*/
public RenameFailedException withExitCode(final boolean code) {
this.exitCode = code;
return this;
}
}
|
RenameFailedException
|
java
|
apache__kafka
|
storage/src/test/java/org/apache/kafka/tiered/storage/actions/AlterLogDirAction.java
|
{
"start": 1494,
"end": 4153
}
|
class ____ implements TieredStorageTestAction {
private final TopicPartition topicPartition;
private final int brokerId;
public AlterLogDirAction(TopicPartition topicPartition,
int brokerId) {
this.topicPartition = topicPartition;
this.brokerId = brokerId;
}
@Override
public void doExecute(TieredStorageTestContext context) throws InterruptedException, ExecutionException, TimeoutException {
Optional<BrokerLocalStorage> localStorage = context.localStorages().stream().filter(storage -> storage.getBrokerId() == brokerId).findFirst();
if (localStorage.isEmpty()) {
throw new IllegalArgumentException("cannot find local storage for this topic partition:" + topicPartition + " in this broker id:" + brokerId);
}
Optional<File> sourceDir = localStorage.get().getBrokerStorageDirectories().stream().filter(dir -> localStorage.get().dirContainsTopicPartition(topicPartition, dir)).findFirst();
if (sourceDir.isEmpty()) {
throw new IllegalArgumentException("No log dir with topic partition:" + topicPartition + " in this broker id:" + brokerId);
}
Optional<File> targetDir = localStorage.get().getBrokerStorageDirectories().stream().filter(dir -> !localStorage.get().dirContainsTopicPartition(topicPartition, dir)).findFirst();
if (targetDir.isEmpty()) {
throw new IllegalArgumentException("No log dir without topic partition:" + topicPartition + " in this broker id:" + brokerId);
}
// build alterReplicaLogDirs request content to move from sourceDir to targetDir
TopicPartitionReplica topicPartitionReplica = new TopicPartitionReplica(topicPartition.topic(), topicPartition.partition(), brokerId);
Map<TopicPartitionReplica, String> logDirs = Map.of(topicPartitionReplica, targetDir.get().getAbsolutePath());
AlterReplicaLogDirsResult results = context.admin().alterReplicaLogDirs(logDirs);
results.values().get(topicPartitionReplica).get(30, TimeUnit.SECONDS);
// wait until the topic partition folder disappears from source dir and appears in the target dir
TestUtils.waitForCondition(() -> localStorage.get().dirContainsTopicPartition(topicPartition, targetDir.get()) &&
!localStorage.get().dirContainsTopicPartition(topicPartition, sourceDir.get()),
"Failed to alter dir:" + logDirs);
}
@Override
public void describe(PrintStream output) {
output.print("alter dir for topic partition:" + topicPartition + " in this broker id:" + brokerId);
}
}
|
AlterLogDirAction
|
java
|
apache__camel
|
components/camel-consul/src/main/java/org/apache/camel/component/consul/ConsulComponent.java
|
{
"start": 1995,
"end": 6075
}
|
class ____ extends DefaultComponent implements SSLContextParametersAware {
@Metadata(label = "advanced")
private ConsulConfiguration configuration = new ConsulConfiguration();
@Metadata(label = "security")
private boolean useGlobalSslContextParameters;
public ConsulComponent() {
}
public ConsulComponent(CamelContext context) {
super(context);
}
// ************************************
// Options
// ************************************
@Override
public boolean isUseGlobalSslContextParameters() {
return this.useGlobalSslContextParameters;
}
/**
* Enable usage of global SSL context parameters.
*/
@Override
public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
this.useGlobalSslContextParameters = useGlobalSslContextParameters;
}
public ConsulConfiguration getConfiguration() {
return configuration;
}
/**
* Consul configuration
*/
public void setConfiguration(ConsulConfiguration configuration) {
this.configuration = configuration;
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
ConsulConfiguration configuration = Optional.ofNullable(this.configuration).orElseGet(ConsulConfiguration::new).copy();
ConsulEndpoint endpoint;
switch (remaining) {
case "kv":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulKeyValueProducer::new),
Optional.of(ConsulKeyValueConsumer::new));
break;
case "event":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulEventProducer::new),
Optional.of(ConsulEventConsumer::new));
break;
case "agent":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulAgentProducer::new), Optional.empty());
break;
case "coordinates":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulCoordinatesProducer::new), Optional.empty());
break;
case "health":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulHealthProducer::new), Optional.empty());
break;
case "status":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulStatusProducer::new), Optional.empty());
break;
case "preparedQuery":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulPreparedQueryProducer::new), Optional.empty());
break;
case "catalog":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulCatalogProducer::new), Optional.empty());
break;
case "session":
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulSessionProducer::new), Optional.empty());
break;
default:
endpoint = new ConsulEndpoint(
remaining, uri, this, configuration, Optional.of(ConsulKeyValueProducer::new),
Optional.of(ConsulKeyValueConsumer::new));
}
setProperties(endpoint, parameters);
// using global ssl context parameters if set
if (configuration.getSslContextParameters() == null) {
configuration.setSslContextParameters(retrieveGlobalSslContextParameters());
}
return endpoint;
}
}
|
ConsulComponent
|
java
|
quarkusio__quarkus
|
integration-tests/native-config-profile/src/test/java/io/quarkus/it/nat/test/profile/RuntimeValueChangeTest.java
|
{
"start": 713,
"end": 959
}
|
class ____ implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Collections.singletonMap("my.config.value", "RuntimeTimeValueChangeTest");
}
}
}
|
CustomTestProfile
|
java
|
bumptech__glide
|
library/src/main/java/com/bumptech/glide/load/engine/cache/DiskCacheAdapter.java
|
{
"start": 674,
"end": 813
}
|
class ____ implements DiskCache.Factory {
@Override
public DiskCache build() {
return new DiskCacheAdapter();
}
}
}
|
Factory
|
java
|
quarkusio__quarkus
|
integration-tests/maven/src/test/resources-filtered/projects/test-nested-tests-mixed-with-normal-tests/src/test/java/org/acme/HelloResourceTest.java
|
{
"start": 1020,
"end": 1454
}
|
class ____ {
@Test
public void testHelloEndpointYetAgain() {
given()
.when()
.get("/app/hello")
.then()
.statusCode(200)
.body(is("Hello from Quarkus REST via config"));
}
}
}
}
}
|
EvenDeeperNestedInnerClass
|
java
|
google__guava
|
android/guava/src/com/google/common/util/concurrent/AbstractFuture.java
|
{
"start": 4189,
"end": 4484
}
|
interface ____<V extends @Nullable Object> extends ListenableFuture<V> {}
/**
* A less abstract subclass of AbstractFuture. This can be used to optimize setFuture by ensuring
* that {@link #get} calls exactly the implementation of {@link AbstractFuture#get}.
*/
abstract static
|
Trusted
|
java
|
junit-team__junit5
|
platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClasspathResourceSourceTests.java
|
{
"start": 886,
"end": 4127
}
|
class ____ extends AbstractTestSourceTests {
private static final String FOO_RESOURCE = "test/foo.xml";
private static final String BAR_RESOURCE = "/config/bar.json";
private static final URI FOO_RESOURCE_URI = URI.create(CLASSPATH_SCHEME + ":/" + FOO_RESOURCE);
@Override
Stream<ClasspathResourceSource> createSerializableInstances() {
return Stream.of(ClasspathResourceSource.from(FOO_RESOURCE));
}
@SuppressWarnings("DataFlowIssue")
@Test
void preconditions() {
assertPreconditionViolationFor(() -> ClasspathResourceSource.from((String) null));
assertPreconditionViolationFor(() -> ClasspathResourceSource.from(""));
assertPreconditionViolationFor(() -> ClasspathResourceSource.from(" "));
assertPreconditionViolationFor(() -> ClasspathResourceSource.from((URI) null));
assertPreconditionViolationFor(() -> ClasspathResourceSource.from(URI.create("file:/foo.txt")));
}
@Test
void resourceWithoutPosition() {
var source = ClasspathResourceSource.from(FOO_RESOURCE);
assertThat(source).isNotNull();
assertThat(source.getClasspathResourceName()).isEqualTo(FOO_RESOURCE);
assertThat(source.getPosition()).isEmpty();
}
@Test
void resourceWithLeadingSlashWithoutPosition() {
var source = ClasspathResourceSource.from("/" + FOO_RESOURCE);
assertThat(source).isNotNull();
assertThat(source.getClasspathResourceName()).isEqualTo(FOO_RESOURCE);
assertThat(source.getPosition()).isEmpty();
}
@Test
void resourceWithPosition() {
var position = FilePosition.from(42, 23);
var source = ClasspathResourceSource.from(FOO_RESOURCE, position);
assertThat(source).isNotNull();
assertThat(source.getClasspathResourceName()).isEqualTo(FOO_RESOURCE);
assertThat(source.getPosition()).hasValue(position);
}
@Test
void resourceFromUriWithoutPosition() {
var source = ClasspathResourceSource.from(FOO_RESOURCE_URI);
assertThat(source).isNotNull();
assertThat(source.getClasspathResourceName()).isEqualTo(FOO_RESOURCE);
assertThat(source.getPosition()).isEmpty();
}
@Test
void resourceFromUriWithLineNumber() {
var position = FilePosition.from(42);
var uri = URI.create(FOO_RESOURCE_URI + "?line=42");
var source = ClasspathResourceSource.from(uri);
assertThat(source).isNotNull();
assertThat(source.getClasspathResourceName()).isEqualTo(FOO_RESOURCE);
assertThat(source.getPosition()).hasValue(position);
}
@Test
void resourceFromUriWithLineAndColumnNumbers() {
var position = FilePosition.from(42, 23);
var uri = URI.create(FOO_RESOURCE_URI + "?line=42&foo=bar&column=23");
var source = ClasspathResourceSource.from(uri);
assertThat(source).isNotNull();
assertThat(source.getClasspathResourceName()).isEqualTo(FOO_RESOURCE);
assertThat(source.getPosition()).hasValue(position);
}
@Test
void equalsAndHashCode() {
assertEqualsAndHashCode(ClasspathResourceSource.from(FOO_RESOURCE), ClasspathResourceSource.from(FOO_RESOURCE),
ClasspathResourceSource.from(BAR_RESOURCE));
var position = FilePosition.from(42, 23);
assertEqualsAndHashCode(ClasspathResourceSource.from(FOO_RESOURCE, position),
ClasspathResourceSource.from(FOO_RESOURCE, position), ClasspathResourceSource.from(BAR_RESOURCE, position));
}
}
|
ClasspathResourceSourceTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/NestedEmbeddedWitnNotOptionalManyToOneTest.java
|
{
"start": 988,
"end": 1945
}
|
class ____ {
@Test
public void testIt(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
ChildEntity child = new ChildEntity( 2, "child" );
SecondEmbeddable secondEmbeddable = new SecondEmbeddable( child );
FirstEmbeddable embedded = new FirstEmbeddable();
embedded.addEntry( secondEmbeddable );
TestEntity testEntity = new TestEntity( 1, "test", embedded );
session.persist( child );
session.persist( testEntity );
}
);
scope.inTransaction(
session -> {
TestEntity testEntity = session.get( TestEntity.class, 1 );
assertNotNull( testEntity );
FirstEmbeddable embeddedAttribute = testEntity.getEmbeddedAttribute();
assertNotNull( embeddedAttribute );
Set<SecondEmbeddable> entries = embeddedAttribute.getEntries();
assertThat( entries.size() ).isEqualTo( 1 );
}
);
}
@Entity(name = "TestEntity")
public static
|
NestedEmbeddedWitnNotOptionalManyToOneTest
|
java
|
spring-projects__spring-framework
|
spring-expression/src/main/java/org/springframework/expression/spel/support/DataBindingPropertyAccessor.java
|
{
"start": 1539,
"end": 2524
}
|
class ____ extends ReflectivePropertyAccessor {
/**
* Create a new property accessor for reading and possibly also writing.
* @param allowWrite whether to also allow for write operations
* @see #canWrite
*/
private DataBindingPropertyAccessor(boolean allowWrite) {
super(allowWrite);
}
@Override
protected boolean isCandidateForProperty(Method method, Class<?> targetClass) {
Class<?> clazz = method.getDeclaringClass();
return (clazz != Object.class && clazz != Class.class && !ClassLoader.class.isAssignableFrom(targetClass));
}
/**
* Create a new data-binding property accessor for read-only operations.
*/
public static DataBindingPropertyAccessor forReadOnlyAccess() {
return new DataBindingPropertyAccessor(false);
}
/**
* Create a new data-binding property accessor for read-write operations.
*/
public static DataBindingPropertyAccessor forReadWriteAccess() {
return new DataBindingPropertyAccessor(true);
}
}
|
DataBindingPropertyAccessor
|
java
|
apache__rocketmq
|
tools/src/main/java/org/apache/rocketmq/tools/command/container/AddBrokerSubCommand.java
|
{
"start": 1203,
"end": 2750
}
|
class ____ implements SubCommand {
@Override
public String commandName() {
return "addBroker";
}
@Override
public String commandDesc() {
return "Add a broker to specified container.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("c", "brokerContainerAddr", true, "Broker container address");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("b", "brokerConfigPath", true, "Broker config path");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
String brokerContainerAddr = commandLine.getOptionValue('c').trim();
String brokerConfigPath = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.addBrokerToContainer(brokerContainerAddr, brokerConfigPath);
System.out.printf("add broker to %s success%n", brokerContainerAddr);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
|
AddBrokerSubCommand
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/objectarrays/ObjectArrays_assertContains_at_Index_Test.java
|
{
"start": 1578,
"end": 5444
}
|
class ____ extends ObjectArraysBaseTest {
@Override
protected void initActualArray() {
actual = array("Yoda", "Luke", "Leia");
}
@Test
void should_fail_if_actual_is_null() {
// WHEN
var error = expectAssertionError(() -> arrays.assertContains(INFO, null, "Yoda", someIndex()));
// THEN
then(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_empty() {
// WHEN
var error = expectAssertionError(() -> arrays.assertContains(INFO, emptyArray(), "Yoda", someIndex()));
// THEN
then(error).hasMessage(actualIsEmpty());
}
@Test
void should_throw_error_if_Index_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertContains(INFO, actual, "Yoda", null))
.withMessage("Index should not be null");
}
@Test
void should_throw_error_if_Index_is_out_of_bounds() {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> arrays.assertContains(INFO,
actual, "Yoda",
atIndex(6)))
.withMessageContaining("Index should be between <0> and <2> (inclusive) but was:%n <6>".formatted());
}
@Test
void should_fail_if_actual_does_not_contain_value_at_index() {
// GIVEN
Index index = atIndex(1);
// WHEN
expectAssertionError(() -> arrays.assertContains(INFO, actual, "Han", index));
// THEN
verify(failures).failure(INFO, shouldContainAtIndex(actual, "Han", index, "Luke"));
}
@Test
void should_pass_if_actual_contains_value_at_index() {
arrays.assertContains(INFO, actual, "Luke", atIndex(1));
}
@Test
void should_throw_error_if_Index_is_null_whatever_custom_comparison_strategy_is() {
assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(INFO,
actual, "YODa",
null))
.withMessage("Index should not be null");
}
@Test
void should_throw_error_if_Index_is_out_of_bounds_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(INFO,
actual,
"YodA",
atIndex(6)))
.withMessageContaining("Index should be between <0> and <2> (inclusive) but was:%n <6>".formatted());
}
@Test
void should_fail_if_actual_does_not_contain_value_at_index_according_to_custom_comparison_strategy() {
// GIVEN
Index index = atIndex(1);
// WHEN
expectAssertionError(() -> arraysWithCustomComparisonStrategy.assertContains(INFO, actual, "Han", index));
// THEN
verify(failures).failure(INFO, shouldContainAtIndex(actual, "Han", index, "Luke", caseInsensitiveStringComparisonStrategy));
}
@Test
void should_pass_if_actual_contains_value_at_index_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertContains(INFO, actual, "LUKe", atIndex(1));
}
}
|
ObjectArrays_assertContains_at_Index_Test
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java
|
{
"start": 42110,
"end": 42789
}
|
class ____ {
@GetMapping("/password")
String password(Authentication authentication) {
return (String) authentication.getCredentials();
}
@GetMapping("/roles")
String roles(Authentication authentication) {
return authentication.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
}
@GetMapping("/details")
String details(Authentication authentication) {
return authentication.getDetails().getClass().getName();
}
@GetMapping("/name")
Callable<String> name(Authentication authentication) {
return () -> authentication.getName();
}
}
@RestController
static
|
AuthenticationController
|
java
|
jhy__jsoup
|
src/main/java/org/jsoup/Connection.java
|
{
"start": 2869,
"end": 23307
}
|
enum ____ {
GET(false),
POST(true),
PUT(true),
DELETE(true),
/**
Note that unfortunately, PATCH is not supported in many JDKs.
*/
PATCH(true),
HEAD(false),
OPTIONS(false),
TRACE(false);
private final boolean hasBody;
Method(boolean hasBody) {
this.hasBody = hasBody;
}
/**
* Check if this HTTP method has/needs a request body
* @return if body needed
*/
public final boolean hasBody() {
return hasBody;
}
}
/**
Creates a new request, using this Connection as the session-state and to initialize the connection settings (which
may then be independently changed on the returned {@link Connection.Request} object).
@return a new Connection object, with a shared Cookie Store and initialized settings from this Connection and Request
@since 1.14.1
*/
Connection newRequest();
/**
Creates a new request, using this Connection as the session-state and to initialize the connection settings (which
may then be independently changed on the returned {@link Connection.Request} object).
@return a new Connection object, with a shared Cookie Store and initialized settings from this Connection and Request
@param url URL for the new request
@since 1.17.1
*/
default Connection newRequest(String url) {
return newRequest().url(url);
}
/**
Creates a new request, using this Connection as the session-state and to initialize the connection settings (which
may then be independently changed on the returned {@link Connection.Request} object).
@return a new Connection object, with a shared Cookie Store and initialized settings from this Connection and Request
@param url URL for the new request
@since 1.17.1
*/
default Connection newRequest(URL url) {
return newRequest().url(url);
}
/**
* Set the request URL to fetch. The protocol must be HTTP or HTTPS.
* @param url URL to connect to
* @return this Connection, for chaining
*/
Connection url(URL url);
/**
* Set the request URL to fetch. The protocol must be HTTP or HTTPS.
* @param url URL to connect to
* @return this Connection, for chaining
*/
Connection url(String url);
/**
* Set the proxy to use for this request. Set to <code>null</code> to disable a previously set proxy.
* @param proxy proxy to use
* @return this Connection, for chaining
*/
Connection proxy(@Nullable Proxy proxy);
/**
* Set the HTTP proxy to use for this request.
* @param host the proxy hostname
* @param port the proxy port
* @return this Connection, for chaining
*/
Connection proxy(String host, int port);
/**
* Set the request user-agent header.
* @param userAgent user-agent to use
* @return this Connection, for chaining
* @see org.jsoup.helper.HttpConnection#DEFAULT_UA
*/
Connection userAgent(String userAgent);
/**
Set the total maximum request duration. If a timeout occurs, an {@link java.net.SocketTimeoutException} will be
thrown.
<p>The default timeout is <b>30 seconds</b> (30,000 millis). A timeout of zero is treated as an infinite timeout.</p>
<p>This timeout specifies the combined maximum duration of the connection time and the time to read
the full response.</p>
<p>Implementation note: when this <code>Connection</code> is backed by <code>HttpURLConnection</code> (rather than <code>HttpClient</code>, as used in JVM 11+), this timeout is implemented by setting both the socket connect and read timeouts to half of the specified value.</p>
@param millis number of milliseconds (thousandths of a second) before timing out connects or reads.
@return this Connection, for chaining
@see #maxBodySize(int)
*/
Connection timeout(int millis);
/**
* Set the maximum bytes to read from the (uncompressed) connection into the body, before the connection is closed,
* and the input truncated (i.e. the body content will be trimmed). <b>The default maximum is 2MB</b>. A max size of
* <code>0</code> is treated as an infinite amount (bounded only by your patience and the memory available on your
* machine).
*
* @param bytes number of bytes to read from the input before truncating
* @return this Connection, for chaining
*/
Connection maxBodySize(int bytes);
/**
* Set the request referrer (aka "referer") header.
* @param referrer referrer to use
* @return this Connection, for chaining
*/
Connection referrer(String referrer);
/**
* Configures the connection to (not) follow server redirects. By default, this is <b>true</b>.
* @param followRedirects true if server redirects should be followed.
* @return this Connection, for chaining
*/
Connection followRedirects(boolean followRedirects);
/**
* Set the request method to use, GET or POST. Default is GET.
* @param method HTTP request method
* @return this Connection, for chaining
*/
Connection method(Method method);
/**
* Configures the connection to not throw exceptions when an HTTP error occurs. (4xx - 5xx, e.g. 404 or 500). By
* default, this is <b>false</b>; an IOException is thrown if an error is encountered. If set to <b>true</b>, the
* response is populated with the error body, and the status message will reflect the error.
* @param ignoreHttpErrors - false (default) if HTTP errors should be ignored.
* @return this Connection, for chaining
*/
Connection ignoreHttpErrors(boolean ignoreHttpErrors);
/**
* Ignore the document's Content-Type when parsing the response. By default, this is <b>false</b>, an unrecognised
* content-type will cause an IOException to be thrown. (This is to prevent producing garbage by attempting to parse
* a JPEG binary image, for example.) Set to true to force a parse attempt regardless of content type.
* @param ignoreContentType set to true if you would like the content type ignored on parsing the response into a
* Document.
* @return this Connection, for chaining
*/
Connection ignoreContentType(boolean ignoreContentType);
/**
Set a custom SSL socket factory for HTTPS connections.
<p>Note: if set, the legacy <code>HttpURLConnection</code> will be used instead of the JVM's
<code>HttpClient</code>.</p>
@param sslSocketFactory SSL socket factory
@return this Connection, for chaining
@see #sslContext(SSLContext)
@deprecated use {@link #sslContext(SSLContext)} instead.
*/
@Deprecated
Connection sslSocketFactory(SSLSocketFactory sslSocketFactory);
/**
Set a custom SSL context for HTTPS connections.
<p>Note: when using the legacy <code>HttpURLConnection</code>, only the <code>SSLSocketFactory</code> from the
context will be used.</p>
@param sslContext SSL context
@return this Connection, for chaining
@since 1.21.2
*/
default Connection sslContext(SSLContext sslContext) {
throw new UnsupportedOperationException();
}
/**
* Add a request data parameter. Request parameters are sent in the request query string for GETs, and in the
* request body for POSTs. A request may have multiple values of the same name.
* @param key data key
* @param value data value
* @return this Connection, for chaining
*/
Connection data(String key, String value);
/**
* Add an input stream as a request data parameter. For GETs, has no effect, but for POSTS this will upload the
* input stream.
* <p>Use the {@link #data(String, String, InputStream, String)} method to set the uploaded file's mimetype.</p>
* @param key data key (form item name)
* @param filename the name of the file to present to the remove server. Typically just the name, not path,
* component.
* @param inputStream the input stream to upload, that you probably obtained from a {@link java.io.FileInputStream}.
* You must close the InputStream in a {@code finally} block.
* @return this Connection, for chaining
* @see #data(String, String, InputStream, String)
*/
Connection data(String key, String filename, InputStream inputStream);
/**
* Add an input stream as a request data parameter. For GETs, has no effect, but for POSTS this will upload the
* input stream.
* @param key data key (form item name)
* @param filename the name of the file to present to the remove server. Typically just the name, not path,
* component.
* @param inputStream the input stream to upload, that you probably obtained from a {@link java.io.FileInputStream}.
* @param contentType the Content Type (aka mimetype) to specify for this file.
* You must close the InputStream in a {@code finally} block.
* @return this Connection, for chaining
*/
Connection data(String key, String filename, InputStream inputStream, String contentType);
/**
* Adds all of the supplied data to the request data parameters
* @param data collection of data parameters
* @return this Connection, for chaining
*/
Connection data(Collection<KeyVal> data);
/**
* Adds all of the supplied data to the request data parameters
* @param data map of data parameters
* @return this Connection, for chaining
*/
Connection data(Map<String, String> data);
/**
Add one or more request {@code key, val} data parameter pairs.
<p>Multiple parameters may be set at once, e.g.:
<code>.data("name", "jsoup", "language", "Java", "language", "English");</code> creates a query string like:
<code>{@literal ?name=jsoup&language=Java&language=English}</code></p>
<p>For GET requests, data parameters will be sent on the request query string. For POST (and other methods that
contain a body), they will be sent as body form parameters, unless the body is explicitly set by
{@link #requestBody(String)}, in which case they will be query string parameters.</p>
@param keyvals a set of key value pairs.
@return this Connection, for chaining
*/
Connection data(String... keyvals);
/**
* Get the data KeyVal for this key, if any
* @param key the data key
* @return null if not set
*/
@Nullable KeyVal data(String key);
/**
* Set a POST (or PUT) request body. Useful when a server expects a plain request body (such as JSON), and not a set
* of URL encoded form key/value pairs. E.g.:
* <code><pre>Jsoup.connect(url)
* .requestBody(json)
* .header("Content-Type", "application/json")
* .post();</pre></code>
* If any data key/vals are supplied, they will be sent as URL query params.
* @see #requestBodyStream(InputStream)
* @return this Request, for chaining
*/
Connection requestBody(String body);
/**
Set the request body. Useful for posting data such as byte arrays or files, and the server expects a single request
body (and not a multipart upload). E.g.:
<code><pre> Jsoup.connect(url)
.requestBody(new ByteArrayInputStream(bytes))
.header("Content-Type", "application/octet-stream")
.post();
</pre></code>
<p>Or, use a FileInputStream to data from disk.</p>
<p>You should close the stream in a finally block.</p>
@param stream the input stream to send.
@return this Request, for chaining
@see #requestBody(String)
@since 1.20.1
*/
default Connection requestBodyStream(InputStream stream) {
throw new UnsupportedOperationException();
}
/**
* Set a request header. Replaces any existing header with the same case-insensitive name.
* @param name header name
* @param value header value
* @return this Connection, for chaining
* @see org.jsoup.Connection.Request#header(String, String)
* @see org.jsoup.Connection.Request#headers()
*/
Connection header(String name, String value);
/**
* Sets each of the supplied headers on the request. Existing headers with the same case-insensitive name will be
* replaced with the new value.
* @param headers map of headers name {@literal ->} value pairs
* @return this Connection, for chaining
* @see org.jsoup.Connection.Request#headers()
*/
Connection headers(Map<String,String> headers);
/**
* Set a cookie to be sent in the request.
* @param name name of cookie
* @param value value of cookie
* @return this Connection, for chaining
*/
Connection cookie(String name, String value);
/**
* Adds each of the supplied cookies to the request.
* @param cookies map of cookie name {@literal ->} value pairs
* @return this Connection, for chaining
*/
Connection cookies(Map<String, String> cookies);
/**
Provide a custom or pre-filled CookieStore to be used on requests made by this Connection.
@param cookieStore a cookie store to use for subsequent requests
@return this Connection, for chaining
@since 1.14.1
*/
Connection cookieStore(CookieStore cookieStore);
/**
Get the cookie store used by this Connection.
@return the cookie store
@since 1.14.1
*/
CookieStore cookieStore();
/**
* Provide a specific parser to use when parsing the response to a Document. If not set, jsoup defaults to the
* {@link Parser#htmlParser() HTML parser}, unless the response content-type is XML, in which case the
* {@link Parser#xmlParser() XML parser} is used.
* @param parser alternate parser
* @return this Connection, for chaining
*/
Connection parser(Parser parser);
/**
* Set the character-set used to encode the request body. Defaults to {@code UTF-8}.
* @param charset character set to encode the request body
* @return this Connection, for chaining
*/
Connection postDataCharset(String charset);
/**
Set the authenticator to use for this connection, enabling requests to URLs, and via proxies, that require
authentication credentials.
<p>The authentication scheme used is automatically detected during the request execution.
Supported schemes (subject to the platform) are {@code basic}, {@code digest}, {@code NTLM},
and {@code Kerberos}.</p>
<p>To use, supply a {@link RequestAuthenticator} function that:
<ol>
<li>validates the URL that is requesting authentication, and</li>
<li>returns the appropriate credentials (username and password)</li>
</ol>
</p>
<p>For example, to authenticate both to a proxy and a downstream web server:
<code><pre>
Connection session = Jsoup.newSession()
.proxy("proxy.example.com", 8080)
.auth(auth -> {
if (auth.isServer()) { // provide credentials for the request url
Validate.isTrue(auth.url().getHost().equals("example.com"));
// check that we're sending credentials were we expect, and not redirected out
return auth.credentials("username", "password");
} else { // auth.isProxy()
return auth.credentials("proxy-user", "proxy-password");
}
});
Connection.Response response = session.newRequest("https://example.com/adminzone/").execute();
</pre></code>
</p>
<p>The system may cache the authentication and use it for subsequent requests to the same resource.</p>
<p><b>Implementation notes</b></p>
<p>For compatibility, on a Java 8 platform, authentication is set up via the system-wide default
{@link java.net.Authenticator#setDefault(Authenticator)} method via a ThreadLocal delegator. Whilst the
authenticator used is request specific and thread-safe, if you have other calls to {@code setDefault}, they will be
incompatible with this implementation.</p>
<p>On Java 9 and above, the preceding note does not apply; authenticators are directly set on the request. </p>
<p>If you are attempting to authenticate to a proxy that uses the {@code basic} scheme and will be fetching HTTPS
URLs, you need to configure your Java platform to enable that, by setting the
{@code jdk.http.auth.tunneling.disabledSchemes} system property to {@code ""}.
This must be executed prior to any authorization attempts. E.g.:
<code><pre>
static {
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
// removes Basic, which is otherwise excluded from auth for CONNECT tunnels
}</pre></code>
</p>
* @param authenticator the authenticator to use in this connection
* @return this Connection, for chaining
* @since 1.17.1
*/
default Connection auth(@Nullable RequestAuthenticator authenticator) {
throw new UnsupportedOperationException();
}
/**
* Execute the request as a GET, and parse the result.
* @return parsed Document
* @throws java.net.MalformedURLException if the request URL is not an HTTP or HTTPS URL, or is otherwise malformed
* @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
* @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
* @throws java.net.SocketTimeoutException if the connection times out
* @throws IOException on error
*/
Document get() throws IOException;
/**
* Execute the request as a POST, and parse the result.
* @return parsed Document
* @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
* @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
* @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
* @throws java.net.SocketTimeoutException if the connection times out
* @throws IOException on error
*/
Document post() throws IOException;
/**
* Execute the request.
* @return the executed {@link Response}
* @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
* @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
* @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
* @throws java.net.SocketTimeoutException if the connection times out
* @throws IOException on error
*/
Response execute() throws IOException;
/**
* Get the request object associated with this connection
* @return request
*/
Request request();
/**
* Set the connection's request
* @param request new request object
* @return this Connection, for chaining
*/
Connection request(Request request);
/**
* Get the response, once the request has been executed.
* @return response
* @throws IllegalArgumentException if called before the response has been executed.
*/
Response response();
/**
* Set the connection's response
* @param response new response
* @return this Connection, for chaining
*/
Connection response(Response response);
/**
Set the response progress handler, which will be called periodically as the response body is downloaded. Since
documents are parsed as they are downloaded, this is also a good proxy for the parse progress.
<p>The Response object is supplied as the progress context, and may be read from to obtain headers etc.</p>
@param handler the progress handler
@return this Connection, for chaining
@since 1.18.1
*/
default Connection onResponseProgress(Progress<Response> handler) {
throw new UnsupportedOperationException();
}
/**
* Common methods for Requests and Responses
* @param <T> Type of Base, either Request or Response
*/
@SuppressWarnings("UnusedReturnValue")
|
Method
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/impl/StartStopAndShutdownRouteTest.java
|
{
"start": 1184,
"end": 2274
}
|
class ____ extends ContextTestSupport {
@Test
public void testStartStopAndShutdownRoute() throws Exception {
// there should still be 2 services on the route
Route myRoute = context.getRoute("foo");
int services = myRoute.getServices().size();
assertTrue(services > 0);
// stop the route
context.getRouteController().stopRoute("foo");
// there should still be the same number of services on the route
assertEquals(services, myRoute.getServices().size());
// shutting down the route, by stop and remove
context.getRouteController().stopRoute("foo");
context.removeRoute("foo");
// and now no more services as the route is shutdown
assertEquals(0, myRoute.getServices().size());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").routeId("foo").to("mock:foo");
}
};
}
}
|
StartStopAndShutdownRouteTest
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/event/DirtiesContextEventPublishingTests.java
|
{
"start": 2310,
"end": 2884
}
|
class ____ {
private static final List<Class<? extends TestContextEvent>> events = new ArrayList<>();
@BeforeEach
@AfterEach
void resetEvents() {
events.clear();
}
@Test
void classLevelDirtiesContext() {
EngineTestKit.engine("junit-jupiter")//
.selectors(selectClass(ClassLevelDirtiesContextTestCase.class))//
.execute()//
.testEvents()//
.assertStatistics(stats -> stats.started(1).succeeded(1).failed(0));
assertThat(events).containsExactly(//
// BeforeTestClassEvent.class -- always missing for 1st test
|
DirtiesContextEventPublishingTests
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java
|
{
"start": 176251,
"end": 176682
}
|
class ____ superclasses.
* @param command the annotated object to create usage help for
* @param ansi whether to emit ANSI escape codes or not */
public Help(final Object command, final Ansi ansi) {
this(command, defaultColorScheme(ansi));
}
/** Constructs a new {@code Help} instance with the specified color scheme, initialized from annotatations
* on the specified
|
and
|
java
|
micronaut-projects__micronaut-core
|
discovery-core/src/main/java/io/micronaut/health/DefaultCurrentHealthStatus.java
|
{
"start": 837,
"end": 1291
}
|
class ____ implements CurrentHealthStatus {
private final AtomicReference<HealthStatus> current = new AtomicReference<>(HealthStatus.UP);
@Override
public HealthStatus current() {
return current.get();
}
@Override
public HealthStatus update(HealthStatus newStatus) {
if (newStatus != null) {
return current.getAndSet(newStatus);
}
return current.get();
}
}
|
DefaultCurrentHealthStatus
|
java
|
quarkusio__quarkus
|
extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/staticmethods/InterceptedStaticMethodsTransformersRegisteredBuildItem.java
|
{
"start": 227,
"end": 389
}
|
class ____ produced by transformers registered by consumers of this build item will be run before visitors used for
* static method interception.
*/
public
|
visitors
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/table/runtime/operators/python/aggregate/arrow/stream/AbstractStreamArrowPythonBoundedRangeOperator.java
|
{
"start": 1761,
"end": 6871
}
|
class ____<K>
extends AbstractStreamArrowPythonOverWindowAggregateFunctionOperator<K> {
private static final long serialVersionUID = 1L;
private transient LinkedList<List<RowData>> inputData;
public AbstractStreamArrowPythonBoundedRangeOperator(
Configuration config,
PythonFunctionInfo[] pandasAggFunctions,
RowType inputType,
RowType udfInputType,
RowType udfOutputType,
int inputTimeFieldIndex,
long lowerBoundary,
GeneratedProjection inputGeneratedProjection) {
super(
config,
pandasAggFunctions,
inputType,
udfInputType,
udfOutputType,
inputTimeFieldIndex,
lowerBoundary,
inputGeneratedProjection);
}
@Override
public void open() throws Exception {
super.open();
inputData = new LinkedList<>();
}
@Override
public void onEventTime(InternalTimer<K, VoidNamespace> timer) throws Exception {
long timestamp = timer.getTimestamp();
Long cleanupTimestamp = cleanupTsState.value();
// if cleanupTsState has not been updated then it is safe to cleanup states
if (cleanupTimestamp != null && cleanupTimestamp <= timestamp) {
inputState.clear();
lastTriggeringTsState.clear();
cleanupTsState.clear();
return;
}
// gets all window data from state for the calculation
List<RowData> inputs = inputState.get(timestamp);
triggerWindowProcess(timestamp, inputs);
lastTriggeringTsState.update(timestamp);
}
@Override
public void onProcessingTime(InternalTimer<K, VoidNamespace> timer) throws Exception {
long timestamp = timer.getTimestamp();
Long cleanupTimestamp = cleanupTsState.value();
// if cleanupTsState has not been updated then it is safe to cleanup states
if (cleanupTimestamp != null && cleanupTimestamp <= timestamp) {
inputState.clear();
cleanupTsState.clear();
return;
}
// we consider the original timestamp of events
// that have registered this time trigger 1 ms ago
long currentTime = timestamp - 1;
// get the list of elements of current proctime
List<RowData> currentElements = inputState.get(currentTime);
triggerWindowProcess(timestamp, currentElements);
}
@Override
@SuppressWarnings("ConstantConditions")
public void emitResult(Tuple3<String, byte[], Integer> resultTuple) throws Exception {
byte[] udafResult = resultTuple.f1;
int length = resultTuple.f2;
bais.setBuffer(udafResult, 0, length);
int rowCount = arrowSerializer.load();
for (int i = 0; i < rowCount; i++) {
RowData data = arrowSerializer.read(i);
List<RowData> input = inputData.poll();
for (RowData ele : input) {
reuseJoinedRow.setRowKind(ele.getRowKind());
rowDataWrapper.collect(reuseJoinedRow.replace(ele, data));
}
}
arrowSerializer.resetReader();
}
void registerCleanupTimer(long timestamp, TimeDomain domain) throws Exception {
long minCleanupTimestamp = timestamp + lowerBoundary + 1;
long maxCleanupTimestamp = timestamp + (long) (lowerBoundary * 1.5) + 1;
// update timestamp and register timer if needed
Long curCleanupTimestamp = cleanupTsState.value();
if (curCleanupTimestamp == null || curCleanupTimestamp < minCleanupTimestamp) {
// we don't delete existing timer since it may delete timer for data processing
if (domain == TimeDomain.EVENT_TIME) {
timerService.registerEventTimeTimer(maxCleanupTimestamp);
} else {
timerService.registerProcessingTimeTimer(maxCleanupTimestamp);
}
cleanupTsState.update(maxCleanupTimestamp);
}
}
private void triggerWindowProcess(long upperLimit, List<RowData> inputs) throws Exception {
long lowerLimit = upperLimit - lowerBoundary;
if (inputs != null) {
Iterator<Map.Entry<Long, List<RowData>>> iter = inputState.iterator();
while (iter.hasNext()) {
Map.Entry<Long, List<RowData>> entry = iter.next();
long dataTs = entry.getKey();
if (dataTs >= lowerLimit) {
if (dataTs <= upperLimit) {
List<RowData> dataList = entry.getValue();
for (RowData data : dataList) {
arrowSerializer.write(getFunctionInput(data));
currentBatchCount++;
}
}
} else {
iter.remove();
}
}
inputData.add(inputs);
invokeCurrentBatch();
}
}
}
|
AbstractStreamArrowPythonBoundedRangeOperator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ArgumentSelectionDefectCheckerTest.java
|
{
"start": 9767,
"end": 10443
}
|
class ____
extends ArgumentSelectionDefectChecker {
public ArgumentSelectionDefectWithNameInCommentsHeuristic() {
super(
ArgumentChangeFinder.builder()
.setDistanceFunction(buildEqualityFunction())
.addHeuristic(new NameInCommentHeuristic())
.build());
}
}
@Test
public void argumentSelectionDefectCheckerWithPenalty_noSwap_withNamedPair() {
CompilationTestHelper.newInstance(
ArgumentSelectionDefectWithNameInCommentsHeuristic.class, getClass())
.addSourceLines(
"Test.java",
"""
abstract
|
ArgumentSelectionDefectWithNameInCommentsHeuristic
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/spi/ValidatorRegistry.java
|
{
"start": 1636,
"end": 3015
}
|
interface ____ extends Map<ValidatorKey, Validator>, StaticService {
/**
* Lookup a {@link Validator} in the registry which supports the validation for the data type represented by the
* key.
*
* @param key a key represents the data type
* @return {@link Validator} if matched, otherwise null
*/
Validator resolveValidator(ValidatorKey key);
/**
* Number of validators in the static registry.
*/
int staticSize();
/**
* Number of validators in the dynamic registry
*/
int dynamicSize();
/**
* Maximum number of entries to store in the dynamic registry
*/
int getMaximumCacheSize();
/**
* Purges the cache (removes validators from the dynamic cache)
*/
void purge();
/**
* Whether the given {@link Validator} is stored in the static cache
*
* @param type the data type
* @return <tt>true</tt> if in static cache, <tt>false</tt> if not
*/
boolean isStatic(DataType type);
/**
* Whether the given {@link Validator} is stored in the dynamic cache
*
* @param type the data type
* @return <tt>true</tt> if in dynamic cache, <tt>false</tt> if not
*/
boolean isDynamic(DataType type);
/**
* Cleanup the cache (purging stale entries)
*/
void cleanUp();
}
|
ValidatorRegistry
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/TypedAttribute.java
|
{
"start": 441,
"end": 1185
}
|
class ____ extends Attribute {
private final DataType dataType;
protected TypedAttribute(
Source source,
String name,
DataType dataType,
String qualifier,
Nullability nullability,
NameId id,
boolean synthetic
) {
super(source, name, qualifier, nullability, id, synthetic);
this.dataType = dataType;
}
@Override
public DataType dataType() {
return dataType;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), dataType);
}
@Override
public boolean equals(Object obj) {
return super.equals(obj) && Objects.equals(dataType, ((TypedAttribute) obj).dataType);
}
}
|
TypedAttribute
|
java
|
apache__thrift
|
lib/javame/src/org/apache/thrift/protocol/TBinaryProtocol.java
|
{
"start": 1315,
"end": 8648
}
|
class ____ implements TProtocolFactory {
protected boolean strictRead_ = false;
protected boolean strictWrite_ = true;
public Factory() {
this(false, true);
}
public Factory(boolean strictRead, boolean strictWrite) {
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
public TProtocol getProtocol(TTransport trans) {
return new TBinaryProtocol(trans, strictRead_, strictWrite_);
}
}
/**
* Constructor
*/
public TBinaryProtocol(TTransport trans) {
this(trans, false, true);
}
public TBinaryProtocol(TTransport trans, boolean strictRead, boolean strictWrite) {
super(trans);
strictRead_ = strictRead;
strictWrite_ = strictWrite;
}
public void writeMessageBegin(TMessage message) throws TException {
if (strictWrite_) {
int version = VERSION_1 | message.type;
writeI32(version);
writeString(message.name);
writeI32(message.seqid);
} else {
writeString(message.name);
writeByte(message.type);
writeI32(message.seqid);
}
}
public void writeMessageEnd() {}
public void writeStructBegin(TStruct struct) {}
public void writeStructEnd() {}
public void writeFieldBegin(TField field) throws TException {
writeByte(field.type);
writeI16(field.id);
}
public void writeFieldEnd() {}
public void writeFieldStop() throws TException {
writeByte(TType.STOP);
}
public void writeMapBegin(TMap map) throws TException {
writeByte(map.keyType);
writeByte(map.valueType);
writeI32(map.size);
}
public void writeMapEnd() {}
public void writeListBegin(TList list) throws TException {
writeByte(list.elemType);
writeI32(list.size);
}
public void writeListEnd() {}
public void writeSetBegin(TSet set) throws TException {
writeByte(set.elemType);
writeI32(set.size);
}
public void writeSetEnd() {}
public void writeBool(boolean b) throws TException {
writeByte(b ? (byte)1 : (byte)0);
}
private byte [] bout = new byte[1];
public void writeByte(byte b) throws TException {
bout[0] = b;
trans_.write(bout, 0, 1);
}
private byte[] i16out = new byte[2];
public void writeI16(short i16) throws TException {
i16out[0] = (byte)(0xff & (i16 >> 8));
i16out[1] = (byte)(0xff & (i16));
trans_.write(i16out, 0, 2);
}
private byte[] i32out = new byte[4];
public void writeI32(int i32) throws TException {
i32out[0] = (byte)(0xff & (i32 >> 24));
i32out[1] = (byte)(0xff & (i32 >> 16));
i32out[2] = (byte)(0xff & (i32 >> 8));
i32out[3] = (byte)(0xff & (i32));
trans_.write(i32out, 0, 4);
}
private byte[] i64out = new byte[8];
public void writeI64(long i64) throws TException {
i64out[0] = (byte)(0xff & (i64 >> 56));
i64out[1] = (byte)(0xff & (i64 >> 48));
i64out[2] = (byte)(0xff & (i64 >> 40));
i64out[3] = (byte)(0xff & (i64 >> 32));
i64out[4] = (byte)(0xff & (i64 >> 24));
i64out[5] = (byte)(0xff & (i64 >> 16));
i64out[6] = (byte)(0xff & (i64 >> 8));
i64out[7] = (byte)(0xff & (i64));
trans_.write(i64out, 0, 8);
}
public void writeDouble(double dub) throws TException {
writeI64(Double.doubleToLongBits(dub));
}
public void writeString(String str) throws TException {
try {
byte[] dat = str.getBytes("UTF-8");
writeI32(dat.length);
trans_.write(dat, 0, dat.length);
} catch (UnsupportedEncodingException uex) {
throw new TException("JVM DOES NOT SUPPORT UTF-8");
}
}
public void writeBinary(byte[] bin) throws TException {
writeI32(bin.length);
trans_.write(bin, 0, bin.length);
}
/**
* Reading methods.
*/
public TMessage readMessageBegin() throws TException {
TMessage message = new TMessage();
int size = readI32();
if (size < 0) {
int version = size & VERSION_MASK;
if (version != VERSION_1) {
throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in readMessageBegin");
}
message.type = (byte)(size & 0x000000ff);
message.name = readString();
message.seqid = readI32();
} else {
if (strictRead_) {
throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?");
}
message.name = readStringBody(size);
message.type = readByte();
message.seqid = readI32();
}
return message;
}
public void readMessageEnd() {}
public TStruct readStructBegin() {
return new TStruct();
}
public void readStructEnd() {}
public TField readFieldBegin() throws TException {
TField field = new TField();
field.type = readByte();
if (field.type != TType.STOP) {
field.id = readI16();
}
return field;
}
public void readFieldEnd() {}
public TMap readMapBegin() throws TException {
TMap map = new TMap();
map.keyType = readByte();
map.valueType = readByte();
map.size = readI32();
return map;
}
public void readMapEnd() {}
public TList readListBegin() throws TException {
TList list = new TList();
list.elemType = readByte();
list.size = readI32();
return list;
}
public void readListEnd() {}
public TSet readSetBegin() throws TException {
TSet set = new TSet();
set.elemType = readByte();
set.size = readI32();
return set;
}
public void readSetEnd() {}
public boolean readBool() throws TException {
return (readByte() == 1);
}
private byte[] bin = new byte[1];
public byte readByte() throws TException {
readAll(bin, 0, 1);
return bin[0];
}
private byte[] i16rd = new byte[2];
public short readI16() throws TException {
readAll(i16rd, 0, 2);
return
(short)
(((i16rd[0] & 0xff) << 8) |
((i16rd[1] & 0xff)));
}
private byte[] i32rd = new byte[4];
public int readI32() throws TException {
readAll(i32rd, 0, 4);
return
((i32rd[0] & 0xff) << 24) |
((i32rd[1] & 0xff) << 16) |
((i32rd[2] & 0xff) << 8) |
((i32rd[3] & 0xff));
}
private byte[] i64rd = new byte[8];
public long readI64() throws TException {
readAll(i64rd, 0, 8);
return
((long)(i64rd[0] & 0xff) << 56) |
((long)(i64rd[1] & 0xff) << 48) |
((long)(i64rd[2] & 0xff) << 40) |
((long)(i64rd[3] & 0xff) << 32) |
((long)(i64rd[4] & 0xff) << 24) |
((long)(i64rd[5] & 0xff) << 16) |
((long)(i64rd[6] & 0xff) << 8) |
((long)(i64rd[7] & 0xff));
}
public double readDouble() throws TException {
return Double.longBitsToDouble(readI64());
}
public String readString() throws TException {
int size = readI32();
return readStringBody(size);
}
public String readStringBody(int size) throws TException {
try {
byte[] buf = new byte[size];
trans_.readAll(buf, 0, size);
return new String(buf, "UTF-8");
} catch (UnsupportedEncodingException uex) {
throw new TException("JVM DOES NOT SUPPORT UTF-8");
}
}
public byte[] readBinary() throws TException {
int size = readI32();
byte[] buf = new byte[size];
trans_.readAll(buf, 0, size);
return buf;
}
private int readAll(byte[] buf, int off, int len) throws TException {
return trans_.readAll(buf, off, len);
}
}
|
Factory
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedRunnableTests.java
|
{
"start": 757,
"end": 1957
}
|
class ____ extends ESTestCase {
// test unit conversion with a controlled clock
public void testGetAgeInMillis() throws Exception {
AtomicLong time = new AtomicLong();
PrioritizedRunnable runnable = new PrioritizedRunnable(Priority.NORMAL, time::get) {
@Override
public void run() {}
};
assertEquals(0, runnable.getAgeInMillis());
int milliseconds = randomIntBetween(1, 256);
time.addAndGet(TimeUnit.NANOSECONDS.convert(milliseconds, TimeUnit.MILLISECONDS));
assertEquals(milliseconds, runnable.getAgeInMillis());
}
// test age advances with System#nanoTime
public void testGetAgeInMillisWithRealClock() throws InterruptedException {
PrioritizedRunnable runnable = new PrioritizedRunnable(Priority.NORMAL) {
@Override
public void run() {}
};
long elapsed = spinForAtLeastOneMillisecond();
// creation happened before start, so age will be at least as
// large as elapsed
assertThat(runnable.getAgeInMillis(), greaterThanOrEqualTo(TimeUnit.MILLISECONDS.convert(elapsed, TimeUnit.NANOSECONDS)));
}
}
|
PrioritizedRunnableTests
|
java
|
apache__logging-log4j2
|
log4j-1.2-api/src/main/java/org/apache/log4j/spi/LoggingEvent.java
|
{
"start": 1231,
"end": 1889
}
|
class ____ {
/**
* Returns the time when the application started, in milliseconds
* elapsed since 01.01.1970.
* @return the JVM start time.
*/
public static long getStartTime() {
return LogEventAdapter.getJvmStartTime();
}
/**
* The number of milliseconds elapsed from 1/1/1970 until logging event was created.
*/
public final long timeStamp;
/**
* Constructs a new instance.
*/
public LoggingEvent() {
timeStamp = System.currentTimeMillis();
}
/**
* Create new instance.
*
* @since 1.2.15
* @param fqnOfCategoryClass Fully qualified
|
LoggingEvent
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/bootstrap/Elasticsearch.java
|
{
"start": 3553,
"end": 3585
}
|
class ____ elasticsearch.
*/
|
starts
|
java
|
apache__camel
|
components/camel-smb/src/test/java/org/apache/camel/component/smb/FromSmbRemoteFileFilterIT.java
|
{
"start": 1136,
"end": 2541
}
|
class ____ extends SmbServerTestSupport {
@BindToRegistry("myFilter")
private final MyFileFilter<Object> filter = new MyFileFilter<>();
protected String getSmbUrl() {
return String.format(
"smb:%s/%s/myfilter?username=%s&password=%s&searchPattern=*&filter=#myFilter&initialDelay=3000",
service.address(), service.shareName(), service.userName(), service.password());
}
@Override
public void doPostSetup() throws Exception {
prepareSmbServer();
}
@Test
public void testSmbFilter() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(2);
mock.expectedBodiesReceivedInAnyOrder("Report 1", "Report 2");
mock.assertIsSatisfied();
}
private void prepareSmbServer() {
// create files on the SMB server
sendFile(getSmbUrl(), "Hello World", "hello.txt");
sendFile(getSmbUrl(), "Report 1", "report1.txt");
sendFile(getSmbUrl(), "Bye World", "bye.txt");
sendFile(getSmbUrl(), "Report 2", "report2.txt");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(getSmbUrl()).convertBodyTo(String.class).to("mock:result");
}
};
}
public static
|
FromSmbRemoteFileFilterIT
|
java
|
quarkusio__quarkus
|
extensions/smallrye-reactive-messaging-rabbitmq/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/rabbitmq/deployment/RabbitMQDevServicesBuildTimeConfig.java
|
{
"start": 469,
"end": 1280
}
|
interface ____ {
/**
* Type of exchange: direct, topic, headers, fanout, etc.
*/
@WithDefault("direct")
String type();
/**
* Should the exchange be deleted when all queues are finished using it?
*/
@WithDefault("false")
Boolean autoDelete();
/**
* Should the exchange remain after restarts?
*/
@WithDefault("false")
Boolean durable();
/**
* What virtual host should the exchange be associated with?
*/
@WithDefault("/")
String vhost();
/**
* Extra arguments for the exchange definition.
*/
@ConfigDocMapKey("argument-name")
Map<String, String> arguments();
}
@ConfigGroup
public
|
Exchange
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openshiftai/embeddings/OpenShiftAiEmbeddingsModel.java
|
{
"start": 1271,
"end": 3558
}
|
class ____ extends OpenShiftAiModel {
public OpenShiftAiEmbeddingsModel(
String inferenceEntityId,
TaskType taskType,
String service,
Map<String, Object> serviceSettings,
ChunkingSettings chunkingSettings,
Map<String, Object> secrets,
ConfigurationParseContext context
) {
this(
inferenceEntityId,
taskType,
service,
OpenShiftAiEmbeddingsServiceSettings.fromMap(serviceSettings, context),
chunkingSettings,
DefaultSecretSettings.fromMap(secrets)
);
}
public OpenShiftAiEmbeddingsModel(OpenShiftAiEmbeddingsModel model, OpenShiftAiEmbeddingsServiceSettings serviceSettings) {
super(model, serviceSettings);
}
/**
* Constructor for creating an OpenShiftAiEmbeddingsModel with specified parameters.
*
* @param inferenceEntityId the unique identifier for the inference entity
* @param taskType the type of task this model is designed for
* @param service the name of the inference service
* @param serviceSettings the settings for the inference service, specific to embeddings
* @param chunkingSettings the chunking settings for processing input data
* @param secrets the secret settings for the model, such as API keys or tokens
*/
public OpenShiftAiEmbeddingsModel(
String inferenceEntityId,
TaskType taskType,
String service,
OpenShiftAiEmbeddingsServiceSettings serviceSettings,
ChunkingSettings chunkingSettings,
SecretSettings secrets
) {
super(
new ModelConfigurations(inferenceEntityId, taskType, service, serviceSettings, EmptyTaskSettings.INSTANCE, chunkingSettings),
new ModelSecrets(secrets)
);
}
@Override
public OpenShiftAiEmbeddingsServiceSettings getServiceSettings() {
return (OpenShiftAiEmbeddingsServiceSettings) super.getServiceSettings();
}
@Override
public ExecutableAction accept(OpenShiftAiActionVisitor creator, Map<String, Object> taskSettings) {
// Embeddings models do not have task settings, so we ignore the taskSettings parameter.
return creator.create(this);
}
}
|
OpenShiftAiEmbeddingsModel
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/Variable.java
|
{
"start": 1212,
"end": 1296
}
|
interface ____ {
/**
* Name of variable
*/
String value();
}
|
Variable
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/search/index/HNSWVectorOptionalArgs.java
|
{
"start": 781,
"end": 1994
}
|
interface ____ extends FieldIndex {
/**
* Defines initial vector capacity.
*
* @param value initial vector capacity
* @return vector options
*/
HNSWVectorOptionalArgs initialCapacity(int value);
/**
* Defines number of maximum allowed outgoing edges for each node.
*
* @param value number of maximum allowed outgoing edges
* @return vector options
*/
HNSWVectorOptionalArgs m(int value);
/**
* Defines number of maximum allowed potential outgoing edges candidates for each node.
*
* @param value number of maximum allowed potential outgoing edges
* @return vector options
*/
HNSWVectorOptionalArgs efConstruction(int value);
/**
* Defines number of maximum top candidates to hold during the KNN search.
*
* @param value number of maximum top candidates
* @return vector options
*/
HNSWVectorOptionalArgs efRuntime(int value);
/**
* Defines relative factor that sets the boundaries in which a range query may search for candidates
*
* @param value relative factor
* @return
*/
HNSWVectorOptionalArgs epsilon(double value);
}
|
HNSWVectorOptionalArgs
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java
|
{
"start": 5735,
"end": 6148
}
|
class ____ {
final int i;
public IntValue(int i) {
this.i = i;
}
@javax.annotation.CheckReturnValue
public IntValue increment() {
return new IntValue(i + 1);
}
public void increment2() {
// BUG: Diagnostic contains:
this.increment();
}
public void increment3() {
// BUG: Diagnostic contains:
increment();
}
}
private static
|
IntValue
|
java
|
spring-projects__spring-security
|
crypto/src/main/java/org/springframework/security/crypto/encrypt/RsaRawEncryptor.java
|
{
"start": 1127,
"end": 5226
}
|
class ____ implements BytesEncryptor, TextEncryptor, RsaKeyHolder {
private static final String DEFAULT_ENCODING = "UTF-8";
private RsaAlgorithm algorithm = RsaAlgorithm.DEFAULT;
private Charset charset;
private RSAPublicKey publicKey;
private @Nullable RSAPrivateKey privateKey;
private Charset defaultCharset;
public RsaRawEncryptor(RsaAlgorithm algorithm) {
this(RsaKeyHelper.generateKeyPair(), algorithm);
}
public RsaRawEncryptor() {
this(RsaKeyHelper.generateKeyPair());
}
public RsaRawEncryptor(KeyPair keyPair, RsaAlgorithm algorithm) {
this(DEFAULT_ENCODING, keyPair.getPublic(), keyPair.getPrivate(), algorithm);
}
public RsaRawEncryptor(KeyPair keyPair) {
this(DEFAULT_ENCODING, keyPair.getPublic(), keyPair.getPrivate());
}
public RsaRawEncryptor(String pemData) {
this(RsaKeyHelper.parseKeyPair(pemData));
}
public RsaRawEncryptor(PublicKey publicKey) {
this(DEFAULT_ENCODING, publicKey, null);
}
public RsaRawEncryptor(String encoding, PublicKey publicKey, @Nullable PrivateKey privateKey) {
this(encoding, publicKey, privateKey, RsaAlgorithm.DEFAULT);
}
public RsaRawEncryptor(String encoding, PublicKey publicKey, @Nullable PrivateKey privateKey,
RsaAlgorithm algorithm) {
this.charset = Charset.forName(encoding);
this.publicKey = (RSAPublicKey) publicKey;
this.privateKey = (RSAPrivateKey) privateKey;
this.defaultCharset = Charset.forName(DEFAULT_ENCODING);
this.algorithm = algorithm;
}
@Override
public String getPublicKey() {
return RsaKeyHelper.encodePublicKey(this.publicKey, "application");
}
@Override
public String encrypt(String text) {
return new String(Base64.getEncoder().encode(encrypt(text.getBytes(this.charset))), this.defaultCharset);
}
@Override
public String decrypt(String encryptedText) {
if (this.privateKey == null) {
throw new IllegalStateException("Private key must be provided for decryption");
}
return new String(decrypt(Base64.getDecoder().decode(encryptedText.getBytes(this.defaultCharset))),
this.charset);
}
@Override
public byte[] encrypt(byte[] byteArray) {
return encrypt(byteArray, this.publicKey, this.algorithm);
}
@Override
public byte[] decrypt(byte[] encryptedByteArray) {
return decrypt(encryptedByteArray, this.privateKey, this.algorithm);
}
private static byte[] encrypt(byte[] text, PublicKey key, RsaAlgorithm alg) {
ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
try {
final Cipher cipher = Cipher.getInstance(alg.getJceName());
int limit = Math.min(text.length, alg.getMaxLength());
int pos = 0;
while (pos < text.length) {
cipher.init(Cipher.ENCRYPT_MODE, key);
cipher.update(text, pos, limit);
pos += limit;
limit = Math.min(text.length - pos, alg.getMaxLength());
byte[] buffer = cipher.doFinal();
output.write(buffer, 0, buffer.length);
}
return output.toByteArray();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot encrypt", ex);
}
}
private static byte[] decrypt(byte[] text, @Nullable RSAPrivateKey key, RsaAlgorithm alg) {
ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
try {
final Cipher cipher = Cipher.getInstance(alg.getJceName());
int maxLength = getByteLength(key);
int pos = 0;
while (pos < text.length) {
int limit = Math.min(text.length - pos, maxLength);
cipher.init(Cipher.DECRYPT_MODE, key);
cipher.update(text, pos, limit);
pos += limit;
byte[] buffer = cipher.doFinal();
output.write(buffer, 0, buffer.length);
}
return output.toByteArray();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot decrypt", ex);
}
}
// copied from sun.security.rsa.RSACore.getByteLength(java.math.BigInteger)
public static int getByteLength(@Nullable RSAKey key) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
int n = key.getModulus().bitLength();
return (n + 7) >> 3;
}
}
|
RsaRawEncryptor
|
java
|
spring-projects__spring-boot
|
integration-test/spring-boot-sni-integration-tests/spring-boot-sni-client-app/src/main/java/org/springframework/boot/sni/client/SniClientApplication.java
|
{
"start": 1277,
"end": 3137
}
|
class ____ {
public static void main(String[] args) {
new SpringApplicationBuilder(SniClientApplication.class)
.web(WebApplicationType.NONE).run(args);
}
@Bean
public RestClient restClient(RestClient.Builder restClientBuilder, RestClientSsl ssl) {
return restClientBuilder.apply(ssl.fromBundle("server")).build();
}
@Bean
public CommandLineRunner commandLineRunner(RestClient client) {
return ((args) -> {
for (String hostname : args) {
callServer(client, hostname);
callActuator(client, hostname);
}
});
}
private static void callServer(RestClient client, String hostname) {
String url = "https://" + hostname + ":8443/";
System.out.println(">>>>>> Calling server at '" + url + "'");
try {
ResponseEntity<String> response = client.get().uri(url).retrieve().toEntity(String.class);
System.out.println(">>>>>> Server response status code is '" + response.getStatusCode() + "'");
System.out.println(">>>>>> Server response body is '" + response + "'");
} catch (Exception ex) {
System.out.println(">>>>>> Exception thrown calling server at '" + url + "': " + ex.getMessage());
ex.printStackTrace();
}
}
private static void callActuator(RestClient client, String hostname) {
String url = "https://" + hostname + ":8444/actuator/health";
System.out.println(">>>>>> Calling server actuator at '" + url + "'");
try {
ResponseEntity<String> response = client.get().uri(url).retrieve().toEntity(String.class);
System.out.println(">>>>>> Server actuator response status code is '" + response.getStatusCode() + "'");
System.out.println(">>>>>> Server actuator response body is '" + response + "'");
} catch (Exception ex) {
System.out.println(">>>>>> Exception thrown calling server actuator at '" + url + "': " + ex.getMessage());
ex.printStackTrace();
}
}
}
|
SniClientApplication
|
java
|
processing__processing4
|
app/src/processing/app/syntax/InputHandler.java
|
{
"start": 31906,
"end": 34825
}
|
class ____ implements ActionListener,
InputHandler.NonRepeatable {
public void actionPerformed(ActionEvent evt) {
JEditTextArea textArea = getTextArea(evt);
String str = evt.getActionCommand();
int repeatCount = textArea.getInputHandler().getRepeatCount();
if (textArea.isEditable()) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < repeatCount; i++)
sb.append(str);
if (Preferences.getBoolean("editor.completion.auto_close") &&
hasBracketsAndQuotes(str)) {
matchBracketsAndQuotes(str, evt, textArea, sb);
} else {
textArea.overwriteSetSelectedText(sb.toString());
}
} else {
textArea.getToolkit().beep();
}
}
private void matchBracketsAndQuotes(String str, ActionEvent evt,
JEditTextArea ta, StringBuilder sb) {
sb.append(bracketsAndQuotesMap.get(str));
ta.overwriteSetSelectedText(sb.toString());
InputHandler.PREV_CHAR.actionPerformed(evt);
}
private boolean hasBracketsAndQuotes(String str) {
for (String item : bracketsAndQuotesMap.keys()) {
if (str.equals(item)) {
return true;
}
}
return false;
}
}
/**
* Locates the start of the word at the specified position.
* Moved from TextUtilities.java [fry 121210].
* @param line The text
* @param pos The position
*/
public static int findWordStart(String line, int pos, String noWordSep) {
char ch = line.charAt(pos - 1);
if (noWordSep == null) {
noWordSep = "";
}
boolean selectNoLetter =
!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1;
int wordStart = 0;
for (int i = pos - 1; i >= 0; i--) {
ch = line.charAt(i);
if (selectNoLetter ^ (!Character.isLetterOrDigit(ch) &&
noWordSep.indexOf(ch) == -1)) {
wordStart = i + 1;
break;
}
}
return wordStart;
}
/**
* Locates the end of the word at the specified position.
* Moved from TextUtilities.java [fry 121210].
* @param line The text
* @param pos The position
*/
public static int findWordEnd(String line, int pos, String noWordSep) {
char ch = line.charAt(pos);
if (noWordSep == null) {
noWordSep = "";
}
boolean selectNoLetter =
!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1;
int wordEnd = line.length();
for (int i = pos; i < line.length(); i++) {
ch = line.charAt(i);
if (selectNoLetter ^
(!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1)) {
wordEnd = i;
break;
}
}
return wordEnd;
}
/**
* Called when input method support committed a character.
*/
public void handleInputMethodCommit() {
}
}
|
insert_char
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/VarianceStates.java
|
{
"start": 711,
"end": 785
}
|
class ____ {
private VarianceStates() {}
static final
|
VarianceStates
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
|
{
"start": 36920,
"end": 38093
}
|
class ____ implements Comparable<CacheOperationCacheKey> {
private final CacheOperation cacheOperation;
private final AnnotatedElementKey methodCacheKey;
private CacheOperationCacheKey(CacheOperation cacheOperation, Method method, Class<?> targetClass) {
this.cacheOperation = cacheOperation;
this.methodCacheKey = new AnnotatedElementKey(method, targetClass);
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof CacheOperationCacheKey that &&
this.cacheOperation.equals(that.cacheOperation) &&
this.methodCacheKey.equals(that.methodCacheKey)));
}
@Override
public int hashCode() {
return (this.cacheOperation.hashCode() * 31 + this.methodCacheKey.hashCode());
}
@Override
public String toString() {
return this.cacheOperation + " on " + this.methodCacheKey;
}
@Override
public int compareTo(CacheOperationCacheKey other) {
int result = this.cacheOperation.getName().compareTo(other.cacheOperation.getName());
if (result == 0) {
result = this.methodCacheKey.compareTo(other.methodCacheKey);
}
return result;
}
}
private
|
CacheOperationCacheKey
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/scheduling/SchedulingAwareRunnable.java
|
{
"start": 1623,
"end": 2500
}
|
interface ____.
* <p>The default implementation returns {@code false}, as of 6.1.
*/
default boolean isLongLived() {
return false;
}
/**
* Return a qualifier associated with this Runnable.
* <p>The default implementation returns {@code null}.
* <p>May be used for custom purposes depending on the scheduler implementation.
* {@link org.springframework.scheduling.config.TaskSchedulerRouter} introspects
* this qualifier in order to determine the target scheduler to be used
* for a given Runnable, matching the qualifier value (or the bean name)
* of a specific {@link org.springframework.scheduling.TaskScheduler} or
* {@link java.util.concurrent.ScheduledExecutorService} bean definition.
* @since 6.1
* @see org.springframework.scheduling.annotation.Scheduled#scheduler()
*/
default @Nullable String getQualifier() {
return null;
}
}
|
overall
|
java
|
grpc__grpc-java
|
istio-interop-testing/src/test/java/io/grpc/testing/istio/EchoTestServerTest.java
|
{
"start": 2009,
"end": 16149
}
|
class ____ {
private static final String[] EXPECTED_KEY_SET = {
"--server_first", "--forwarding-address",
"--bind_ip", "--istio-version", "--bind_localhost", "--grpc", "--tls",
"--cluster", "--key", "--tcp", "--crt", "--metrics", "--port", "--version"
};
private static final String TEST_ARGS =
"--metrics=15014 --cluster=\"cluster-0\" --port=\"18080\" --grpc=\"17070\" --port=\"18085\""
+ " --tcp=\"19090\" --port=\"18443\" --tls=18443 --tcp=\"16060\" --server_first=16060"
+ " --tcp=\"19091\" --tcp=\"16061\" --server_first=16061 --port=\"18081\""
+ " --grpc=\"17071\" --port=\"19443\" --tls=19443 --port=\"18082\" --bind_ip=18082"
+ " --port=\"18084\" --bind_localhost=18084 --tcp=\"19092\" --port=\"18083\""
+ " --port=\"8080\" --port=\"3333\" --version=\"v1\" --istio-version=3 --crt=/cert.crt"
+ " --key=/cert.key --forwarding-address=192.168.1.10:7072";
private static final String TEST_ARGS_PORTS =
"--metrics=15014 --cluster=\"cluster-0\" --port=\"18080\" --grpc=17070 --port=18085"
+ " --tcp=\"19090\" --port=\"18443\" --tls=18443 --tcp=16060 --server_first=16060"
+ " --tcp=\"19091\" --tcp=\"16061\" --server_first=16061 --port=\"18081\""
+ " --grpc=\"17071\" --port=\"19443\" --tls=\"19443\" --port=\"18082\" --bind_ip=18082"
+ " --port=\"18084\" --bind_localhost=18084 --tcp=\"19092\" --port=\"18083\""
+ " --port=\"8080\" --port=3333 --version=\"v1\" --istio-version=3 --crt=/cert.crt"
+ " --key=/cert.key --xds-grpc-server=12034 --xds-grpc-server=\"34012\"";
@Test
public void preprocessArgsTest() {
String[] splitArgs = TEST_ARGS.split(" ");
Map<String, List<String>> processedArgs = EchoTestServer.preprocessArgs(splitArgs);
assertEquals(processedArgs.keySet(), ImmutableSet.copyOf(EXPECTED_KEY_SET));
assertEquals(processedArgs.get("--server_first"), ImmutableList.of("16060", "16061"));
assertEquals(processedArgs.get("--bind_ip"), ImmutableList.of("18082"));
assertEquals(processedArgs.get("--bind_localhost"), ImmutableList.of("18084"));
assertEquals(processedArgs.get("--grpc"), ImmutableList.of("\"17070\"", "\"17071\""));
assertEquals(processedArgs.get("--tls"), ImmutableList.of("18443", "19443"));
assertEquals(processedArgs.get("--cluster"), ImmutableList.of("\"cluster-0\""));
assertEquals(processedArgs.get("--key"), ImmutableList.of("/cert.key"));
assertEquals(processedArgs.get("--tcp"), ImmutableList.of("\"19090\"", "\"16060\"",
"\"19091\"","\"16061\"","\"19092\""));
assertEquals(processedArgs.get("--istio-version"), ImmutableList.of("3"));
assertEquals(processedArgs.get("--crt"), ImmutableList.of("/cert.crt"));
assertEquals(processedArgs.get("--metrics"), ImmutableList.of("15014"));
assertEquals(ImmutableList.of("192.168.1.10:7072"), processedArgs.get("--forwarding-address"));
assertEquals(
processedArgs.get("--port"),
ImmutableList.of(
"\"18080\"",
"\"18085\"",
"\"18443\"",
"\"18081\"",
"\"19443\"",
"\"18082\"",
"\"18084\"",
"\"18083\"",
"\"8080\"",
"\"3333\""));
}
@Test
public void preprocessArgsPortsTest() {
String[] splitArgs = TEST_ARGS_PORTS.split(" ");
Map<String, List<String>> processedArgs = EchoTestServer.preprocessArgs(splitArgs);
Set<Integer> ports = EchoTestServer.getPorts(processedArgs, "--port");
assertThat(ports).containsExactly(18080, 8080, 18081, 18082, 19443, 18083, 18084, 18085,
3333, 18443);
ports = EchoTestServer.getPorts(processedArgs, "--grpc");
assertThat(ports).containsExactly(17070, 17071);
ports = EchoTestServer.getPorts(processedArgs, "--tls");
assertThat(ports).containsExactly(18443, 19443);
ports = EchoTestServer.getPorts(processedArgs, "--xds-grpc-server");
assertThat(ports).containsExactly(34012, 12034);
}
@Test
public void echoTest() throws IOException, InterruptedException {
EchoTestServer echoTestServer = new EchoTestServer();
echoTestServer.runServers(
"test-host",
ImmutableList.of(0, 0),
ImmutableList.of(),
ImmutableList.of(),
"0.0.0.0:7072",
null);
assertEquals(2, echoTestServer.servers.size());
int port = echoTestServer.servers.get(0).getPort();
assertNotEquals(0, port);
assertNotEquals(0, echoTestServer.servers.get(1).getPort());
ManagedChannelBuilder<?> channelBuilder =
Grpc.newChannelBuilderForAddress("localhost", port, InsecureChannelCredentials.create());
ManagedChannel channel = channelBuilder.build();
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("header1", Metadata.ASCII_STRING_MARSHALLER), "value1");
metadata.put(Metadata.Key.of("header2", Metadata.ASCII_STRING_MARSHALLER), "value2");
EchoTestServiceGrpc.EchoTestServiceBlockingStub stub =
EchoTestServiceGrpc.newBlockingStub(channel)
.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata));
EchoRequest echoRequest = EchoRequest.newBuilder()
.setMessage("test-message1")
.build();
EchoResponse echoResponse = stub.echo(echoRequest);
String echoMessage = echoResponse.getMessage();
Set<String> lines = ImmutableSet.copyOf(echoMessage.split("\n"));
assertThat(lines).contains("RequestHeader=header1:value1");
assertThat(lines).contains("RequestHeader=header2:value2");
assertThat(lines).contains("Echo=test-message1");
assertThat(lines).contains("Hostname=test-host");
assertThat(lines).contains("Host=localhost:" + port);
assertThat(lines).contains("StatusCode=200");
echoTestServer.stopServers();
echoTestServer.blockUntilShutdown();
}
static final int COUNT_OF_REQUESTS_TO_FORWARD = 60;
@Test
public void forwardEchoTest() throws IOException, InterruptedException {
EchoTestServer echoTestServer = new EchoTestServer();
echoTestServer.runServers(
"test-host",
ImmutableList.of(0, 0),
ImmutableList.of(),
ImmutableList.of(),
"0.0.0.0:7072",
null);
assertEquals(2, echoTestServer.servers.size());
int port1 = echoTestServer.servers.get(0).getPort();
int port2 = echoTestServer.servers.get(1).getPort();
ManagedChannelBuilder<?> channelBuilder =
Grpc.newChannelBuilderForAddress("localhost", port1, InsecureChannelCredentials.create());
ManagedChannel channel = channelBuilder.build();
ForwardEchoRequest forwardEchoRequest =
ForwardEchoRequest.newBuilder()
.setCount(COUNT_OF_REQUESTS_TO_FORWARD)
.setQps(100)
.setTimeoutMicros(5000_000L) // 5000 millis
.setUrl("grpc://localhost:" + port2)
.addHeaders(
Header.newBuilder().setKey("test-key1").setValue("test-value1").build())
.addHeaders(
Header.newBuilder().setKey("test-key2").setValue("test-value2").build())
.setMessage("forward-echo-test-message")
.build();
EchoTestServiceGrpc.EchoTestServiceBlockingStub stub =
EchoTestServiceGrpc.newBlockingStub(channel);
Instant start = Instant.now();
ForwardEchoResponse forwardEchoResponse = stub.forwardEcho(forwardEchoRequest);
Instant end = Instant.now();
List<String> outputs = forwardEchoResponse.getOutputList();
assertEquals(COUNT_OF_REQUESTS_TO_FORWARD, outputs.size());
for (int i = 0; i < COUNT_OF_REQUESTS_TO_FORWARD; i++) {
validateOutput(outputs.get(i), i);
}
long duration = Duration.between(start, end).toMillis();
assertThat(duration).isAtLeast(COUNT_OF_REQUESTS_TO_FORWARD * 10L);
echoTestServer.stopServers();
echoTestServer.blockUntilShutdown();
}
private static void validateOutput(String output, int i) {
List<String> content = Splitter.on('\n').splitToList(output);
assertThat(content.size()).isAtLeast(7); // see echo implementation
assertThat(content.get(0))
.isEqualTo(String.format("[%d] grpcecho.Echo(forward-echo-test-message)", i));
String prefix = "[" + i + " body] ";
assertThat(content).contains(prefix + "RequestHeader=x-request-id:" + i);
assertThat(content).contains(prefix + "RequestHeader=test-key1:test-value1");
assertThat(content).contains(prefix + "RequestHeader=test-key2:test-value2");
assertThat(content).contains(prefix + "Hostname=test-host");
assertThat(content).contains(prefix + "StatusCode=200");
}
@Test
public void nonGrpcForwardEchoTest() throws IOException, InterruptedException {
ForwardServiceForNonGrpcImpl forwardServiceForNonGrpc = new ForwardServiceForNonGrpcImpl();
forwardServiceForNonGrpc.receivedRequests = new ArrayList<>();
forwardServiceForNonGrpc.responsesToReturn = new ArrayList<>();
Server nonGrpcEchoServer =
EchoTestServer.runServer(
0, forwardServiceForNonGrpc.bindService(), InsecureServerCredentials.create(),
"", false);
int nonGrpcEchoServerPort = nonGrpcEchoServer.getPort();
EchoTestServer echoTestServer = new EchoTestServer();
echoTestServer.runServers(
"test-host",
ImmutableList.of(0),
ImmutableList.of(),
ImmutableList.of(),
"0.0.0.0:" + nonGrpcEchoServerPort,
null);
assertEquals(1, echoTestServer.servers.size());
int port1 = echoTestServer.servers.get(0).getPort();
ManagedChannelBuilder<?> channelBuilder =
Grpc.newChannelBuilderForAddress("localhost", port1, InsecureChannelCredentials.create());
ManagedChannel channel = channelBuilder.build();
EchoTestServiceGrpc.EchoTestServiceBlockingStub stub =
EchoTestServiceGrpc.newBlockingStub(channel);
forwardServiceForNonGrpc.responsesToReturn.add(
ForwardEchoResponse.newBuilder().addOutput("line 1").addOutput("line 2").build());
ForwardEchoRequest forwardEchoRequest =
ForwardEchoRequest.newBuilder()
.setCount(COUNT_OF_REQUESTS_TO_FORWARD)
.setQps(100)
.setTimeoutMicros(2000_000L) // 2000 millis
.setUrl("http://www.example.com") // non grpc protocol
.addHeaders(
Header.newBuilder().setKey("test-key1").setValue("test-value1").build())
.addHeaders(
Header.newBuilder().setKey("test-key2").setValue("test-value2").build())
.setMessage("non-grpc-forward-echo-test-message1")
.build();
ForwardEchoResponse forwardEchoResponse = stub.forwardEcho(forwardEchoRequest);
List<String> outputs = forwardEchoResponse.getOutputList();
assertEquals(2, outputs.size());
assertThat(outputs.get(0)).isEqualTo("line 1");
assertThat(outputs.get(1)).isEqualTo("line 2");
assertThat(forwardServiceForNonGrpc.receivedRequests).hasSize(1);
ForwardEchoRequest receivedRequest = forwardServiceForNonGrpc.receivedRequests.remove(0);
assertThat(receivedRequest.getUrl()).isEqualTo("http://www.example.com");
assertThat(receivedRequest.getMessage()).isEqualTo("non-grpc-forward-echo-test-message1");
assertThat(receivedRequest.getCount()).isEqualTo(COUNT_OF_REQUESTS_TO_FORWARD);
assertThat(receivedRequest.getQps()).isEqualTo(100);
forwardServiceForNonGrpc.responsesToReturn.add(
Status.UNIMPLEMENTED.asRuntimeException());
forwardEchoRequest =
ForwardEchoRequest.newBuilder()
.setCount(1)
.setQps(100)
.setTimeoutMicros(2000_000L) // 2000 millis
.setUrl("redis://192.168.1.1") // non grpc protocol
.addHeaders(
Header.newBuilder().setKey("test-key1").setValue("test-value1").build())
.setMessage("non-grpc-forward-echo-test-message2")
.build();
try {
ForwardEchoResponse unused = stub.forwardEcho(forwardEchoRequest);
fail("exception expected");
} catch (StatusRuntimeException e) {
assertThat(e.getStatus()).isEqualTo(Status.UNIMPLEMENTED);
}
assertThat(forwardServiceForNonGrpc.receivedRequests).hasSize(1);
receivedRequest = forwardServiceForNonGrpc.receivedRequests.remove(0);
assertThat(receivedRequest.getUrl()).isEqualTo("redis://192.168.1.1");
assertThat(receivedRequest.getMessage()).isEqualTo("non-grpc-forward-echo-test-message2");
assertThat(receivedRequest.getCount()).isEqualTo(1);
forwardServiceForNonGrpc.responsesToReturn.add(
ForwardEchoResponse.newBuilder().addOutput("line 3").build());
forwardEchoRequest =
ForwardEchoRequest.newBuilder()
.setCount(1)
.setQps(100)
.setTimeoutMicros(2000_000L) // 2000 millis
.setUrl("http2://192.168.1.1") // non grpc protocol
.addHeaders(
Header.newBuilder().setKey("test-key3").setValue("test-value3").build())
.setMessage("non-grpc-forward-echo-test-message3")
.build();
forwardEchoResponse = stub.forwardEcho(forwardEchoRequest);
outputs = forwardEchoResponse.getOutputList();
assertEquals(1, outputs.size());
assertThat(outputs.get(0)).isEqualTo("line 3");
assertThat(forwardServiceForNonGrpc.receivedRequests).hasSize(1);
receivedRequest = forwardServiceForNonGrpc.receivedRequests.remove(0);
assertThat(receivedRequest.getUrl()).isEqualTo("http2://192.168.1.1");
assertThat(receivedRequest.getMessage()).isEqualTo("non-grpc-forward-echo-test-message3");
List<Header> headers = receivedRequest.getHeadersList();
assertThat(headers).hasSize(1);
assertThat(headers.get(0).getKey()).isEqualTo("test-key3");
assertThat(headers.get(0).getValue()).isEqualTo("test-value3");
echoTestServer.stopServers();
echoTestServer.blockUntilShutdown();
nonGrpcEchoServer.shutdown();
nonGrpcEchoServer.awaitTermination(5, TimeUnit.SECONDS);
}
/**
* Emulate the Go Echo server that receives the non-grpc protocol requests.
*/
private static
|
EchoTestServerTest
|
java
|
apache__logging-log4j2
|
log4j-1.2-api/src/test/java/org/apache/log4j/MDCTestCase.java
|
{
"start": 1009,
"end": 1450
}
|
class ____ {
@BeforeEach
void setUp() {
MDC.clear();
}
@AfterEach
void tearDown() {
MDC.clear();
}
@Test
void testPut() {
MDC.put("key", "some value");
assertEquals("some value", MDC.get("key"));
assertEquals(1, MDC.getContext().size());
}
@Test
void testRemoveLastKey() {
MDC.put("key", "some value");
MDC.remove("key");
}
}
|
MDCTestCase
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/SqlResultSetMappingJpaAnnotation.java
|
{
"start": 608,
"end": 3044
}
|
class ____ implements SqlResultSetMapping {
private String name;
private jakarta.persistence.EntityResult[] entities;
private jakarta.persistence.ConstructorResult[] classes;
private jakarta.persistence.ColumnResult[] columns;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public SqlResultSetMappingJpaAnnotation(ModelsContext modelContext) {
this.entities = new jakarta.persistence.EntityResult[0];
this.classes = new jakarta.persistence.ConstructorResult[0];
this.columns = new jakarta.persistence.ColumnResult[0];
}
/**
* Used in creating annotation instances from JDK variant
*/
public SqlResultSetMappingJpaAnnotation(SqlResultSetMapping annotation, ModelsContext modelContext) {
this.name = annotation.name();
this.entities = extractJdkValue( annotation, JpaAnnotations.SQL_RESULT_SET_MAPPING, "entities", modelContext );
this.classes = extractJdkValue( annotation, JpaAnnotations.SQL_RESULT_SET_MAPPING, "classes", modelContext );
this.columns = extractJdkValue( annotation, JpaAnnotations.SQL_RESULT_SET_MAPPING, "columns", modelContext );
}
/**
* Used in creating annotation instances from Jandex variant
*/
public SqlResultSetMappingJpaAnnotation(
Map<String, Object> attributeValues,
ModelsContext modelContext) {
this.name = (String) attributeValues.get( "name" );
this.entities = (jakarta.persistence.EntityResult[]) attributeValues.get( "entities" );
this.classes = (jakarta.persistence.ConstructorResult[]) attributeValues.get( "classes" );
this.columns = (jakarta.persistence.ColumnResult[]) attributeValues.get( "columns" );
}
@Override
public Class<? extends Annotation> annotationType() {
return SqlResultSetMapping.class;
}
@Override
public String name() {
return name;
}
public void name(String value) {
this.name = value;
}
@Override
public jakarta.persistence.EntityResult[] entities() {
return entities;
}
public void entities(jakarta.persistence.EntityResult[] value) {
this.entities = value;
}
@Override
public jakarta.persistence.ConstructorResult[] classes() {
return classes;
}
public void classes(jakarta.persistence.ConstructorResult[] value) {
this.classes = value;
}
@Override
public jakarta.persistence.ColumnResult[] columns() {
return columns;
}
public void columns(jakarta.persistence.ColumnResult[] value) {
this.columns = value;
}
}
|
SqlResultSetMappingJpaAnnotation
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsResourceCalculator.java
|
{
"start": 1769,
"end": 2301
}
|
class ____ within a MapReduce job.
* However, it is important to note that instances of ResourceCalculatorProcessTree operate
* within the context of a MapReduce task. This presents a limitation:
* these instances do not have access to the ResourceHandlerModule,
* which is only initialized within the NodeManager process
* and not within individual containers where MapReduce tasks execute.
* As a result, the current implementation of ResourceCalculatorProcessTree is incompatible
* with the mapreduce.job.process-tree.
|
property
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/support/single/shard/TransportSingleShardAction.java
|
{
"start": 12340,
"end": 12447
}
|
class ____ gets built on each node. Holds the original request plus additional info.
*/
protected
|
that
|
java
|
alibaba__nacos
|
console/src/main/java/com/alibaba/nacos/console/paramcheck/ConsoleDefaultHttpParamExtractor.java
|
{
"start": 1019,
"end": 1943
}
|
class ____ extends AbstractHttpParamExtractor {
@Override
public List<ParamInfo> extractParam(HttpServletRequest request) {
ParamInfo paramInfo = new ParamInfo();
paramInfo.setNamespaceId(getAliasNamespaceId(request));
paramInfo.setNamespaceShowName(getAliasNamespaceShowName(request));
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
return paramInfos;
}
private String getAliasNamespaceId(HttpServletRequest request) {
String namespaceId = request.getParameter("namespaceId");
if (StringUtils.isBlank(namespaceId)) {
namespaceId = request.getParameter("customNamespaceId");
}
return namespaceId;
}
private String getAliasNamespaceShowName(HttpServletRequest request) {
return request.getParameter("namespaceName");
}
}
|
ConsoleDefaultHttpParamExtractor
|
java
|
quarkusio__quarkus
|
extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/NonApplicationRootPathBuildItem.java
|
{
"start": 17509,
"end": 17628
}
|
interface ____ using {@code https}.
*
* @param config the config
* @return {@code true} if the management
|
is
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldHaveBinaryContent_create_Test.java
|
{
"start": 995,
"end": 1792
}
|
class ____ {
@Test
void should_create_error_message() {
// GIVEN
InputStream actual = new ByteArrayInputStream(new byte[] { 1, 3 });
BinaryDiffResult diff = new BinaryDiffResult(1, 11, 3);
// WHEN
String errorMessage = shouldHaveBinaryContent(actual, diff).create(new TestDescription("TEST"));
// THEN
then(errorMessage).isEqualTo("[TEST] %n"
+ "InputStream%n"
+ " %s%n"
+ "does not have expected binary content at offset 1, expecting:%n"
+ " \"0xB\"%n"
+ "but was:%n"
+ " \"0x3\"",
actual);
}
}
|
ShouldHaveBinaryContent_create_Test
|
java
|
quarkusio__quarkus
|
extensions/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/OpenTelemetryAgroalDataSource.java
|
{
"start": 608,
"end": 1940
}
|
class ____ extends OpenTelemetryDataSource implements AgroalDataSource {
private final AgroalDataSource delegate;
public OpenTelemetryAgroalDataSource(AgroalDataSource delegate) {
super(delegate, Arc.container().instance(OpenTelemetry.class).get());
this.delegate = delegate;
}
@Override
public boolean isHealthy(boolean newConnection) throws SQLException {
return delegate.isHealthy(newConnection);
}
@Override
public AgroalDataSourceConfiguration getConfiguration() {
return delegate.getConfiguration();
}
@Override
public AgroalDataSourceMetrics getMetrics() {
return delegate.getMetrics();
}
@Override
public void flush(FlushMode mode) {
delegate.flush(mode);
}
@Override
public void setPoolInterceptors(Collection<? extends AgroalPoolInterceptor> interceptors) {
delegate.setPoolInterceptors(interceptors);
}
@Override
public List<AgroalPoolInterceptor> getPoolInterceptors() {
return delegate.getPoolInterceptors();
}
@Override
public ShardingKeyBuilder createShardingKeyBuilder() throws SQLException {
return delegate.createShardingKeyBuilder();
}
@Override
public void close() {
delegate.close();
}
}
|
OpenTelemetryAgroalDataSource
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyCustomSqlMutationsTest.java
|
{
"start": 1438,
"end": 4229
}
|
class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final User u1 = new User( "user1" );
final User u2 = new User( "user2" );
final Project p1 = new Project( "p1" );
p1.getMembers().add( u1 );
p1.getMembers().add( u2 );
final User u3 = new User( "user3" );
final Project p2 = new Project( "p2" );
p2.getMembers().add( u3 );
p2.getOrderedUsers().add( u2 );
p2.getOrderedUsers().add( u1 );
session.persist( u1 );
session.persist( u2 );
session.persist( u3 );
session.persist( p1 );
session.persist( p2 );
} );
}
@Test
public void testSQLDelete(SessionFactoryScope scope) {
final SQLStatementInspector inspector = scope.getCollectingStatementInspector();
scope.inTransaction( session -> {
final Project project = session.find( Project.class, "p1" );
project.getMembers().remove( project.getMembers().iterator().next() );
inspector.clear();
} );
assertThat( inspector.getSqlQueries() ).hasSize( 1 );
assertThat( inspector.getSqlQueries().get( 0 ) ).contains( "1=1" );
scope.inTransaction( session -> assertThat(
session.find( Project.class, "p1" ).getMembers()
).hasSize( 1 ) );
}
@Test
public void testSQLDeleteAll(SessionFactoryScope scope) {
final SQLStatementInspector inspector = scope.getCollectingStatementInspector();
scope.inTransaction( session -> {
final Project project = session.find( Project.class, "p2" );
project.getMembers().remove( project.getMembers().iterator().next() );
inspector.clear();
} );
assertThat( inspector.getSqlQueries() ).hasSize( 1 );
assertThat( inspector.getSqlQueries().get( 0 ) ).contains( "2=2" );
scope.inTransaction( session -> assertThat(
session.find( Project.class, "p2" ).getMembers()
).isEmpty() );
}
@Test
public void testSQLUpdate(SessionFactoryScope scope) {
final SQLStatementInspector inspector = scope.getCollectingStatementInspector();
scope.inTransaction( session -> {
final Project project = session.find( Project.class, "p2" );
assertThat( project.getOrderedUsers().stream().map( User::getName ) ).containsExactly( "user2", "user1" );
project.getOrderedUsers().sort( Comparator.comparing( User::getName ) );
inspector.clear();
} );
assertThat( inspector.getSqlQueries() ).hasSize( 4 );
assertThat( inspector.getSqlQueries().get( 0 ) ).contains( "3=3" );
assertThat( inspector.getSqlQueries().get( 1 ) ).contains( "3=3" );
scope.inTransaction( session -> {
final Project project = session.find( Project.class, "p2" );
assertThat( project.getOrderedUsers().stream().map( User::getName ) ).containsExactly( "user1", "user2" );
} );
}
@Entity( name = "Project" )
@Table( name = "t_project" )
public static
|
OneToManyCustomSqlMutationsTest
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/core/convert/support/ObjectToObjectConverter.java
|
{
"start": 3190,
"end": 8442
}
|
class ____ implements ConditionalGenericConverter {
// Cache for the latest to-method, static factory method, or factory constructor
// resolved on a given Class
private static final Map<Class<?>, Executable> conversionExecutableCache =
new ConcurrentReferenceHashMap<>(32);
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, Object.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return (sourceType.getType() != targetType.getType() &&
hasConversionMethodOrConstructor(targetType.getType(), sourceType.getType()));
}
@Override
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
Class<?> sourceClass = sourceType.getType();
Class<?> targetClass = targetType.getType();
Executable executable = getValidatedExecutable(targetClass, sourceClass);
try {
if (executable instanceof Method method) {
ReflectionUtils.makeAccessible(method);
if (!Modifier.isStatic(method.getModifiers())) {
return method.invoke(source);
}
else {
return method.invoke(null, source);
}
}
else if (executable instanceof Constructor<?> constructor) {
ReflectionUtils.makeAccessible(constructor);
return constructor.newInstance(source);
}
}
catch (InvocationTargetException ex) {
throw new ConversionFailedException(sourceType, targetType, source, ex.getTargetException());
}
catch (Throwable ex) {
throw new ConversionFailedException(sourceType, targetType, source, ex);
}
// If sourceClass is Number and targetClass is Integer, the following message should expand to:
// No toInteger() method exists on java.lang.Number, and no static valueOf/of/from(java.lang.Number)
// method or Integer(java.lang.Number) constructor exists on java.lang.Integer.
throw new IllegalStateException(String.format("No to%3$s() method exists on %1$s, " +
"and no static valueOf/of/from(%1$s) method or %3$s(%1$s) constructor exists on %2$s.",
sourceClass.getName(), targetClass.getName(), targetClass.getSimpleName()));
}
static boolean hasConversionMethodOrConstructor(Class<?> targetClass, Class<?> sourceClass) {
return (getValidatedExecutable(targetClass, sourceClass) != null);
}
private static @Nullable Executable getValidatedExecutable(Class<?> targetClass, Class<?> sourceClass) {
Executable executable = conversionExecutableCache.get(targetClass);
if (executable != null && isApplicable(executable, sourceClass)) {
return executable;
}
executable = determineToMethod(targetClass, sourceClass);
if (executable == null) {
executable = determineFactoryMethod(targetClass, sourceClass);
if (executable == null) {
executable = determineFactoryConstructor(targetClass, sourceClass);
if (executable == null) {
return null;
}
}
}
conversionExecutableCache.put(targetClass, executable);
return executable;
}
private static boolean isApplicable(Executable executable, Class<?> sourceClass) {
if (executable instanceof Method method) {
return (!Modifier.isStatic(method.getModifiers()) ?
ClassUtils.isAssignable(method.getDeclaringClass(), sourceClass) :
method.getParameterTypes()[0] == sourceClass);
}
else if (executable instanceof Constructor<?> constructor) {
return (constructor.getParameterTypes()[0] == sourceClass);
}
else {
return false;
}
}
private static @Nullable Method determineToMethod(Class<?> targetClass, Class<?> sourceClass) {
if (String.class == targetClass || String.class == sourceClass) {
// Do not accept a toString() method or any to methods on String itself
return null;
}
Method method = ClassUtils.getMethodIfAvailable(sourceClass, "to" + targetClass.getSimpleName());
return (method != null && !Modifier.isStatic(method.getModifiers()) &&
ClassUtils.isAssignable(targetClass, method.getReturnType()) ? method : null);
}
private static @Nullable Method determineFactoryMethod(Class<?> targetClass, Class<?> sourceClass) {
if (String.class == targetClass) {
// Do not accept the String.valueOf(Object) method
return null;
}
Method method = ClassUtils.getStaticMethod(targetClass, "valueOf", sourceClass);
if (method == null) {
method = ClassUtils.getStaticMethod(targetClass, "of", sourceClass);
if (method == null) {
method = ClassUtils.getStaticMethod(targetClass, "from", sourceClass);
}
}
return (method != null && areRelatedTypes(targetClass, method.getReturnType()) ? method : null);
}
/**
* Determine if the two types reside in the same type hierarchy (i.e., type 1
* is assignable to type 2 or vice versa).
* @since 5.3.21
* @see ClassUtils#isAssignable(Class, Class)
*/
private static boolean areRelatedTypes(Class<?> type1, Class<?> type2) {
return (ClassUtils.isAssignable(type1, type2) || ClassUtils.isAssignable(type2, type1));
}
private static @Nullable Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
}
|
ObjectToObjectConverter
|
java
|
google__guava
|
guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
|
{
"start": 7613,
"end": 7745
}
|
interface ____ {
static String create(String s) {
return checkNotNull(s);
}
}
private
|
InterfaceStaticMethodChecksNull
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/ListActionTaker.java
|
{
"start": 2522,
"end": 10100
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(
ListActionTaker.class);
private final Path path;
private final AbfsBlobClient abfsClient;
private final TracingContext tracingContext;
private final ExecutorService executorService;
private final AtomicBoolean producerThreadToBeStopped = new AtomicBoolean(
false);
/** Constructor.
*
* @param path the path to list recursively.
* @param abfsClient the AbfsBlobClient to use for listing.
* @param tracingContext the tracing context to use for listing.
*/
public ListActionTaker(Path path,
AbfsBlobClient abfsClient,
TracingContext tracingContext) {
this.path = path;
this.abfsClient = abfsClient;
this.tracingContext = tracingContext;
executorService = Executors.newFixedThreadPool(
getMaxConsumptionParallelism());
}
public AbfsBlobClient getAbfsClient() {
return abfsClient;
}
/** Get the maximum number of parallelism for consumption.
*
* @return the maximum number of parallelism for consumption.
*/
abstract int getMaxConsumptionParallelism();
/** Take action on a path.
*
* @param path the path to take action on.
* @return true if the action is successful.
* @throws AzureBlobFileSystemException if the action fails.
*/
abstract boolean takeAction(Path path) throws AzureBlobFileSystemException;
private boolean takeAction(List<Path> paths)
throws AzureBlobFileSystemException {
List<Future<Boolean>> futureList = new ArrayList<>();
for (Path path : paths) {
Future<Boolean> future = executorService.submit(() -> takeAction(path));
futureList.add(future);
}
AzureBlobFileSystemException executionException = null;
boolean actionResult = true;
for (Future<Boolean> future : futureList) {
try {
Boolean result = future.get();
if (!result) {
actionResult = false;
}
} catch (InterruptedException e) {
LOG.debug("Thread interrupted while taking action on path: {}",
path.toUri().getPath());
} catch (ExecutionException e) {
LOG.debug("Execution exception while taking action on path: {}",
path.toUri().getPath());
if (e.getCause() instanceof AzureBlobFileSystemException) {
executionException = (AzureBlobFileSystemException) e.getCause();
} else {
executionException =
new FileSystemOperationUnhandledException(executionException);
}
}
}
if (executionException != null) {
throw executionException;
}
return actionResult;
}
/**
* Spawns a producer thread that list the children of the path recursively and queue
* them in into {@link ListBlobQueue}. On the main thread, it dequeues the
* path and supply them to parallel thread for relevant action which is defined
* in {@link #takeAction(Path)}.
*
* @return true if the action is successful.
* @throws AzureBlobFileSystemException if the action fails.
*/
public boolean listRecursiveAndTakeAction()
throws AzureBlobFileSystemException {
AbfsConfiguration configuration = getAbfsClient().getAbfsConfiguration();
Thread producerThread = null;
try {
ListBlobQueue listBlobQueue = createListBlobQueue(configuration);
producerThread = new SubjectInheritingThread(() -> {
try {
produceConsumableList(listBlobQueue);
} catch (AzureBlobFileSystemException e) {
listBlobQueue.markProducerFailure(e);
}
});
producerThread.start();
while (!listBlobQueue.getIsCompleted()) {
List<Path> paths = listBlobQueue.consume();
if (paths == null) {
continue;
}
try {
boolean resultOnPartAction = takeAction(paths);
if (!resultOnPartAction) {
return false;
}
} catch (AzureBlobFileSystemException parallelConsumptionException) {
listBlobQueue.markConsumptionFailed();
throw parallelConsumptionException;
}
}
return true;
} finally {
if (producerThread != null) {
producerThreadToBeStopped.set(true);
}
executorService.shutdownNow();
}
}
/**
* Create a {@link ListBlobQueue} instance.
*
* @param configuration the configuration to use.
* @return the created {@link ListBlobQueue} instance.
* @throws InvalidConfigurationValueException if the configuration is invalid.
*/
@VisibleForTesting
protected ListBlobQueue createListBlobQueue(final AbfsConfiguration configuration)
throws InvalidConfigurationValueException {
return new ListBlobQueue(
configuration.getProducerQueueMaxSize(),
getMaxConsumptionParallelism(),
configuration.getListingMaxConsumptionLag()
);
}
/**
* Produce the consumable list of paths.
*
* @param listBlobQueue the {@link ListBlobQueue} to enqueue the paths.
* @throws AzureBlobFileSystemException if the listing fails.
*/
private void produceConsumableList(final ListBlobQueue listBlobQueue)
throws AzureBlobFileSystemException {
String continuationToken = null;
do {
continuationToken = listAndEnqueue(listBlobQueue, continuationToken);
} while (!producerThreadToBeStopped.get() && continuationToken != null
&& !listBlobQueue.getConsumptionFailed());
listBlobQueue.complete();
}
/**
* List the paths and enqueue them into the {@link ListBlobQueue}.
*
* @param listBlobQueue the {@link ListBlobQueue} to enqueue the paths.
* @param continuationToken the continuation token to use for listing.
* @return the continuation token for the next listing.
* @throws AzureBlobFileSystemException if the listing fails.
*/
@VisibleForTesting
protected String listAndEnqueue(final ListBlobQueue listBlobQueue,
String continuationToken) throws AzureBlobFileSystemException {
final int queueAvailableSizeForProduction = Math.min(
DEFAULT_AZURE_LIST_MAX_RESULTS,
listBlobQueue.availableSizeForProduction());
if (queueAvailableSizeForProduction == 0) {
return null;
}
final AbfsRestOperation op;
try {
op = getAbfsClient().listPath(path.toUri().getPath(),
true,
queueAvailableSizeForProduction, continuationToken,
tracingContext, null).getOp();
} catch (AzureBlobFileSystemException ex) {
throw ex;
} catch (IOException ex) {
throw new AbfsRestOperationException(-1, null,
"Unknown exception from listing: " + ex.getMessage(), ex);
}
ListResultSchema retrievedSchema = op.getResult().getListResultSchema();
if (retrievedSchema == null) {
return continuationToken;
}
continuationToken
= ((BlobListResultSchema) retrievedSchema).getNextMarker();
List<Path> paths = new ArrayList<>();
addPaths(paths, retrievedSchema);
listBlobQueue.enqueue(paths);
return continuationToken;
}
/**
* Add the paths from the retrieved schema to the list of paths.
*
* @param paths the list of paths to add to.
* @param retrievedSchema the retrieved schema.
*/
@VisibleForTesting
protected void addPaths(final List<Path> paths,
final ListResultSchema retrievedSchema) {
for (ListResultEntrySchema entry : retrievedSchema.paths()) {
Path entryPath = new Path(ROOT_PATH + entry.name());
if (!entryPath.equals(this.path)) {
paths.add(entryPath);
}
}
}
}
|
ListActionTaker
|
java
|
bumptech__glide
|
annotation/compiler/src/main/java/com/bumptech/glide/annotation/compiler/GlideAnnotationProcessor.java
|
{
"start": 5063,
"end": 6188
}
|
class ____.
* <li>If we wrote any {@code Indexer}s, return and wait for the next round.
* <li>If we didn't write any {@code Indexer}s and there is a {@code AppGlideModule}, write the
* {@code GeneratedAppGlideModule}. Once the {@code GeneratedAppGlideModule} is written, we
* expect to be finished. Any further generation of related classes will result in errors.
* </ol>
*/
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
processorUtil.process();
boolean newModulesWritten = libraryModuleProcessor.processModules(env);
boolean newExtensionWritten = extensionProcessor.processExtensions(env);
appModuleProcessor.processModules(set, env);
if (newExtensionWritten || newModulesWritten) {
if (isGeneratedAppGlideModuleWritten) {
throw new IllegalStateException("Cannot process annotations after writing AppGlideModule");
}
return false;
}
if (!isGeneratedAppGlideModuleWritten) {
isGeneratedAppGlideModuleWritten = appModuleProcessor.maybeWriteAppModule();
}
return false;
}
}
|
name
|
java
|
google__dagger
|
javatests/dagger/hilt/android/ViewModelWithBaseTest.java
|
{
"start": 2715,
"end": 2766
}
|
class ____ {
@Inject
Foo() {}
}
static
|
Foo
|
java
|
spring-projects__spring-boot
|
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/CompositeMeterRegistryAutoConfigurationTests.java
|
{
"start": 4176,
"end": 4441
}
|
class ____ {
@Bean
MeterRegistry meterRegistryOne() {
return new TestMeterRegistry();
}
@Bean
MeterRegistry meterRegistryTwo() {
return new SimpleMeterRegistry();
}
}
@Configuration(proxyBeanMethods = false)
static
|
MultipleMeterRegistriesConfig
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/transform/transforms/QueryConfigTests.java
|
{
"start": 1508,
"end": 6471
}
|
class ____ extends AbstractSerializingTransformTestCase<QueryConfig> {
private boolean lenient;
public static QueryConfig randomQueryConfig() {
QueryBuilder queryBuilder = randomBoolean() ? new MatchAllQueryBuilder() : new MatchNoneQueryBuilder();
LinkedHashMap<String, Object> source = null;
try (XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()) {
XContentBuilder content = queryBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
source = (LinkedHashMap<String, Object>) XContentHelper.convertToMap(BytesReference.bytes(content), true, XContentType.JSON)
.v2();
} catch (IOException e) {
// should not happen
fail("failed to create random query config");
}
return new QueryConfig(source, queryBuilder);
}
public static QueryConfig randomInvalidQueryConfig() {
// create something broken but with a source
LinkedHashMap<String, Object> source = new LinkedHashMap<>();
for (String key : randomUnique(() -> randomAlphaOfLengthBetween(1, 20), randomIntBetween(1, 10))) {
source.put(key, randomAlphaOfLengthBetween(1, 20));
}
return new QueryConfig(source, null);
}
@Before
public void setRandomFeatures() {
lenient = randomBoolean();
}
@Override
protected QueryConfig doParseInstance(XContentParser parser) throws IOException {
return QueryConfig.fromXContent(parser, lenient);
}
@Override
protected QueryConfig createTestInstance() {
return lenient ? randomBoolean() ? randomQueryConfig() : randomInvalidQueryConfig() : randomQueryConfig();
}
@Override
protected QueryConfig mutateInstance(QueryConfig instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Reader<QueryConfig> instanceReader() {
return QueryConfig::new;
}
public void testValidQueryParsing() throws IOException {
QueryBuilder query = new MatchQueryBuilder("key", "value");
String source = query.toString();
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryConfig queryConfig = QueryConfig.fromXContent(parser, true);
assertNotNull(queryConfig.getQuery());
assertEquals(query, queryConfig.getQuery());
}
}
public void testFailOnStrictPassOnLenient() throws IOException {
String source = "{\"query_element_does_not_exist\" : {}}";
// lenient, passes but reports invalid
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryConfig query = QueryConfig.fromXContent(parser, true);
assertNull(query.getQuery());
}
// strict throws
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
expectThrows(ParsingException.class, () -> QueryConfig.fromXContent(parser, false));
}
}
public void testFailOnEmptyQuery() throws IOException {
String source = "";
// lenient, passes but reports invalid
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryConfig query = QueryConfig.fromXContent(parser, true);
assertNull(query.getQuery());
}
// strict throws
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
expectThrows(IllegalArgumentException.class, () -> QueryConfig.fromXContent(parser, false));
}
}
public void testFailOnEmptyQueryClause() throws IOException {
String source = "{}";
// lenient, passes but reports invalid
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryConfig query = QueryConfig.fromXContent(parser, true);
assertNull(query.getQuery());
ValidationException validationException = query.validate(null);
assertThat(validationException, is(notNullValue()));
assertThat(validationException.getMessage(), containsString("source.query must not be null"));
}
// strict throws
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
expectThrows(IllegalArgumentException.class, () -> QueryConfig.fromXContent(parser, false));
}
}
public void testDeprecation() throws IOException {
String source = "{\"" + MockDeprecatedQueryBuilder.NAME + "\" : {}}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryConfig query = QueryConfig.fromXContent(parser, false);
assertNotNull(query.getQuery());
assertWarnings(MockDeprecatedQueryBuilder.DEPRECATION_MESSAGE);
}
}
}
|
QueryConfigTests
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
|
{
"start": 72558,
"end": 73546
}
|
class ____
implements FileSystemAccess.FileSystemExecutor<String> {
public FSGetErasureCodingPolicies() {
}
@Override
public String execute(FileSystem fs) throws IOException {
Collection<ErasureCodingPolicyInfo> ecPolicyInfos = null;
if (fs instanceof DistributedFileSystem) {
DistributedFileSystem dfs = (DistributedFileSystem) fs;
ecPolicyInfos = dfs.getAllErasureCodingPolicies();
} else {
throw new UnsupportedOperationException("getErasureCodingPolicies is " +
"not supported for HttpFs on " + fs.getClass() +
". Please check your fs.defaultFS configuration");
}
HttpFSServerWebApp.get().getMetrics().incrOpsAllECPolicies();
return JsonUtil.toJsonString(ecPolicyInfos.stream().toArray(ErasureCodingPolicyInfo[]::new));
}
}
/**
* Executor that performs a FSGetErasureCodingCodecs operation.
*/
@InterfaceAudience.Private
public static
|
FSGetErasureCodingPolicies
|
java
|
apache__flink
|
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/aftermatch/SkipToLastStrategy.java
|
{
"start": 986,
"end": 1617
}
|
class ____ extends SkipToElementStrategy {
private static final long serialVersionUID = 7585116990619594531L;
SkipToLastStrategy(String patternName, boolean shouldThrowException) {
super(patternName, shouldThrowException);
}
@Override
public SkipToElementStrategy throwExceptionOnMiss() {
return new SkipToLastStrategy(getPatternName().get(), true);
}
@Override
int getIndex(int size) {
return size - 1;
}
@Override
public String toString() {
return "SkipToLastStrategy{" + "patternName='" + getPatternName().get() + '\'' + '}';
}
}
|
SkipToLastStrategy
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/DeprecatedVariableTest.java
|
{
"start": 1182,
"end": 1431
}
|
class ____ {
@Deprecated int x;
void f(@Deprecated int x) {
@Deprecated int y;
}
}
""")
.addOutputLines(
"Test.java",
"""
|
Test
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/asm/Symbol.java
|
{
"start": 7309,
"end": 10148
}
|
class ____ for {@link #CONSTANT_CLASS_TAG}, {@link #TYPE_TAG}, {@link
* #UNINITIALIZED_TYPE_TAG} and {@link #FORWARD_UNINITIALIZED_TYPE_TAG} symbols,
* <li>{@literal null} for the other types of symbol.
* </ul>
*/
final String value;
/**
* The numeric value of this symbol. This is:
*
* <ul>
* <li>the symbol's value for {@link #CONSTANT_INTEGER_TAG},{@link #CONSTANT_FLOAT_TAG}, {@link
* #CONSTANT_LONG_TAG}, {@link #CONSTANT_DOUBLE_TAG},
* <li>the CONSTANT_MethodHandle_info reference_kind field value for {@link
* #CONSTANT_METHOD_HANDLE_TAG} symbols (or this value left shifted by 8 bits for
* reference_kind values larger than or equal to H_INVOKEVIRTUAL and if the method owner is
* an interface),
* <li>the CONSTANT_InvokeDynamic_info bootstrap_method_attr_index field value for {@link
* #CONSTANT_INVOKE_DYNAMIC_TAG} symbols,
* <li>the offset of a bootstrap method in the BootstrapMethods boostrap_methods array, for
* {@link #CONSTANT_DYNAMIC_TAG} or {@link #BOOTSTRAP_METHOD_TAG} symbols,
* <li>the bytecode offset of the NEW instruction that created an {@link
* Frame#ITEM_UNINITIALIZED} type for {@link #UNINITIALIZED_TYPE_TAG} symbols,
* <li>the index of the {@link Label} (in the {@link SymbolTable#labelTable} table) of the NEW
* instruction that created an {@link Frame#ITEM_UNINITIALIZED} type for {@link
* #FORWARD_UNINITIALIZED_TYPE_TAG} symbols,
* <li>the indices (in the class' type table) of two {@link #TYPE_TAG} source types for {@link
* #MERGED_TYPE_TAG} symbols,
* <li>0 for the other types of symbol.
* </ul>
*/
final long data;
/**
* Additional information about this symbol, generally computed lazily. <i>Warning: the value of
* this field is ignored when comparing Symbol instances</i> (to avoid duplicate entries in a
* SymbolTable). Therefore, this field should only contain data that can be computed from the
* other fields of this class. It contains:
*
* <ul>
* <li>the {@link Type#getArgumentsAndReturnSizes} of the symbol's method descriptor for {@link
* #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG} and {@link
* #CONSTANT_INVOKE_DYNAMIC_TAG} symbols,
* <li>the index in the InnerClasses_attribute 'classes' array (plus one) corresponding to this
* class, for {@link #CONSTANT_CLASS_TAG} symbols,
* <li>the index (in the class' type table) of the merged type of the two source types for
* {@link #MERGED_TYPE_TAG} symbols,
* <li>0 for the other types of symbol, or if this field has not been computed yet.
* </ul>
*/
int info;
/**
* Constructs a new Symbol. This constructor can't be used directly because the Symbol
|
name
|
java
|
quarkusio__quarkus
|
extensions/oidc-client/deployment/src/test/java/io/quarkus/oidc/client/OidcClientPasswordGrantSecretIsMissingTestCase.java
|
{
"start": 453,
"end": 2158
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource(new StringAsset(
"# Disable Dev Services, Keycloak is started by a Maven plugin\n"
+ "quarkus.keycloak.devservices.enabled=false\n"
+ "quarkus.oidc-client.token-path=http://localhost:8180/oidc/tokens\n"
+ "quarkus.oidc-client.client-id=quarkus\n"
+ "quarkus.oidc-client.credentials.secret=secret\n"
+ "quarkus.oidc-client.grant.type=password\n"
+ "quarkus.oidc-client.grant-options.password.user=alice\n"),
"application.properties"))
.assertException(t -> {
Throwable e = t;
ConfigurationException te = null;
while (e != null) {
if (e instanceof ConfigurationException) {
te = (ConfigurationException) e;
break;
}
e = e.getCause();
}
assertNotNull(te, "Expected ConfigurationException, but got: " + t);
assertTrue(
te.getMessage()
.contains("Username and password must be set when a password grant is used"),
te.getMessage());
});
@Test
public void test() {
Assertions.fail();
}
}
|
OidcClientPasswordGrantSecretIsMissingTestCase
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/queue/event/NegativelyAcknowledgedEventListener.java
|
{
"start": 886,
"end": 1225
}
|
interface ____ extends QueueEventListener {
/**
* Called when messages are negatively acknowledged by a consumer.
*
* @param status The reason for the negative acknowledgment
* @param ids message ids
*/
void onNegativelyAcknowledged(NAckStatus status, List<String> ids);
}
|
NegativelyAcknowledgedEventListener
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/LogicalOptimizerContext.java
|
{
"start": 505,
"end": 1950
}
|
class ____ {
private final Configuration configuration;
private final FoldContext foldCtx;
private final TransportVersion minimumVersion;
public LogicalOptimizerContext(Configuration configuration, FoldContext foldCtx, TransportVersion minimumVersion) {
this.configuration = configuration;
this.foldCtx = foldCtx;
this.minimumVersion = minimumVersion;
}
public Configuration configuration() {
return configuration;
}
public FoldContext foldCtx() {
return foldCtx;
}
public TransportVersion minimumVersion() {
return minimumVersion;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (LogicalOptimizerContext) obj;
return this.configuration.equals(that.configuration)
&& this.foldCtx.equals(that.foldCtx)
&& Objects.equals(this.minimumVersion, that.minimumVersion);
}
@Override
public int hashCode() {
return Objects.hash(configuration, foldCtx, minimumVersion);
}
@Override
public String toString() {
return "LogicalOptimizerContext[configuration="
+ configuration
+ ", foldCtx="
+ foldCtx
+ ", minimumVersion="
+ minimumVersion
+ ']';
}
}
|
LogicalOptimizerContext
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/BlockingFlowableLatest.java
|
{
"start": 1771,
"end": 4154
}
|
class ____<T> extends DisposableSubscriber<Notification<T>> implements Iterator<T> {
final Semaphore notify = new Semaphore(0);
// observer's notification
final AtomicReference<Notification<T>> value = new AtomicReference<>();
// iterator's notification
Notification<T> iteratorNotification;
@Override
public void onNext(Notification<T> args) {
boolean wasNotAvailable = value.getAndSet(args) == null;
if (wasNotAvailable) {
notify.release();
}
}
@Override
public void onError(Throwable e) {
RxJavaPlugins.onError(e);
}
@Override
public void onComplete() {
// not expected
}
@Override
public boolean hasNext() {
if (iteratorNotification != null && iteratorNotification.isOnError()) {
throw ExceptionHelper.wrapOrThrow(iteratorNotification.getError());
}
if (iteratorNotification == null || iteratorNotification.isOnNext()) {
if (iteratorNotification == null) {
try {
BlockingHelper.verifyNonBlocking();
notify.acquire();
} catch (InterruptedException ex) {
dispose();
iteratorNotification = Notification.createOnError(ex);
throw ExceptionHelper.wrapOrThrow(ex);
}
Notification<T> n = value.getAndSet(null);
iteratorNotification = n;
if (n.isOnError()) {
throw ExceptionHelper.wrapOrThrow(n.getError());
}
}
}
return iteratorNotification.isOnNext();
}
@Override
public T next() {
if (hasNext()) {
if (iteratorNotification.isOnNext()) {
T v = iteratorNotification.getValue();
iteratorNotification = null;
return v;
}
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Read-only iterator.");
}
}
}
|
LatestSubscriberIterator
|
java
|
spring-projects__spring-framework
|
spring-webflux/src/main/java/org/springframework/web/reactive/resource/AbstractFileNameVersionStrategy.java
|
{
"start": 1149,
"end": 2079
}
|
class ____ implements VersionStrategy {
protected final Log logger = LogFactory.getLog(getClass());
private static final Pattern pattern = Pattern.compile("-(\\S*)\\.");
@Override
public @Nullable String extractVersion(String requestPath) {
Matcher matcher = pattern.matcher(requestPath);
if (matcher.find()) {
String match = matcher.group(1);
return (match.contains("-") ? match.substring(match.lastIndexOf('-') + 1) : match);
}
else {
return null;
}
}
@Override
public String removeVersion(String requestPath, String version) {
return StringUtils.delete(requestPath, "-" + version);
}
@Override
public String addVersion(String requestPath, String version) {
String baseFilename = StringUtils.stripFilenameExtension(requestPath);
String extension = StringUtils.getFilenameExtension(requestPath);
return (baseFilename + '-' + version + '.' + extension);
}
}
|
AbstractFileNameVersionStrategy
|
java
|
apache__dubbo
|
dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java
|
{
"start": 3466,
"end": 5103
}
|
interface ____ {
// MetricsPushListener
MetricsCat APPLICATION_PUSH_POST =
new MetricsCat(MetricsKey.METADATA_PUSH_METRIC_NUM, MetricsApplicationListener::onPostEventBuild);
MetricsCat APPLICATION_PUSH_FINISH = new MetricsCat(
MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild);
MetricsCat APPLICATION_PUSH_ERROR = new MetricsCat(
MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild);
// MetricsSubscribeListener
MetricsCat APPLICATION_SUBSCRIBE_POST =
new MetricsCat(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM, MetricsApplicationListener::onPostEventBuild);
MetricsCat APPLICATION_SUBSCRIBE_FINISH = new MetricsCat(
MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild);
MetricsCat APPLICATION_SUBSCRIBE_ERROR = new MetricsCat(
MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild);
// MetricsSubscribeListener
MetricsCat SERVICE_SUBSCRIBE_POST =
new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA, MetricsServiceListener::onPostEventBuild);
MetricsCat SERVICE_SUBSCRIBE_FINISH =
new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_SUCCEED, MetricsServiceListener::onFinishEventBuild);
MetricsCat SERVICE_SUBSCRIBE_ERROR =
new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_FAILED, MetricsServiceListener::onErrorEventBuild);
}
}
|
MCat
|
java
|
apache__avro
|
lang/java/avro/src/main/java/org/apache/avro/file/FileReader.java
|
{
"start": 1047,
"end": 1916
}
|
interface ____<D> extends Iterator<D>, Iterable<D>, Closeable {
/** Return the schema for data in this file. */
Schema getSchema();
/**
* Read the next datum from the file.
*
* @param reuse an instance to reuse.
* @throws NoSuchElementException if no more remain in the file.
*/
D next(D reuse) throws IOException;
/**
* Move to the next synchronization point after a position. To process a range
* of file entries, call this with the starting position, then check
* {@link #pastSync(long)} with the end point before each call to
* {@link #next()}.
*/
void sync(long position) throws IOException;
/** Return true if past the next synchronization point after a position. */
boolean pastSync(long position) throws IOException;
/** Return the current position in the input. */
long tell() throws IOException;
}
|
FileReader
|
java
|
google__auto
|
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
|
{
"start": 13686,
"end": 14152
}
|
class ____ {
public abstract float floatProperty();
public static FloatProperty create(float floatProperty) {
return new AutoValue_AutoValueTest_FloatProperty(floatProperty);
}
}
@Test
public void testFloatHashCode() {
float floatValue = 123456f;
FloatProperty floatProperty = FloatProperty.create(floatValue);
assertEquals(singlePropertyHash(floatValue), floatProperty.hashCode());
}
@AutoValue
abstract static
|
FloatProperty
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertIsSorted_Test.java
|
{
"start": 1460,
"end": 4289
}
|
class ____ extends DoubleArraysBaseTest {
@Override
protected void initActualArray() {
actual = arrayOf(1.0, 2.0, 3.0, 4.0, 4.0);
}
@Test
void should_pass_if_actual_is_sorted_in_ascending_order() {
arrays.assertIsSorted(someInfo(), actual);
}
@Test
void should_pass_if_actual_is_empty() {
arrays.assertIsSorted(someInfo(), emptyArray());
}
@Test
void should_pass_if_actual_contains_only_one_element() {
arrays.assertIsSorted(someInfo(), arrayOf(1.0));
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertIsSorted(someInfo(), null))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_not_sorted_in_ascending_order() {
actual = arrayOf(1.0, 3.0, 2.0);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertIsSorted(someInfo(), actual))
.withMessage(shouldBeSorted(1, actual).create());
}
@Test
void should_pass_if_actual_is_sorted_in_ascending_order_according_to_custom_comparison_strategy() {
actual = arrayOf(1.0, -2.0, 3.0, -4.0, 4.0);
arraysWithCustomComparisonStrategy.assertIsSorted(someInfo(), actual);
}
@Test
void should_pass_if_actual_is_empty_whatever_custom_comparison_strategy_is() {
arraysWithCustomComparisonStrategy.assertIsSorted(someInfo(), emptyArray());
}
@Test
void should_pass_if_actual_contains_only_one_element_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertIsSorted(someInfo(), arrayOf(1.0));
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertIsSorted(someInfo(),
null))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_not_sorted_in_ascending_order_according_to_custom_comparison_strategy() {
actual = arrayOf(1.0, 3.0, 2.0);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertIsSorted(someInfo(),
actual))
.withMessage(shouldBeSortedAccordingToGivenComparator(1, actual,
comparatorForCustomComparisonStrategy()).create());
}
}
|
DoubleArrays_assertIsSorted_Test
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/api/transformations/TwoInputTransformation.java
|
{
"start": 2081,
"end": 9673
}
|
class ____<IN1, IN2, OUT> extends PhysicalTransformation<OUT> {
private final Transformation<IN1> input1;
private final Transformation<IN2> input2;
private final StreamOperatorFactory<OUT> operatorFactory;
private KeySelector<IN1, ?> stateKeySelector1;
private KeySelector<IN2, ?> stateKeySelector2;
private TypeInformation<?> stateKeyType;
/**
* Creates a new {@code TwoInputTransformation} from the given inputs and operator.
*
* @param input1 The first input {@code Transformation}
* @param input2 The second input {@code Transformation}
* @param name The name of the {@code Transformation}, this will be shown in Visualizations and
* the Log
* @param operator The {@code TwoInputStreamOperator}
* @param outputType The type of the elements produced by this Transformation
* @param parallelism The parallelism of this Transformation
*/
public TwoInputTransformation(
Transformation<IN1> input1,
Transformation<IN2> input2,
String name,
TwoInputStreamOperator<IN1, IN2, OUT> operator,
TypeInformation<OUT> outputType,
int parallelism) {
this(input1, input2, name, SimpleOperatorFactory.of(operator), outputType, parallelism);
}
public TwoInputTransformation(
Transformation<IN1> input1,
Transformation<IN2> input2,
String name,
TwoInputStreamOperator<IN1, IN2, OUT> operator,
TypeInformation<OUT> outputType,
int parallelism,
boolean parallelismConfigured) {
this(
input1,
input2,
name,
SimpleOperatorFactory.of(operator),
outputType,
parallelism,
parallelismConfigured);
}
public TwoInputTransformation(
Transformation<IN1> input1,
Transformation<IN2> input2,
String name,
StreamOperatorFactory<OUT> operatorFactory,
TypeInformation<OUT> outputType,
int parallelism) {
super(name, outputType, parallelism);
this.input1 = input1;
this.input2 = input2;
this.operatorFactory = operatorFactory;
}
/**
* Creates a new {@code TwoInputTransformation} from the given inputs and operator.
*
* @param input1 The first input {@code Transformation}
* @param input2 The second input {@code Transformation}
* @param name The name of the {@code Transformation}, this will be shown in Visualizations and
* the Log
* @param operatorFactory The {@code TwoInputStreamOperator} factory
* @param outputType The type of the elements produced by this Transformation
* @param parallelism The parallelism of this Transformation
* @param parallelismConfigured If true, the parallelism of the transformation is explicitly set
* and should be respected. Otherwise the parallelism can be changed at runtime.
*/
public TwoInputTransformation(
Transformation<IN1> input1,
Transformation<IN2> input2,
String name,
StreamOperatorFactory<OUT> operatorFactory,
TypeInformation<OUT> outputType,
int parallelism,
boolean parallelismConfigured) {
super(name, outputType, parallelism, parallelismConfigured);
this.input1 = input1;
this.input2 = input2;
this.operatorFactory = operatorFactory;
}
/** Returns the first input {@code Transformation} of this {@code TwoInputTransformation}. */
public Transformation<IN1> getInput1() {
return input1;
}
/** Returns the second input {@code Transformation} of this {@code TwoInputTransformation}. */
public Transformation<IN2> getInput2() {
return input2;
}
@Override
public List<Transformation<?>> getInputs() {
final List<Transformation<?>> inputs = new ArrayList<>();
inputs.add(input1);
inputs.add(input2);
return inputs;
}
/** Returns the {@code TypeInformation} for the elements from the first input. */
public TypeInformation<IN1> getInputType1() {
return input1.getOutputType();
}
/** Returns the {@code TypeInformation} for the elements from the second input. */
public TypeInformation<IN2> getInputType2() {
return input2.getOutputType();
}
@VisibleForTesting
public TwoInputStreamOperator<IN1, IN2, OUT> getOperator() {
return (TwoInputStreamOperator<IN1, IN2, OUT>)
((SimpleOperatorFactory) operatorFactory).getOperator();
}
/** Returns the {@code StreamOperatorFactory} of this Transformation. */
public StreamOperatorFactory<OUT> getOperatorFactory() {
return operatorFactory;
}
/**
* Sets the {@link KeySelector KeySelectors} that must be used for partitioning keyed state of
* this transformation.
*
* @param stateKeySelector1 The {@code KeySelector} to set for the first input
* @param stateKeySelector2 The {@code KeySelector} to set for the first input
*/
public void setStateKeySelectors(
KeySelector<IN1, ?> stateKeySelector1, KeySelector<IN2, ?> stateKeySelector2) {
this.stateKeySelector1 = stateKeySelector1;
this.stateKeySelector2 = stateKeySelector2;
updateManagedMemoryStateBackendUseCase(
stateKeySelector1 != null || stateKeySelector2 != null);
}
/**
* Returns the {@code KeySelector} that must be used for partitioning keyed state in this
* Operation for the first input.
*
* @see #setStateKeySelectors
*/
public KeySelector<IN1, ?> getStateKeySelector1() {
return stateKeySelector1;
}
/**
* Returns the {@code KeySelector} that must be used for partitioning keyed state in this
* Operation for the second input.
*
* @see #setStateKeySelectors
*/
public KeySelector<IN2, ?> getStateKeySelector2() {
return stateKeySelector2;
}
public void setStateKeyType(TypeInformation<?> stateKeyType) {
this.stateKeyType = stateKeyType;
}
public TypeInformation<?> getStateKeyType() {
return stateKeyType;
}
@Override
protected List<Transformation<?>> getTransitivePredecessorsInternal() {
List<Transformation<?>> predecessors =
Stream.of(input1, input2)
.flatMap(input -> input.getTransitivePredecessors().stream())
.distinct()
.collect(Collectors.toList());
predecessors.add(this);
return predecessors;
}
@Override
public final void setChainingStrategy(ChainingStrategy strategy) {
operatorFactory.setChainingStrategy(strategy);
}
public boolean isOutputOnlyAfterEndOfStream() {
return operatorFactory.getOperatorAttributes().isOutputOnlyAfterEndOfStream();
}
public boolean isInternalSorterSupported() {
return operatorFactory.getOperatorAttributes().isInternalSorterSupported();
}
@Override
public void enableAsyncState() {
TwoInputStreamOperator<IN1, IN2, OUT> operator =
(TwoInputStreamOperator<IN1, IN2, OUT>)
((SimpleOperatorFactory<OUT>) operatorFactory).getOperator();
if (!(operator instanceof AsyncKeyOrderedProcessingOperator)) {
super.enableAsyncState();
}
}
}
|
TwoInputTransformation
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/wrappedio/impl/DynamicWrappedIO.java
|
{
"start": 6657,
"end": 14210
}
|
class ____ found and loaded.
*/
public boolean loaded() {
return loaded;
}
/**
* For testing: verify that all methods were found.
* @throws UnsupportedOperationException if the method was not found.
*/
void requireAllMethodsAvailable() throws UnsupportedOperationException {
final DynMethods.UnboundMethod[] methods = {
bulkDeleteDeleteMethod,
bulkDeletePageSizeMethod,
fileSystemOpenFileMethod,
pathCapabilitiesHasPathCapabilityMethod,
streamCapabilitiesHasCapabilityMethod,
byteBufferPositionedReadableReadFullyAvailableMethod,
byteBufferPositionedReadableReadFullyMethod,
};
for (DynMethods.UnboundMethod method : methods) {
LOG.info("Checking method {}", method);
if (!available(method)) {
throw new UnsupportedOperationException("Unbound " + method);
}
}
}
/**
* Are the bulk delete methods available?
* @return true if the methods were found.
*/
public boolean bulkDelete_available() {
return available(bulkDeleteDeleteMethod);
}
/**
* Get the maximum number of objects/files to delete in a single request.
* @param fileSystem filesystem
* @param path path to delete under.
* @return a number greater than or equal to zero.
* @throws UnsupportedOperationException bulk delete under that path is not supported.
* @throws IllegalArgumentException path not valid.
* @throws IOException problems resolving paths
* @throws RuntimeException invocation failure.
*/
public int bulkDelete_pageSize(final FileSystem fileSystem, final Path path)
throws IOException {
checkAvailable(bulkDeletePageSizeMethod);
return extractIOEs(() ->
bulkDeletePageSizeMethod.invoke(null, fileSystem, path));
}
/**
* Delete a list of files/objects.
* <ul>
* <li>Files must be under the path provided in {@code base}.</li>
* <li>The size of the list must be equal to or less than the page size.</li>
* <li>Directories are not supported; the outcome of attempting to delete
* directories is undefined (ignored; undetected, listed as failures...).</li>
* <li>The operation is not atomic.</li>
* <li>The operation is treated as idempotent: network failures may
* trigger resubmission of the request -any new objects created under a
* path in the list may then be deleted.</li>
* <li>There is no guarantee that any parent directories exist after this call.
* </li>
* </ul>
* @param fs filesystem
* @param base path to delete under.
* @param paths list of paths which must be absolute and under the base path.
* @return a list of all the paths which couldn't be deleted for a reason other than
* "not found" and any associated error message.
* @throws UnsupportedOperationException bulk delete under that path is not supported.
* @throws IllegalArgumentException if a path argument is invalid.
* @throws IOException IO problems including networking, authentication and more.
*/
public List<Map.Entry<Path, String>> bulkDelete_delete(FileSystem fs,
Path base,
Collection<Path> paths) throws IOException {
checkAvailable(bulkDeleteDeleteMethod);
return extractIOEs(() ->
bulkDeleteDeleteMethod.invoke(null, fs, base, paths));
}
/**
* Is the {@link #fileSystem_openFile(FileSystem, Path, String, FileStatus, Long, Map)}
* method available.
* @return true if the optimized open file method can be invoked.
*/
public boolean fileSystem_openFile_available() {
return available(fileSystemOpenFileMethod);
}
/**
* OpenFile assistant, easy reflection-based access to
* {@code FileSystem#openFile(Path)} and blocks
* awaiting the operation completion.
* @param fs filesystem
* @param path path
* @param policy read policy
* @param status optional file status
* @param length optional file length
* @param options nullable map of other options
* @return stream of the opened file
* @throws IOException if the operation was attempted and failed.
*/
public FSDataInputStream fileSystem_openFile(
final FileSystem fs,
final Path path,
final String policy,
@Nullable final FileStatus status,
@Nullable final Long length,
@Nullable final Map<String, String> options)
throws IOException {
checkAvailable(fileSystemOpenFileMethod);
return extractIOEs(() ->
fileSystemOpenFileMethod.invoke(null,
fs, path, policy, status, length, options));
}
/**
* Does a path have a given capability?
* Calls {@code PathCapabilities#hasPathCapability(Path, String)},
* mapping IOExceptions to false.
* @param fs filesystem
* @param path path to query the capability of.
* @param capability non-null, non-empty string to query the path for support.
* @return true if the capability is supported
* under that part of the FS
* false if the method is not loaded or the path lacks the capability.
* @throws IllegalArgumentException invalid arguments
*/
public boolean pathCapabilities_hasPathCapability(Object fs,
Path path,
String capability) {
if (!available(pathCapabilitiesHasPathCapabilityMethod)) {
return false;
}
return pathCapabilitiesHasPathCapabilityMethod.invoke(null, fs, path, capability);
}
/**
* Does an object implement {@code StreamCapabilities} and, if so,
* what is the result of the probe for the capability?
* Calls {@code StreamCapabilities#hasCapability(String)},
* @param object object to probe
* @param capability capability string
* @return true iff the object implements StreamCapabilities and the capability is
* declared available.
*/
public boolean streamCapabilities_hasCapability(Object object, String capability) {
if (!available(streamCapabilitiesHasCapabilityMethod)) {
return false;
}
return streamCapabilitiesHasCapabilityMethod.invoke(null, object, capability);
}
/**
* Are the ByteBufferPositionedReadable methods loaded?
* This does not check that a specific stream implements the API;
* use {@link #byteBufferPositionedReadable_readFullyAvailable(InputStream)}.
* @return true if the hadoop libraries have the method.
*/
public boolean byteBufferPositionedReadable_available() {
return available(byteBufferPositionedReadableReadFullyAvailableMethod);
}
/**
* Probe to see if the input stream is an instance of ByteBufferPositionedReadable.
* If the stream is an FSDataInputStream, the wrapped stream is checked.
* @param in input stream
* @return true if the API is available, the stream implements the interface
* (including the innermost wrapped stream) and that it declares the stream capability.
* @throws IOException if the operation was attempted and failed.
*/
public boolean byteBufferPositionedReadable_readFullyAvailable(
InputStream in) throws IOException {
if (available(byteBufferPositionedReadableReadFullyAvailableMethod)) {
return extractIOEs(() ->
byteBufferPositionedReadableReadFullyAvailableMethod.invoke(null, in));
} else {
return false;
}
}
/**
* Delegate to {@code ByteBufferPositionedReadable#read(long, ByteBuffer)}.
* @param in input stream
* @param position position within file
* @param buf the ByteBuffer to receive the results of the read operation.
* @throws UnsupportedOperationException if the input doesn't implement
* the
|
was
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/FuzzyEqualsShouldNotBeUsedInEqualsMethodTest.java
|
{
"start": 2738,
"end": 3196
}
|
class ____ {
public void test() {
boolean t = DoubleMath.fuzzyEquals(0, 2, 0.3);
}
public boolean equals(Object other) {
return true;
}
public boolean equals(Object other, double a) {
return DoubleMath.fuzzyEquals(0, 1, 0.2);
}
}
}\
""")
.doTest();
}
}
|
TestClass
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/StandbyCheckpointer.java
|
{
"start": 2743,
"end": 4227
}
|
class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(StandbyCheckpointer.class);
private static final long PREVENT_AFTER_CANCEL_MS = 2*60*1000L;
private final CheckpointConf checkpointConf;
private final Configuration conf;
private final FSNamesystem namesystem;
private long lastCheckpointTime;
private final CheckpointerThread thread;
private final ThreadFactory uploadThreadFactory;
private List<URL> activeNNAddresses;
private URL myNNAddress;
private final Object cancelLock = new Object();
private Canceler canceler;
// Keep track of how many checkpoints were canceled.
// This is for use in tests.
private static int canceledCount = 0;
// A map from NN url to the most recent image upload time.
private final HashMap<String, CheckpointReceiverEntry> checkpointReceivers;
public StandbyCheckpointer(Configuration conf, FSNamesystem ns)
throws IOException {
this.namesystem = ns;
this.conf = conf;
this.checkpointConf = new CheckpointConf(conf);
this.thread = new CheckpointerThread();
this.uploadThreadFactory = new ThreadFactoryBuilder().setDaemon(true)
.setNameFormat("TransferFsImageUpload-%d").build();
setNameNodeAddresses(conf);
this.checkpointReceivers = new HashMap<>();
for (URL address : activeNNAddresses) {
this.checkpointReceivers.put(address.toString(),
new CheckpointReceiverEntry());
}
}
private static final
|
StandbyCheckpointer
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_283_current_user.java
|
{
"start": 880,
"end": 2027
}
|
class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT current_user from t where u = CURRENT_USER";
SQLStatement stmt = SQLUtils
.parseSingleStatement(sql, DbType.mysql, SQLParserFeature.EnableCurrentUserExpr);
assertEquals("SELECT CURRENT_USER\n" +
"FROM t\n" +
"WHERE u = CURRENT_USER", stmt.toString());
assertEquals("select current_user\n" +
"from t\n" +
"where u = current_user", stmt.toLowerCaseString());
}
public void test_1() throws Exception {
String sql = "SELECT current_user from t where u = CURRENT_USER";
SQLStatement stmt = SQLUtils
.parseSingleStatement(sql, DbType.hive, SQLParserFeature.EnableCurrentUserExpr);
assertEquals("SELECT CURRENT_USER\n" +
"FROM t\n" +
"WHERE u = CURRENT_USER", stmt.toString());
assertEquals("select current_user\n" +
"from t\n" +
"where u = current_user", stmt.toLowerCaseString());
}
}
|
MySqlSelectTest_283_current_user
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java
|
{
"start": 12627,
"end": 12797
}
|
class ____ {
@Bean
String bar() {
return "bar";
}
}
@Configuration(proxyBeanMethods = false)
@Conditional(FilteredClassLoaderCondition.class)
static
|
BarConfig
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-extras/src/test/java/org/apache/hadoop/tools/TestDistCh.java
|
{
"start": 2822,
"end": 4047
}
|
class ____ {
private final FileSystem fs;
private final String root;
private final Path rootdir;
private int fcount = 0;
Path createSmallFile(Path dir) throws IOException {
final Path f = new Path(dir, "f" + ++fcount);
assertTrue(!fs.exists(f));
final DataOutputStream out = fs.create(f);
try {
out.writeBytes("createSmallFile: f=" + f);
} finally {
out.close();
}
assertTrue(fs.exists(f));
return f;
}
Path mkdir(Path dir) throws IOException {
assertTrue(fs.mkdirs(dir));
assertTrue(fs.getFileStatus(dir).isDirectory());
return dir;
}
FileTree(FileSystem fs, String name) throws IOException {
this.fs = fs;
this.root = "/test/" + name;
this.rootdir = mkdir(new Path(root));
for(int i = 0; i < 3; i++) {
createSmallFile(rootdir);
}
for(int i = 0; i < NUN_SUBS; i++) {
final Path sub = mkdir(new Path(root, "sub" + i));
int num_files = RANDOM.nextInt(3);
for(int j = 0; j < num_files; j++) {
createSmallFile(sub);
}
}
System.out.println("rootdir = " + rootdir);
}
}
static
|
FileTree
|
java
|
elastic__elasticsearch
|
modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/InjectConstantAnnotationParser.java
|
{
"start": 579,
"end": 1515
}
|
class ____ implements WhitelistAnnotationParser {
public static final InjectConstantAnnotationParser INSTANCE = new InjectConstantAnnotationParser();
private InjectConstantAnnotationParser() {}
@Override
public Object parse(Map<String, String> arguments) {
if (arguments.isEmpty()) {
throw new IllegalArgumentException("[@inject_constant] requires at least one name to inject");
}
ArrayList<String> argList = new ArrayList<>(arguments.size());
for (int i = 1; i <= arguments.size(); i++) {
String argNum = Integer.toString(i);
if (arguments.containsKey(argNum) == false) {
throw new IllegalArgumentException("[@inject_constant] missing argument number [" + argNum + "]");
}
argList.add(arguments.get(argNum));
}
return new InjectConstantAnnotation(argList);
}
}
|
InjectConstantAnnotationParser
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/chain/Chain.java
|
{
"start": 22326,
"end": 24119
}
|
class
____ index = getIndex(jobConf, prefix);
jobConf.setClass(prefix + CHAIN_MAPPER_CLASS + index, klass, Mapper.class);
validateKeyValueTypes(isMap, jobConf, inputKeyClass, inputValueClass,
outputKeyClass, outputValueClass, index, prefix);
setMapperConf(isMap, jobConf, inputKeyClass, inputValueClass,
outputKeyClass, outputValueClass, mapperConf, index, prefix);
}
// if a reducer chain check the Reducer has been already set or not
protected static void checkReducerAlreadySet(boolean isMap,
Configuration jobConf, String prefix, boolean shouldSet) {
if (!isMap) {
if (shouldSet) {
if (jobConf.getClass(prefix + CHAIN_REDUCER_CLASS, null) == null) {
throw new IllegalStateException(
"A Mapper can be added to the chain only after the Reducer has "
+ "been set");
}
} else {
if (jobConf.getClass(prefix + CHAIN_REDUCER_CLASS, null) != null) {
throw new IllegalStateException("Reducer has been already set");
}
}
}
}
protected static void validateKeyValueTypes(boolean isMap,
Configuration jobConf, Class<?> inputKeyClass, Class<?> inputValueClass,
Class<?> outputKeyClass, Class<?> outputValueClass, int index,
String prefix) {
// if it is a reducer chain and the first Mapper is being added check the
// key and value input classes of the mapper match those of the reducer
// output.
if (!isMap && index == 0) {
Configuration reducerConf = getChainElementConf(jobConf, prefix
+ CHAIN_REDUCER_CONFIG);
if (!inputKeyClass.isAssignableFrom(reducerConf.getClass(
REDUCER_OUTPUT_KEY_CLASS, null))) {
throw new IllegalArgumentException("The Reducer output key
|
int
|
java
|
apache__camel
|
components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramConstants.java
|
{
"start": 2015,
"end": 3279
}
|
enum ____\n"
+
"belonging to the `org.apache.camel.component.telegram.TelegramMediaType` enumeration.",
javaType = "org.apache.camel.component.telegram.TelegramMediaType or String")
public static final String TELEGRAM_MEDIA_TYPE = "CamelTelegramMediaType";
@Metadata(description = "This header is used to provide a caption or title\n" +
"for outgoing binary messages.",
javaType = "String")
public static final String TELEGRAM_MEDIA_TITLE_CAPTION = "CamelTelegramMediaTitleCaption";
@Metadata(description = "The reply markup.", javaType = "org.apache.camel.component.telegram.model.ReplyMarkup")
public static final String TELEGRAM_MEDIA_MARKUP = "CamelTelegramMediaMarkup";
@Metadata(description = "This header is used to format text messages using HTML or Markdown",
javaType = "org.apache.camel.component.telegram.TelegramParseMode")
public static final String TELEGRAM_PARSE_MODE = "CamelTelegramParseMode";
@Metadata(description = "The message timestamp.", javaType = "long")
public static final String MESSAGE_TIMESTAMP = Exchange.MESSAGE_TIMESTAMP;
private TelegramConstants() {
}
}
|
values
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/SlotPool.java
|
{
"start": 1664,
"end": 7797
}
|
interface ____ extends AllocatedSlotActions, AutoCloseable {
// ------------------------------------------------------------------------
// lifecycle
// ------------------------------------------------------------------------
void start(JobMasterId jobMasterId, String newJobManagerAddress) throws Exception;
void close();
// ------------------------------------------------------------------------
// resource manager connection
// ------------------------------------------------------------------------
/**
* Connects the SlotPool to the given ResourceManager. After this method is called, the SlotPool
* will be able to request resources from the given ResourceManager.
*
* @param resourceManagerGateway The RPC gateway for the resource manager.
*/
void connectToResourceManager(ResourceManagerGateway resourceManagerGateway);
/**
* Disconnects the slot pool from its current Resource Manager. After this call, the pool will
* not be able to request further slots from the Resource Manager, and all currently pending
* requests to the resource manager will be canceled.
*
* <p>The slot pool will still be able to serve slots from its internal pool.
*/
void disconnectResourceManager();
// ------------------------------------------------------------------------
// registering / un-registering TaskManagers and slots
// ------------------------------------------------------------------------
/**
* Registers a TaskExecutor with the given {@link ResourceID} at {@link SlotPool}.
*
* @param resourceID identifying the TaskExecutor to register
* @return true iff a new resource id was registered
*/
boolean registerTaskManager(ResourceID resourceID);
/**
* Releases a TaskExecutor with the given {@link ResourceID} from the {@link SlotPool}.
*
* @param resourceId identifying the TaskExecutor which shall be released from the SlotPool
* @param cause for the releasing of the TaskManager
* @return true iff a given registered resource id was removed
*/
boolean releaseTaskManager(final ResourceID resourceId, final Exception cause);
/**
* Offers multiple slots to the {@link SlotPool}. The slot offerings can be individually
* accepted or rejected by returning the collection of accepted slot offers.
*
* @param taskManagerLocation from which the slot offers originate
* @param taskManagerGateway to talk to the slot offerer
* @param offers slot offers which are offered to the {@link SlotPool}
* @return A collection of accepted slot offers. The remaining slot offers are implicitly
* rejected.
*/
Collection<SlotOffer> offerSlots(
TaskManagerLocation taskManagerLocation,
TaskManagerGateway taskManagerGateway,
Collection<SlotOffer> offers);
// ------------------------------------------------------------------------
// allocating and disposing slots
// ------------------------------------------------------------------------
/**
* Returns all free slot tracker.
*
* @return all free slot tracker
*/
FreeSlotTracker getFreeSlotTracker();
/**
* Returns a list of {@link SlotInfo} objects about all slots that are currently allocated in
* the slot pool.
*
* @return a list of {@link SlotInfo} objects about all slots that are currently allocated in
* the slot pool.
*/
Collection<SlotInfo> getAllocatedSlotsInformation();
/**
* Allocates the available slot with the given physical slot request. The slot must be able to
* fulfill the requirement profile, otherwise an {@link IllegalStateException} will be thrown.
*
* @param allocationID the allocation id of the requested available slot
* @param physicalSlotRequest the physical slot request.
* @return the previously available slot with the given allocation id, if a slot with this
* allocation id exists
*/
Optional<PhysicalSlot> allocateAvailableSlot(
AllocationID allocationID, PhysicalSlotRequest physicalSlotRequest);
/**
* Request the allocation of a new slot from the resource manager. This method will not return a
* slot from the already available slots from the pool, but instead will add a new slot to that
* pool that is immediately allocated and returned.
*
* @param physicalSlotRequest the physical slot request descriptor.
* @param timeout timeout for the allocation procedure
* @return a newly allocated slot that was previously not available.
*/
CompletableFuture<PhysicalSlot> requestNewAllocatedSlot(
PhysicalSlotRequest physicalSlotRequest, @Nullable Duration timeout);
/**
* Requests the allocation of a new batch slot from the resource manager. Unlike the normal
* slot, a batch slot will only time out if the slot pool does not contain a suitable slot.
* Moreover, it won't react to failure signals from the resource manager.
*
* @param physicalSlotRequest the physical slot request descriptor.
* @return a future which is completed with newly allocated batch slot
*/
CompletableFuture<PhysicalSlot> requestNewAllocatedBatchSlot(
PhysicalSlotRequest physicalSlotRequest);
/**
* Disables batch slot request timeout check. Invoked when someone else wants to take over the
* timeout check responsibility.
*/
void disableBatchSlotRequestTimeoutCheck();
/**
* Create report about the allocated slots belonging to the specified task manager.
*
* @param taskManagerId identifies the task manager
* @return the allocated slots on the task manager
*/
AllocatedSlotReport createAllocatedSlotReport(ResourceID taskManagerId);
/**
* Sets whether the underlying job is currently restarting or not.
*
* @param isJobRestarting whether the job is restarting or not
*/
void setIsJobRestarting(boolean isJobRestarting);
}
|
SlotPool
|
java
|
apache__maven
|
its/core-it-support/core-it-plugins/maven-it-plugin-touch/src/main/java/org/apache/maven/plugin/coreit/CoreItTouchMojo.java
|
{
"start": 1600,
"end": 4757
}
|
class ____ extends AbstractMojo {
@Parameter(defaultValue = "${project}")
private MavenProject project;
/**
* Output directory for touched files.
*/
@Parameter(defaultValue = "${project.build.directory}", required = true)
private String outputDirectory;
/**
* Test setting of plugin-artifacts on the PluginDescriptor instance.
*/
@Parameter(defaultValue = "${plugin.artifactMap}", required = true)
private Map<String, Artifact> pluginArtifacts;
/**
* Parameter to check that File attribute is injected with absolute path, even if parameter
* value is relative: a <code>touch.txt</code> file will be created in specified directory, to be able
* to check that absolute value is at right place.
*/
@Parameter(defaultValue = "target/test-basedir-alignment")
private File basedirAlignmentDirectory;
/**
*/
@Parameter(alias = "pluginFile")
private String pluginItem = "foo";
/**
*/
@Parameter
private String goalItem = "bar";
/**
* Touch a file named after artifact absolute file name, replacing '/' and ':' by '_' and adding ".txt".
*/
@Parameter(property = "artifactToFile")
private String artifactToFile;
/**
* Should the goal cause a failure before doing anything else?
*/
@Parameter(property = "fail")
private boolean fail = false;
public void execute() throws MojoExecutionException {
if (fail) {
throw new MojoExecutionException(
"Failing per \'fail\' parameter" + " (specified in pom or system properties)");
}
File outDir = new File(outputDirectory);
touch(outDir, "touch.txt");
// This parameter should be aligned to the basedir as the parameter type is specified
// as java.io.File
if (!basedirAlignmentDirectory.isAbsolute()) {
throw new MojoExecutionException("basedirAlignmentDirectory not aligned");
}
touch(basedirAlignmentDirectory, "touch.txt");
// Test parameter setting
if (pluginItem != null) {
touch(outDir, pluginItem);
}
if (goalItem != null) {
touch(outDir, goalItem);
}
if (artifactToFile != null) {
Artifact artifact = pluginArtifacts.get(artifactToFile);
File artifactFile = artifact.getFile();
String filename = artifactFile.getAbsolutePath().replace('/', '_').replace(':', '_') + ".txt";
touch(outDir, filename);
}
project.getBuild().setFinalName("coreitified");
}
private void touch(File dir, String file) throws MojoExecutionException {
try {
if (!dir.exists()) {
dir.mkdirs();
}
File touch = new File(dir, file);
getLog().info("Touching file: " + touch.getAbsolutePath());
FileWriter w = new FileWriter(touch);
w.write(file);
w.close();
} catch (IOException e) {
throw new MojoExecutionException("Error touching file", e);
}
}
}
|
CoreItTouchMojo
|
java
|
apache__dubbo
|
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java
|
{
"start": 1519,
"end": 3357
}
|
class ____ extends RegistryProtocol {
@Override
protected URL getRegistryUrl(Invoker<?> originInvoker) {
URL registryUrl = originInvoker.getUrl();
if (REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) {
String protocol = registryUrl.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY);
registryUrl = registryUrl.setProtocol(protocol).removeParameter(REGISTRY_KEY);
}
return registryUrl;
}
@Override
protected URL getRegistryUrl(URL url) {
return URLBuilder.from(url)
.setProtocol(url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY))
.removeParameter(REGISTRY_KEY)
.build();
}
@Override
public <T> ClusterInvoker<T> getInvoker(Cluster cluster, Registry registry, Class<T> type, URL url) {
DynamicDirectory<T> directory = new RegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
@Override
public <T> ClusterInvoker<T> getServiceDiscoveryInvoker(
Cluster cluster, Registry registry, Class<T> type, URL url) {
registry = getRegistry(super.getRegistryUrl(url));
DynamicDirectory<T> directory = new ServiceDiscoveryRegistryDirectory<>(type, url);
return doCreateInvoker(directory, cluster, registry, type);
}
@Override
protected <T> ClusterInvoker<T> getMigrationInvoker(
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
// ClusterInvoker<T> invoker = getInvoker(cluster, registry, type, url);
return new MigrationInvoker<>(registryProtocol, cluster, registry, type, url, consumerUrl);
}
}
|
InterfaceCompatibleRegistryProtocol
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/component/bean/issues/FilterBeanLanguageNonRegistryTest.java
|
{
"start": 1763,
"end": 1891
}
|
class ____ {
public boolean isGoldCustomer(String name) {
return "Camel".equals(name);
}
}
}
|
MyBean
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/testsupport/TestHelper.java
|
{
"start": 117892,
"end": 118351
}
|
class ____ such as {@code Maybe}
* @return the File pointing to the source
* @throws Exception on error
*/
public static File findSource(String baseClassName) throws Exception {
return findSource(baseClassName, "io.reactivex.rxjava3.core");
}
/**
* Given a base reactive type name, try to find its source in the current runtime
* path and return a file to it or null if not found.
* @param baseClassName the
|
name
|
java
|
quarkusio__quarkus
|
core/devmode-spi/src/main/java/io/quarkus/dev/console/CurrentAppExceptionHighlighter.java
|
{
"start": 439,
"end": 573
}
|
class ____ {
public static volatile BiConsumer<LogRecord, Consumer<LogRecord>> THROWABLE_FORMATTER;
}
|
CurrentAppExceptionHighlighter
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesCapacitySchedulerMixedModeAbsoluteAndWeight.java
|
{
"start": 3892,
"end": 5699
}
|
class ____ extends AbstractBinder {
@Override
protected void configure() {
Map<String, String> configMap = new HashMap<>();
configMap.put("yarn.scheduler.capacity.legacy-queue-mode.enabled", "false");
configMap.put("yarn.scheduler.capacity.root.queues", "default, test_1, test_2");
configMap.put("yarn.scheduler.capacity.root.test_1.queues", "test_1_1, test_1_2, test_1_3");
configMap.put("yarn.scheduler.capacity.root.default.capacity", "1w");
configMap.put("yarn.scheduler.capacity.root.test_1.capacity", "[memory=16384, vcores=16]");
configMap.put("yarn.scheduler.capacity.root.test_2.capacity", "3w");
configMap.put("yarn.scheduler.capacity.root.test_1.test_1_1.capacity",
"[memory=2048, vcores=2]");
configMap.put("yarn.scheduler.capacity.root.test_1.test_1_2.capacity",
"[memory=2048, vcores=2]");
configMap.put("yarn.scheduler.capacity.root.test_1.test_1_3.capacity", "1w");
conf = createConfiguration(configMap);
rm = createRM(createConfiguration(configMap));
final HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getScheme()).thenReturn("http");
final HttpServletResponse response = mock(HttpServletResponse.class);
rmWebServices = new RMWebServices(rm, conf);
bind(rm).to(ResourceManager.class).named("rm");
bind(conf).to(Configuration.class).named("conf");
bind(rmWebServices).to(RMWebServices.class);
bind(request).to(HttpServletRequest.class);
rmWebServices.setResponse(response);
bind(response).to(HttpServletResponse.class);
}
}
@Test
public void testSchedulerAbsoluteAndWeight() throws Exception {
runTest(EXPECTED_FILE_TMPL, "testSchedulerAbsoluteAndWeight", rm, target());
}
}
|
JerseyBinder
|
java
|
apache__flink
|
flink-queryable-state/flink-queryable-state-runtime/src/test/java/org/apache/flink/queryablestate/itcases/AbstractQueryableStateTestBase.java
|
{
"start": 47368,
"end": 48932
}
|
class ____
extends RichParallelSourceFunction<Tuple2<Integer, Long>> {
private static final long serialVersionUID = 1459935229498173245L;
private final long maxValue;
private volatile boolean isRunning = true;
TestAscendingValueSource(long maxValue) {
Preconditions.checkArgument(maxValue >= 0);
this.maxValue = maxValue;
}
@Override
public void open(OpenContext openContext) throws Exception {
super.open(openContext);
}
@Override
public void run(SourceContext<Tuple2<Integer, Long>> ctx) throws Exception {
// f0 => key
int key = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask();
Tuple2<Integer, Long> record = new Tuple2<>(key, 0L);
long currentValue = 0;
while (isRunning && currentValue <= maxValue) {
synchronized (ctx.getCheckpointLock()) {
record.f1 = currentValue;
ctx.collect(record);
}
currentValue++;
}
while (isRunning) {
synchronized (this) {
wait();
}
}
}
@Override
public void cancel() {
isRunning = false;
synchronized (this) {
notifyAll();
}
}
}
/** Test source producing (key, 1) tuples with random key in key range (numKeys). */
private static
|
TestAscendingValueSource
|
java
|
netty__netty
|
common/src/main/java/io/netty/util/concurrent/RejectedExecutionHandler.java
|
{
"start": 805,
"end": 1065
}
|
interface ____ {
/**
* Called when someone tried to add a task to {@link SingleThreadEventExecutor} but this failed due capacity
* restrictions.
*/
void rejected(Runnable task, SingleThreadEventExecutor executor);
}
|
RejectedExecutionHandler
|
java
|
apache__avro
|
lang/java/mapred/src/main/java/org/apache/avro/mapred/AvroMultipleInputs.java
|
{
"start": 2917,
"end": 3527
}
|
class ____ extends AvroMapper<Type2Record, Pair<ComparingKeyRecord, CommonValueRecord>>
* </pre>
*
* <p>
* <strong>Note on InputFormat:</strong> The InputFormat used will always be
* {@link AvroInputFormat} when using this class.
* </p>
* <p>
* <strong>Note on collector outputs:</strong> When using this class, you will
* need to ensure that the mapper implementations involved must all emit the
* same Key type and Value record types, as set by
* {@link AvroJob#setOutputSchema(JobConf, Schema)} or
* {@link AvroJob#setMapOutputSchema(JobConf, Schema)}.
* </p>
*/
public
|
Type2AvroMapper
|
java
|
quarkusio__quarkus
|
extensions/oidc-client-registration/runtime/src/main/java/io/quarkus/oidc/client/registration/OidcClientRegistrationConfig.java
|
{
"start": 319,
"end": 950
}
|
interface ____ extends OidcCommonConfig {
/**
* OIDC Client Registration id
*/
Optional<String> id();
/**
* If this client registration configuration is enabled.
*/
@WithDefault("true")
boolean registrationEnabled();
/**
* If the client configured with {@link #metadata} must be registered at startup.
*/
@WithDefault("true")
boolean registerEarly();
/**
* Initial access token
*/
Optional<String> initialToken();
/**
* Client metadata
*/
Metadata metadata();
/**
* Client metadata
*/
|
OidcClientRegistrationConfig
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/deduplicate/ProcTimeDeduplicateKeepFirstRowFunctionTest.java
|
{
"start": 1375,
"end": 4091
}
|
class ____ extends ProcTimeDeduplicateFunctionTestBase {
private OneInputStreamOperatorTestHarness<RowData, RowData> createTestHarness(
ProcTimeDeduplicateKeepFirstRowFunction func) throws Exception {
KeyedProcessOperator<RowData, RowData, RowData> operator = new KeyedProcessOperator<>(func);
return new KeyedOneInputStreamOperatorTestHarness<>(
operator, rowKeySelector, rowKeySelector.getProducedType());
}
@Test
void test() throws Exception {
ProcTimeDeduplicateKeepFirstRowFunction func =
new ProcTimeDeduplicateKeepFirstRowFunction(minTime.toMillis());
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createTestHarness(func);
testHarness.open();
testHarness.processElement(insertRecord("book", 1L, 12));
testHarness.processElement(insertRecord("book", 2L, 11));
testHarness.processElement(insertRecord("book", 1L, 13));
testHarness.close();
// Keep FirstRow in deduplicate will not send retraction
List<Object> expectedOutput = new ArrayList<>();
expectedOutput.add(insertRecord("book", 1L, 12));
expectedOutput.add(insertRecord("book", 2L, 11));
assertor.assertOutputEqualsSorted("output wrong.", expectedOutput, testHarness.getOutput());
}
@Test
void testWithStateTtl() throws Exception {
ProcTimeDeduplicateKeepFirstRowFunction func =
new ProcTimeDeduplicateKeepFirstRowFunction(minTime.toMillis());
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createTestHarness(func);
testHarness.open();
testHarness.processElement(insertRecord("book", 1L, 12));
testHarness.processElement(insertRecord("book", 2L, 11));
testHarness.processElement(insertRecord("book", 1L, 13));
testHarness.setStateTtlProcessingTime(30);
testHarness.processElement(insertRecord("book", 1L, 17));
testHarness.processElement(insertRecord("book", 2L, 18));
testHarness.processElement(insertRecord("book", 1L, 19));
// Keep FirstRow in deduplicate will not send retraction
List<Object> expectedOutput = new ArrayList<>();
expectedOutput.add(insertRecord("book", 1L, 12));
expectedOutput.add(insertRecord("book", 2L, 11));
// (1L,12),(2L,11) has retired, so output (1L,17) and (2L,18)
expectedOutput.add(insertRecord("book", 1L, 17));
expectedOutput.add(insertRecord("book", 2L, 18));
assertor.assertOutputEqualsSorted("output wrong.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
}
|
ProcTimeDeduplicateKeepFirstRowFunctionTest
|
java
|
resilience4j__resilience4j
|
resilience4j-feign/src/main/java/io/github/resilience4j/feign/DecoratorInvocationHandler.java
|
{
"start": 2016,
"end": 4401
}
|
interface ____ the {@link
* MethodHandler}s.
* @param invocationDecorator the {@link FeignDecorator} with which to decorate the {@link
* MethodHandler}s.
* @param target the target feign interface.
* @return a new map where the {@link MethodHandler}s are decorated with the {@link
* FeignDecorator}.
*/
private Map<Method, CheckedFunction<Object[], Object>> decorateMethodHandlers(
Map<Method, MethodHandler> dispatch,
FeignDecorator invocationDecorator, Target<?> target) {
final Map<Method, CheckedFunction<Object[], Object>> map = new HashMap<>();
for (final Map.Entry<Method, MethodHandler> entry : dispatch.entrySet()) {
final Method method = entry.getKey();
final MethodHandler methodHandler = entry.getValue();
if (methodHandler != null) {
CheckedFunction<Object[], Object> decorated = invocationDecorator
.decorate(methodHandler::invoke, method, methodHandler, target);
map.put(method, decorated);
}
}
return map;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable {
switch (method.getName()) {
case "equals":
return equals(args.length > 0 ? args[0] : null);
case "hashCode":
return hashCode();
case "toString":
return toString();
default:
break;
}
return decoratedDispatch.get(method).apply(args);
}
@Override
public boolean equals(Object obj) {
Object compareTo = obj;
if (compareTo == null) {
return false;
}
if (Proxy.isProxyClass(compareTo.getClass())) {
compareTo = Proxy.getInvocationHandler(compareTo);
}
if (compareTo instanceof DecoratorInvocationHandler) {
final DecoratorInvocationHandler other = (DecoratorInvocationHandler) compareTo;
return target.equals(other.target);
}
return false;
}
@Override
public int hashCode() {
return target.hashCode();
}
@Override
public String toString() {
return target.toString();
}
}
|
to
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/event/spi/LockEvent.java
|
{
"start": 268,
"end": 392
}
|
class ____ {@link org.hibernate.Session#lock}.
*
* @author Steve Ebersole
*
* @see org.hibernate.Session#lock
*/
public
|
for
|
java
|
hibernate__hibernate-orm
|
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/superdao/SuperDao.java
|
{
"start": 368,
"end": 533
}
|
interface ____ {
EntityManager em();
@Find
List<Book> books1(@Pattern String title);
@HQL("where title like :title")
List<Book> books2(String title);
}
|
SuperDao
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/core/ResolvableType.java
|
{
"start": 49153,
"end": 50510
}
|
class ____ declares the method
* includes generic parameter variables that are satisfied by the implementation class.
* @param method the source method (must not be {@code null})
* @param parameterIndex the parameter index
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified method parameter
* @see #forMethodParameter(Method, int, Class)
* @see #forMethodParameter(MethodParameter)
*/
public static ResolvableType forMethodParameter(Method method, int parameterIndex, Class<?> implementationClass) {
Assert.notNull(method, "Method must not be null");
MethodParameter methodParameter = new MethodParameter(method, parameterIndex, implementationClass);
return forMethodParameter(methodParameter);
}
/**
* Return a {@code ResolvableType} for the specified {@link MethodParameter}.
* @param methodParameter the source method parameter (must not be {@code null})
* @return a {@code ResolvableType} for the specified method parameter
* @see #forMethodParameter(Method, int)
*/
public static ResolvableType forMethodParameter(MethodParameter methodParameter) {
return forMethodParameter(methodParameter, (Type) null);
}
/**
* Return a {@code ResolvableType} for the specified {@link MethodParameter} with a
* given implementation type. Use this variant when the
|
that
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.