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
quarkusio__quarkus
extensions/websockets-next/runtime/src/main/java/io/quarkus/websockets/next/runtime/WebSocketEndpointBase.java
{ "start": 936, "end": 14551 }
class ____ implements WebSocketEndpoint { private static final Logger LOG = Logger.getLogger(WebSocketEndpointBase.class); // Keep this field public - there's a problem with ConnectionArgumentProvider reading the protected field in the test mode public final WebSocketConnectionBase connection; protected final Codecs codecs; private final ErrorInterceptor errorInterceptor; private final ConcurrencyLimiter limiter; private final ArcContainer container; private final ContextSupport contextSupport; private final SecuritySupport securitySupport; private final InjectableBean<?> bean; private final Object beanInstance; public WebSocketEndpointBase(WebSocketConnectionBase connection, Codecs codecs, ContextSupport contextSupport, SecuritySupport securitySupport, ErrorInterceptor errorInterceptor) { this.connection = connection; this.codecs = codecs; this.limiter = inboundProcessingMode() == InboundProcessingMode.SERIAL ? new ConcurrencyLimiter(connection) : null; this.container = Arc.container(); this.contextSupport = contextSupport; this.securitySupport = securitySupport; this.errorInterceptor = errorInterceptor; InjectableBean<?> bean = container.bean(beanIdentifier()); if (bean.getScope().equals(ApplicationScoped.class) || bean.getScope().equals(Singleton.class)) { // For certain scopes, we can optimize and obtain the contextual reference immediately this.bean = null; this.beanInstance = container.instance(bean).get(); } else { this.bean = bean; this.beanInstance = null; } } @Override public Future<Void> onOpen() { return execute(null, onOpenExecutionModel(), this::doOnOpen, false); } @Override public Future<Void> onTextMessage(Object message) { return execute(message, onTextMessageExecutionModel(), this::doOnTextMessage, false); } @Override public Future<Void> onBinaryMessage(Object message) { return execute(message, onBinaryMessageExecutionModel(), this::doOnBinaryMessage, false); } @Override public Future<Void> onPingMessage(Buffer message) { return execute(message, onPingMessageExecutionModel(), this::doOnPingMessage, false); } @Override public Future<Void> onPongMessage(Buffer message) { return execute(message, onPongMessageExecutionModel(), this::doOnPongMessage, false); } @Override public Future<Void> onClose() { return execute(null, onCloseExecutionModel(), this::doOnClose, true); } private <M> Future<Void> execute(M message, ExecutionModel executionModel, Function<M, Uni<Void>> action, boolean terminateSession) { if (executionModel == ExecutionModel.NONE) { if (terminateSession) { // Just start and terminate the session context contextSupport.startSession(); contextSupport.endSession(); } return Future.succeededFuture(); } Promise<Void> promise = Promise.promise(); Context context = Vertx.currentContext(); if (limiter != null) { PromiseComplete complete = limiter.newComplete(promise); limiter.run(context, new Runnable() { @Override public void run() { doExecute(context, message, executionModel, action, terminateSession, complete::complete, complete::failure); } }); } else { // No need to limit the concurrency doExecute(context, message, executionModel, action, terminateSession, promise::complete, promise::fail); } return promise.future(); } private <M> void doExecute(Context context, M message, ExecutionModel executionModel, Function<M, Uni<Void>> action, boolean terminateSession, Runnable onComplete, Consumer<? super Throwable> onFailure) { Handler<Void> contextSupportEnd = executionModel.isBlocking() ? new Handler<Void>() { @Override public void handle(Void event) { contextSupport.end(terminateSession); } } : null; if (executionModel == ExecutionModel.VIRTUAL_THREAD) { VirtualThreadsRecorder.getCurrent().execute(new Runnable() { @Override public void run() { Context context = Vertx.currentContext(); contextSupport.start(); action.apply(message).subscribe().with( v -> { context.runOnContext(contextSupportEnd); onComplete.run(); }, t -> { context.runOnContext(contextSupportEnd); onFailure.accept(t); }); } }); } else if (executionModel == ExecutionModel.WORKER_THREAD) { context.executeBlocking(new Callable<Void>() { @Override public Void call() { Context context = Vertx.currentContext(); contextSupport.start(); action.apply(message).subscribe().with( v -> { context.runOnContext(contextSupportEnd); onComplete.run(); }, t -> { context.runOnContext(contextSupportEnd); onFailure.accept(t); }); return null; } }, false); } else { // Event loop contextSupport.start(); action.apply(message).subscribe().with( v -> { contextSupport.end(terminateSession); onComplete.run(); }, t -> { contextSupport.end(terminateSession); onFailure.accept(t); }); } } public Uni<Void> doErrorExecute(Throwable throwable, ExecutionModel executionModel, Function<Throwable, Uni<Void>> action) { Promise<Void> promise = Promise.promise(); // Always execute error handler on a new duplicated context ContextSupport.createNewDuplicatedContext(Vertx.currentContext(), connection).runOnContext(new Handler<Void>() { @Override public void handle(Void event) { Handler<Void> contextSupportEnd = new Handler<Void>() { @Override public void handle(Void event) { contextSupport.end(false); } }; if (executionModel == ExecutionModel.VIRTUAL_THREAD) { VirtualThreadsRecorder.getCurrent().execute(new Runnable() { @Override public void run() { Context context = Vertx.currentContext(); contextSupport.start(); action.apply(throwable).subscribe().with( v -> { context.runOnContext(contextSupportEnd); promise.complete(); }, t -> { context.runOnContext(contextSupportEnd); promise.fail(t); }); } }); } else if (executionModel == ExecutionModel.WORKER_THREAD) { Vertx.currentContext().executeBlocking(new Callable<Void>() { @Override public Void call() { Context context = Vertx.currentContext(); contextSupport.start(); action.apply(throwable).subscribe().with( v -> { context.runOnContext(contextSupportEnd); promise.complete(); }, t -> { context.runOnContext(contextSupportEnd); promise.fail(t); }); return null; } }, false); } else { Vertx.currentContext().runOnContext(new Handler<Void>() { @Override public void handle(Void event) { Context context = Vertx.currentContext(); contextSupport.start(); action.apply(throwable).subscribe().with( v -> { context.runOnContext(contextSupportEnd); promise.complete(); }, t -> { context.runOnContext(contextSupportEnd); promise.fail(t); }); } }); } } }); return Uni.createFrom().completionStage(() -> promise.future().toCompletionStage()); } public Object beanInstance() { return beanInstance != null ? beanInstance : container.instance(bean).get(); } public Object beanInstance(String identifier) { return container.instance(container.bean(identifier)).get(); } protected Uni<Void> doOnOpen(Object message) { return Uni.createFrom().voidItem(); } protected Uni<Void> doOnTextMessage(Object message) { return Uni.createFrom().voidItem(); } protected Uni<Void> doOnBinaryMessage(Object message) { return Uni.createFrom().voidItem(); } protected Uni<Void> doOnPingMessage(Buffer message) { return Uni.createFrom().voidItem(); } protected Uni<Void> doOnPongMessage(Buffer message) { return Uni.createFrom().voidItem(); } protected Uni<Void> doOnClose(Object message) { return Uni.createFrom().voidItem(); } @Override public Uni<Void> doOnError(Throwable t) { // This method is overridden if there is at least one error handler defined interceptError(t); return Uni.createFrom().failure(t); } // method is used in generated subclasses, if you change a name, change bytecode generation as well public void interceptError(Throwable t) { if (errorInterceptor != null) { errorInterceptor.intercept(t); } } public Object decodeText(Type type, String value, Class<?> codecBeanClass) { return codecs.textDecode(type, value, codecBeanClass); } public String encodeText(Object value, Class<?> codecBeanClass) { if (value == null) { return null; } return codecs.textEncode(value, codecBeanClass); } public Object decodeBinary(Type type, Buffer value, Class<?> codecBeanClass) { return codecs.binaryDecode(type, value, codecBeanClass); } public Buffer encodeBinary(Object value, Class<?> codecBeanClass) { if (value == null) { return null; } return codecs.binaryEncode(value, codecBeanClass); } public Uni<Void> sendText(String message, boolean broadcast) { return broadcast ? connection.broadcast().sendText(message) : connection.sendText(message); } public Uni<Void> multiText(Multi<Object> multi, Function<? super Object, Uni<?>> action) { multi // Encode and send message .onItem().call(action) .onFailure().recoverWithMulti(t -> { return doOnError(t).toMulti(); }) .subscribe().with( m -> LOG.debugf("Multi >> text message: %s", connection), t -> LOG.errorf(t, "Unable to send text message from Multi: %s ", connection)); return Uni.createFrom().voidItem(); } public Uni<Void> sendBinary(Buffer message, boolean broadcast) { return broadcast ? connection.broadcast().sendBinary(message) : connection.sendBinary(message); } public Uni<Void> multiBinary(Multi<Object> multi, Function<? super Object, Uni<?>> action) { multi // Encode and send message .onItem().call(action) .onFailure().recoverWithMulti(t -> doOnError(t).toMulti()) .subscribe().with( m -> LOG.debugf("Multi >> binary message: %s", connection), t -> LOG.errorf(t, "Unable to send binary message from Multi: %s ", connection)); return Uni.createFrom().voidItem(); } }
WebSocketEndpointBase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/QuotedIdentifierTest.java
{ "start": 2050, "end": 2300 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "`index`") private int index; @Column(name = "`timestamp`") private long timestamp; @Column(name = "`from`") private String from; } }
QuotedIdentifier
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ClassNewInstanceTest.java
{ "start": 871, "end": 1188 }
class ____ { private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(ClassNewInstance.class, getClass()); @Test public void differentHandles() { testHelper .addInputLines( "in/Test.java", """
ClassNewInstanceTest
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson/OidcUserAuthorityMixin.java
{ "start": 1196, "end": 1658 }
class ____ used to serialize/deserialize {@link OidcUserAuthority}. * * @author Sebastien Deleuze * @author Joe Grandja * @since 7.0 * @see OidcUserAuthority * @see OAuth2ClientJacksonModule */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties({ "attributes" }) abstract
is
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/AllocationTagInfo.java
{ "start": 1166, "end": 1695 }
class ____ { private String allocationTag; private long allocationsCount; public AllocationTagInfo() { // JAXB needs this } public AllocationTagInfo(String tag, long count) { this.allocationTag = tag; this.allocationsCount = count; } public String getAllocationTag() { return this.allocationTag; } public long getAllocationsCount() { return this.allocationsCount; } @Override public String toString() { return allocationTag + "(" + allocationsCount + ")"; } }
AllocationTagInfo
java
apache__camel
components/camel-whatsapp/src/test/java/org/apache/camel/component/whatsapp/WhatsAppApiConfig.java
{ "start": 862, "end": 2694 }
class ____ { private final String authorizationToken; private final int port; private final String baseUri; private final String phoneNumberId; private final String apiVersion; private final String recipientPhoneNumber; public WhatsAppApiConfig(String baseUri, int port, String authorizationToken, String phoneNumberId, String apiVersion, String recipientPhoneNumber) { this.baseUri = baseUri; this.port = port; this.authorizationToken = authorizationToken; this.phoneNumberId = phoneNumberId; this.apiVersion = apiVersion; this.recipientPhoneNumber = recipientPhoneNumber; } public static WhatsAppApiConfig fromEnv() { final String authorizationToken = System.getenv("WHATSAPP_AUTHORIZATION_TOKEN"); final String phoneNumberId = System.getenv("WHATSAPP_PHONE_NUMBER_ID"); final String recipientPhoneNumber = System.getenv("WHATSAPP_RECIPIENT_PHONE_NUMBER"); return new WhatsAppApiConfig( WhatsAppComponent.API_DEFAULT_URL, 443, authorizationToken, phoneNumberId, WhatsAppComponent.API_DEFAULT_VERSION, recipientPhoneNumber); } public static WhatsAppApiConfig mock(int port) { return new WhatsAppApiConfig("http://localhost:" + port, port, "mock-token", "-1", "v1", "1"); } public String getAuthorizationToken() { return authorizationToken; } public String getBaseUri() { return baseUri; } public int getPort() { return port; } public String getPhoneNumberId() { return phoneNumberId; } public String getApiVersion() { return apiVersion; } public String getRecipientPhoneNumber() { return recipientPhoneNumber; } }
WhatsAppApiConfig
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/create/MySQLCreateMaterializedViewTest7.java
{ "start": 852, "end": 6939 }
class ____ extends MysqlTest { public void test1() throws Exception { String sql = "create materialized view `a` (\n" + " `__adb_auto_id__` bigint AUTO_INCREMENT,\n" + " `id` int comment 'id',\n" + " `name` varchar(10),\n" + " `value` double,\n" + " index index_id(`name` ASC, `value` ASC),\n" + " primary key (`__adb_auto_id__`)\n" + ") DISTRIBUTED BY HASH(`__adb_auto_id__`)\n" + "comment 'materialized view a'\n" + "as select * from base;"; ok(sql, "CREATE MATERIALIZED VIEW `a` (\n" + "\t`__adb_auto_id__` bigint AUTO_INCREMENT,\n" + "\t`id` int COMMENT 'id',\n" + "\t`name` varchar(10),\n" + "\t`value` double,\n" + "\tINDEX index_id(`name` ASC, `value` ASC),\n" + "\tPRIMARY KEY (`__adb_auto_id__`)\n" + ")\n" + "DISTRIBUTED BY HASH(`__adb_auto_id__`)\n" + "COMMENT 'materialized view a'\n" + "AS\n" + "SELECT *\n" + "FROM base;"); } public void test2() throws Exception { String sql = "create materialized view `b` (\n" + " `id` int comment 'id',\n" + " `name` varchar(10) primary key\n" + ") \n" + "DISTRIBUTED BY BROADCAST\n" + "INDEX_ALL = 'Y'\n" + "comment 'materialized view b'\n" + "as select * from base;"; ok(sql, "CREATE MATERIALIZED VIEW `b` (\n" + "\t`id` int COMMENT 'id',\n" + "\t`name` varchar(10) PRIMARY KEY\n" + ")\n" + "DISTRIBUTED BY BROADCAST INDEX_ALL = 'Y'\n" + "COMMENT 'materialized view b'\n" + "AS\n" + "SELECT *\n" + "FROM base;"); } public void test3() throws Exception { String sql = "create materialized view c (\n" + " key index_id(id) comment 'id',\n" + " name varchar(10),\n" + " value double,\n" + " clustered key idex(name, value),\n" + " primary key(id)\n" + ") \n" + "DISTRIBUTED by hash(id)\n" + "partition by value(date_format(dat, \"%Y%m%d\")) LIFECYCLE 30\n" + "comment 'materialized view c'\n" + "as select * from base;"; ok(sql, "CREATE MATERIALIZED VIEW c (\n" + "\tKEY index_id (id) COMMENT 'id',\n" + "\tname varchar(10),\n" + "\tvalue double,\n" + "\tCLUSTERED KEY idex (name, value),\n" + "\tPRIMARY KEY (id)\n" + ")\n" + "DISTRIBUTED BY HASH(id)\n" + "COMMENT 'materialized view c'\n" + "PARTITION BY VALUE (date_format(dat, '%Y%m%d'))\n" + "LIFECYCLE 30\n" + "AS\n" + "SELECT *\n" + "FROM base;"); } public void test4() throws Exception { String sql = "create materialized view d (\n" + " id bigint(20) not null comment 'id',\n" + " name varchar(10)\n" + ") \n" + "ENGINE = 'CSTORE'\n" + "INDEX_ALL = 'Y'\n" + "DISTRIBUTED BY HASH(`ID`)\n" + "partition by value(name) LIFECYCLE 15\n" + "COMMENT 'materialized view d'\n" + "as select * from base;"; ok(sql, "CREATE MATERIALIZED VIEW d (\n" + "\tid bigint(20) NOT NULL COMMENT 'id',\n" + "\tname varchar(10)\n" + ")\n" + "DISTRIBUTED BY HASH(`ID`) ENGINE = 'CSTORE' INDEX_ALL = 'Y'\n" + "COMMENT 'materialized view d'\n" + "PARTITION BY VALUE (name)\n" + "LIFECYCLE 15\n" + "AS\n" + "SELECT *\n" + "FROM base;"); } public void test5() throws Exception { String sql = "Create Materialized View `mview_0` (\n" + " `a` int,\n" + " `b` double,\n" + " `c` float,\n" + " `d` int,\n" + " `e` double,\n" + " `f` float,\n" + " primary key (`a`)\n" + ") DISTRIBUTED BY HASH(`a`) INDEX_ALL='Y'\n" + " REFRESH COMPLETE ON DEMAND\n" + " START WITH '2020-09-02 16:06:05'\n" + " NEXT adddatedatetime(now(), INTERVAL '10' MINUTE)\n" + " DISABLE QUERY REWRITE\n" + "AS SELECT *\n" + "FROM\n" + " `base0`\n" + ", `base1`\n" + "WHERE ((`a` = `d`) AND (`c` <> `F`))"; ok(sql, "CREATE MATERIALIZED VIEW `mview_0` (\n" + "\t`a` int,\n" + "\t`b` double,\n" + "\t`c` float,\n" + "\t`d` int,\n" + "\t`e` double,\n" + "\t`f` float,\n" + "\tPRIMARY KEY (`a`)\n" + ")\n" + "DISTRIBUTED BY HASH(`a`) INDEX_ALL = 'Y'\n" + "REFRESH COMPLETE ON DEMAND\n" + "START WITH '2020-09-02 16:06:05' NEXT adddatedatetime(now(), INTERVAL '10' MINUTE)\n" + "DISABLE QUERY REWRITE\n" + "AS\n" + "SELECT *\n" + "FROM `base0`, `base1`\n" + "WHERE ((`a` = `d`)\n" + "\tAND (`c` <> `F`))"); } public void ok(String sql, String expectedSql) { SQLStatement stmt = SQLUtils.parseSingleMysqlStatement(sql); assertEquals(expectedSql, stmt.toString(VisitorFeature.OutputDistributedLiteralInCreateTableStmt)); } }
MySQLCreateMaterializedViewTest7
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/property/access/spi/EnhancedSetterImpl.java
{ "start": 923, "end": 1724 }
class ____ extends SetterFieldImpl { private final String propertyName; private final int enhancementState; public EnhancedSetterImpl(Class<?> containerClass, String propertyName, Field field) { super( containerClass, propertyName, field ); this.propertyName = propertyName; this.enhancementState = determineEnhancementState( containerClass, field.getType() ); } @Override public void set(Object target, @Nullable Object value) { super.set( target, value ); handleEnhancedInjection( target, value, enhancementState, propertyName ); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // serialization @Serial private Object writeReplace() { return new SerialForm( getContainerClass(), propertyName, getField() ); } private static
EnhancedSetterImpl
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java
{ "start": 2176, "end": 8053 }
class ____ extends LoggingCodecSupport implements HttpMessageReader<Part> { private int maxInMemorySize = 256 * 1024; private int maxHeadersSize = 10 * 1024; private long maxDiskUsagePerPart = -1; private int maxParts = -1; private @Nullable Scheduler blockingOperationScheduler; private FileStorage fileStorage = FileStorage.tempDirectory(this::getBlockingOperationScheduler); private Charset headersCharset = StandardCharsets.UTF_8; /** * Configure the maximum amount of memory that is allowed per headers section of each part. * When the limit * @param byteCount the maximum amount of memory for headers */ public void setMaxHeadersSize(int byteCount) { this.maxHeadersSize = byteCount; } /** * Get the {@link #setMaxInMemorySize configured} maximum in-memory size. */ public int getMaxInMemorySize() { return this.maxInMemorySize; } /** * Configure the maximum amount of memory allowed per part. * When the limit is exceeded: * <ul> * <li>file parts are written to a temporary file. * <li>non-file parts are rejected with {@link DataBufferLimitException}. * </ul> * <p>By default this is set to 256K. * @param maxInMemorySize the in-memory limit in bytes; if set to -1 the entire * contents will be stored in memory */ public void setMaxInMemorySize(int maxInMemorySize) { this.maxInMemorySize = maxInMemorySize; } /** * Configure the maximum amount of disk space allowed for file parts. * <p>By default this is set to -1, meaning that there is no maximum. * <p>Note that this property is ignored when * {@link #setMaxInMemorySize(int) maxInMemorySize} is set to -1. */ public void setMaxDiskUsagePerPart(long maxDiskUsagePerPart) { this.maxDiskUsagePerPart = maxDiskUsagePerPart; } /** * Specify the maximum number of parts allowed in a given multipart request. * <p>By default this is set to -1, meaning that there is no maximum. */ public void setMaxParts(int maxParts) { this.maxParts = maxParts; } /** * Set the directory used to store parts larger than * {@link #setMaxInMemorySize(int) maxInMemorySize}. By default, a directory * named {@code spring-webflux-multipart} is created under the system * temporary directory. * <p>Note that this property is ignored when * {@link #setMaxInMemorySize(int) maxInMemorySize} is set to -1. * @throws IOException if an I/O error occurs, or the parent directory * does not exist */ public void setFileStorageDirectory(Path fileStorageDirectory) throws IOException { Assert.notNull(fileStorageDirectory, "FileStorageDirectory must not be null"); this.fileStorage = FileStorage.fromPath(fileStorageDirectory); } /** * Set the Reactor {@link Scheduler} to be used for creating files and * directories, and writing to files. By default, * {@link Schedulers#boundedElastic()} is used, but this property allows for * changing it to an externally managed scheduler. * <p>Note that this property is ignored when * {@link #setMaxInMemorySize(int) maxInMemorySize} is set to -1. * @see Schedulers#boundedElastic */ public void setBlockingOperationScheduler(Scheduler blockingOperationScheduler) { Assert.notNull(blockingOperationScheduler, "'blockingOperationScheduler' must not be null"); this.blockingOperationScheduler = blockingOperationScheduler; } private Scheduler getBlockingOperationScheduler() { return (this.blockingOperationScheduler != null ? this.blockingOperationScheduler : Schedulers.boundedElastic()); } /** * Set the character set used to decode headers. * Defaults to UTF-8 as per RFC 7578. * @param headersCharset the charset to use for decoding headers * @since 5.3.6 * @see <a href="https://tools.ietf.org/html/rfc7578#section-5.1">RFC-7578 Section 5.1</a> */ public void setHeadersCharset(Charset headersCharset) { Assert.notNull(headersCharset, "HeadersCharset must not be null"); this.headersCharset = headersCharset; } @Override public List<MediaType> getReadableMediaTypes() { return Collections.singletonList(MediaType.MULTIPART_FORM_DATA); } @Override public boolean canRead(ResolvableType elementType, @Nullable MediaType mediaType) { return Part.class.equals(elementType.toClass()) && (mediaType == null || MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)); } @Override public Mono<Part> readMono(ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) { return Mono.error(new UnsupportedOperationException("Cannot read multipart request body into single Part")); } @Override public Flux<Part> read(ResolvableType elementType, ReactiveHttpInputMessage message, Map<String, Object> hints) { return Flux.defer(() -> { byte[] boundary = MultipartUtils.boundary(message, this.headersCharset); if (boundary == null) { return Flux.error(new DecodingException("No multipart boundary found in Content-Type: \"" + message.getHeaders().getContentType() + "\"")); } Flux<MultipartParser.Token> allPartsTokens = MultipartParser.parse(message.getBody(), boundary, this.maxHeadersSize, this.headersCharset); AtomicInteger partCount = new AtomicInteger(); return allPartsTokens .windowUntil(MultipartParser.Token::isLast) .concatMap(partsTokens -> { if (tooManyParts(partCount)) { return Mono.error(new DecodingException("Too many parts (" + partCount.get() + "/" + this.maxParts + " allowed)")); } else { return PartGenerator.createPart(partsTokens, this.maxInMemorySize, this.maxDiskUsagePerPart, this.fileStorage.directory(), getBlockingOperationScheduler()); } }); }); } private boolean tooManyParts(AtomicInteger partCount) { int count = partCount.incrementAndGet(); return this.maxParts > 0 && count > this.maxParts; } }
DefaultPartHttpMessageReader
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/issues/DerivedClass.java
{ "start": 859, "end": 1117 }
class ____ extends BaseClass { private String body; public void process(String body) { this.body = body; } public String getAndClearBody() { String answer = body; body = null; return answer; } }
DerivedClass
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldNotStartWithWhitespaces.java
{ "start": 810, "end": 1425 }
class ____ extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldNotStartWithWhitespaces}</code>. * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotStartWithWhitespaces(CharSequence actual) { return new ShouldNotStartWithWhitespaces(actual); } private ShouldNotStartWithWhitespaces(Object actual) { super("%n" + "Expecting string not to start with whitespaces but found one, string was:%n" + " %s", actual); } }
ShouldNotStartWithWhitespaces
java
quarkusio__quarkus
extensions/observability-devservices/runtime/src/main/java/io/quarkus/observability/runtime/DevResourcesConfigBuilder.java
{ "start": 225, "end": 585 }
class ____ implements ConfigBuilder { @Override public SmallRyeConfigBuilder configBuilder(SmallRyeConfigBuilder builder) { return builder.withSources(new DevResourcesConfigSource()); } @Override public int priority() { // greater than any default Microprofile ConfigSource return 500; } }
DevResourcesConfigBuilder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/ExpectedTestException.java
{ "start": 993, "end": 1268 }
class ____ extends RuntimeException { public static final String MESSAGE = "Expected Test Exception"; public ExpectedTestException() { super(MESSAGE); } public ExpectedTestException(String message) { super(message); } }
ExpectedTestException
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/SessionContext.java
{ "start": 370, "end": 1244 }
class ____ extends CurrentManagedContext { public SessionContext(CurrentContext<CurrentContextState> currentContext, Notifier<Object> initializedNotifier, Notifier<Object> beforeDestroyedNotifier, Notifier<Object> destroyedNotifier, Supplier<ContextInstances> contextInstances) { super(currentContext, contextInstances, initializedNotifier != null ? initializedNotifier::notify : null, beforeDestroyedNotifier != null ? beforeDestroyedNotifier::notify : null, destroyedNotifier != null ? destroyedNotifier::notify : null); } @Override public Class<? extends Annotation> getScope() { return SessionScoped.class; } @Override protected ContextNotActiveException notActive() { return new ContextNotActiveException("Session context is not active"); } }
SessionContext
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/settings/put/UpdateSettingsRequestBuilder.java
{ "start": 979, "end": 3126 }
class ____ extends AcknowledgedRequestBuilder< UpdateSettingsRequest, AcknowledgedResponse, UpdateSettingsRequestBuilder> { public UpdateSettingsRequestBuilder(ElasticsearchClient client, String... indices) { super(client, TransportUpdateSettingsAction.TYPE, new UpdateSettingsRequest(indices)); } /** * Sets the indices the update settings will execute on */ public UpdateSettingsRequestBuilder setIndices(String... indices) { request.indices(indices); return this; } /** * Specifies what type of requested indices to ignore and wildcard indices expressions. * <p> * For example indices that don't exist. */ public UpdateSettingsRequestBuilder setIndicesOptions(IndicesOptions options) { request.indicesOptions(options); return this; } /** * Sets the settings to be updated */ public UpdateSettingsRequestBuilder setSettings(Settings settings) { request.settings(settings); return this; } /** * Sets the settings to be updated */ public UpdateSettingsRequestBuilder setSettings(Settings.Builder settings) { request.settings(settings); return this; } /** * Sets the settings to be updated (either json or yaml format) */ public UpdateSettingsRequestBuilder setSettings(String source, XContentType xContentType) { request.settings(source, xContentType); return this; } /** * Sets the settings to be updated */ public UpdateSettingsRequestBuilder setSettings(Map<String, Object> source) { request.settings(source); return this; } public UpdateSettingsRequestBuilder setPreserveExisting(boolean preserveExisting) { request.setPreserveExisting(preserveExisting); return this; } /** * Sets the origin to use, only set this when the settings update is requested by ES internal processes. */ public UpdateSettingsRequestBuilder origin(String origin) { request.origin(origin); return this; } }
UpdateSettingsRequestBuilder
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerConfig.java
{ "start": 8919, "end": 17013 }
interface ____ you to plug in a custom assignment strategy.</p>"; /** * <code>auto.offset.reset</code> */ public static final String AUTO_OFFSET_RESET_CONFIG = "auto.offset.reset"; public static final String AUTO_OFFSET_RESET_DOC = "What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server " + "(e.g. because that data has been deleted): " + "<ul><li>earliest: automatically reset the offset to the earliest offset</li>" + "<li>latest: automatically reset the offset to the latest offset</li>" + "<li>by_duration:&lt;duration&gt;: automatically reset the offset to a configured &lt;duration&gt; from the current timestamp. &lt;duration&gt; must be specified in ISO8601 format (PnDTnHnMn.nS). " + "Negative duration is not allowed.</li>" + "<li>none: throw exception to the consumer if no previous offset is found for the consumer's group</li>" + "<li>anything else: throw exception to the consumer.</li></ul>" + "<p>Note that altering partition numbers while setting this config to latest may cause message delivery loss since " + "producers could start to send messages to newly added partitions (i.e. no initial offsets exist yet) before consumers reset their offsets."; /** * <code>fetch.min.bytes</code> */ public static final String FETCH_MIN_BYTES_CONFIG = "fetch.min.bytes"; public static final int DEFAULT_FETCH_MIN_BYTES = 1; private static final String FETCH_MIN_BYTES_DOC = "The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. The default setting of " + DEFAULT_FETCH_MIN_BYTES + " byte means that fetch requests are answered as soon as that many byte(s) of data is available or the fetch request times out waiting for data to arrive. Setting this to a larger value will cause the server to wait for larger amounts of data to accumulate which can improve server throughput a bit at the cost of some additional latency. Even if the total data available in the broker exceeds fetch.min.bytes, the actual returned size may still be less than this value due to per-partition limits max.partition.fetch.bytes and max returned limits fetch.max.bytes."; /** * <code>fetch.max.bytes</code> */ public static final String FETCH_MAX_BYTES_CONFIG = "fetch.max.bytes"; private static final String FETCH_MAX_BYTES_DOC = "The maximum amount of data the server should return for a fetch request. " + "Records are fetched in batches by the consumer, and if the first record batch in the first non-empty partition of the fetch is larger than " + "this value, the record batch will still be returned to ensure that the consumer can make progress. As such, this is not a absolute maximum. " + "The maximum record batch size accepted by the broker is defined via <code>message.max.bytes</code> (broker config) or " + "<code>max.message.bytes</code> (topic config). A fetch request consists of many partitions, and there is another setting that controls how much " + "data is returned for each partition in a fetch request - see <code>max.partition.fetch.bytes</code>. Note that the consumer performs multiple fetches in parallel."; public static final int DEFAULT_FETCH_MAX_BYTES = 50 * 1024 * 1024; /** * <code>fetch.max.wait.ms</code> */ public static final String FETCH_MAX_WAIT_MS_CONFIG = "fetch.max.wait.ms"; private static final String FETCH_MAX_WAIT_MS_DOC = "The maximum amount of time the server will block before " + "answering the fetch request there isn't sufficient data to immediately satisfy the requirement given by " + "fetch.min.bytes. This config is used only for local log fetch. To tune the remote fetch maximum wait " + "time, please refer to 'remote.fetch.max.wait.ms' broker config"; public static final int DEFAULT_FETCH_MAX_WAIT_MS = 500; /** <code>metadata.max.age.ms</code> */ public static final String METADATA_MAX_AGE_CONFIG = CommonClientConfigs.METADATA_MAX_AGE_CONFIG; /** * <code>max.partition.fetch.bytes</code> */ public static final String MAX_PARTITION_FETCH_BYTES_CONFIG = "max.partition.fetch.bytes"; private static final String MAX_PARTITION_FETCH_BYTES_DOC = "The maximum amount of data per-partition the server " + "will return. Records are fetched in batches by the consumer. If the first record batch in the first non-empty " + "partition of the fetch is larger than this limit, the " + "batch will still be returned to ensure that the consumer can make progress. The maximum record batch size " + "accepted by the broker is defined via <code>message.max.bytes</code> (broker config) or " + "<code>max.message.bytes</code> (topic config). See " + FETCH_MAX_BYTES_CONFIG + " for limiting the consumer request size."; public static final int DEFAULT_MAX_PARTITION_FETCH_BYTES = 1 * 1024 * 1024; /** <code>send.buffer.bytes</code> */ public static final String SEND_BUFFER_CONFIG = CommonClientConfigs.SEND_BUFFER_CONFIG; /** <code>receive.buffer.bytes</code> */ public static final String RECEIVE_BUFFER_CONFIG = CommonClientConfigs.RECEIVE_BUFFER_CONFIG; /** * <code>client.id</code> */ public static final String CLIENT_ID_CONFIG = CommonClientConfigs.CLIENT_ID_CONFIG; /** * <code>client.rack</code> */ public static final String CLIENT_RACK_CONFIG = CommonClientConfigs.CLIENT_RACK_CONFIG; public static final String DEFAULT_CLIENT_RACK = CommonClientConfigs.DEFAULT_CLIENT_RACK; /** * <code>reconnect.backoff.ms</code> */ public static final String RECONNECT_BACKOFF_MS_CONFIG = CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG; /** * <code>reconnect.backoff.max.ms</code> */ public static final String RECONNECT_BACKOFF_MAX_MS_CONFIG = CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG; /** * <code>retry.backoff.ms</code> */ public static final String RETRY_BACKOFF_MS_CONFIG = CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG; /** * <code>enable.metrics.push</code> */ public static final String ENABLE_METRICS_PUSH_CONFIG = CommonClientConfigs.ENABLE_METRICS_PUSH_CONFIG; public static final String ENABLE_METRICS_PUSH_DOC = CommonClientConfigs.ENABLE_METRICS_PUSH_DOC; /** * <code>retry.backoff.max.ms</code> */ public static final String RETRY_BACKOFF_MAX_MS_CONFIG = CommonClientConfigs.RETRY_BACKOFF_MAX_MS_CONFIG; /** * <code>metrics.sample.window.ms</code> */ public static final String METRICS_SAMPLE_WINDOW_MS_CONFIG = CommonClientConfigs.METRICS_SAMPLE_WINDOW_MS_CONFIG; /** * <code>metrics.num.samples</code> */ public static final String METRICS_NUM_SAMPLES_CONFIG = CommonClientConfigs.METRICS_NUM_SAMPLES_CONFIG; /** * <code>metrics.log.level</code> */ public static final String METRICS_RECORDING_LEVEL_CONFIG = CommonClientConfigs.METRICS_RECORDING_LEVEL_CONFIG; /** * <code>metric.reporters</code> */ public static final String METRIC_REPORTER_CLASSES_CONFIG = CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG; /** * <code>check.crcs</code> */ public static final String CHECK_CRCS_CONFIG = "check.crcs"; private static final String CHECK_CRCS_DOC = "Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance."; /** <code>key.deserializer</code> */ public static final String KEY_DESERIALIZER_CLASS_CONFIG = "key.deserializer"; public static final String KEY_DESERIALIZER_CLASS_DOC = "Deserializer
allows
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/foreach/MyBeanWithPrimary.java
{ "start": 741, "end": 1034 }
class ____ { final MyConfigurationWithPrimary configuration; MyBeanWithPrimary(MyConfigurationWithPrimary configuration) { this.configuration = configuration; } public MyConfigurationWithPrimary getConfiguration() { return configuration; } }
MyBeanWithPrimary
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/main/java/org/hibernate/processor/util/TypeUtils.java
{ "start": 27042, "end": 27195 }
class ____ generated in a previous compilation. (It could be * part of a separate jar. See also METAGEN-35.) * * @param superClassElement the super
was
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/handler/predicate/GatewayPredicate.java
{ "start": 3069, "end": 3822 }
class ____ implements GatewayPredicate { private final GatewayPredicate left; private final GatewayPredicate right; public AndGatewayPredicate(GatewayPredicate left, GatewayPredicate right) { Objects.requireNonNull(left, "Left GatewayPredicate must not be null"); Objects.requireNonNull(right, "Right GatewayPredicate must not be null"); this.left = left; this.right = right; } @Override public boolean test(ServerWebExchange t) { return (this.left.test(t) && this.right.test(t)); } @Override public void accept(Visitor visitor) { left.accept(visitor); right.accept(visitor); } @Override public String toString() { return String.format("(%s && %s)", this.left, this.right); } }
AndGatewayPredicate
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-links/deployment/src/main/java/io/quarkus/resteasy/reactive/links/deployment/GetterAccessorImplementor.java
{ "start": 334, "end": 1252 }
class ____ { /** * Implements a {@link GetterAccessor} that knows how to access a specific getter method of a specific type. */ void implement(ClassOutput classOutput, GetterMetadata getterMetadata) { ClassCreator classCreator = ClassCreator.builder() .classOutput(classOutput).className(getterMetadata.getGetterAccessorName()) .interfaces(GetterAccessor.class) .build(); MethodCreator methodCreator = classCreator.getMethodCreator("get", Object.class, Object.class); ResultHandle value = methodCreator.invokeVirtualMethod( ofMethod(getterMetadata.getEntityType(), getterMetadata.getGetterName(), getterMetadata.getFieldType()), methodCreator.getMethodParam(0)); methodCreator.returnValue(value); methodCreator.close(); classCreator.close(); } }
GetterAccessorImplementor
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/resource/GenericEntityFloatWriter.java
{ "start": 575, "end": 1895 }
class ____ implements MessageBodyWriter<List<Float>> { private static final Logger LOG = Logger.getLogger(GenericEntityFloatWriter.class); public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (!List.class.isAssignableFrom(type)) { return false; } if (!(genericType instanceof ParameterizedType)) { return false; } ParameterizedType pt = (ParameterizedType) genericType; boolean result = pt.getActualTypeArguments()[0].equals(Float.class); LOG.debug("FloatWriter result!!!: " + result); return result; } public long getSize(List<Float> floats, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } public void writeTo(List<Float> floats, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { StringBuilder buf = new StringBuilder(); for (Float f : floats) { buf.append(f.toString()).append("F "); } entityStream.write(buf.toString().getBytes()); } }
GenericEntityFloatWriter
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-common/spi/src/main/java/io/quarkus/resteasy/common/spi/ResteasyDotNames.java
{ "start": 4504, "end": 5167 }
class ____ implements Predicate<DotName> { @Override public boolean test(DotName dotName) { if (ResteasyDotNames.TYPES_IGNORED_FOR_REFLECTION.contains(dotName) || ReflectiveHierarchyBuildItem.DefaultIgnoreTypePredicate.INSTANCE.test(dotName)) { return true; } String name = dotName.toString(); for (String packageName : PACKAGES_IGNORED_FOR_REFLECTION) { if (name.startsWith(packageName)) { return true; } } return false; } } private static
IgnoreTypeForReflectionPredicate
java
elastic__elasticsearch
x-pack/plugin/deprecation/src/main/java/org/elasticsearch/xpack/deprecation/logging/DeprecationIndexingAppender.java
{ "start": 1335, "end": 3880 }
class ____ extends AbstractAppender { private static final Logger logger = LogManager.getLogger(DeprecationIndexingAppender.class); public static final String DEPRECATION_MESSAGES_DATA_STREAM = ".logs-elasticsearch.deprecation-default"; private final Consumer<IndexRequest> requestConsumer; /** * You can't start and stop an appender to toggle it, so this flag reflects whether * writes should in fact be carried out. */ private volatile boolean isEnabled = false; /** * Creates a new appender. * * @param name the appender's name * @param filter a filter to apply directly on the appender * @param layout the layout to use for formatting message. It must return a JSON string. * @param requestConsumer a callback to handle the actual indexing of the log message. */ public DeprecationIndexingAppender(String name, Filter filter, Layout<String> layout, Consumer<IndexRequest> requestConsumer) { super(name, filter, layout); this.requestConsumer = Objects.requireNonNull(requestConsumer, "requestConsumer cannot be null"); } /** * Constructs an index request for a deprecation message, and passes it to the callback that was * supplied to {@link #DeprecationIndexingAppender(String, Filter, Layout, Consumer)}. */ @Override public void append(LogEvent event) { logger.trace( () -> Strings.format( "Received deprecation log event. Appender is %s. message = %s", isEnabled ? "enabled" : "disabled", event.getMessage().getFormattedMessage() ) ); if (this.isEnabled == false) { return; } final byte[] payload = this.getLayout().toByteArray(event); final IndexRequest request = new IndexRequest(DEPRECATION_MESSAGES_DATA_STREAM).source(payload, XContentType.JSON) .opType(DocWriteRequest.OpType.CREATE); this.requestConsumer.accept(request); } /** * Sets whether this appender is enabled or disabled. When disabled, the appender will * not perform indexing operations. * * @param enabled the enabled status of the appender. */ public void setEnabled(boolean enabled) { this.isEnabled = enabled; } /** * Returns whether the appender is enabled i.e. performing indexing operations. */ public boolean isEnabled() { return isEnabled; } }
DeprecationIndexingAppender
java
netty__netty
transport-sctp/src/test/java/io/netty/channel/sctp/nio/NioSctpLimitStreamsTest.java
{ "start": 956, "end": 1411 }
class ____ extends SctpLimitStreamsTest { @Override protected EventLoopGroup newEventLoopGroup() { return new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); } @Override protected Class<? extends SctpChannel> clientClass() { return NioSctpChannel.class; } @Override protected Class<? extends SctpServerChannel> serverClass() { return NioSctpServerChannel.class; } }
NioSctpLimitStreamsTest
java
apache__camel
components/camel-aws/camel-aws2-kms/src/test/java/org/apache/camel/component/aws2/kms/AmazonKMSClientMock.java
{ "start": 1996, "end": 4272 }
class ____ implements KmsClient { public AmazonKMSClientMock() { } @Override public CreateKeyResponse createKey(CreateKeyRequest createKeyRequest) { CreateKeyResponse.Builder res = CreateKeyResponse.builder(); KeyMetadata.Builder metadata = KeyMetadata.builder(); metadata.keyId("test"); metadata.enabled(true); res.keyMetadata(metadata.build()); return res.build(); } @Override public DescribeKeyResponse describeKey(DescribeKeyRequest describeKeyRequest) { DescribeKeyResponse.Builder res = DescribeKeyResponse.builder(); KeyMetadata.Builder metadata = KeyMetadata.builder(); metadata.enabled(false); metadata.description("MyCamelKey"); metadata.keyId("test"); res.keyMetadata(metadata.build()); return res.build(); } @Override public DisableKeyResponse disableKey(DisableKeyRequest disableKeyRequest) { DisableKeyResponse res = DisableKeyResponse.builder().build(); return res; } @Override public EnableKeyResponse enableKey(EnableKeyRequest enableKeyRequest) { EnableKeyResponse res = EnableKeyResponse.builder().build(); return res; } @Override public ListKeysResponse listKeys(ListKeysRequest listKeysRequest) { ListKeysResponse.Builder result = ListKeysResponse.builder(); List<KeyListEntry> keyList = new ArrayList<>(); KeyListEntry.Builder kle = KeyListEntry.builder(); kle.keyId("keyId"); keyList.add(kle.build()); result.keys(keyList); return result.build(); } @Override public ScheduleKeyDeletionResponse scheduleKeyDeletion(ScheduleKeyDeletionRequest scheduleKeyDeletionRequest) { ScheduleKeyDeletionResponse.Builder response = ScheduleKeyDeletionResponse.builder(); response.keyId("test"); return response.build(); } @Override public KmsServiceClientConfiguration serviceClientConfiguration() { return null; } @Override public String serviceName() { // TODO Auto-generated method stub return null; } @Override public void close() { // TODO Auto-generated method stub } }
AmazonKMSClientMock
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/support/GeneratedKeyHolder.java
{ "start": 1444, "end": 3659 }
class ____ implements KeyHolder { private final List<Map<String, Object>> keyList; /** * Create a new GeneratedKeyHolder with a default list. */ public GeneratedKeyHolder() { this.keyList = new ArrayList<>(1); } /** * Create a new GeneratedKeyHolder with a given list. * @param keyList a list to hold maps of keys */ public GeneratedKeyHolder(List<Map<String, Object>> keyList) { this.keyList = keyList; } @Override public @Nullable Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException { return getKeyAs(Number.class); } @Override public <T> @Nullable T getKeyAs(Class<T> keyType) throws InvalidDataAccessApiUsageException, DataRetrievalFailureException { if (this.keyList.isEmpty()) { return null; } if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) { throw new InvalidDataAccessApiUsageException( "The getKey method should only be used when a single key is returned. " + "The current key entry contains multiple keys: " + this.keyList); } Iterator<Object> keyIter = this.keyList.get(0).values().iterator(); if (keyIter.hasNext()) { Object key = keyIter.next(); if (key == null || !(keyType.isAssignableFrom(key.getClass()))) { throw new DataRetrievalFailureException( "The generated key type is not supported. " + "Unable to cast [" + (key != null ? key.getClass().getName() : null) + "] to [" + keyType.getName() + "]."); } return keyType.cast(key); } else { throw new DataRetrievalFailureException("Unable to retrieve the generated key. " + "Check that the table has an identity column enabled."); } } @Override public @Nullable Map<String, Object> getKeys() throws InvalidDataAccessApiUsageException { if (this.keyList.isEmpty()) { return null; } if (this.keyList.size() > 1) { throw new InvalidDataAccessApiUsageException( "The getKeys method should only be used when keys for a single row are returned. " + "The current key list contains keys for multiple rows: " + this.keyList); } return this.keyList.get(0); } @Override public List<Map<String, Object>> getKeyList() { return this.keyList; } }
GeneratedKeyHolder
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/jwt/JwtRealmGenerateTests.java
{ "start": 28262, "end": 28440 }
enum ____ { YML, BUILD_GRADLE; public String fileName() { return name().toLowerCase(Locale.ROOT).replace('_', '.'); } } }
OutputStyle
java
greenrobot__EventBus
EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusMultithreadedTest.java
{ "start": 6423, "end": 7186 }
class ____ extends Thread { private final CountDownLatch startLatch; private final int iterations; private final Object eventToPost; public PosterThread(CountDownLatch latch, int iterations, Object eventToPost) { this.startLatch = latch; this.iterations = iterations; this.eventToPost = eventToPost; } @Override public void run() { startLatch.countDown(); try { startLatch.await(); } catch (InterruptedException e) { log("Unexpected interrupt", e); } for (int i = 0; i < iterations; i++) { eventBus.post(eventToPost); } } } }
PosterThread
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/role/PutRoleResponse.java
{ "start": 664, "end": 1259 }
class ____ extends ActionResponse implements ToXContentObject { private final boolean created; public PutRoleResponse(boolean created) { this.created = created; } public boolean isCreated() { return created; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject().field("created", created).endObject(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeBoolean(created); } }
PutRoleResponse
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/MapperBuilderContext.java
{ "start": 764, "end": 5106 }
class ____ { /** * The root context, to be used when building a tree of mappers */ public static MapperBuilderContext root(boolean isSourceSynthetic, boolean isDataStream) { return root(isSourceSynthetic, isDataStream, MergeReason.MAPPING_UPDATE); } public static MapperBuilderContext root(boolean isSourceSynthetic, boolean isDataStream, MergeReason mergeReason) { return new MapperBuilderContext(null, isSourceSynthetic, isDataStream, false, ObjectMapper.Defaults.DYNAMIC, mergeReason, false); } private final String path; private final boolean isSourceSynthetic; private final boolean isDataStream; private final boolean parentObjectContainsDimensions; private final ObjectMapper.Dynamic dynamic; private final MergeReason mergeReason; private final boolean inNestedContext; MapperBuilderContext( String path, boolean isSourceSynthetic, boolean isDataStream, boolean parentObjectContainsDimensions, ObjectMapper.Dynamic dynamic, MergeReason mergeReason, boolean inNestedContext ) { Objects.requireNonNull(dynamic, "dynamic must not be null"); this.path = path; this.isSourceSynthetic = isSourceSynthetic; this.isDataStream = isDataStream; this.parentObjectContainsDimensions = parentObjectContainsDimensions; this.dynamic = dynamic; this.mergeReason = mergeReason; this.inNestedContext = inNestedContext; } /** * Creates a new MapperBuilderContext that is a child of this context * * @param name the name of the child context * @param dynamic strategy for handling dynamic mappings in this context * @return a new MapperBuilderContext with this context as its parent */ public MapperBuilderContext createChildContext(String name, @Nullable ObjectMapper.Dynamic dynamic) { return createChildContext(name, this.parentObjectContainsDimensions, dynamic); } /** * Creates a new MapperBuilderContext that is a child of this context * * @param name the name of the child context * @param dynamic strategy for handling dynamic mappings in this context * @param parentObjectContainsDimensions whether the parent object contains dimensions * @return a new MapperBuilderContext with this context as its parent */ public MapperBuilderContext createChildContext( String name, boolean parentObjectContainsDimensions, @Nullable ObjectMapper.Dynamic dynamic ) { return new MapperBuilderContext( buildFullName(name), this.isSourceSynthetic, this.isDataStream, parentObjectContainsDimensions, getDynamic(dynamic), this.mergeReason, isInNestedContext() ); } protected ObjectMapper.Dynamic getDynamic(@Nullable ObjectMapper.Dynamic dynamic) { return dynamic == null ? this.dynamic : dynamic; } /** * Builds the full name of the field, taking into account parent objects */ public String buildFullName(String name) { if (Strings.isEmpty(path)) { return name; } return path + "." + name; } /** * Is the {@code _source} field being reconstructed on the fly? */ public boolean isSourceSynthetic() { return isSourceSynthetic; } /** * Are these mappings being built for a data stream index? */ public boolean isDataStream() { return isDataStream; } /** * Are these field mappings being built dimensions? */ public boolean parentObjectContainsDimensions() { return parentObjectContainsDimensions; } public ObjectMapper.Dynamic getDynamic() { return dynamic; } /** * The merge reason to use when merging mappers while building the mapper. * See also {@link ObjectMapper.Builder#buildMappers(MapperBuilderContext)}. */ public MergeReason getMergeReason() { return mergeReason; } /** * Returns true if this context is included in a nested context, either directly or any of its ancestors. */ public boolean isInNestedContext() { return inNestedContext; } }
MapperBuilderContext
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorFactoryTests.java
{ "start": 12026, "end": 12291 }
class ____ implements BeanFactoryInitializationAotProcessor { @Override public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) { return null; } } static
TestBeanFactoryInitializationAotProcessorBean
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/function/scalar/math/ToNumber.java
{ "start": 1833, "end": 4127 }
class ____ extends ScalarFunction implements OptionalArgument { private final Expression value, base; public ToNumber(Source source, Expression value, Expression base) { super(source, Arrays.asList(value, base != null ? base : new Literal(source, null, DataTypes.NULL))); this.value = value; this.base = arguments().get(1); } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } TypeResolution valueResolution = isStringAndExact(value, sourceText(), ParamOrdinal.FIRST); if (valueResolution.unresolved()) { return valueResolution; } return isInteger(base, sourceText(), SECOND); } @Override protected Pipe makePipe() { return new ToNumberFunctionPipe(source(), this, Expressions.pipe(value), Expressions.pipe(base)); } @Override public boolean foldable() { return value.foldable() && base.foldable(); } @Override public Object fold() { return doProcess(value.fold(), base.fold()); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, ToNumber::new, value, base); } @Override public ScriptTemplate asScript() { ScriptTemplate valueScript = asScript(value); ScriptTemplate baseScript = asScript(base); return new ScriptTemplate( format(Locale.ROOT, formatTemplate("{eql}.%s(%s,%s)"), "number", valueScript.template(), baseScript.template()), paramsBuilder().script(valueScript.params()).script(baseScript.params()).build(), dataType() ); } @Override public ScriptTemplate scriptWithField(FieldAttribute field) { return new ScriptTemplate( processScript(Scripts.DOC_VALUE), paramsBuilder().variable(field.exactAttribute().name()).build(), dataType() ); } @Override public DataType dataType() { return DataTypes.DOUBLE; } @Override public Expression replaceChildren(List<Expression> newChildren) { return new ToNumber(source(), newChildren.get(0), newChildren.get(1)); } }
ToNumber
java
apache__avro
lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Foo.java
{ "start": 48969, "end": 49186 }
class ____ implements org.apache.thrift.scheme.SchemeFactory { public add_argsStandardScheme getScheme() { return new add_argsStandardScheme(); } } private static
add_argsStandardSchemeFactory
java
elastic__elasticsearch
libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java
{ "start": 1766, "end": 2089 }
class ____ are not duplicated across jars.</li> * <li>Checks any {@code X-Compile-Target-JDK} value in the jar * manifest is compatible with current JRE</li> * <li>Checks any {@code X-Compile-Elasticsearch-Version} value in * the jar manifest is compatible with the current ES</li> * </ul> */ public
files
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/SqlDateSerializer.java
{ "start": 3298, "end": 3474 }
class ____ extends SimpleTypeSerializerSnapshot<Date> { public SqlDateSerializerSnapshot() { super(() -> INSTANCE); } } }
SqlDateSerializerSnapshot
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/AssociatedIndexDescriptor.java
{ "start": 4439, "end": 5675 }
class ____ only handle * simple wildcard expressions, but system index name patterns may use full Lucene regular expression syntax, * * @param project The current project metadata to get the list of matching indices from * @return A list of index names that match this descriptor */ @Override public List<String> getMatchingIndices(ProjectMetadata project) { return project.indices().keySet().stream().filter(this::matchesIndexPattern).toList(); } /** * Checks whether an index name matches the system index name pattern for this descriptor. * @param index The index name to be checked against the index pattern given at construction time. * @return True if the name matches the pattern, false otherwise. */ private boolean matchesIndexPattern(String index) { return indexPatternAutomaton.run(index); } @Override public String toString() { return "AssociatedIndexDescriptor{" + "indexPattern='" + indexPattern + '\'' + ", description='" + description + '\'' + ", indexPatternAutomaton=" + indexPatternAutomaton + '}'; } }
can
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultPage.java
{ "start": 975, "end": 2212 }
class ____<T> implements Page<T>, Serializable { private static final long serialVersionUID = 1099331838954070419L; private final int requestOffset; private final int pageSize; private final int totalSize; private final List<T> data; private final int totalPages; private final boolean hasNext; public DefaultPage(int requestOffset, int pageSize, List<T> data, int totalSize) { this.requestOffset = requestOffset; this.pageSize = pageSize; this.data = data; this.totalSize = totalSize; int remain = totalSize % pageSize; this.totalPages = remain > 0 ? (totalSize / pageSize) + 1 : totalSize / pageSize; this.hasNext = totalSize - requestOffset - pageSize > 0; } @Override public int getOffset() { return requestOffset; } @Override public int getPageSize() { return pageSize; } @Override public int getTotalSize() { return totalSize; } @Override public int getTotalPages() { return totalPages; } @Override public List<T> getData() { return data; } @Override public boolean hasNext() { return hasNext; } }
DefaultPage
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/reflect/MulticastDelegate.java
{ "start": 1436, "end": 2774 }
class ____ implements Cloneable { protected Object[] targets = {}; protected MulticastDelegate() { } public List getTargets() { return new ArrayList(Arrays.asList(targets)); } abstract public MulticastDelegate add(Object target); protected MulticastDelegate addHelper(Object target) { MulticastDelegate copy = newInstance(); copy.targets = new Object[targets.length + 1]; System.arraycopy(targets, 0, copy.targets, 0, targets.length); copy.targets[targets.length] = target; return copy; } public MulticastDelegate remove(Object target) { for (int i = targets.length - 1; i >= 0; i--) { if (targets[i].equals(target)) { MulticastDelegate copy = newInstance(); copy.targets = new Object[targets.length - 1]; System.arraycopy(targets, 0, copy.targets, 0, i); System.arraycopy(targets, i + 1, copy.targets, i, targets.length - i - 1); return copy; } } return this; } abstract public MulticastDelegate newInstance(); public static MulticastDelegate create(Class iface) { Generator gen = new Generator(); gen.setInterface(iface); return gen.create(); } public static
MulticastDelegate
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/selector/LabelSelectorTest.java
{ "start": 1067, "end": 1795 }
class ____ { private SelectorManager selectorManager; @BeforeEach void setUp() { selectorManager = new SelectorManager(); selectorManager.init(); } @Test void testParseSelector() throws NacosException { Selector selector = selectorManager.parseSelector("label", "CONSUMER.label.A=PROVIDER.label.A &CONSUMER.label.B=PROVIDER.label.B"); assertTrue(selector instanceof LabelSelector); LabelSelector labelSelector = (LabelSelector) selector; assertEquals(2, labelSelector.getLabels().size()); assertTrue(labelSelector.getLabels().contains("A")); assertTrue(labelSelector.getLabels().contains("B")); } }
LabelSelectorTest
java
alibaba__druid
core/src/main/java/com/alibaba/druid/util/jdbc/ResultSetMetaDataBase.java
{ "start": 778, "end": 4799 }
class ____ implements ResultSetMetaData { public ResultSetMetaDataBase() { } private final List<ColumnMetaData> columns = new ArrayList<ColumnMetaData>(); public List<ColumnMetaData> getColumns() { return columns; } public int findColumn(String columnName) throws SQLException { for (int i = 0; i < columns.size(); ++i) { ColumnMetaData column = columns.get(i); if (column.getColumnName().equals(columnName)) { return i + 1; } } throw new SQLException("column '" + columnName + "' not found."); } @SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (isWrapperFor(iface)) { return (T) this; } return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { if (iface == null) { return false; } return iface.isAssignableFrom(this.getClass()); } @Override public int getColumnCount() throws SQLException { return columns.size(); } @Override public boolean isAutoIncrement(int column) throws SQLException { return getColumn(column).isAutoIncrement(); } @Override public boolean isCaseSensitive(int column) throws SQLException { return getColumn(column).isCaseSensitive(); } @Override public boolean isSearchable(int column) throws SQLException { return getColumn(column).isSearchable(); } @Override public boolean isCurrency(int column) throws SQLException { return getColumn(column).isCurrency(); } @Override public int isNullable(int column) throws SQLException { return getColumn(column).getNullable(); } @Override public boolean isSigned(int column) throws SQLException { return getColumn(column).isSigned(); } @Override public int getColumnDisplaySize(int column) throws SQLException { return getColumn(column).getColumnDisplaySize(); } @Override public String getColumnLabel(int column) throws SQLException { return getColumn(column).getColumnLabel(); } public ColumnMetaData getColumn(int column) { return columns.get(column - 1); } @Override public String getColumnName(int column) throws SQLException { return getColumn(column).getColumnName(); } @Override public String getSchemaName(int column) throws SQLException { return getColumn(column).getSchemaName(); } @Override public int getPrecision(int column) throws SQLException { return getColumn(column).getPrecision(); } @Override public int getScale(int column) throws SQLException { return getColumn(column).getScale(); } @Override public String getTableName(int column) throws SQLException { return getColumn(column).getTableName(); } @Override public String getCatalogName(int column) throws SQLException { return getColumn(column).getCatalogName(); } @Override public int getColumnType(int column) throws SQLException { return getColumn(column).getColumnType(); } @Override public String getColumnTypeName(int column) throws SQLException { return getColumn(column).getColumnTypeName(); } @Override public boolean isReadOnly(int column) throws SQLException { return getColumn(column).isReadOnly(); } @Override public boolean isWritable(int column) throws SQLException { return getColumn(column).isWritable(); } @Override public boolean isDefinitelyWritable(int column) throws SQLException { return getColumn(column).isDefinitelyWritable(); } @Override public String getColumnClassName(int column) throws SQLException { return getColumn(column).getColumnClassName(); } public static
ResultSetMetaDataBase
java
google__truth
core/src/main/java/com/google/common/truth/Correspondence.java
{ "start": 6662, "end": 6949 }
interface ____<A extends @Nullable Object, E extends @Nullable Object> { /** * Returns whether or not the actual and expected values satisfy the condition defined by this * predicate. */ boolean apply(A actual, E expected); } private static final
BinaryPredicate
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conversion/java8time/custompatterndatetimeformattergenerated/SourceTargetMapper.java
{ "start": 404, "end": 987 }
interface ____ { String LOCAL_DATE_TIME_FORMAT = "dd.MM.yyyy HH:mm"; String VERY_SIMILAR_LOCAL_DATE_TIME_FORMAT = "dd.MM.yyyy HH.mm"; SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class ); @Mapping(target = "localDateTime1", dateFormat = LOCAL_DATE_TIME_FORMAT) @Mapping(target = "localDateTime2", dateFormat = LOCAL_DATE_TIME_FORMAT) @Mapping(target = "localDateTime3", dateFormat = VERY_SIMILAR_LOCAL_DATE_TIME_FORMAT) Target map(Source source); @InheritInverseConfiguration Source map(Target target); }
SourceTargetMapper
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RReadWriteLock.java
{ "start": 1175, "end": 1514 }
interface ____ extends ReadWriteLock { /** * Returns the lock used for reading. * * @return the lock used for reading */ @Override RLock readLock(); /** * Returns the lock used for writing. * * @return the lock used for writing */ @Override RLock writeLock(); }
RReadWriteLock
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/SearchServiceSingleNodeTests.java
{ "start": 85150, "end": 142965 }
class ____ extends ShardSearchRequest { private final TimeValue scroll; ShardScrollRequestTest(ShardId shardId) { super( OriginalIndices.NONE, new SearchRequest().allowPartialSearchResults(true), shardId, 0, 1, AliasFilter.EMPTY, 1f, -1, null ); this.scroll = TimeValue.timeValueMinutes(1); } @Override public TimeValue scroll() { return this.scroll; } } public void testCanMatch() throws Exception { createIndex("index"); final SearchService service = getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); assertTrue( service.canMatch( new ShardSearchRequest(OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1f, -1, null) ).canMatch() ); searchRequest.source(new SearchSourceBuilder()); assertTrue( service.canMatch( new ShardSearchRequest(OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1f, -1, null) ).canMatch() ); searchRequest.source(new SearchSourceBuilder().query(new MatchAllQueryBuilder())); assertTrue( service.canMatch( new ShardSearchRequest(OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1f, -1, null) ).canMatch() ); searchRequest.source( new SearchSourceBuilder().query(new MatchNoneQueryBuilder()) .aggregation(new TermsAggregationBuilder("test").userValueTypeHint(ValueType.STRING).minDocCount(0)) ); assertTrue( service.canMatch( new ShardSearchRequest(OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1f, -1, null) ).canMatch() ); searchRequest.source( new SearchSourceBuilder().query(new MatchNoneQueryBuilder()).aggregation(new GlobalAggregationBuilder("test")) ); assertTrue( service.canMatch( new ShardSearchRequest(OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1f, -1, null) ).canMatch() ); searchRequest.source(new SearchSourceBuilder().query(new MatchNoneQueryBuilder())); assertFalse( service.canMatch( new ShardSearchRequest(OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1f, -1, null) ).canMatch() ); assertEquals(5, numWrapInvocations.get()); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null ); /* * Checks that canMatch takes into account the alias filter */ // the source cannot be rewritten to a match_none searchRequest.indices("alias").source(new SearchSourceBuilder().query(new MatchAllQueryBuilder())); assertFalse( service.canMatch( new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.of(new TermQueryBuilder("foo", "bar"), "alias"), 1f, -1, null ) ).canMatch() ); // the source can match and can be rewritten to a match_none, but not the alias filter final DocWriteResponse response = prepareIndex("index").setSource("id", "1").get(); assertEquals(RestStatus.CREATED, response.status()); searchRequest.indices("alias").source(new SearchSourceBuilder().query(new TermQueryBuilder("id", "1"))); assertFalse( service.canMatch( new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.of(new TermQueryBuilder("foo", "bar"), "alias"), 1f, -1, null ) ).canMatch() ); CountDownLatch latch = new CountDownLatch(1); SearchShardTask task = new SearchShardTask(123L, "", "", "", null, emptyMap()); // Because the foo field used in alias filter is unmapped the term query builder rewrite can resolve to a match no docs query, // without acquiring a searcher and that means the wrapper is not called assertEquals(5, numWrapInvocations.get()); service.executeQueryPhase(request, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult searchPhaseResult) { try { // make sure that the wrapper is called when the query is actually executed assertEquals(6, numWrapInvocations.get()); } finally { latch.countDown(); } } @Override public void onFailure(Exception e) { try { throw new AssertionError(e); } finally { latch.countDown(); } } }); latch.await(); } public void testCanRewriteToMatchNone() { assertFalse( SearchService.canRewriteToMatchNone( new SearchSourceBuilder().query(new MatchNoneQueryBuilder()).aggregation(new GlobalAggregationBuilder("test")) ) ); assertFalse(SearchService.canRewriteToMatchNone(new SearchSourceBuilder())); assertFalse(SearchService.canRewriteToMatchNone(null)); assertFalse( SearchService.canRewriteToMatchNone( new SearchSourceBuilder().query(new MatchNoneQueryBuilder()) .aggregation(new TermsAggregationBuilder("test").userValueTypeHint(ValueType.STRING).minDocCount(0)) ) ); assertTrue(SearchService.canRewriteToMatchNone(new SearchSourceBuilder().query(new TermQueryBuilder("foo", "bar")))); assertTrue( SearchService.canRewriteToMatchNone( new SearchSourceBuilder().query(new MatchNoneQueryBuilder()) .aggregation(new TermsAggregationBuilder("test").userValueTypeHint(ValueType.STRING).minDocCount(1)) ) ); assertFalse( SearchService.canRewriteToMatchNone( new SearchSourceBuilder().query(new MatchNoneQueryBuilder()) .aggregation(new TermsAggregationBuilder("test").userValueTypeHint(ValueType.STRING).minDocCount(1)) .suggest(new SuggestBuilder()) ) ); assertFalse( SearchService.canRewriteToMatchNone( new SearchSourceBuilder().query(new TermQueryBuilder("foo", "bar")).suggest(new SuggestBuilder()) ) ); } public void testAggContextGetsMatchAll() throws IOException { createIndex("test"); withAggregationContext("test", context -> assertThat(context.query(), equalTo(new MatchAllDocsQuery()))); } public void testAggContextGetsNestedFilter() throws IOException { XContentBuilder mapping = JsonXContent.contentBuilder().startObject().startObject("properties"); mapping.startObject("nested").field("type", "nested").endObject(); mapping.endObject().endObject(); createIndex("test", Settings.EMPTY, mapping); withAggregationContext("test", context -> assertThat(context.query(), equalTo(new MatchAllDocsQuery()))); } /** * Build an {@link AggregationContext} with the named index. */ private void withAggregationContext(String index, Consumer<AggregationContext> check) throws IOException { IndexService indexService = getInstanceFromNode(IndicesService.class).indexServiceSafe(resolveIndex(index)); ShardId shardId = new ShardId(indexService.index(), 0); SearchRequest request = new SearchRequest().indices(index) .source(new SearchSourceBuilder().aggregation(new FiltersAggregationBuilder("test", new MatchAllQueryBuilder()))) .allowPartialSearchResults(false); ShardSearchRequest shardRequest = new ShardSearchRequest( OriginalIndices.NONE, request, shardId, 0, 1, AliasFilter.EMPTY, 1, 0, null ); try (ReaderContext readerContext = createReaderContext(indexService, indexService.getShard(0))) { try ( SearchContext context = getInstanceFromNode(SearchService.class).createContext( readerContext, shardRequest, mock(SearchShardTask.class), ResultsType.QUERY, true ) ) { check.accept(context.aggregations().factories().context()); } } } public void testExpandSearchFrozen() { String indexName = "frozen_index"; createIndex(indexName); client().execute( InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.INSTANCE, new InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.Request(indexName, "index.frozen", "true") ).actionGet(); prepareIndex(indexName).setId("1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); assertHitCount(client().prepareSearch(), 0L); assertHitCount(client().prepareSearch().setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED), 1L); assertWarnings(TransportSearchAction.FROZEN_INDICES_DEPRECATION_MESSAGE.replace("{}", indexName)); } public void testCreateReduceContext() { SearchService service = getInstanceFromNode(SearchService.class); AggregationReduceContext.Builder reduceContextBuilder = service.aggReduceContextBuilder( () -> false, new SearchRequest().source(new SearchSourceBuilder()).source().aggregations() ); { AggregationReduceContext reduceContext = reduceContextBuilder.forFinalReduction(); expectThrows( MultiBucketConsumerService.TooManyBucketsException.class, () -> reduceContext.consumeBucketsAndMaybeBreak(MultiBucketConsumerService.DEFAULT_MAX_BUCKETS + 1) ); } { AggregationReduceContext reduceContext = reduceContextBuilder.forPartialReduction(); reduceContext.consumeBucketsAndMaybeBreak(MultiBucketConsumerService.DEFAULT_MAX_BUCKETS + 1); } } public void testMultiBucketConsumerServiceCB() { MultiBucketConsumerService service = new MultiBucketConsumerService( getInstanceFromNode(ClusterService.class), Settings.EMPTY, new NoopCircuitBreaker("test") { @Override public void addEstimateBytesAndMaybeBreak(long bytes, String label) throws CircuitBreakingException { throw new CircuitBreakingException("tripped", getDurability()); } } ); // for partial { IntConsumer consumer = service.createForPartial(); for (int i = 0; i < 1023; i++) { consumer.accept(0); } CircuitBreakingException ex = expectThrows(CircuitBreakingException.class, () -> consumer.accept(0)); assertThat(ex.getMessage(), equalTo("tripped")); } // for final { IntConsumer consumer = service.createForFinal(); for (int i = 0; i < 1023; i++) { consumer.accept(0); } CircuitBreakingException ex = expectThrows(CircuitBreakingException.class, () -> consumer.accept(0)); assertThat(ex.getMessage(), equalTo("tripped")); } } public void testCreateSearchContext() throws IOException { String index = randomAlphaOfLengthBetween(5, 10).toLowerCase(Locale.ROOT); IndexService indexService = createIndex(index); final SearchService service = getInstanceFromNode(SearchService.class); ShardId shardId = new ShardId(indexService.index(), 0); long nowInMillis = System.currentTimeMillis(); String clusterAlias = randomBoolean() ? null : randomAlphaOfLengthBetween(3, 10); SearchRequest searchRequest = new SearchRequest(); searchRequest.allowPartialSearchResults(randomBoolean()); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, shardId, 0, indexService.numberOfShards(), AliasFilter.EMPTY, 1f, nowInMillis, clusterAlias ); try (SearchContext searchContext = service.createSearchContext(request, new TimeValue(System.currentTimeMillis()))) { assertTrue(searchContext.searcher().hasExecutor()); SearchShardTarget searchShardTarget = searchContext.shardTarget(); SearchExecutionContext searchExecutionContext = searchContext.getSearchExecutionContext(); String expectedIndexName = clusterAlias == null ? index : clusterAlias + ":" + index; assertEquals(expectedIndexName, searchExecutionContext.getFullyQualifiedIndex().getName()); assertEquals(expectedIndexName, searchShardTarget.getFullyQualifiedIndexName()); assertEquals(clusterAlias, searchShardTarget.getClusterAlias()); assertEquals(shardId, searchShardTarget.getShardId()); assertNull(searchContext.dfsResult()); searchContext.addDfsResult(); assertSame(searchShardTarget, searchContext.dfsResult().getSearchShardTarget()); assertNull(searchContext.queryResult()); searchContext.addQueryResult(); assertSame(searchShardTarget, searchContext.queryResult().getSearchShardTarget()); assertNull(searchContext.fetchResult()); searchContext.addFetchResult(); assertSame(searchShardTarget, searchContext.fetchResult().getSearchShardTarget()); } } /** * While we have no NPE in DefaultContext constructor anymore, we still want to guard against it (or other failures) in the future to * avoid leaking searchers. */ public void testCreateSearchContextFailure() throws Exception { final String index = randomAlphaOfLengthBetween(5, 10).toLowerCase(Locale.ROOT); final IndexService indexService = createIndex(index); final SearchService service = getInstanceFromNode(SearchService.class); final ShardId shardId = new ShardId(indexService.index(), 0); final ShardSearchRequest request = new ShardSearchRequest(shardId, 0, null) { @Override public SearchType searchType() { // induce an artificial NPE throw new NullPointerException("expected"); } }; try (ReaderContext reader = createReaderContext(indexService, indexService.getShard(shardId.id()))) { NullPointerException e = expectThrows( NullPointerException.class, () -> service.createContext(reader, request, mock(SearchShardTask.class), ResultsType.NONE, randomBoolean()) ); assertEquals("expected", e.getMessage()); } // Needs to busily assert because Engine#refreshNeeded can increase the refCount. assertBusy( () -> assertEquals("should have 2 store refs (IndexService + InternalEngine)", 2, indexService.getShard(0).store().refCount()) ); } public void testMatchNoDocsEmptyResponse() throws InterruptedException { createIndex("index"); Thread currentThread = Thread.currentThread(); SearchService service = getInstanceFromNode(SearchService.class); IndicesService indicesService = getInstanceFromNode(IndicesService.class); IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(false) .source(new SearchSourceBuilder().aggregation(AggregationBuilders.count("count").field("value"))); ShardSearchRequest shardRequest = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 5, AliasFilter.EMPTY, 1.0f, 0, null ); SearchShardTask task = new SearchShardTask(123L, "", "", "", null, emptyMap()); { CountDownLatch latch = new CountDownLatch(1); shardRequest.source().query(new MatchAllQueryBuilder()); service.executeQueryPhase(shardRequest, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult result) { try { assertNotSame(Thread.currentThread(), currentThread); assertThat(Thread.currentThread().getName(), startsWith("elasticsearch[node_s_0][search]")); assertThat(result, instanceOf(QuerySearchResult.class)); assertFalse(result.queryResult().isNull()); assertNotNull(result.queryResult().topDocs()); assertNotNull(result.queryResult().aggregations()); } finally { latch.countDown(); } } @Override public void onFailure(Exception exc) { try { throw new AssertionError(exc); } finally { latch.countDown(); } } }); latch.await(); } { CountDownLatch latch = new CountDownLatch(1); shardRequest.source().query(new MatchNoneQueryBuilder()); service.executeQueryPhase(shardRequest, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult result) { try { assertNotSame(Thread.currentThread(), currentThread); assertThat(Thread.currentThread().getName(), startsWith("elasticsearch[node_s_0][search]")); assertThat(result, instanceOf(QuerySearchResult.class)); assertFalse(result.queryResult().isNull()); assertNotNull(result.queryResult().topDocs()); assertNotNull(result.queryResult().aggregations()); } finally { latch.countDown(); } } @Override public void onFailure(Exception exc) { try { throw new AssertionError(exc); } finally { latch.countDown(); } } }); latch.await(); } { CountDownLatch latch = new CountDownLatch(1); shardRequest.canReturnNullResponseIfMatchNoDocs(true); service.executeQueryPhase(shardRequest, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult result) { try { // make sure we don't use the search threadpool assertSame(Thread.currentThread(), currentThread); assertThat(result, instanceOf(QuerySearchResult.class)); assertTrue(result.queryResult().isNull()); } finally { latch.countDown(); } } @Override public void onFailure(Exception e) { try { throw new AssertionError(e); } finally { latch.countDown(); } } }); latch.await(); } } public void testDeleteIndexWhileSearch() throws Exception { createIndex("test"); int numDocs = randomIntBetween(1, 20); for (int i = 0; i < numDocs; i++) { prepareIndex("test").setSource("f", "v").get(); } indicesAdmin().prepareRefresh("test").get(); AtomicBoolean stopped = new AtomicBoolean(false); Thread[] searchers = new Thread[randomIntBetween(1, 4)]; CountDownLatch latch = new CountDownLatch(searchers.length); for (int i = 0; i < searchers.length; i++) { searchers[i] = new Thread(() -> { latch.countDown(); while (stopped.get() == false) { try { client().prepareSearch("test").setRequestCache(false).get().decRef(); } catch (Exception ignored) { return; } } }); searchers[i].start(); } latch.await(); indicesAdmin().prepareDelete("test").get(); stopped.set(true); for (Thread searcher : searchers) { searcher.join(); } } public void testLookUpSearchContext() throws Exception { createIndex("index"); SearchService searchService = getInstanceFromNode(SearchService.class); IndicesService indicesService = getInstanceFromNode(IndicesService.class); IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); IndexShard indexShard = indexService.getShard(0); List<ShardSearchContextId> contextIds = new ArrayList<>(); int numContexts = randomIntBetween(1, 10); CountDownLatch latch = new CountDownLatch(1); indexShard.getThreadPool().executor(ThreadPool.Names.SEARCH).execute(() -> { try { for (int i = 0; i < numContexts; i++) { ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, new SearchRequest().allowPartialSearchResults(true), indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null ); final ReaderContext context = searchService.createAndPutReaderContext( request, indexService, indexShard, indexShard.acquireSearcherSupplier(), SearchService.KEEPALIVE_INTERVAL_SETTING.get(Settings.EMPTY).millis() ); assertThat(context.id().getId(), equalTo((long) (i + 1))); contextIds.add(context.id()); } assertThat(searchService.getActiveContexts(), equalTo(contextIds.size())); while (contextIds.isEmpty() == false) { final ShardSearchContextId contextId = randomFrom(contextIds); assertFalse(searchService.freeReaderContext(new ShardSearchContextId(UUIDs.randomBase64UUID(), contextId.getId()))); assertThat(searchService.getActiveContexts(), equalTo(contextIds.size())); if (randomBoolean()) { assertTrue(searchService.freeReaderContext(contextId)); } else { assertTrue( searchService.freeReaderContext((new ShardSearchContextId(contextId.getSessionId(), contextId.getId()))) ); } contextIds.remove(contextId); assertThat(searchService.getActiveContexts(), equalTo(contextIds.size())); assertFalse(searchService.freeReaderContext(contextId)); assertThat(searchService.getActiveContexts(), equalTo(contextIds.size())); } } finally { latch.countDown(); } }); latch.await(); } public void testOpenReaderContext() { createIndex("index"); SearchService searchService = getInstanceFromNode(SearchService.class); PlainActionFuture<ShardSearchContextId> future = new PlainActionFuture<>(); searchService.openReaderContext(new ShardId(resolveIndex("index"), 0), TimeValue.timeValueMinutes(between(1, 10)), future); future.actionGet(); assertThat(searchService.getActiveContexts(), equalTo(1)); assertTrue(searchService.freeReaderContext(future.actionGet())); } public void testCancelQueryPhaseEarly() throws Exception { createIndex("index"); final MockSearchService service = (MockSearchService) getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null ); CountDownLatch latch1 = new CountDownLatch(1); SearchShardTask task = new SearchShardTask(1, "", "", "", TaskId.EMPTY_TASK_ID, emptyMap()); service.executeQueryPhase(request, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult searchPhaseResult) { service.freeReaderContext(searchPhaseResult.getContextId()); latch1.countDown(); } @Override public void onFailure(Exception e) { try { fail("Search should not be cancelled"); } finally { latch1.countDown(); } } }); latch1.await(); CountDownLatch latch2 = new CountDownLatch(1); service.executeDfsPhase(request, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult searchPhaseResult) { service.freeReaderContext(searchPhaseResult.getContextId()); latch2.countDown(); } @Override public void onFailure(Exception e) { try { fail("Search should not be cancelled"); } finally { latch2.countDown(); } } }); latch2.await(); AtomicBoolean searchContextCreated = new AtomicBoolean(false); service.setOnCreateSearchContext(c -> searchContextCreated.set(true)); CountDownLatch latch3 = new CountDownLatch(1); TaskCancelHelper.cancel(task, "simulated"); service.executeQueryPhase(request, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult searchPhaseResult) { try { fail("Search not cancelled early"); } finally { service.freeReaderContext(searchPhaseResult.getContextId()); searchPhaseResult.decRef(); latch3.countDown(); } } @Override public void onFailure(Exception e) { assertThat(e, is(instanceOf(TaskCancelledException.class))); assertThat(e.getMessage(), is("task cancelled [simulated]")); assertThat(((TaskCancelledException) e).status(), is(RestStatus.BAD_REQUEST)); assertThat(searchContextCreated.get(), is(false)); latch3.countDown(); } }); latch3.await(); searchContextCreated.set(false); CountDownLatch latch4 = new CountDownLatch(1); service.executeDfsPhase(request, task, new ActionListener<>() { @Override public void onResponse(SearchPhaseResult searchPhaseResult) { try { fail("Search not cancelled early"); } finally { service.freeReaderContext(searchPhaseResult.getContextId()); latch4.countDown(); } } @Override public void onFailure(Exception e) { assertThat(e, is(instanceOf(TaskCancelledException.class))); assertThat(e.getMessage(), is("task cancelled [simulated]")); assertThat(((TaskCancelledException) e).status(), is(RestStatus.BAD_REQUEST)); assertThat(searchContextCreated.get(), is(false)); latch4.countDown(); } }); latch4.await(); } public void testCancelFetchPhaseEarly() throws Exception { createIndex("index"); final MockSearchService service = (MockSearchService) getInstanceFromNode(SearchService.class); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); AtomicBoolean searchContextCreated = new AtomicBoolean(false); service.setOnCreateSearchContext(c -> searchContextCreated.set(true)); // Test fetch phase is cancelled early String scrollId; var searchResponse = client().search(searchRequest.allowPartialSearchResults(false).scroll(TimeValue.timeValueMinutes(10))).get(); try { scrollId = searchResponse.getScrollId(); } finally { searchResponse.decRef(); } client().searchScroll(new SearchScrollRequest(scrollId)).get().decRef(); assertThat(searchContextCreated.get(), is(true)); ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(scrollId); client().clearScroll(clearScrollRequest); searchResponse = client().search(searchRequest.allowPartialSearchResults(false).scroll(TimeValue.timeValueMinutes(10))).get(); try { scrollId = searchResponse.getScrollId(); } finally { searchResponse.decRef(); } searchContextCreated.set(false); service.setOnCheckCancelled(t -> { SearchShardTask task = new SearchShardTask(randomLong(), "transport", "action", "", TaskId.EMPTY_TASK_ID, emptyMap()); TaskCancelHelper.cancel(task, "simulated"); return task; }); CountDownLatch latch = new CountDownLatch(1); client().searchScroll(new SearchScrollRequest(scrollId), new ActionListener<>() { @Override public void onResponse(SearchResponse searchResponse) { try { fail("Search not cancelled early"); } finally { latch.countDown(); } } @Override public void onFailure(Exception e) { Throwable cancelledExc = e.getCause().getCause(); assertThat(cancelledExc, is(instanceOf(TaskCancelledException.class))); assertThat(cancelledExc.getMessage(), is("task cancelled [simulated]")); assertThat(((TaskCancelledException) cancelledExc).status(), is(RestStatus.BAD_REQUEST)); latch.countDown(); } }); latch.await(); assertThat(searchContextCreated.get(), is(false)); clearScrollRequest.setScrollIds(singletonList(scrollId)); client().clearScroll(clearScrollRequest); } public void testWaitOnRefresh() throws ExecutionException, InterruptedException { createIndex("index"); final SearchService service = getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); searchRequest.setWaitForCheckpointsTimeout(TimeValue.timeValueSeconds(30)); searchRequest.setWaitForCheckpoints(Collections.singletonMap("index", new long[] { 0 })); final DocWriteResponse response = prepareIndex("index").setSource("id", "1").get(); assertEquals(RestStatus.CREATED, response.status()); SearchShardTask task = new SearchShardTask(123L, "", "", "", null, emptyMap()); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null, null, null, SplitShardCountSummary.UNSET ); PlainActionFuture<Void> future = new PlainActionFuture<>(); service.executeQueryPhase(request, task, future.delegateFailure((l, r) -> { assertEquals(1, r.queryResult().getTotalHits().value()); l.onResponse(null); })); future.get(); } public void testWaitOnRefreshFailsWithRefreshesDisabled() { createIndex("index", Settings.builder().put("index.refresh_interval", "-1").build()); final SearchService service = getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); searchRequest.setWaitForCheckpointsTimeout(TimeValue.timeValueSeconds(30)); searchRequest.setWaitForCheckpoints(Collections.singletonMap("index", new long[] { 0 })); final DocWriteResponse response = prepareIndex("index").setSource("id", "1").get(); assertEquals(RestStatus.CREATED, response.status()); SearchShardTask task = new SearchShardTask(123L, "", "", "", null, emptyMap()); PlainActionFuture<SearchPhaseResult> future = new PlainActionFuture<>(); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null, null, null, SplitShardCountSummary.UNSET ); service.executeQueryPhase(request, task, future); IllegalArgumentException illegalArgumentException = expectThrows(IllegalArgumentException.class, future::actionGet); assertThat( illegalArgumentException.getMessage(), containsString("Cannot use wait_for_checkpoints with [index.refresh_interval=-1]") ); } public void testWaitOnRefreshFailsIfCheckpointNotIndexed() { createIndex("index"); final SearchService service = getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); // Increased timeout to avoid cancelling the search task prior to its completion, // as we expect to raise an Exception. Timeout itself is tested on the following `testWaitOnRefreshTimeout` test. searchRequest.setWaitForCheckpointsTimeout(TimeValue.timeValueMillis(randomIntBetween(200, 300))); searchRequest.setWaitForCheckpoints(Collections.singletonMap("index", new long[] { 1 })); final DocWriteResponse response = prepareIndex("index").setSource("id", "1").get(); assertEquals(RestStatus.CREATED, response.status()); SearchShardTask task = new SearchShardTask(123L, "", "", "", null, emptyMap()); PlainActionFuture<SearchPhaseResult> future = new PlainActionFuture<>(); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null, null, null, SplitShardCountSummary.UNSET ); service.executeQueryPhase(request, task, future); IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, future::actionGet); assertThat( ex.getMessage(), containsString("Cannot wait for unissued seqNo checkpoint [wait_for_checkpoint=1, max_issued_seqNo=0]") ); } public void testWaitOnRefreshTimeout() { createIndex("index", Settings.builder().put("index.refresh_interval", "60s").build()); final SearchService service = getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); searchRequest.setWaitForCheckpointsTimeout(TimeValue.timeValueMillis(randomIntBetween(10, 100))); searchRequest.setWaitForCheckpoints(Collections.singletonMap("index", new long[] { 0 })); final DocWriteResponse response = prepareIndex("index").setSource("id", "1").get(); assertEquals(RestStatus.CREATED, response.status()); SearchShardTask task = new SearchShardTask(123L, "", "", "", null, emptyMap()); PlainActionFuture<SearchPhaseResult> future = new PlainActionFuture<>(); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null, null, null, SplitShardCountSummary.UNSET ); service.executeQueryPhase(request, task, future); SearchTimeoutException ex = expectThrows(SearchTimeoutException.class, future::actionGet); assertThat(ex.getMessage(), containsString("Wait for seq_no [0] refreshed timed out [")); } public void testMinimalSearchSourceInShardRequests() { createIndex("test"); int numDocs = between(0, 10); for (int i = 0; i < numDocs; i++) { prepareIndex("test").setSource("id", Integer.toString(i)).get(); } indicesAdmin().prepareRefresh("test").get(); BytesReference pitId = client().execute( TransportOpenPointInTimeAction.TYPE, new OpenPointInTimeRequest("test").keepAlive(TimeValue.timeValueMinutes(10)) ).actionGet().getPointInTimeId(); final MockSearchService searchService = (MockSearchService) getInstanceFromNode(SearchService.class); final List<ShardSearchRequest> shardRequests = new CopyOnWriteArrayList<>(); searchService.setOnCreateSearchContext(ctx -> shardRequests.add(ctx.request())); try { assertHitCount( client().prepareSearch() .setSource( new SearchSourceBuilder().size(between(numDocs, numDocs * 2)).pointInTimeBuilder(new PointInTimeBuilder(pitId)) ), numDocs ); } finally { client().execute(TransportClosePointInTimeAction.TYPE, new ClosePointInTimeRequest(pitId)).actionGet(); } assertThat(shardRequests, not(emptyList())); for (ShardSearchRequest shardRequest : shardRequests) { assertNotNull(shardRequest.source()); assertNotNull(shardRequest.source().pointInTimeBuilder()); assertThat(shardRequest.source().pointInTimeBuilder().getEncodedId(), equalTo(BytesArray.EMPTY)); } } public void testDfsQueryPhaseRewrite() { createIndex("index"); prepareIndex("index").setId("1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get(); final SearchService service = getInstanceFromNode(SearchService.class); final IndicesService indicesService = getInstanceFromNode(IndicesService.class); final IndexService indexService = indicesService.indexServiceSafe(resolveIndex("index")); final IndexShard indexShard = indexService.getShard(0); SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(true); searchRequest.source(SearchSourceBuilder.searchSource().query(new TestRewriteCounterQueryBuilder())); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, searchRequest, indexShard.shardId(), 0, 1, AliasFilter.EMPTY, 1.0f, -1, null ); final Engine.SearcherSupplier reader = indexShard.acquireSearcherSupplier(); ReaderContext context = service.createAndPutReaderContext( request, indexService, indexShard, reader, SearchService.KEEPALIVE_INTERVAL_SETTING.get(Settings.EMPTY).millis() ); PlainActionFuture<QuerySearchResult> plainActionFuture = new PlainActionFuture<>(); service.executeQueryPhase( new QuerySearchRequest(null, context.id(), request, new AggregatedDfs(Map.of(), Map.of(), 10)), new SearchShardTask(42L, "", "", "", null, emptyMap()), plainActionFuture, TransportVersion.current() ); plainActionFuture.actionGet(); assertThat(((TestRewriteCounterQueryBuilder) request.source().query()).asyncRewriteCount, equalTo(1)); final ShardSearchContextId contextId = context.id(); assertTrue(service.freeReaderContext(contextId)); } public void testEnableSearchWorkerThreads() throws IOException { IndexService indexService = createIndex("index", Settings.EMPTY); IndexShard indexShard = indexService.getShard(0); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, new SearchRequest().allowPartialSearchResults(randomBoolean()), indexShard.shardId(), 0, indexService.numberOfShards(), AliasFilter.EMPTY, 1f, System.currentTimeMillis(), null ); try (ReaderContext readerContext = createReaderContext(indexService, indexShard)) { SearchService service = getInstanceFromNode(SearchService.class); SearchShardTask task = new SearchShardTask(0, "type", "action", "description", null, emptyMap()); try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.DFS, randomBoolean())) { assertTrue(searchContext.searcher().hasExecutor()); } try { ClusterUpdateSettingsResponse response = client().admin() .cluster() .prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().put(SEARCH_WORKER_THREADS_ENABLED.getKey(), false).build()) .get(); assertTrue(response.isAcknowledged()); try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.DFS, randomBoolean())) { assertFalse(searchContext.searcher().hasExecutor()); } } finally { // reset original default setting client().admin() .cluster() .prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().putNull(SEARCH_WORKER_THREADS_ENABLED.getKey()).build()) .get(); try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.DFS, randomBoolean())) { assertTrue(searchContext.searcher().hasExecutor()); } } } } /** * Verify that a single slice is created for requests that don't support parallel collection, while an executor is still * provided to the searcher to parallelize other operations. Also ensure multiple slices are created for requests that do support * parallel collection. */ public void testSlicingBehaviourForParallelCollection() throws Exception { IndexService indexService = createIndex("index", Settings.EMPTY); ThreadPoolExecutor executor = (ThreadPoolExecutor) indexService.getThreadPool().executor(ThreadPool.Names.SEARCH); // We configure the executor pool size explicitly in nodeSettings to be independent of CPU cores assert String.valueOf(SEARCH_POOL_SIZE).equals(node().settings().get("thread_pool.search.size")) : "Unexpected thread_pool.search.size"; int numDocs = randomIntBetween(50, 100); for (int i = 0; i < numDocs; i++) { prepareIndex("index").setId(String.valueOf(i)).setSource("field", "value").get(); if (i % 5 == 0) { indicesAdmin().prepareRefresh("index").get(); } } final IndexShard indexShard = indexService.getShard(0); ShardSearchRequest request = new ShardSearchRequest( OriginalIndices.NONE, new SearchRequest().allowPartialSearchResults(randomBoolean()), indexShard.shardId(), 0, indexService.numberOfShards(), AliasFilter.EMPTY, 1f, System.currentTimeMillis(), null ); SearchService service = getInstanceFromNode(SearchService.class); NonCountingTermQuery termQuery = new NonCountingTermQuery(new Term("field", "value")); assertEquals(0, executor.getCompletedTaskCount()); try (ReaderContext readerContext = createReaderContext(indexService, indexShard)) { SearchShardTask task = new SearchShardTask(0, "type", "action", "description", null, emptyMap()); { try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.DFS, true)) { ContextIndexSearcher searcher = searchContext.searcher(); assertTrue(searcher.hasExecutor()); final int maxPoolSize = executor.getMaximumPoolSize(); assertEquals( "Sanity check to ensure this isn't the default of 1 when pool size is unset", SEARCH_POOL_SIZE, maxPoolSize ); final int expectedSlices = ContextIndexSearcher.computeSlices( searcher.getIndexReader().leaves(), maxPoolSize, 1 ).length; assertNotEquals("Sanity check to ensure this isn't the default of 1 when pool size is unset", 1, expectedSlices); final long priorExecutorTaskCount = executor.getCompletedTaskCount(); searcher.search(termQuery, new TotalHitCountCollectorManager(searcher.getSlices())); assertBusy( () -> assertEquals( "DFS supports parallel collection, so the number of slices should be > 1.", expectedSlices - 1, // one slice executes on the calling thread executor.getCompletedTaskCount() - priorExecutorTaskCount ) ); } } { try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.QUERY, true)) { ContextIndexSearcher searcher = searchContext.searcher(); assertTrue(searcher.hasExecutor()); final int maxPoolSize = executor.getMaximumPoolSize(); assertEquals( "Sanity check to ensure this isn't the default of 1 when pool size is unset", SEARCH_POOL_SIZE, maxPoolSize ); final int expectedSlices = ContextIndexSearcher.computeSlices( searcher.getIndexReader().leaves(), maxPoolSize, 1 ).length; assertNotEquals("Sanity check to ensure this isn't the default of 1 when pool size is unset", 1, expectedSlices); final long priorExecutorTaskCount = executor.getCompletedTaskCount(); searcher.search(termQuery, new TotalHitCountCollectorManager(searcher.getSlices())); assertBusy( () -> assertEquals( "QUERY supports parallel collection when enabled, so the number of slices should be > 1.", expectedSlices - 1, // one slice executes on the calling thread executor.getCompletedTaskCount() - priorExecutorTaskCount ) ); } } { try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.FETCH, true)) { ContextIndexSearcher searcher = searchContext.searcher(); assertFalse(searcher.hasExecutor()); final long priorExecutorTaskCount = executor.getCompletedTaskCount(); searcher.search(termQuery, new TotalHitCountCollectorManager(searcher.getSlices())); assertBusy( () -> assertEquals( "The number of slices should be 1 as FETCH does not support parallel collection and thus runs on the calling" + " thread.", 0, executor.getCompletedTaskCount() - priorExecutorTaskCount ) ); } } { try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.NONE, true)) { ContextIndexSearcher searcher = searchContext.searcher(); assertFalse(searcher.hasExecutor()); final long priorExecutorTaskCount = executor.getCompletedTaskCount(); searcher.search(termQuery, new TotalHitCountCollectorManager(searcher.getSlices())); assertBusy( () -> assertEquals( "The number of slices should be 1 as NONE does not support parallel collection.", 0, // zero since one slice executes on the calling thread executor.getCompletedTaskCount() - priorExecutorTaskCount ) ); } } try { ClusterUpdateSettingsResponse response = client().admin() .cluster() .prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().put(QUERY_PHASE_PARALLEL_COLLECTION_ENABLED.getKey(), false).build()) .get(); assertTrue(response.isAcknowledged()); { try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.QUERY, true)) { ContextIndexSearcher searcher = searchContext.searcher(); assertFalse(searcher.hasExecutor()); final long priorExecutorTaskCount = executor.getCompletedTaskCount(); searcher.search(termQuery, new TotalHitCountCollectorManager(searcher.getSlices())); assertBusy( () -> assertEquals( "The number of slices should be 1 when QUERY parallel collection is disabled.", 0, // zero since one slice executes on the calling thread executor.getCompletedTaskCount() - priorExecutorTaskCount ) ); } } } finally { // Reset to the original default setting and check to ensure it takes effect. client().admin() .cluster() .prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().putNull(QUERY_PHASE_PARALLEL_COLLECTION_ENABLED.getKey()).build()) .get(); { try (SearchContext searchContext = service.createContext(readerContext, request, task, ResultsType.QUERY, true)) { ContextIndexSearcher searcher = searchContext.searcher(); assertTrue(searcher.hasExecutor()); final int maxPoolSize = executor.getMaximumPoolSize(); assertEquals( "Sanity check to ensure this isn't the default of 1 when pool size is unset", SEARCH_POOL_SIZE, maxPoolSize ); final int expectedSlices = ContextIndexSearcher.computeSlices( searcher.getIndexReader().leaves(), maxPoolSize, 1 ).length; assertNotEquals("Sanity check to ensure this isn't the default of 1 when pool size is unset", 1, expectedSlices); final long priorExecutorTaskCount = executor.getCompletedTaskCount(); searcher.search(termQuery, new TotalHitCountCollectorManager(searcher.getSlices())); assertBusy( () -> assertEquals( "QUERY supports parallel collection when enabled, so the number of slices should be > 1.", expectedSlices - 1, // one slice executes on the calling thread executor.getCompletedTaskCount() - priorExecutorTaskCount ) ); } } } } } private static ReaderContext createReaderContext(IndexService indexService, IndexShard indexShard) { return new ReaderContext( new ShardSearchContextId(UUIDs.randomBase64UUID(), randomNonNegativeLong()), indexService, indexShard, indexShard.acquireSearcherSupplier(), randomNonNegativeLong(), false ); } private List<String> parseFeatureData(SearchHit hit, String fieldName) { Object fieldValue = hit.getFields().get(fieldName).getValue(); @SuppressWarnings("unchecked") List<String> fieldValues = fieldValue instanceof List ? (List<String>) fieldValue : List.of(String.valueOf(fieldValue)); return fieldValues; } private static
ShardScrollRequestTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/AdsDumpTest_0.java
{ "start": 299, "end": 1721 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "/*+dump-merge=true*/DUMP DATA SELECT amp.buyer_add_cart_info.buyer_id,amp.buyer_add_cart_info.pre_score,amp.buyer_add_cart_info.cart_price FROM amp.buyer_add_cart_info JOIN amp.crm_user_base_info ON amp.crm_user_base_info.user_id = amp.buyer_add_cart_info.buyer_id where (((amp.buyer_add_cart_info.seller_id=1921906956)) AND ((amp.buyer_add_cart_info.auction_id=562769960283)) AND ((amp.buyer_add_cart_info.show_price>=13300))) LIMIT 144800 "; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLDumpStatement stmt = (SQLDumpStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("/*+dump-merge=true*/\n" + "DUMP DATA SELECT amp.buyer_add_cart_info.buyer_id, amp.buyer_add_cart_info.pre_score, amp.buyer_add_cart_info.cart_price\n" + "FROM amp.buyer_add_cart_info\n" + "\tJOIN amp.crm_user_base_info ON amp.crm_user_base_info.user_id = amp.buyer_add_cart_info.buyer_id\n" + "WHERE ((amp.buyer_add_cart_info.seller_id = 1921906956)\n" + "\tAND (amp.buyer_add_cart_info.auction_id = 562769960283)\n" + "\tAND (amp.buyer_add_cart_info.show_price >= 13300))\n" + "LIMIT 144800", stmt.toString()); } }
AdsDumpTest_0
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/discriminator/DiscriminatorTest.java
{ "start": 1121, "end": 3519 }
class ____ { private static SqlSessionFactory sqlSessionFactory; @BeforeAll static void setUp() throws Exception { // create an SqlSessionFactory try ( Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/discriminator/mybatis-config.xml")) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } // populate in-memory database BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), "org/apache/ibatis/submitted/discriminator/CreateDB.sql"); } @Test void shouldSwitchResultType() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); List<Vehicle> vehicles = mapper.selectVehicles(); assertEquals(Car.class, vehicles.get(0).getClass()); assertEquals(Integer.valueOf(5), ((Car) vehicles.get(0)).getDoorCount()); assertEquals(Truck.class, vehicles.get(1).getClass()); assertEquals(Float.valueOf(1.5f), ((Truck) vehicles.get(1)).getCarryingCapacity()); } } @Test void shouldInheritResultType() { // #486 try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); List<Owner> owners = mapper.selectOwnersWithAVehicle(); assertEquals(Truck.class, owners.get(0).getVehicle().getClass()); assertEquals(Car.class, owners.get(1).getVehicle().getClass()); } } @Test void shouldBeAppliedToResultMapInConstructorArg() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); List<Owner> owners = mapper.selectOwnersWithAVehicleConstructor(); assertEquals(Truck.class, owners.get(0).getVehicle().getClass()); assertEquals(Car.class, owners.get(1).getVehicle().getClass()); } } @Test void shouldBeAppliedToResultMapInConstructorArgNested() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); List<Contract> contracts = mapper.selectContracts(); assertEquals(2, contracts.size()); assertEquals(Truck.class, contracts.get(0).getOwner().getVehicle().getClass()); assertEquals(Car.class, contracts.get(1).getOwner().getVehicle().getClass()); } } }
DiscriminatorTest
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/benchmarks/BenchmarkContext.java
{ "start": 715, "end": 1377 }
class ____ { private static final EventExecutor EXECUTOR = new EventExecutor() { @Override public boolean inThread() { throw new UnsupportedOperationException(); } @Override public void execute(Runnable command) { command.run(); } }; public static ContextInternal create(Vertx vertx) { VertxImpl impl = (VertxImpl) vertx; return new ContextImpl( impl, new Object[0], new EventLoopExecutor(impl.eventLoopGroup().next()), ThreadingModel.WORKER, EXECUTOR, impl.workerPool(), null, null, Thread.currentThread().getContextClassLoader() ); } }
BenchmarkContext
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoOnErrorResume.java
{ "start": 1124, "end": 1830 }
class ____<T> extends InternalMonoOperator<T, T> { final Function<? super Throwable, ? extends Publisher<? extends T>> nextFactory; MonoOnErrorResume(Mono<? extends T> source, Function<? super Throwable, ? extends Mono<? extends T>> nextFactory) { super(source); this.nextFactory = Objects.requireNonNull(nextFactory, "nextFactory"); } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { return new FluxOnErrorResume.ResumeSubscriber<>(actual, nextFactory); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } }
MonoOnErrorResume
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Restarting.java
{ "start": 1635, "end": 5166 }
class ____ extends StateWithExecutionGraph { private final Context context; private final Duration backoffTime; @Nullable private ScheduledFuture<?> goToSubsequentStateFuture; private final @Nullable VertexParallelism restartWithParallelism; Restarting( Context context, ExecutionGraph executionGraph, ExecutionGraphHandler executionGraphHandler, OperatorCoordinatorHandler operatorCoordinatorHandler, Logger logger, Duration backoffTime, @Nullable VertexParallelism restartWithParallelism, ClassLoader userCodeClassLoader, List<ExceptionHistoryEntry> failureCollection) { super( context, executionGraph, executionGraphHandler, operatorCoordinatorHandler, logger, userCodeClassLoader, failureCollection); this.context = context; this.backoffTime = backoffTime; this.restartWithParallelism = restartWithParallelism; getExecutionGraph().cancel(); } @Override public void onLeave(Class<? extends State> newState) { if (goToSubsequentStateFuture != null) { goToSubsequentStateFuture.cancel(false); } super.onLeave(newState); } @Override public JobStatus getJobStatus() { return JobStatus.RESTARTING; } @Override public void suspend(Throwable cause) { suspend(cause, JobStatus.SUSPENDED); } @Override public void cancel() { context.goToCanceling( getExecutionGraph(), getExecutionGraphHandler(), getOperatorCoordinatorHandler(), getFailures()); } @Override void onFailure(Throwable failure, CompletableFuture<Map<String, String>> failureLabels) { // We've already cancelled the execution graph, so there is noting else we can do. } @Override void onGloballyTerminalState(JobStatus globallyTerminalState) { Preconditions.checkArgument(globallyTerminalState == JobStatus.CANCELED); goToSubsequentStateFuture = context.runIfState(this, this::goToSubsequentState, backoffTime); } private void goToSubsequentState() { if (availableParallelismNotChanged(restartWithParallelism)) { context.goToCreatingExecutionGraph(getExecutionGraph()); } else { context.goToWaitingForResources(getExecutionGraph()); } } private boolean availableParallelismNotChanged(VertexParallelism restartWithParallelism) { if (this.restartWithParallelism == null) { return false; } return context.getAvailableVertexParallelism() .map( vertexParallelism -> vertexParallelism.getVertices().stream() .allMatch( vertex -> restartWithParallelism.getParallelism( vertex) == vertexParallelism.getParallelism( vertex))) .orElse(false); } /** Context of the {@link Restarting} state. */
Restarting
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ops/MergeNewTest.java
{ "start": 632, "end": 2237 }
class ____ { @AfterEach public void tearDown(EntityManagerFactoryScope scope) { scope.getEntityManagerFactory().getSchemaManager().truncate(); } @Test public void testMergeNew(EntityManagerFactoryScope scope) { scope.inEntityManager( entityManager -> { try { Workload load = new Workload(); load.name = "Cleaning"; load.load = 10; entityManager.getTransaction().begin(); load = entityManager.merge( load ); assertNotNull( load.id ); entityManager.flush(); assertNotNull( load.id ); } finally { if ( entityManager.getTransaction().isActive() ) { entityManager.getTransaction().rollback(); } } } ); } @Test public void testMergeAfterRemove(EntityManagerFactoryScope scope) { Integer load_id = scope.fromTransaction( entityManager -> { Workload _load = new Workload(); _load.name = "Cleaning"; _load.load = 10; _load = entityManager.merge( _load ); entityManager.flush(); return _load.getId(); } ); Workload load =scope.fromTransaction( entityManager -> { Workload _load = entityManager.find( Workload.class, load_id ); entityManager.remove( _load ); entityManager.flush(); return _load; } ); scope.inTransaction( entityManager -> { try { entityManager.merge( load ); entityManager.flush(); } catch (OptimisticLockException e) { //expected since object can be inferred detached assertTrue( e.getCause() instanceof StaleObjectStateException ); } } ); } }
MergeNewTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitDateConvertersTest.java
{ "start": 1442, "end": 1846 }
class ____ implements AttributeConverter<Date,Long> { @Override public Long convertToDatabaseColumn(Date attribute) { convertToDatabaseColumnCalled = true; return attribute.getTime(); } @Override public Date convertToEntityAttribute(Long dbData) { convertToEntityAttributeCalled = true; return new Date( dbData ); } } @Entity( name = "Entity1" ) public static
LongToDateConverter
java
spring-projects__spring-boot
module/spring-boot-hazelcast/src/test/java/org/springframework/boot/hazelcast/autoconfigure/HazelcastAutoConfigurationServerTests.java
{ "start": 11673, "end": 12415 }
class ____ implements HazelcastConfigCustomizer { @Override public void customize(Config config) { config.setManagedContext(null); } } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @WithResource(name = "hazelcast.xml", content = """ <hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-config-5.0.xsd" xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <instance-name>default-instance</instance-name> <map name="defaultCache" /> <network> <join> <auto-detection enabled="false" /> <multicast enabled="false" /> </join> </network> </hazelcast> """) @
TestHazelcastConfigCustomizer
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/ParsedJob.java
{ "start": 1148, "end": 1323 }
class ____ {@link LoggedJob}. This provides also the * extra information about the job obtained from job history which is not * written to the JSON trace file. */ public
around
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/requests/DeleteGroupsResponseTest.java
{ "start": 1404, "end": 3360 }
class ____ { private static final String GROUP_ID_1 = "groupId1"; private static final String GROUP_ID_2 = "groupId2"; private static final int THROTTLE_TIME_MS = 10; private static final DeleteGroupsResponse DELETE_GROUPS_RESPONSE = new DeleteGroupsResponse( new DeleteGroupsResponseData() .setResults( new DeletableGroupResultCollection(Arrays.asList( new DeletableGroupResult() .setGroupId(GROUP_ID_1) .setErrorCode(Errors.NONE.code()), new DeletableGroupResult() .setGroupId(GROUP_ID_2) .setErrorCode(Errors.GROUP_AUTHORIZATION_FAILED.code())).iterator() ) ) .setThrottleTimeMs(THROTTLE_TIME_MS)); @Test public void testGetErrorWithExistingGroupIds() { assertEquals(Errors.NONE, DELETE_GROUPS_RESPONSE.get(GROUP_ID_1)); assertEquals(Errors.GROUP_AUTHORIZATION_FAILED, DELETE_GROUPS_RESPONSE.get(GROUP_ID_2)); Map<String, Errors> expectedErrors = new HashMap<>(); expectedErrors.put(GROUP_ID_1, Errors.NONE); expectedErrors.put(GROUP_ID_2, Errors.GROUP_AUTHORIZATION_FAILED); assertEquals(expectedErrors, DELETE_GROUPS_RESPONSE.errors()); Map<Errors, Integer> expectedErrorCounts = new EnumMap<>(Errors.class); expectedErrorCounts.put(Errors.NONE, 1); expectedErrorCounts.put(Errors.GROUP_AUTHORIZATION_FAILED, 1); assertEquals(expectedErrorCounts, DELETE_GROUPS_RESPONSE.errorCounts()); } @Test public void testGetErrorWithInvalidGroupId() { assertThrows(IllegalArgumentException.class, () -> DELETE_GROUPS_RESPONSE.get("invalid-group-id")); } @Test public void testGetThrottleTimeMs() { assertEquals(THROTTLE_TIME_MS, DELETE_GROUPS_RESPONSE.throttleTimeMs()); } }
DeleteGroupsResponseTest
java
quarkusio__quarkus
devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/reactive-routes-codestart/java/src/main/java/org/acme/MyDeclarativeRoutes.java
{ "start": 221, "end": 536 }
class ____ { // neither path nor regex is set - match a path derived from the method name (ie helloRoute => /hello-route ) @Route(methods = Route.HttpMethod.GET) void helloRoute(RoutingExchange ex) { ex.ok("Hello " + ex.getParam("name").orElse("Reactive Route") +" !!"); } }
MyDeclarativeRoutes
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/instant/InstantWithNormalizedTest.java
{ "start": 1510, "end": 3118 }
class ____ { @Test public void test(EntityManagerFactoryScope scope) { Instant now = Instant.now(); ZoneOffset zone = ZoneOffset.of("+01:00");// ZoneOffset.ofHours(1); scope.getEntityManagerFactory() .runInTransaction( entityManager -> { Instants instants = new Instants(); instants.instantInUtc = now; instants.instantInLocalTimeZone = now; instants.instantWithTimeZone = now; instants.localDateTime = LocalDateTime.ofInstant( now, zone ); instants.offsetDateTime = OffsetDateTime.ofInstant( now, zone ); instants.localDateTimeUtc = LocalDateTime.ofInstant( now, ZoneOffset.UTC ); instants.offsetDateTimeUtc = OffsetDateTime.ofInstant( now, ZoneOffset.UTC ); entityManager.persist( instants ); } ); scope.getEntityManagerFactory() .runInTransaction( entityManager -> { Instants instants = entityManager.find( Instants.class, 0 ); assertEqualInstants( now, instants.instantInUtc ); assertEqualInstants( now, instants.instantInLocalTimeZone ); assertEqualInstants( now, instants.instantWithTimeZone ); assertEqualInstants( now, instants.offsetDateTime.toInstant() ); assertEqualInstants( now, instants.localDateTime.toInstant( zone ) ); assertEqualInstants( now, instants.offsetDateTimeUtc.toInstant() ); assertEqualInstants( now, instants.localDateTimeUtc.toInstant( ZoneOffset.UTC ) ); } ); } void assertEqualInstants(Instant x, Instant y) { assertEquals( x.truncatedTo( ChronoUnit.SECONDS ), y.truncatedTo( ChronoUnit.SECONDS ) ); } @Entity(name="Instants2") static
InstantWithNormalizedTest
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BuildExtension.java
{ "start": 1110, "end": 2717 }
interface ____<T> { // Built-in keys static String BUILT_IN_PREFIX = BuildExtension.class.getPackage().getName() + "."; static Key<IndexView> INDEX = simpleBuiltIn("index"); static Key<Collection<InjectionPointInfo>> INJECTION_POINTS = simpleBuiltIn("injectionPoints"); static Key<Collection<BeanInfo>> BEANS = simpleBuiltIn("beans"); static Key<Collection<BeanInfo>> REMOVED_BEANS = simpleBuiltIn("removedBeans"); static Key<Collection<ObserverInfo>> OBSERVERS = simpleBuiltIn("observers"); static Key<Collection<InterceptorInfo>> INTERCEPTORS = simpleBuiltIn("interceptors"); static Key<Collection<InterceptorInfo>> REMOVED_INTERCEPTORS = simpleBuiltIn("removedInterceptors"); static Key<Collection<DecoratorInfo>> DECORATORS = simpleBuiltIn("decorators"); static Key<Collection<DecoratorInfo>> REMOVED_DECORATORS = simpleBuiltIn("removedDecorators"); static Key<AnnotationStore> ANNOTATION_STORE = simpleBuiltIn("annotationStore"); static Key<Collection<ScopeInfo>> SCOPES = simpleBuiltIn("scopes"); static Key<Map<DotName, ClassInfo>> QUALIFIERS = simpleBuiltIn("qualifiers"); static Key<Map<DotName, ClassInfo>> INTERCEPTOR_BINDINGS = simpleBuiltIn("interceptorBindings"); static Key<Map<DotName, StereotypeInfo>> STEREOTYPES = simpleBuiltIn("stereotypes"); static Key<InvokerFactory> INVOKER_FACTORY = simpleBuiltIn("invokerFactory"); static Key<BeanDeployment> DEPLOYMENT = simpleBuiltIn("deployment"); String asString(); } public static
Key
java
spring-projects__spring-boot
module/spring-boot-zipkin/src/test/java/org/springframework/boot/zipkin/autoconfigure/ZipkinAutoConfigurationTests.java
{ "start": 4537, "end": 4698 }
class ____ { @Bean Encoding customEncoding() { return Encoding.PROTO3; } } @Configuration(proxyBeanMethods = false) static
CustomEncodingConfiguration
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java
{ "start": 23397, "end": 23983 }
class ____ { @Nullable public String[] getMessage(boolean b) { return b ? null : new String[0]; } } """) .doTest(); } @Test public void arrayTypeUse() { createRefactoringTestHelper() .addInputLines( "in/com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", """ package com.google.errorprone.bugpatterns.nullness; import org.checkerframework.checker.nullness.qual.Nullable; public
LiteralNullReturnTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/VirtualTableGroup.java
{ "start": 150, "end": 280 }
interface ____ TableGroup impls that are virtual - should not be rendered * into the SQL. * * @author Steve Ebersole */ public
for
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/bind/support/SessionAttributeStore.java
{ "start": 792, "end": 974 }
interface ____ storing model attributes in a backend session. * * @author Juergen Hoeller * @since 2.5 * @see org.springframework.web.bind.annotation.SessionAttributes */ public
for
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/util/MRBuilderUtils.java
{ "start": 1577, "end": 4571 }
class ____ { public static JobId newJobId(ApplicationId appId, int id) { JobId jobId = Records.newRecord(JobId.class); jobId.setAppId(appId); jobId.setId(id); return jobId; } public static JobId newJobId(long clusterTs, int appIdInt, int id) { ApplicationId appId = ApplicationId.newInstance(clusterTs, appIdInt); return MRBuilderUtils.newJobId(appId, id); } public static TaskId newTaskId(JobId jobId, int id, TaskType taskType) { TaskId taskId = Records.newRecord(TaskId.class); taskId.setJobId(jobId); taskId.setId(id); taskId.setTaskType(taskType); return taskId; } public static TaskAttemptId newTaskAttemptId(TaskId taskId, int attemptId) { TaskAttemptId taskAttemptId = Records.newRecord(TaskAttemptId.class); taskAttemptId.setTaskId(taskId); taskAttemptId.setId(attemptId); return taskAttemptId; } public static JobReport newJobReport(JobId jobId, String jobName, String userName, JobState state, long submitTime, long startTime, long finishTime, float setupProgress, float mapProgress, float reduceProgress, float cleanupProgress, String jobFile, List<AMInfo> amInfos, boolean isUber, String diagnostics) { return newJobReport(jobId, jobName, userName, state, submitTime, startTime, finishTime, setupProgress, mapProgress, reduceProgress, cleanupProgress, jobFile, amInfos, isUber, diagnostics, Priority.newInstance(0)); } public static JobReport newJobReport(JobId jobId, String jobName, String userName, JobState state, long submitTime, long startTime, long finishTime, float setupProgress, float mapProgress, float reduceProgress, float cleanupProgress, String jobFile, List<AMInfo> amInfos, boolean isUber, String diagnostics, Priority priority) { JobReport report = Records.newRecord(JobReport.class); report.setJobId(jobId); report.setJobName(jobName); report.setUser(userName); report.setJobState(state); report.setSubmitTime(submitTime); report.setStartTime(startTime); report.setFinishTime(finishTime); report.setSetupProgress(setupProgress); report.setCleanupProgress(cleanupProgress); report.setMapProgress(mapProgress); report.setReduceProgress(reduceProgress); report.setJobFile(jobFile); report.setAMInfos(amInfos); report.setIsUber(isUber); report.setDiagnostics(diagnostics); report.setJobPriority(priority); return report; } public static AMInfo newAMInfo(ApplicationAttemptId appAttemptId, long startTime, ContainerId containerId, String nmHost, int nmPort, int nmHttpPort) { AMInfo amInfo = Records.newRecord(AMInfo.class); amInfo.setAppAttemptId(appAttemptId); amInfo.setStartTime(startTime); amInfo.setContainerId(containerId); amInfo.setNodeManagerHost(nmHost); amInfo.setNodeManagerPort(nmPort); amInfo.setNodeManagerHttpPort(nmHttpPort); return amInfo; } }
MRBuilderUtils
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/naming/pojo/healthcheck/AbstractHealthChecker.java
{ "start": 1615, "end": 2365 }
class ____ implements Cloneable, Serializable { private static final long serialVersionUID = 3848305577423336421L; @JsonIgnore protected final String type; protected AbstractHealthChecker(String type) { this.type = type; } public String getType() { return type; } /** * Clone all fields of this instance to another one. * * @return Another instance with exactly the same fields * @throws CloneNotSupportedException clone not supported exception */ @Override public abstract AbstractHealthChecker clone() throws CloneNotSupportedException; /** * Default implementation of Health checker. */ public static
AbstractHealthChecker
java
spring-projects__spring-security
ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java
{ "start": 17208, "end": 17762 }
class ____ implements NamingEnumeration<SearchResult> { private SearchResult sr; MockNamingEnumeration(SearchResult sr) { this.sr = sr; } @Override public SearchResult next() { SearchResult result = this.sr; this.sr = null; return result; } @Override public boolean hasMore() { return this.sr != null; } @Override public void close() { } @Override public boolean hasMoreElements() { return hasMore(); } @Override public SearchResult nextElement() { return next(); } } }
MockNamingEnumeration
java
google__gson
gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java
{ "start": 1703, "end": 2457 }
class ____ { // public Object allocateInstance(Class<?> type); // } try { Class<?> unsafeClass = Class.forName("sun.misc.Unsafe"); Field f = unsafeClass.getDeclaredField("theUnsafe"); f.setAccessible(true); Object unsafe = f.get(null); Method allocateInstance = unsafeClass.getMethod("allocateInstance", Class.class); return new UnsafeAllocator() { @Override @SuppressWarnings("unchecked") public <T> T newInstance(Class<T> c) throws Exception { assertInstantiable(c); return (T) allocateInstance.invoke(unsafe, c); } }; } catch (Exception ignored) { // OK: try the next way } // try dalvikvm, post-gingerbread // public
Unsafe
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/FilesSimpleBaseTest.java
{ "start": 1421, "end": 2621 }
class ____ { protected static final AssertionInfo INFO = someInfo(); protected Path tempDir; protected File tempDirAsFile; protected Files files; protected Failures failures; @BeforeEach public void setUp(@TempDir Path tempDir) { this.tempDir = tempDir; tempDirAsFile = tempDir.toFile(); failures = spy(Failures.instance()); files = new Files(); files.failures = failures; } public Path createDirectory(Path parent, String name, String... files) { Path directory = parent.resolve(name); try { java.nio.file.Files.createDirectory(directory); stream(files).forEach(f -> createFile(directory, f)); } catch (IOException e) { throw new UncheckedIOException("error during fixture directory creation", e); } return directory; } public Path createDirectoryWithDefaultParent(String name, String... files) { return createDirectory(tempDir, name, files); } private void createFile(Path directory, String f) { try { java.nio.file.Files.createFile(directory.resolve(f)); } catch (IOException e) { throw new UncheckedIOException("error during fixture file creation", e); } } }
FilesSimpleBaseTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/util/AbstractStreamOperatorTestHarness.java
{ "start": 6081, "end": 36331 }
class ____<OUT> implements AutoCloseable { protected StreamOperator<OUT> operator; protected final StreamOperatorFactory<OUT> factory; protected final ConcurrentLinkedQueue<Object> outputList; protected final Map<OutputTag<?>, ConcurrentLinkedQueue<Object>> sideOutputLists; protected final StreamConfig config; protected final ExecutionConfig executionConfig; protected final TestProcessingTimeService processingTimeService; protected final MockTtlTimeProvider ttlTimeProvider; protected final MockStreamTask<OUT, ?> mockTask; protected final TestTaskStateManager taskStateManager; final MockEnvironment environment; private final Optional<MockEnvironment> internalEnvironment; protected StreamTaskStateInitializer streamTaskStateInitializer; private final TaskMailbox taskMailbox; // use this as default for tests protected StateBackend stateBackend = new HashMapStateBackend(); private CheckpointStorageAccess checkpointStorageAccess = new JobManagerCheckpointStorage().createCheckpointStorage(new JobID()); private final Object checkpointLock; private static final OperatorStateRepartitioner<OperatorStateHandle> operatorStateRepartitioner = RoundRobinOperatorStateRepartitioner.INSTANCE; private InternalTimeServiceManagerImpl<?> timeServiceManager; private InternalTimeServiceManager.Provider timeServiceManagerProvider = new InternalTimeServiceManager.Provider() { @Override public <K> InternalTimeServiceManager<K> create( TaskIOMetricGroup taskIOMetricGroup, PriorityQueueSetFactory factory, KeyGroupRange keyGroupRange, ClassLoader userClassloader, KeyContext keyContext, ProcessingTimeService processingTimeService, Iterable<KeyGroupStatePartitionStreamProvider> rawKeyedStates, StreamTaskCancellationContext cancellationContext) throws Exception { InternalTimeServiceManagerImpl<K> typedTimeServiceManager = InternalTimeServiceManagerImpl.create( taskIOMetricGroup, factory, keyGroupRange, userClassloader, keyContext, processingTimeService, rawKeyedStates, cancellationContext); if (timeServiceManager == null) { timeServiceManager = typedTimeServiceManager; } return typedTimeServiceManager; } }; /** Whether setup() was called on the operator. This is reset when calling close(). */ private boolean setupCalled = false; private boolean initializeCalled = false; private volatile boolean wasFailedExternally = false; private long restoredCheckpointId = 0; private Function<TypeSerializer<OUT>, Output<StreamRecord<OUT>>> outputCreator = MockOutput::new; public AbstractStreamOperatorTestHarness( StreamOperator<OUT> operator, int maxParallelism, int parallelism, int subtaskIndex) throws Exception { this(operator, maxParallelism, parallelism, subtaskIndex, new OperatorID()); } public AbstractStreamOperatorTestHarness( StreamOperator<OUT> operator, int maxParallelism, int parallelism, int subtaskIndex, OperatorID operatorID) throws Exception { this( operator, SimpleOperatorFactory.of(operator), new MockEnvironmentBuilder() .setTaskName("MockTask") .setManagedMemorySize(3 * 1024 * 1024) .setInputSplitProvider(new MockInputSplitProvider()) .setBufferSize(1024) .setMaxParallelism(maxParallelism) .setParallelism(parallelism) .setSubtaskIndex(subtaskIndex) .build(), true, operatorID); } public AbstractStreamOperatorTestHarness( StreamOperatorFactory<OUT> factory, MockEnvironment env) throws Exception { this(null, factory, env, false, new OperatorID()); } public AbstractStreamOperatorTestHarness( StreamOperatorFactory<OUT> factory, int maxParallelism, int parallelism, int subtaskIndex) throws Exception { this(factory, maxParallelism, parallelism, subtaskIndex, new OperatorID()); } public AbstractStreamOperatorTestHarness( StreamOperatorFactory<OUT> factory, int maxParallelism, int parallelism, int subtaskIndex, OperatorID operatorID) throws Exception { this( null, factory, new MockEnvironmentBuilder() .setTaskName("MockTask") .setManagedMemorySize(3 * 1024 * 1024) .setInputSplitProvider(new MockInputSplitProvider()) .setBufferSize(1024) .setMaxParallelism(maxParallelism) .setParallelism(parallelism) .setSubtaskIndex(subtaskIndex) .build(), true, operatorID); } public AbstractStreamOperatorTestHarness(StreamOperator<OUT> operator, MockEnvironment env) throws Exception { this(operator, SimpleOperatorFactory.of(operator), env, false, new OperatorID()); } public AbstractStreamOperatorTestHarness( StreamOperator<OUT> operator, String taskName, OperatorID operatorID) throws Exception { this( operator, SimpleOperatorFactory.of(operator), new MockEnvironmentBuilder() .setTaskName(taskName) .setManagedMemorySize(3 * 1024 * 1024) .setInputSplitProvider(new MockInputSplitProvider()) .setBufferSize(1024) .setMaxParallelism(1) .setParallelism(1) .setSubtaskIndex(0) .build(), false, operatorID); } private AbstractStreamOperatorTestHarness( StreamOperator<OUT> operator, StreamOperatorFactory<OUT> factory, MockEnvironment env, boolean environmentIsInternal, OperatorID operatorID) throws Exception { this.operator = operator; this.factory = factory; this.outputList = new ConcurrentLinkedQueue<>(); this.sideOutputLists = new HashMap<>(); Configuration underlyingConfig = env.getTaskConfiguration(); this.config = new StreamConfig(underlyingConfig); this.config.setOperatorID(operatorID); this.config.setStateBackendUsesManagedMemory(true); this.config.setManagedMemoryFractionOperatorOfUseCase( ManagedMemoryUseCase.STATE_BACKEND, 1.0); this.config.setManagedMemoryFractionOperatorOfUseCase(ManagedMemoryUseCase.OPERATOR, 1.0); this.executionConfig = env.getExecutionConfig(); this.checkpointLock = new Object(); this.environment = Preconditions.checkNotNull(env); this.taskStateManager = (TestTaskStateManager) env.getTaskStateManager(); this.internalEnvironment = environmentIsInternal ? Optional.of(environment) : Optional.empty(); processingTimeService = new TestProcessingTimeService(); processingTimeService.setCurrentTime(0); ttlTimeProvider = new MockTtlTimeProvider(); ttlTimeProvider.setCurrentTimestamp(0); this.streamTaskStateInitializer = createStreamTaskStateManager( environment, stateBackend, ttlTimeProvider, timeServiceManagerProvider); BiConsumer<String, Throwable> handleAsyncException = (message, t) -> { wasFailedExternally = true; }; this.taskMailbox = new TaskMailboxImpl(); // TODO remove this once we introduce AbstractStreamOperatorTestHarnessBuilder. try { this.checkpointStorageAccess = environment.getCheckpointStorageAccess(); } catch (NullPointerException | UnsupportedOperationException e) { // cannot get checkpoint storage from environment, use default one. } mockTask = new MockStreamTaskBuilder(env) .setCheckpointLock(checkpointLock) .setConfig(config) .setExecutionConfig(executionConfig) .setStreamTaskStateInitializer(streamTaskStateInitializer) .setCheckpointStorage(checkpointStorageAccess) .setTimerService(processingTimeService) .setHandleAsyncException(handleAsyncException) .setTaskMailbox(taskMailbox) .build(); } private StreamTaskStateInitializer createStreamTaskStateManager( Environment env, StateBackend stateBackend, TtlTimeProvider ttlTimeProvider, InternalTimeServiceManager.Provider timeServiceManagerProvider) { return new StreamTaskStateInitializerImpl( env, stateBackend, new SubTaskInitializationMetricsBuilder( SystemClock.getInstance().absoluteTimeMillis()), ttlTimeProvider, timeServiceManagerProvider, StreamTaskCancellationContext.alwaysRunning()); } public void setStateBackend(StateBackend stateBackend) { this.stateBackend = stateBackend; if (stateBackend instanceof CheckpointStorage) { setCheckpointStorage((CheckpointStorage) stateBackend); } } public void setOutputCreator( Function<TypeSerializer<OUT>, Output<StreamRecord<OUT>>> outputCreator) { this.outputCreator = outputCreator; } public void setCheckpointStorage(CheckpointStorage storage) { if (stateBackend instanceof CheckpointStorage) { return; } try { this.checkpointStorageAccess = storage.createCheckpointStorage(new JobID()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } /** * @deprecated Checkpoint lock in {@link StreamTask} is replaced by {@link * org.apache.flink.streaming.runtime.tasks.StreamTaskActionExecutor * StreamTaskActionExecutor}. */ @Deprecated public Object getCheckpointLock() { return mockTask.getCheckpointLock(); } public MockEnvironment getEnvironment() { return environment; } public ExecutionConfig getExecutionConfig() { return executionConfig; } public StreamConfig getStreamConfig() { return config; } public void setRestoredCheckpointId(long restoredCheckpointId) { this.restoredCheckpointId = restoredCheckpointId; } /** Get all the output from the task. This contains StreamRecords and Events interleaved. */ public ConcurrentLinkedQueue<Object> getOutput() { return outputList; } @SuppressWarnings("unchecked") public Collection<StreamRecord<OUT>> getRecordOutput() { return outputList.stream() .filter(element -> element instanceof StreamRecord) .map(element -> (StreamRecord<OUT>) element) .collect(Collectors.toList()); } @SuppressWarnings({"unchecked", "rawtypes"}) public <X> ConcurrentLinkedQueue<StreamRecord<X>> getSideOutput(OutputTag<X> tag) { return (ConcurrentLinkedQueue) sideOutputLists.get(tag); } /** Get only the {@link StreamRecord StreamRecords} emitted by the operator. */ @SuppressWarnings("unchecked") public List<StreamRecord<? extends OUT>> extractOutputStreamRecords() { List<StreamRecord<? extends OUT>> resultElements = new LinkedList<>(); for (Object e : getOutput()) { if (e instanceof StreamRecord) { resultElements.add((StreamRecord<OUT>) e); } } return resultElements; } /** Get the list of OUT values emitted by the operator. */ public List<OUT> extractOutputValues() { List<StreamRecord<? extends OUT>> streamRecords = extractOutputStreamRecords(); List<OUT> outputValues = new ArrayList<>(); for (StreamRecord<? extends OUT> streamRecord : streamRecords) { outputValues.add(streamRecord.getValue()); } return outputValues; } /** * Calls {@link * org.apache.flink.streaming.api.operators.StreamOperatorUtils#setupStreamOperator(AbstractStreamOperator, * StreamTask, StreamConfig, Output)} ()}. */ public void setup() { setup(null); } /** * Calls {@link * org.apache.flink.streaming.api.operators.StreamOperatorUtils#setupStreamOperator(AbstractStreamOperator, * StreamTask, StreamConfig, Output)} ()}. */ public void setup(TypeSerializer<OUT> outputSerializer) { if (!setupCalled) { streamTaskStateInitializer = createStreamTaskStateManager( environment, stateBackend, ttlTimeProvider, timeServiceManagerProvider); mockTask.setStreamTaskStateInitializer(streamTaskStateInitializer); if (operator == null) { this.operator = StreamOperatorFactoryUtil.createOperator( factory, mockTask, config, outputCreator.apply(outputSerializer), new OperatorEventDispatcherImpl( this.getClass().getClassLoader(), new NoOpTaskOperatorEventGateway())) .f0; } else { if (operator instanceof AbstractStreamOperator) { setProcessingTimeService( (AbstractStreamOperator) operator, processingTimeService); setupStreamOperator( (AbstractStreamOperator) operator, mockTask, config, outputCreator.apply(outputSerializer)); } } setupCalled = true; this.mockTask.init(); } } /** * Calls {@link * org.apache.flink.streaming.api.operators.StreamOperator#initializeState(StreamTaskStateInitializer)}. * Calls {@link * org.apache.flink.streaming.api.operators.StreamOperatorUtils#setupStreamOperator(AbstractStreamOperator, * StreamTask, StreamConfig, Output)} if it was not called before. */ public void initializeState(OperatorSubtaskState operatorStateHandles) throws Exception { initializeState(operatorStateHandles, null); } public void initializeState(String operatorStateSnapshotPath) throws Exception { initializeState(OperatorSnapshotUtil.readStateHandle(operatorStateSnapshotPath)); } public void initializeEmptyState() throws Exception { initializeState((OperatorSubtaskState) null); } /** * Returns the reshaped the state handles to include only those key-group states in the local * key-group range and the operator states that would be assigned to the local subtask. */ public static OperatorSubtaskState repartitionOperatorState( final OperatorSubtaskState operatorStateHandles, final int numKeyGroups, final int oldParallelism, final int newParallelism, final int subtaskIndex) { Preconditions.checkNotNull( operatorStateHandles, "the previous operatorStateHandles should not be null."); // create a new OperatorStateHandles that only contains the state for our key-groups List<KeyGroupRange> keyGroupPartitions = StateAssignmentOperation.createKeyGroupPartitions(numKeyGroups, newParallelism); KeyGroupRange localKeyGroupRange = keyGroupPartitions.get(subtaskIndex); List<KeyedStateHandle> localManagedKeyGroupState = new ArrayList<>(); StateAssignmentOperation.extractIntersectingState( operatorStateHandles.getManagedKeyedState(), localKeyGroupRange, localManagedKeyGroupState); List<KeyedStateHandle> localRawKeyGroupState = new ArrayList<>(); StateAssignmentOperation.extractIntersectingState( operatorStateHandles.getRawKeyedState(), localKeyGroupRange, localRawKeyGroupState); StateObjectCollection<OperatorStateHandle> managedOperatorStates = operatorStateHandles.getManagedOperatorState(); Collection<OperatorStateHandle> localManagedOperatorState; if (!managedOperatorStates.isEmpty()) { List<List<OperatorStateHandle>> managedOperatorState = managedOperatorStates.stream() .map(Collections::singletonList) .collect(Collectors.toList()); localManagedOperatorState = operatorStateRepartitioner .repartitionState(managedOperatorState, oldParallelism, newParallelism) .get(subtaskIndex); } else { localManagedOperatorState = Collections.emptyList(); } StateObjectCollection<OperatorStateHandle> rawOperatorStates = operatorStateHandles.getRawOperatorState(); Collection<OperatorStateHandle> localRawOperatorState; if (!rawOperatorStates.isEmpty()) { List<List<OperatorStateHandle>> rawOperatorState = rawOperatorStates.stream() .map(Collections::singletonList) .collect(Collectors.toList()); localRawOperatorState = operatorStateRepartitioner .repartitionState(rawOperatorState, oldParallelism, newParallelism) .get(subtaskIndex); } else { localRawOperatorState = Collections.emptyList(); } return OperatorSubtaskState.builder() .setManagedOperatorState( new StateObjectCollection<>( nullToEmptyCollection(localManagedOperatorState))) .setRawOperatorState( new StateObjectCollection<>(nullToEmptyCollection(localRawOperatorState))) .setManagedKeyedState( new StateObjectCollection<>( nullToEmptyCollection(localManagedKeyGroupState))) .setRawKeyedState( new StateObjectCollection<>(nullToEmptyCollection(localRawKeyGroupState))) .build(); } /** * Calls {@link org.apache.flink.streaming.api.operators.StreamOperator#initializeState()}. * Calls {@link * org.apache.flink.streaming.api.operators.StreamOperatorUtils#setupStreamOperator(AbstractStreamOperator, * StreamTask, StreamConfig, Output)} if it was not called before. * * @param jmOperatorStateHandles the primary state (owned by JM) * @param tmOperatorStateHandles the (optional) local state (owned by TM) or null. * @throws Exception */ public void initializeState( OperatorSubtaskState jmOperatorStateHandles, OperatorSubtaskState tmOperatorStateHandles) throws Exception { checkState( !initializeCalled, "TestHarness has already been initialized. Have you " + "opened this harness before initializing it?"); if (!setupCalled) { setup(); } if (jmOperatorStateHandles != null) { TaskStateSnapshot jmTaskStateSnapshot = new TaskStateSnapshot(); jmTaskStateSnapshot.putSubtaskStateByOperatorID( operator.getOperatorID(), jmOperatorStateHandles); taskStateManager.setReportedCheckpointId(restoredCheckpointId); taskStateManager.setJobManagerTaskStateSnapshotsByCheckpointId( Collections.singletonMap(restoredCheckpointId, jmTaskStateSnapshot)); if (tmOperatorStateHandles != null) { TaskStateSnapshot tmTaskStateSnapshot = new TaskStateSnapshot(); tmTaskStateSnapshot.putSubtaskStateByOperatorID( operator.getOperatorID(), tmOperatorStateHandles); taskStateManager.setTaskManagerTaskStateSnapshotsByCheckpointId( Collections.singletonMap(restoredCheckpointId, tmTaskStateSnapshot)); } } operator.initializeState( mockTask.createStreamTaskStateInitializer( new SubTaskInitializationMetricsBuilder( SystemClock.getInstance().absoluteTimeMillis()))); initializeCalled = true; } private static <T> Collection<T> nullToEmptyCollection(Collection<T> collection) { return collection != null ? collection : Collections.<T>emptyList(); } /** * Takes the different {@link OperatorSubtaskState} created by calling {@link #snapshot(long, * long)} on different instances of {@link AbstractStreamOperatorTestHarness} (each one * representing one subtask) and repacks them into a single {@link OperatorSubtaskState} so that * the parallelism of the test can change arbitrarily (i.e. be able to scale both up and down). * * <p>After repacking the partial states, remember to use {@link * #repartitionOperatorState(OperatorSubtaskState, int, int, int, int)} to reshape the state * handles to include only those key-group states in the local key-group range and the operator * states that would be assigned to the local subtask. Bear in mind that for parallelism greater * than one, you have to use the constructor {@link * #AbstractStreamOperatorTestHarness(StreamOperator, int, int, int)}. * * <p><b>NOTE: </b> each of the {@code handles} in the argument list is assumed to be from a * single task of a single operator (i.e. chain length of one). * * <p>For an example of how to use it, have a look at {@link * AbstractStreamOperatorTest#testStateAndTimerStateShufflingScalingDown()}. * * @param handles the different states to be merged. * @return the resulting state, or {@code null} if no partial states are specified. */ public static OperatorSubtaskState repackageState(OperatorSubtaskState... handles) throws Exception { if (handles.length < 1) { return null; } else if (handles.length == 1) { return handles[0]; } List<OperatorStateHandle> mergedManagedOperatorState = new ArrayList<>(handles.length); List<OperatorStateHandle> mergedRawOperatorState = new ArrayList<>(handles.length); List<KeyedStateHandle> mergedManagedKeyedState = new ArrayList<>(handles.length); List<KeyedStateHandle> mergedRawKeyedState = new ArrayList<>(handles.length); for (OperatorSubtaskState handle : handles) { Collection<OperatorStateHandle> managedOperatorState = handle.getManagedOperatorState(); Collection<OperatorStateHandle> rawOperatorState = handle.getRawOperatorState(); Collection<KeyedStateHandle> managedKeyedState = handle.getManagedKeyedState(); Collection<KeyedStateHandle> rawKeyedState = handle.getRawKeyedState(); mergedManagedOperatorState.addAll(managedOperatorState); mergedRawOperatorState.addAll(rawOperatorState); mergedManagedKeyedState.addAll(managedKeyedState); mergedRawKeyedState.addAll(rawKeyedState); } return OperatorSubtaskState.builder() .setManagedOperatorState(new StateObjectCollection<>(mergedManagedOperatorState)) .setRawOperatorState(new StateObjectCollection<>(mergedRawOperatorState)) .setManagedKeyedState(new StateObjectCollection<>(mergedManagedKeyedState)) .setRawKeyedState(new StateObjectCollection<>(mergedRawKeyedState)) .build(); } /** * Calls {@link StreamOperator#open()}. This also calls {@link * org.apache.flink.streaming.api.operators.StreamOperatorUtils#setupStreamOperator(AbstractStreamOperator, * StreamTask, StreamConfig, Output)} if it was not called before. */ public void open() throws Exception { if (!initializeCalled) { initializeEmptyState(); } operator.open(); } /** Calls {@link StreamOperator#prepareSnapshotPreBarrier(long)}. */ public void prepareSnapshotPreBarrier(long checkpointId) throws Exception { operator.prepareSnapshotPreBarrier(checkpointId); } /** * Calls {@link StreamOperator#snapshotState(long, long, CheckpointOptions, * org.apache.flink.runtime.state.CheckpointStreamFactory)}. */ public OperatorSubtaskState snapshot(long checkpointId, long timestamp) throws Exception { return snapshotWithLocalState(checkpointId, timestamp).getJobManagerOwnedState(); } /** * Calls {@link StreamOperator#snapshotState(long, long, CheckpointOptions, * org.apache.flink.runtime.state.CheckpointStreamFactory)}. */ public OperatorSnapshotFinalizer snapshotWithLocalState(long checkpointId, long timestamp) throws Exception { return snapshotWithLocalState(checkpointId, timestamp, CheckpointType.CHECKPOINT); } /** * Calls {@link StreamOperator#snapshotState(long, long, CheckpointOptions, * org.apache.flink.runtime.state.CheckpointStreamFactory)}. */ public OperatorSnapshotFinalizer snapshotWithLocalState( long checkpointId, long timestamp, SnapshotType checkpointType) throws Exception { CheckpointStorageLocationReference locationReference = CheckpointStorageLocationReference.getDefault(); OperatorSnapshotFutures operatorStateResult = operator.snapshotState( checkpointId, timestamp, new CheckpointOptions(checkpointType, locationReference), checkpointStorageAccess.resolveCheckpointStorageLocation( checkpointId, locationReference)); return OperatorSnapshotFinalizer.create(operatorStateResult); } /** * Calls {@link * org.apache.flink.streaming.api.operators.StreamOperator#notifyCheckpointComplete(long)} ()}. */ public void notifyOfCompletedCheckpoint(long checkpointId) throws Exception { operator.notifyCheckpointComplete(checkpointId); } /** Calls finish and close on the operator. */ public void close() throws Exception { if (processingTimeService != null) { processingTimeService.shutdownService(); } setupCalled = false; operator.finish(); operator.close(); if (internalEnvironment.isPresent()) { internalEnvironment.get().close(); } mockTask.cleanUpInternal(); } public AbstractStreamOperator<OUT> getOperator() { return (AbstractStreamOperator<OUT>) operator; } public StreamOperatorFactory<OUT> getOperatorFactory() { return factory; } public void advanceTime(long delta) throws Exception { processingTimeService.advance(delta); } public void setProcessingTime(long time) throws Exception { processingTimeService.setCurrentTime(time); } public void setStateTtlProcessingTime(long timeStamp) { ttlTimeProvider.setCurrentTimestamp(timeStamp); } public long getProcessingTime() { return processingTimeService.getCurrentProcessingTime(); } public boolean wasFailedExternally() { return wasFailedExternally; } @VisibleForTesting public int numProcessingTimeTimers() { if (timeServiceManager != null) { return timeServiceManager.numProcessingTimeTimers(); } else { throw new UnsupportedOperationException(); } } @VisibleForTesting public int numEventTimeTimers() { if (timeServiceManager != null) { return timeServiceManager.numEventTimeTimers(); } else { throw new UnsupportedOperationException(); } } @VisibleForTesting public TestProcessingTimeService getProcessingTimeService() { return processingTimeService; } @VisibleForTesting public TaskMailbox getTaskMailbox() { return taskMailbox; } public void setTimeServiceManagerProvider( InternalTimeServiceManager.Provider timeServiceManagerProvider) { this.timeServiceManagerProvider = timeServiceManagerProvider; }
AbstractStreamOperatorTestHarness
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/integer_/IntegerAssert_isNotCloseTo_int_Test.java
{ "start": 994, "end": 1433 }
class ____ extends IntegerAssertBaseTest { private final Offset<Integer> offset = offset(13); private final int value = 7; @Override protected IntegerAssert invoke_api_method() { return assertions.isNotCloseTo(value, offset); } @Override protected void verify_internal_effects() { verify(integers).assertIsNotCloseTo(getInfo(assertions), getActual(assertions), value, offset); } }
IntegerAssert_isNotCloseTo_int_Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/java8stream/defaultimplementation/SourceTargetMapper.java
{ "start": 529, "end": 1914 }
interface ____ { SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class ); @Mapping(target = "fooListNoSetter", source = "fooStream") Target sourceToTarget(Source source); TargetFoo sourceFooToTargetFoo(SourceFoo sourceFoo); List<TargetFoo> streamToList(Stream<SourceFoo> foos); Set<TargetFoo> streamToSet(Stream<SourceFoo> foos); Collection<TargetFoo> streamToCollection(Stream<SourceFoo> foos); Iterable<TargetFoo> streamToIterable(Stream<SourceFoo> foos); void sourceFoosToTargetFoosUsingTargetParameter(@MappingTarget List<TargetFoo> targetFoos, Stream<SourceFoo> sourceFoos); Iterable<TargetFoo> sourceFoosToTargetFoosUsingTargetParameterAndReturn(Stream<SourceFoo> sourceFoos, @MappingTarget List<TargetFoo> targetFoos); SortedSet<TargetFoo> streamToSortedSet(Stream<SourceFoo> foos); NavigableSet<TargetFoo> streamToNavigableSet(Stream<SourceFoo> foos); void streamToArrayUsingTargetParameter(@MappingTarget TargetFoo[] targetFoos, Stream<SourceFoo> sourceFoo); TargetFoo[] streamToArrayUsingTargetParameterAndReturn(Stream<SourceFoo> sourceFoos, @MappingTarget TargetFoo[] targetFoos); }
SourceTargetMapper
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/impl/converter/CoreTypeConverterRegistry.java
{ "start": 2112, "end": 2726 }
class ____ extends ServiceSupport implements TypeConverter, TypeConverterRegistry { protected static final TypeConverter MISS_CONVERTER = new TypeConverterSupport() { @Override public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException { return (T) MISS_VALUE; } }; private static final Logger LOG = LoggerFactory.getLogger(CoreTypeConverterRegistry.class); // fallback converters protected final List<FallbackTypeConverter> fallbackConverters = new CopyOnWriteArrayList<>(); // special
CoreTypeConverterRegistry
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/MaxInExpressionParameterPaddingTest.java
{ "start": 7231, "end": 7422 }
class ____ extends H2Dialect { public MaxCountInExpressionH2Dialect() { } @Override public int getInExpressionCountLimit() { return MAX_COUNT; } } }
MaxCountInExpressionH2Dialect
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/internal/util/NullnessHelper.java
{ "start": 314, "end": 3316 }
class ____ { private NullnessHelper() { } public static <T> T nullif(T test, T fallback) { return coalesce( test, fallback ); } public static <T> T nullif(T test, Supplier<T> fallbackSupplier) { return test != null ? test : fallbackSupplier.get(); } /** * Operates like SQL coalesce expression, returning the first non-empty value * * @implNote This impl treats empty strings (`""`) as null. * * @param values The list of values. * @param <T> Generic type of values to coalesce * * @return The first non-empty value, or null if all values were empty */ @SafeVarargs public static <T> T coalesce(T... values) { if ( values == null ) { return null; } for ( T value : values ) { if ( value != null ) { if ( value instanceof String string) { if ( isNotEmpty( string ) ) { return value; } } else { return value; } } } return null; } /** * Operates like SQL coalesce expression, returning the first non-empty value * * @implNote This impl treats empty strings (`""`) as null. * * @param valueSuppliers List of value Suppliers * @param <T> Generic type of values to coalesce * * @return The first non-empty value, or null if all values were empty */ @SafeVarargs public static <T> T coalesceSuppliedValues(Supplier<T>... valueSuppliers) { return coalesceSuppliedValues( (value) -> value instanceof String string && isNotEmpty( string ) || value != null, valueSuppliers ); } /** * Operates like SQL coalesce expression, returning the first non-empty value * * @implNote This impl treats empty strings (`""`) as null. * * @param valueSuppliers List of value Suppliers * @param <T> Generic type of values to coalesce * * @return The first non-empty value, or null if all values were empty */ @SafeVarargs public static <T> T coalesceSuppliedValues(Function<T,Boolean> checker, Supplier<T>... valueSuppliers) { if ( valueSuppliers == null ) { return null; } for ( Supplier<T> valueSupplier : valueSuppliers ) { if ( valueSupplier != null ) { final T value = valueSupplier.get(); if ( checker.apply( value ) ) { return value; } } } return null; } /** * Ensures that either:<ul> * <li>all values are null</li> * <li>all values are non-null</li> * </ul> */ public static boolean areSameNullness(Object... values) { if ( values == null || values.length > 2 ) { // we have no elements or 1 return true; } final boolean firstValueIsNull = values[0] == null; for ( int i = 1; i < values.length; i++ ) { // look for mismatch if ( firstValueIsNull != (values[i] == null) ) { return false; } } return true; } public static boolean areAllNonNull(Object... objects) { if ( objects == null || objects.length == 0 ) { return true; } for ( int i = 0; i < objects.length; i++ ) { if ( objects[i] == null ) { return false; } } return true; } }
NullnessHelper
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/context/AuthorizationServerContext.java
{ "start": 1021, "end": 2403 }
interface ____ { /** * Returns {@link AuthorizationServerSettings#getIssuer()} if available, otherwise, * resolves the issuer identifier from the <i>"current"</i> request. * * <p> * The issuer identifier may contain a path component to support * {@link AuthorizationServerSettings#isMultipleIssuersAllowed() multiple issuers per * host} in a multi-tenant hosting configuration. * * <p> * For example: * <ul> * <li>{@code https://example.com/issuer1/oauth2/token} &mdash; resolves the issuer to * {@code https://example.com/issuer1}</li> * <li>{@code https://example.com/issuer2/oauth2/token} &mdash; resolves the issuer to * {@code https://example.com/issuer2}</li> * <li>{@code https://example.com/authz/issuer1/oauth2/token} &mdash; resolves the * issuer to {@code https://example.com/authz/issuer1}</li> * <li>{@code https://example.com/authz/issuer2/oauth2/token} &mdash; resolves the * issuer to {@code https://example.com/authz/issuer2}</li> * </ul> * @return {@link AuthorizationServerSettings#getIssuer()} if available, otherwise, * resolves the issuer identifier from the <i>"current"</i> request */ String getIssuer(); /** * Returns the {@link AuthorizationServerSettings}. * @return the {@link AuthorizationServerSettings} */ AuthorizationServerSettings getAuthorizationServerSettings(); }
AuthorizationServerContext
java
apache__camel
components/camel-google/camel-google-bigquery/src/main/java/org/apache/camel/component/google/bigquery/GoogleBigQueryEndpoint.java
{ "start": 2439, "end": 4592 }
class ____ extends DefaultEndpoint implements EndpointServiceLocation { @UriParam protected final GoogleBigQueryConfiguration configuration; private BigQuery bigQuery; protected GoogleBigQueryEndpoint(String endpointUri, GoogleBigQueryComponent component, GoogleBigQueryConfiguration configuration) { super(endpointUri, component); this.configuration = configuration; } @Override public Producer createProducer() throws Exception { return new GoogleBigQueryProducer(bigQuery, this, configuration); } @Override protected void doStart() throws Exception { super.doStart(); GoogleBigQueryConnectionFactory connFactory = configuration.getConnectionFactory(); if (connFactory == null) { connFactory = new GoogleBigQueryConnectionFactory() .setCamelContext(getCamelContext()) .setServiceAccountKeyFile(configuration.getServiceAccountKey()); configuration.setConnectionFactory(connFactory); } bigQuery = connFactory.getDefaultClient(); } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("Cannot consume from the BigQuery endpoint: " + getEndpointUri()); } public GoogleBigQueryConfiguration getConfiguration() { return configuration; } @Override public GoogleBigQueryComponent getComponent() { return (GoogleBigQueryComponent) super.getComponent(); } @Override public String getServiceUrl() { if (ObjectHelper.isNotEmpty(configuration.getProjectId()) && ObjectHelper.isNotEmpty(configuration.getDatasetId()) && ObjectHelper.isNotEmpty(configuration.getTableId())) { return getServiceProtocol() + ":" + configuration.getProjectId() + ":" + configuration.getDatasetId() + ":" + configuration.getTableId(); } return null; } @Override public String getServiceProtocol() { return "big-query"; } }
GoogleBigQueryEndpoint
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/log/LoggerTest.java
{ "start": 937, "end": 3252 }
class ____ extends ClassLoader { private ClassLoader loader; private Set<String> definedSet = new HashSet<String>(); public TestLoader() { super(null); loader = DruidDriver.class.getClassLoader(); } public URL getResource(String name) { return loader.getResource(name); } public Enumeration<URL> getResources(String name) throws IOException { return loader.getResources(name); } public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith("java")) { return loader.loadClass(name); } if (definedSet.contains(name)) { return super.loadClass(name); } String resourceName = name.replace('.', '/') + ".class"; InputStream is = loader.getResourceAsStream(resourceName); if (is == null) { throw new ClassNotFoundException(); } try { byte[] bytes = Utils.readByteArray(is); this.defineClass(name, bytes, 0, bytes.length, DOMAIN); definedSet.add(name); } catch (IOException e) { throw new ClassNotFoundException(e.getMessage(), e); } try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Class<?> clazz = super.loadClass(name); return clazz; } } public void test_log() throws Exception { TestLoader classLoader = new TestLoader(); Thread.currentThread().setContextClassLoader(classLoader); dataSource = new DruidDataSource(); dataSource.setFilters("log"); dataSource.setUrl("jdbc:mock:xx"); Connection conn = dataSource.getConnection(); conn.close(); } @Override protected void setUp() throws Exception { contextClassLoader = Thread.currentThread().getContextClassLoader(); } @Override protected void tearDown() throws Exception { Thread.currentThread().setContextClassLoader(contextClassLoader); JdbcUtils.close(dataSource); } }
TestLoader
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/delayedOperation/BagDelayedOperationNoCascadeTest.java
{ "start": 6275, "end": 7258 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false) private String name; @ManyToOne private Parent parent; public Child() { } public Child(String name) { this.name = name; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } @Override public String toString() { return "Child{" + "id=" + id + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Child child = (Child) o; return name.equals( child.name ); } @Override public int hashCode() { return name.hashCode(); } } }
Child
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/assertion/RecursiveAssertionAssert_withMapPolicy_Test.java
{ "start": 1205, "end": 2811 }
class ____ { @Test void should_use_given_MapAssertionPolicy() { // GIVEN Object object = "foo"; RecursiveAssertionConfiguration.MapAssertionPolicy mapAssertionPolicy = MAP_OBJECT_ONLY; // WHEN RecursiveAssertionAssert recursiveAssertionAssert = assertThat(object).usingRecursiveAssertion() .withMapAssertionPolicy(mapAssertionPolicy); // THEN RecursiveAssertionConfiguration expectedConfig = RecursiveAssertionConfiguration.builder() .withMapAssertionPolicy(mapAssertionPolicy) .build(); then(recursiveAssertionAssert).hasFieldOrPropertyWithValue("recursiveAssertionConfiguration", expectedConfig); } @Test void should_use_given_MAP_VALUES_ONLY_MapAssertionPolicy_by_default() { // GIVEN Object object = "foo"; // WHEN RecursiveAssertionAssert recursiveAssertionAssert = assertThat(object).usingRecursiveAssertion(); // THEN RecursiveAssertionConfiguration expectedConfig = RecursiveAssertionConfiguration.builder() .withMapAssertionPolicy(MAP_VALUES_ONLY) .build(); then(recursiveAssertionAssert).hasFieldOrPropertyWithValue("recursiveAssertionConfiguration", expectedConfig); } }
RecursiveAssertionAssert_withMapPolicy_Test
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringFunction.java
{ "start": 1310, "end": 3026 }
class ____ extends UnaryScalarFunction { protected UnaryStringFunction(Source source, Expression field) { super(source, field); } @Override public boolean foldable() { return field().foldable(); } @Override public Object fold() { return operation().apply(field().fold()); } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } return isStringAndExact(field(), sourceText(), DEFAULT); } @Override protected Processor makeProcessor() { return new StringProcessor(operation()); } protected abstract StringOperation operation(); @Override public ScriptTemplate scriptWithField(FieldAttribute field) { // TODO change this to use _source instead of the exact form (aka field.keyword for text fields) return new ScriptTemplate( processScript(Scripts.DOC_VALUE), paramsBuilder().variable(field.exactAttribute().name()).build(), dataType() ); } @Override public String processScript(String template) { return formatTemplate(format(Locale.ROOT, "{sql}.%s(%s)", StringUtils.underscoreToLowerCamelCase(operation().name()), template)); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } UnaryStringFunction other = (UnaryStringFunction) obj; return Objects.equals(other.field(), field()); } @Override public int hashCode() { return Objects.hash(field()); } }
UnaryStringFunction
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2SettingsReceivedConsumer.java
{ "start": 702, "end": 778 }
interface ____ consume remote settings received but not yet ACKed. */ public
to
java
apache__camel
components/camel-kubernetes/src/generated/java/org/apache/camel/component/kubernetes/namespaces/KubernetesNamespacesEndpointUriFactory.java
{ "start": 531, "end": 3826 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":masterUrl"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(34); props.add("apiVersion"); props.add("bridgeErrorHandler"); props.add("caCertData"); props.add("caCertFile"); props.add("clientCertData"); props.add("clientCertFile"); props.add("clientKeyAlgo"); props.add("clientKeyData"); props.add("clientKeyFile"); props.add("clientKeyPassphrase"); props.add("connectionTimeout"); props.add("crdGroup"); props.add("crdName"); props.add("crdPlural"); props.add("crdScope"); props.add("crdVersion"); props.add("dnsDomain"); props.add("exceptionHandler"); props.add("exchangePattern"); props.add("kubernetesClient"); props.add("labelKey"); props.add("labelValue"); props.add("lazyStartProducer"); props.add("masterUrl"); props.add("namespace"); props.add("oauthToken"); props.add("operation"); props.add("password"); props.add("poolSize"); props.add("portName"); props.add("portProtocol"); props.add("resourceName"); props.add("trustCerts"); props.add("username"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(12); secretProps.add("caCertData"); secretProps.add("caCertFile"); secretProps.add("clientCertData"); secretProps.add("clientCertFile"); secretProps.add("clientKeyAlgo"); secretProps.add("clientKeyData"); secretProps.add("clientKeyFile"); secretProps.add("clientKeyPassphrase"); secretProps.add("oauthToken"); secretProps.add("password"); secretProps.add("trustCerts"); secretProps.add("username"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "kubernetes-namespaces".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "masterUrl", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
KubernetesNamespacesEndpointUriFactory
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/expressions/aggregate/Count.java
{ "start": 1175, "end": 1622 }
class ____ extends ExpressionWithToString implements AggregateFunc { private final Expression input; private final boolean isDistinct; public Count(Expression column, boolean isDistinct) { this.input = column; this.isDistinct = isDistinct; } public Expression column() { return input; } public boolean isDistinct() { return isDistinct; } @Override public Expression[] children() { return new Expression[]{ input }; } }
Count
java
netty__netty
codec-compression/src/main/java/io/netty/handler/codec/compression/LzfEncoder.java
{ "start": 1405, "end": 11179 }
class ____ extends MessageToByteEncoder<ByteBuf> { /** * Minimum block size ready for compression. Blocks with length * less than {@link #MIN_BLOCK_TO_COMPRESS} will write as uncompressed. */ private static final int MIN_BLOCK_TO_COMPRESS = 16; private static final boolean DEFAULT_SAFE = !PlatformDependent.hasUnsafe(); /** * Compress threshold for LZF format. When the amount of input data is less than compressThreshold, * we will construct an uncompressed output according to the LZF format. * <p> * When the value is less than {@see ChunkEncoder#MIN_BLOCK_TO_COMPRESS}, since LZF will not compress data * that is less than {@see ChunkEncoder#MIN_BLOCK_TO_COMPRESS}, compressThreshold will not work. */ private final int compressThreshold; /** * Underlying decoder in use. */ private final ChunkEncoder encoder; /** * Object that handles details of buffer recycling. */ private final BufferRecycler recycler; /** * Creates a new LZF encoder with the most optimal available methods for underlying data access. * It will "unsafe" instance if one can be used on current JVM. * It should be safe to call this constructor as implementations are dynamically loaded; however, on some * non-standard platforms it may be necessary to use {@link #LzfEncoder(boolean)} with {@code true} param. */ public LzfEncoder() { this(DEFAULT_SAFE); } /** * Creates a new LZF encoder with specified encoding instance. * * @param safeInstance If {@code true} encoder will use {@link ChunkEncoder} that only uses * standard JDK access methods, and should work on all Java platforms and JVMs. * Otherwise encoder will try to use highly optimized {@link ChunkEncoder} * implementation that uses Sun JDK's {@link sun.misc.Unsafe} * class (which may be included by other JDK's as well). * @deprecated Use the constructor without the {@code safeInstance} parameter. */ @Deprecated public LzfEncoder(boolean safeInstance) { this(safeInstance, MAX_CHUNK_LEN); } /** * Creates a new LZF encoder with specified encoding instance and compressThreshold. * * @param safeInstance If {@code true} encoder will use {@link ChunkEncoder} that only uses standard * JDK access methods, and should work on all Java platforms and JVMs. * Otherwise encoder will try to use highly optimized {@link ChunkEncoder} * implementation that uses Sun JDK's {@link sun.misc.Unsafe} * class (which may be included by other JDK's as well). * @param totalLength Expected total length of content to compress; only matters for outgoing messages * that is smaller than maximum chunk size (64k), to optimize encoding hash tables. * @deprecated Use the constructor without the {@code safeInstance} parameter. */ @Deprecated public LzfEncoder(boolean safeInstance, int totalLength) { this(safeInstance, totalLength, MIN_BLOCK_TO_COMPRESS); } /** * Creates a new LZF encoder with specified total length of encoded chunk. You can configure it to encode * your data flow more efficient if you know the average size of messages that you send. * * @param totalLength Expected total length of content to compress; * only matters for outgoing messages that is smaller than maximum chunk size (64k), * to optimize encoding hash tables. */ public LzfEncoder(int totalLength) { this(DEFAULT_SAFE, totalLength); } /** * Creates a new LZF encoder with specified settings. * * @param totalLength Expected total length of content to compress; only matters for outgoing messages * that is smaller than maximum chunk size (64k), to optimize encoding hash tables. * @param compressThreshold Compress threshold for LZF format. When the amount of input data is less than * compressThreshold, we will construct an uncompressed output according * to the LZF format. */ public LzfEncoder(int totalLength, int compressThreshold) { this(DEFAULT_SAFE, totalLength, compressThreshold); } /** * Creates a new LZF encoder with specified settings. * * @param safeInstance If {@code true} encoder will use {@link ChunkEncoder} that only uses standard JDK * access methods, and should work on all Java platforms and JVMs. * Otherwise encoder will try to use highly optimized {@link ChunkEncoder} * implementation that uses Sun JDK's {@link sun.misc.Unsafe} * class (which may be included by other JDK's as well). * @param totalLength Expected total length of content to compress; only matters for outgoing messages * that is smaller than maximum chunk size (64k), to optimize encoding hash tables. * @param compressThreshold Compress threshold for LZF format. When the amount of input data is less than * compressThreshold, we will construct an uncompressed output according * to the LZF format. * @deprecated Use the constructor without the {@code safeInstance} parameter. */ @Deprecated public LzfEncoder(boolean safeInstance, int totalLength, int compressThreshold) { super(ByteBuf.class, false); if (totalLength < MIN_BLOCK_TO_COMPRESS || totalLength > MAX_CHUNK_LEN) { throw new IllegalArgumentException("totalLength: " + totalLength + " (expected: " + MIN_BLOCK_TO_COMPRESS + '-' + MAX_CHUNK_LEN + ')'); } if (compressThreshold < MIN_BLOCK_TO_COMPRESS) { // not a suitable value. throw new IllegalArgumentException("compressThreshold:" + compressThreshold + " expected >=" + MIN_BLOCK_TO_COMPRESS); } this.compressThreshold = compressThreshold; this.encoder = safeInstance ? ChunkEncoderFactory.safeNonAllocatingInstance(totalLength) : ChunkEncoderFactory.optimalNonAllocatingInstance(totalLength); this.recycler = BufferRecycler.instance(); } @Override protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception { final int length = in.readableBytes(); final int idx = in.readerIndex(); final byte[] input; final int inputPtr; if (in.hasArray()) { input = in.array(); inputPtr = in.arrayOffset() + idx; } else { input = recycler.allocInputBuffer(length); in.getBytes(idx, input, 0, length); inputPtr = 0; } // Estimate may apparently under-count by one in some cases. final int maxOutputLength = LZFEncoder.estimateMaxWorkspaceSize(length) + 1; out.ensureWritable(maxOutputLength); final byte[] output; final int outputPtr; if (out.hasArray()) { output = out.array(); outputPtr = out.arrayOffset() + out.writerIndex(); } else { output = new byte[maxOutputLength]; outputPtr = 0; } final int outputLength; if (length >= compressThreshold) { // compress. outputLength = encodeCompress(input, inputPtr, length, output, outputPtr); } else { // not compress. outputLength = encodeNonCompress(input, inputPtr, length, output, outputPtr); } if (out.hasArray()) { out.writerIndex(out.writerIndex() + outputLength); } else { out.writeBytes(output, 0, outputLength); } in.skipBytes(length); if (!in.hasArray()) { recycler.releaseInputBuffer(input); } } private int encodeCompress(byte[] input, int inputPtr, int length, byte[] output, int outputPtr) { return LZFEncoder.appendEncoded(encoder, input, inputPtr, length, output, outputPtr) - outputPtr; } private static int lzfEncodeNonCompress(byte[] input, int inputPtr, int length, byte[] output, int outputPtr) { int left = length; int chunkLen = Math.min(LZFChunk.MAX_CHUNK_LEN, left); outputPtr = LZFChunk.appendNonCompressed(input, inputPtr, chunkLen, output, outputPtr); left -= chunkLen; if (left < 1) { return outputPtr; } inputPtr += chunkLen; do { chunkLen = Math.min(left, LZFChunk.MAX_CHUNK_LEN); outputPtr = LZFChunk.appendNonCompressed(input, inputPtr, chunkLen, output, outputPtr); inputPtr += chunkLen; left -= chunkLen; } while (left > 0); return outputPtr; } /** * Use lzf uncompressed format to encode a piece of input. */ private static int encodeNonCompress(byte[] input, int inputPtr, int length, byte[] output, int outputPtr) { return lzfEncodeNonCompress(input, inputPtr, length, output, outputPtr) - outputPtr; } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { encoder.close(); super.handlerRemoved(ctx); } }
LzfEncoder
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/cluster/topology/TopologyRefreshIntegrationTests.java
{ "start": 1772, "end": 12147 }
class ____ extends TestSupport { private static final String host = TestSettings.hostAddr(); private final RedisClient client; private RedisClusterClient clusterClient; private RedisCommands<String, String> redis1; private RedisCommands<String, String> redis2; @Inject TopologyRefreshIntegrationTests(RedisClient client) { this.client = client; } @BeforeEach void openConnection() { clusterClient = RedisClusterClient.create(client.getResources(), RedisURI.Builder.redis(host, ClusterTestSettings.port1).build()); redis1 = client.connect(RedisURI.Builder.redis(ClusterTestSettings.host, ClusterTestSettings.port1).build()).sync(); redis2 = client.connect(RedisURI.Builder.redis(ClusterTestSettings.host, ClusterTestSettings.port2).build()).sync(); } @AfterEach void closeConnection() { redis1.getStatefulConnection().close(); redis2.getStatefulConnection().close(); FastShutdown.shutdown(clusterClient); } @Test void changeTopologyWhileOperations() { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() .enablePeriodicRefresh(true)// .refreshPeriod(1, TimeUnit.SECONDS)// .build(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async(); clusterClient.getPartitions().clear(); Wait.untilTrue(() -> { return !clusterClient.getPartitions().isEmpty(); }).waitOrTimeout(); clusterConnection.getStatefulConnection().close(); } @Test void dynamicSourcesProvidesClientCountForAllNodes() { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.create(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async(); for (RedisClusterNode redisClusterNode : clusterClient.getPartitions()) { assertThat(redisClusterNode).isInstanceOf(RedisClusterNodeSnapshot.class); RedisClusterNodeSnapshot snapshot = (RedisClusterNodeSnapshot) redisClusterNode; assertThat(snapshot.getConnectedClients()).isNotNull().isGreaterThanOrEqualTo(0); } clusterConnection.getStatefulConnection().close(); } @Test void staticSourcesProvidesClientCountForSeedNodes() { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() .dynamicRefreshSources(false).build(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async(); Partitions partitions = clusterClient.getPartitions(); RedisClusterNodeSnapshot node1 = (RedisClusterNodeSnapshot) partitions.getPartitionBySlot(0); assertThat(node1.getConnectedClients()).isGreaterThanOrEqualTo(1); RedisClusterNodeSnapshot node2 = (RedisClusterNodeSnapshot) partitions.getPartitionBySlot(15000); assertThat(node2.getConnectedClients()).isNull(); clusterConnection.getStatefulConnection().close(); } @Test void adaptiveTopologyUpdateOnDisconnectNodeIdConnection() { runReconnectTest((clusterConnection, node) -> { RedisClusterAsyncCommands<String, String> connection = clusterConnection.getConnection(node.getUri().getHost(), node.getUri().getPort()); return connection; }); } @Test void adaptiveTopologyUpdateOnDisconnectHostAndPortConnection() { runReconnectTest((clusterConnection, node) -> { RedisClusterAsyncCommands<String, String> connection = clusterConnection.getConnection(node.getUri().getHost(), node.getUri().getPort()); return connection; }); } @Test void adaptiveTopologyUpdateOnDisconnectDefaultConnection() { runReconnectTest((clusterConnection, node) -> { return clusterConnection; }); } @Test void adaptiveTopologyUpdateIsRateLimited() { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()// .adaptiveRefreshTriggersTimeout(1, TimeUnit.HOURS)// .refreshTriggersReconnectAttempts(0)// .enableAllAdaptiveRefreshTriggers()// .build(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async(); clusterClient.getPartitions().clear(); clusterConnection.quit(); Wait.untilTrue(() -> { return !clusterClient.getPartitions().isEmpty(); }).waitOrTimeout(); clusterClient.getPartitions().clear(); clusterConnection.quit(); Delay.delay(Duration.ofMillis(200)); assertThat(clusterClient.getPartitions()).isEmpty(); clusterConnection.getStatefulConnection().close(); } @Test void adaptiveTopologyUpdateUsesTimeout() { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()// .adaptiveRefreshTriggersTimeout(500, TimeUnit.MILLISECONDS)// .refreshTriggersReconnectAttempts(0)// .enableAllAdaptiveRefreshTriggers()// .build(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async(); clusterConnection.quit(); Delay.delay(Duration.ofMillis(700)); Wait.untilTrue(() -> { return !clusterClient.getPartitions().isEmpty(); }).waitOrTimeout(); clusterClient.getPartitions().clear(); clusterConnection.quit(); Wait.untilTrue(() -> { return !clusterClient.getPartitions().isEmpty(); }).waitOrTimeout(); clusterConnection.getStatefulConnection().close(); } @Test void adaptiveTriggerDoesNotFireOnSingleReconnect() { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()// .enableAllAdaptiveRefreshTriggers()// .build(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async(); clusterClient.getPartitions().clear(); clusterConnection.quit(); Delay.delay(Duration.ofMillis(500)); assertThat(clusterClient.getPartitions()).isEmpty(); clusterConnection.getStatefulConnection().close(); } @Test void adaptiveTriggerOnMoveRedirection() { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()// .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT)// .build(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); StatefulRedisClusterConnection<String, String> connection = clusterClient.connect(); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = connection.async(); Partitions partitions = connection.getPartitions(); RedisClusterNode node1 = partitions.getPartitionBySlot(0); RedisClusterNode node2 = partitions.getPartitionBySlot(12000); List<Integer> slots = node2.getSlots(); slots.addAll(node1.getSlots()); node2.setSlots(slots); node1.setSlots(Collections.emptyList()); partitions.updateCache(); assertThat(clusterClient.getPartitions().getPartitionByNodeId(node1.getNodeId()).getSlots()).hasSize(0); assertThat(clusterClient.getPartitions().getPartitionByNodeId(node2.getNodeId()).getSlots()).hasSize(16384); connection.reactive().set("b", value).toFuture();// slot 3300 Wait.untilEquals(12000, () -> clusterClient.getPartitions().getPartitionByNodeId(node1.getNodeId()).getSlots().size()) .waitOrTimeout(); assertThat(clusterClient.getPartitions().getPartitionByNodeId(node1.getNodeId()).getSlots()).hasSize(12000); assertThat(clusterClient.getPartitions().getPartitionByNodeId(node2.getNodeId()).getSlots()).hasSize(4384); clusterConnection.getStatefulConnection().close(); } private void runReconnectTest( BiFunction<RedisAdvancedClusterAsyncCommands<String, String>, RedisClusterNode, BaseRedisAsyncCommands> function) { ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()// .refreshTriggersReconnectAttempts(0)// .enableAllAdaptiveRefreshTriggers()// .build(); clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async(); RedisClusterNode node = clusterClient.getPartitions().getPartition(0); BaseRedisAsyncCommands closeable = function.apply(clusterConnection, node); clusterClient.getPartitions().clear(); closeable.quit(); Wait.untilTrue(() -> { return !clusterClient.getPartitions().isEmpty(); }).waitOrTimeout(); if (closeable instanceof RedisAdvancedClusterCommands) { ((RedisAdvancedClusterCommands) closeable).getStatefulConnection().close(); } clusterConnection.getStatefulConnection().close(); } }
TopologyRefreshIntegrationTests
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/runtime/src/main/java/io/quarkus/restclient/runtime/QuarkusProxyInvocationHandler.java
{ "start": 2030, "end": 11120 }
class ____ implements InvocationHandler { private static final Logger LOGGER = Logger.getLogger(QuarkusProxyInvocationHandler.class); public static final Type[] NO_TYPES = {}; private final Object target; private final Set<Object> providerInstances; private final Map<Method, List<QuarkusInvocationContextImpl.InterceptorInvocation>> interceptorChains; private final Map<Method, Set<Annotation>> interceptorBindingsMap; private final ResteasyClient client; private final CreationalContext<?> creationalContext; private final AtomicBoolean closed; public QuarkusProxyInvocationHandler(final Class<?> restClientInterface, final Object target, final Set<Object> providerInstances, final ResteasyClient client, final BeanManager beanManager) { this.target = target; this.providerInstances = providerInstances; this.client = client; this.closed = new AtomicBoolean(); if (beanManager != null) { this.creationalContext = beanManager.createCreationalContext(null); this.interceptorBindingsMap = new HashMap<>(); this.interceptorChains = initInterceptorChains(beanManager, creationalContext, restClientInterface, interceptorBindingsMap); } else { this.creationalContext = null; this.interceptorChains = Collections.emptyMap(); this.interceptorBindingsMap = Collections.emptyMap(); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (RestClientProxy.class.equals(method.getDeclaringClass())) { return invokeRestClientProxyMethod(method); } // Autocloseable/Closeable if (method.getName().equals("close") && (args == null || args.length == 0)) { close(); return null; } // Check if this proxy is closed or the client itself is closed. The client may be closed if this proxy was a // sub-resource and the resource client itself was closed. if (closed.get() || client.isClosed()) { closed.set(true); throw new IllegalStateException("RestClientProxy is closed"); } boolean replacementNeeded = false; Object[] argsReplacement = args != null ? new Object[args.length] : null; Annotation[][] parameterAnnotations = method.getParameterAnnotations(); if (args != null) { for (Object p : providerInstances) { if (p instanceof ParamConverterProvider) { int index = 0; for (Object arg : args) { // ParamConverter's are not allowed to be passed null values. If we have a null value do not process // it through the provider. if (arg == null) { continue; } if (parameterAnnotations[index].length > 0) { // does a parameter converter apply? ParamConverter<?> converter = ((ParamConverterProvider) p).getConverter(arg.getClass(), null, parameterAnnotations[index]); if (converter != null) { Type[] genericTypes = getGenericTypes(converter.getClass()); if (genericTypes.length == 1) { // minimum supported types switch (genericTypes[0].getTypeName()) { case "java.lang.String": @SuppressWarnings("unchecked") ParamConverter<String> stringConverter = (ParamConverter<String>) converter; argsReplacement[index] = stringConverter.toString((String) arg); replacementNeeded = true; break; case "java.lang.Integer": @SuppressWarnings("unchecked") ParamConverter<Integer> intConverter = (ParamConverter<Integer>) converter; argsReplacement[index] = intConverter.toString((Integer) arg); replacementNeeded = true; break; case "java.lang.Boolean": @SuppressWarnings("unchecked") ParamConverter<Boolean> boolConverter = (ParamConverter<Boolean>) converter; argsReplacement[index] = boolConverter.toString((Boolean) arg); replacementNeeded = true; break; default: continue; } } } } else { argsReplacement[index] = arg; } index++; } } } } if (replacementNeeded) { args = argsReplacement; } List<QuarkusInvocationContextImpl.InterceptorInvocation> chain = interceptorChains.get(method); if (chain != null) { // Invoke business method interceptors return new QuarkusInvocationContextImpl(target, method, args, chain, interceptorBindingsMap.get(method)).proceed(); } else { try { final Object result = method.invoke(target, args); final Class<?> returnType = method.getReturnType(); // Check if this is a sub-resource. A sub-resource must be an interface. if (returnType.isInterface()) { final Annotation[] annotations = method.getDeclaredAnnotations(); boolean hasPath = false; boolean hasHttpMethod = false; // Check the annotations. If the method has one of the @HttpMethod annotations, we will just use the // current method. If it only has a @Path, then we need to create a proxy for the return type. for (Annotation annotation : annotations) { final Class<?> type = annotation.annotationType(); if (type.equals(Path.class)) { hasPath = true; } else if (type.getDeclaredAnnotation(HttpMethod.class) != null) { hasHttpMethod = true; } } if (!hasHttpMethod && hasPath) { // Create a proxy of the return type re-using the providers and client, but do not add the required // interfaces for the sub-resource. return createProxy(returnType, result, false, providerInstances, client); } } return result; } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof CompletionException) { cause = cause.getCause(); } if (cause instanceof ExceptionMapping.HandlerException) { ((ExceptionMapping.HandlerException) cause).mapException(method); // no applicable exception mapper found or applicable mapper returned null return null; } if (cause instanceof ResponseProcessingException) { ResponseProcessingException rpe = (ResponseProcessingException) cause; cause = rpe.getCause(); if (cause instanceof RuntimeException) { throw cause; } } else { if (cause instanceof ProcessingException && cause.getCause() instanceof ClientHeaderFillingException) { throw cause.getCause().getCause(); } if (cause instanceof RuntimeException) { throw cause; } } throw e; } } } /** * Creates a proxy for the interface. * <p> * If {@code addExtendedInterfaces} is set to {@code true}, the proxy will implement the interfaces * {@link RestClientProxy} and {@link Closeable}. * </p> * * @param resourceInterface the resource
QuarkusProxyInvocationHandler
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 50051, "end": 50343 }
class ____ { public abstract String notNullable(); @Nullable public abstract String nullable(); public static Builder builder() { return new AutoValue_AutoValueTest_NullablePropertyWithBuilder.Builder(); } @AutoValue.Builder public
NullablePropertyWithBuilder
java
quarkusio__quarkus
core/builder/src/main/java/io/quarkus/builder/Json.java
{ "start": 8959, "end": 15156 }
class ____ extends JsonBuilder<JsonObjectBuilder> { private final Map<String, Object> properties; private JsonObjectBuilder(boolean ignoreEmptyBuilders, boolean skipEscapeCharacters) { super(ignoreEmptyBuilders, skipEscapeCharacters); this.properties = new HashMap<String, Object>(); } public JsonObjectBuilder put(String name, String value) { putInternal(name, value); return this; } public JsonObjectBuilder put(String name, JsonObjectBuilder value) { putInternal(name, value); return this; } public JsonObjectBuilder put(String name, JsonArrayBuilder value) { putInternal(name, value); return this; } public JsonObjectBuilder put(String name, boolean value) { putInternal(name, value); return this; } JsonObjectBuilder put(String name, int value) { putInternal(name, value); return this; } JsonObjectBuilder put(String name, long value) { putInternal(name, value); return this; } boolean has(String name) { return properties.containsKey(name); } void putInternal(String name, Object value) { Objects.requireNonNull(name); if (value != null) { properties.put(name, value); } } public boolean isEmpty() { if (properties.isEmpty()) { return true; } return isValuesEmpty(properties.values()); } String build() throws IOException { StringBuilder builder = new StringBuilder(); appendTo(builder); return builder.toString(); } @Override public void appendTo(Appendable appendable) throws IOException { appendable.append(OBJECT_START); int idx = 0; for (Entry<String, Object> entry : properties.entrySet()) { if (isIgnored(entry.getValue())) { continue; } if (++idx > 1) { appendable.append(ENTRY_SEPARATOR); } appendStringValue(appendable, entry.getKey(), skipEscapeCharacters); appendable.append(NAME_VAL_SEPARATOR); appendValue(appendable, entry.getValue(), skipEscapeCharacters); } appendable.append(OBJECT_END); } @Override protected JsonObjectBuilder self() { return this; } @Override void add(JsonValue element) { if (element instanceof JsonMember member) { final String attribute = member.attribute().value(); final JsonValue value = member.value(); if (value instanceof JsonString) { put(attribute, ((JsonString) value).value()); } else if (value instanceof JsonInteger) { final long longValue = ((JsonInteger) value).longValue(); final int intValue = (int) longValue; if (longValue == intValue) { put(attribute, intValue); } else { put(attribute, longValue); } } else if (value instanceof JsonBoolean) { final boolean booleanValue = ((JsonBoolean) value).value(); put(attribute, booleanValue); } else if (value instanceof JsonArray) { final JsonArrayBuilder arrayBuilder = Json.array(ignoreEmptyBuilders, skipEscapeCharacters); arrayBuilder.transform((JsonArray) value, transform); put(attribute, arrayBuilder); } else if (value instanceof JsonObject) { final JsonObjectBuilder objectBuilder = Json.object(ignoreEmptyBuilders, skipEscapeCharacters); objectBuilder.transform((JsonObject) value, transform); if (!objectBuilder.isEmpty()) { put(attribute, objectBuilder); } } } } } static void appendValue(Appendable appendable, Object value, boolean skipEscapeCharacters) throws IOException { if (value instanceof JsonObjectBuilder) { appendable.append(((JsonObjectBuilder) value).build()); } else if (value instanceof JsonArrayBuilder) { appendable.append(((JsonArrayBuilder) value).build()); } else if (value instanceof String) { appendStringValue(appendable, value.toString(), skipEscapeCharacters); } else if (value instanceof Boolean || value instanceof Integer || value instanceof Long) { appendable.append(value.toString()); } else { throw new IllegalStateException("Unsupported value type: " + value); } } static void appendStringValue(Appendable appendable, String value, boolean skipEscapeCharacters) throws IOException { appendable.append(CHAR_QUOTATION_MARK); if (skipEscapeCharacters) { appendable.append(value); } else { appendable.append(escape(value)); } appendable.append(CHAR_QUOTATION_MARK); } /** * Escape quotation mark, reverse solidus and control characters (U+0000 through U+001F). * * @param value * @return escaped value * @see <a href="https://www.ietf.org/rfc/rfc4627.txt">https://www.ietf.org/rfc/rfc4627.txt</a> */ static String escape(String value) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); String replacement = REPLACEMENTS.get(c); if (replacement != null) { builder.append(replacement); } else { builder.append(c); } } return builder.toString(); } private static final
JsonObjectBuilder
java
apache__camel
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ComponentVerifierExtension.java
{ "start": 8789, "end": 11385 }
interface ____ extends Code { /** * Authentication failed */ StandardCode AUTHENTICATION = new StandardErrorCode("AUTHENTICATION"); /** * An exception occurred */ StandardCode EXCEPTION = new StandardErrorCode("EXCEPTION"); /** * Internal error while performing the verification */ StandardCode INTERNAL = new StandardErrorCode("INTERNAL"); /** * A mandatory parameter is missing */ StandardCode MISSING_PARAMETER = new StandardErrorCode("MISSING_PARAMETER"); /** * A given parameter is not known to the component */ StandardCode UNKNOWN_PARAMETER = new StandardErrorCode("UNKNOWN_PARAMETER"); /** * A given parameter is illegal */ StandardCode ILLEGAL_PARAMETER = new StandardErrorCode("ILLEGAL_PARAMETER"); /** * A combination of parameters is illegal. See {@link VerificationError#getParameterKeys()} for the set of * affected parameters */ StandardCode ILLEGAL_PARAMETER_GROUP_COMBINATION = new StandardErrorCode("ILLEGAL_PARAMETER_GROUP_COMBINATION"); /** * A parameter <em>value</em> is not valid */ StandardCode ILLEGAL_PARAMETER_VALUE = new StandardErrorCode("ILLEGAL_PARAMETER_VALUE"); /** * A group of parameters is not complete in order to be valid */ StandardCode INCOMPLETE_PARAMETER_GROUP = new StandardErrorCode("INCOMPLETE_PARAMETER_GROUP"); /** * The verification is not supported */ StandardCode UNSUPPORTED = new StandardErrorCode("UNSUPPORTED"); /** * The requested {@link Scope} is not supported */ StandardCode UNSUPPORTED_SCOPE = new StandardErrorCode("UNSUPPORTED_SCOPE"); /** * The requested Component is not supported */ StandardCode UNSUPPORTED_COMPONENT = new StandardErrorCode("UNSUPPORTED_COMPONENT"); /** * Generic error which is explained in more details with {@link VerificationError#getDetails()} */ StandardCode GENERIC = new StandardErrorCode("GENERIC"); } /** * Interface defining an attribute which is a key for the detailed error messages. */
StandardCode
java
google__dagger
javatests/dagger/android/support/functional/TestActivityWithScope.java
{ "start": 775, "end": 888 }
class ____ extends DaggerAppCompatActivity { @Inject Provider<String> scopedStringProvider; }
TestActivityWithScope
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/model/BaseMessage.java
{ "start": 917, "end": 2594 }
class ____ { /** * Messaging service used for the request. Use "whatsapp". */ @JsonProperty("messaging_product") private String messagingProduct = "whatsapp"; /** * Currently, you can only send messages to individuals. Set this as individual. */ @JsonProperty("recipient_type") private String recipientType = "individual"; /** * WhatsApp ID or phone number for the person you want to send a message to. */ private String to; /** * The type of message you want to send. Default: text Supported Options audio: for audio messages. contacts: for * contact messages. document: for document messages. image: for image messages. interactive: for list and reply * button messages. location: for location messages. sticker: for sticker messages. template: for template messages. * Text and media (images and documents) message templates are supported. text: for text messages. */ private String type = "text"; public BaseMessage() { } public String getMessagingProduct() { return messagingProduct; } public void setMessagingProduct(String messagingProduct) { this.messagingProduct = messagingProduct; } public String getRecipientType() { return recipientType; } public void setRecipientType(String recipientType) { this.recipientType = recipientType; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
BaseMessage
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue_for_oschina_3087749_2215732.java
{ "start": 550, "end": 714 }
class ____ { private List<String> datas = new ArrayList<String>(); public List<String> getDatas() { return datas; } } }
JsonBean
java
netty__netty
resolver-dns/src/main/java/io/netty/resolver/dns/PreferredAddressTypeComparator.java
{ "start": 847, "end": 1934 }
class ____ implements Comparator<InetAddress> { private static final PreferredAddressTypeComparator IPv4 = new PreferredAddressTypeComparator(Inet4Address.class); private static final PreferredAddressTypeComparator IPv6 = new PreferredAddressTypeComparator(Inet6Address.class); static PreferredAddressTypeComparator comparator(SocketProtocolFamily family) { switch (family) { case INET: return IPv4; case INET6: return IPv6; default: throw new IllegalArgumentException(); } } private final Class<? extends InetAddress> preferredAddressType; private PreferredAddressTypeComparator(Class<? extends InetAddress> preferredAddressType) { this.preferredAddressType = preferredAddressType; } @Override public int compare(InetAddress o1, InetAddress o2) { if (o1.getClass() == o2.getClass()) { return 0; } return preferredAddressType.isAssignableFrom(o1.getClass()) ? -1 : 1; } }
PreferredAddressTypeComparator
java
alibaba__druid
core/src/test/java/com/alibaba/druid/benckmark/pool/druid/DruidCase0.java
{ "start": 844, "end": 2357 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setFilters("stat"); dataSource.setMaxActive(8); dataSource.setMinIdle(1); dataSource.setMinEvictableIdleTimeMillis(1000 * 60 * 5); } protected void tearDown() throws Exception { dataSource.close(); } public void test_benchmark() throws Exception { Connection conn = dataSource.getConnection(); conn.close(); for (int i = 0; i < 5; ++i) { long startMillis = System.currentTimeMillis(); benchmark(); long millis = System.currentTimeMillis() - startMillis; System.out.println("millis : " + millis); // 1043 } } public void benchmark() throws Exception { for (int i = 0; i < 1000 * 1000 * 10; ++i) { Connection conn = dataSource.getConnection(); // Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("select 1"); // rs.close(); // stmt.close(); PreparedStatement pstmt = conn.prepareStatement("select 1"); ResultSet rs = pstmt.executeQuery(); // rs.next(); // rs.getInt(1); // rs.getInt(1); rs.close(); pstmt.close(); conn.close(); } } }
DruidCase0
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java
{ "start": 18035, "end": 20896 }
class ____ implements BeanPostProcessor { private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class); private final ConfigurableListableBeanFactory beanFactory; private final String[] postProcessorNames; private final int beanPostProcessorTargetCount; public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, String[] postProcessorNames, int beanPostProcessorTargetCount) { this.beanFactory = beanFactory; this.postProcessorNames = postProcessorNames; this.beanPostProcessorTargetCount = beanPostProcessorTargetCount; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) && this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) { if (logger.isWarnEnabled()) { Set<String> bppsInCreation = new LinkedHashSet<>(2); for (String bppName : this.postProcessorNames) { if (this.beanFactory.isCurrentlyInCreation(bppName)) { bppsInCreation.add(bppName); } } if (bppsInCreation.size() == 1) { String bppName = bppsInCreation.iterator().next(); if (this.beanFactory.containsBeanDefinition(bppName) && beanName.equals(this.beanFactory.getBeanDefinition(bppName).getFactoryBeanName())) { logger.warn("Bean '" + beanName + "' of type [" + bean.getClass().getName() + "] is not eligible for getting processed by all BeanPostProcessors " + "(for example: not eligible for auto-proxying). The currently created " + "BeanPostProcessor " + bppsInCreation + " is declared through a non-static " + "factory method on that class; consider declaring it as static instead."); return bean; } } logger.warn("Bean '" + beanName + "' of type [" + bean.getClass().getName() + "] is not eligible for getting processed by all BeanPostProcessors " + "(for example: not eligible for auto-proxying). Is this bean getting eagerly " + "injected/applied to a currently created BeanPostProcessor " + bppsInCreation + "? " + "Check the corresponding BeanPostProcessor declaration and its dependencies/advisors. " + "If this bean does not have to be post-processed, declare it with ROLE_INFRASTRUCTURE."); } } return bean; } private boolean isInfrastructureBean(@Nullable String beanName) { if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) { BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName); return (bd.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE); } return false; } } private static final
BeanPostProcessorChecker
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/log/LogThrottlingHelper.java
{ "start": 4122, "end": 13321 }
interface ____ { /** * @return Return the number of records encapsulated in this action; that is, the * number of times {@code record} was called to produce this action, * including the current one. */ int getCount(); /** * @return Return summary information for the value that was recorded at index * {@code idx}. Corresponds to the ordering of values passed to * {@link #record(double...)}. * @param idx input idx. */ SummaryStatistics getStats(int idx); /** * @return If this is true, the caller should write to its log. Otherwise, the * caller should take no action, and it is an error to call other methods * on this object. */ boolean shouldLog(); } /** * A {@link LogAction} representing a state that should not yet be logged. * If any attempt is made to extract information from this, it will throw * an {@link IllegalStateException}. */ public static final LogAction DO_NOT_LOG = new NoLogAction(); private static final String DEFAULT_RECORDER_NAME = "__DEFAULT_RECORDER_NAME__"; /** * This throttler will not trigger log statements more frequently than this * period. */ private final long minLogPeriodMs; /** * The name of the recorder treated as the primary; this is the only one which * will trigger logging. Other recorders are dependent on the state of this * recorder. This may be null, in which case a primary has not yet been set. */ private String primaryRecorderName; private final Timer timer; private final Map<String, LoggingAction> currentLogs; private long lastLogTimestampMs = Long.MIN_VALUE; /** * Create a log helper without any primary recorder. * * @see #LogThrottlingHelper(long, String) * @param minLogPeriodMs input minLogPeriodMs. */ public LogThrottlingHelper(long minLogPeriodMs) { this(minLogPeriodMs, null); } /** * Create a log helper with a specified primary recorder name; this can be * used in conjunction with {@link #record(String, long, double...)} to set up * primary and dependent recorders. See * {@link #record(String, long, double...)} for more details. * * @param minLogPeriodMs The minimum period with which to log; do not log * more frequently than this. * @param primaryRecorderName The name of the primary recorder. */ public LogThrottlingHelper(long minLogPeriodMs, String primaryRecorderName) { this(minLogPeriodMs, primaryRecorderName, new Timer()); } @VisibleForTesting LogThrottlingHelper(long minLogPeriodMs, String primaryRecorderName, Timer timer) { this.minLogPeriodMs = minLogPeriodMs; this.primaryRecorderName = primaryRecorderName; this.timer = timer; this.currentLogs = new HashMap<>(); } /** * Record some set of values at the current time into this helper. Note that * this does <i>not</i> actually write information to any log. Instead, this * will return a LogAction indicating whether or not the caller should write * to its own log. The LogAction will additionally contain summary information * about the values specified since the last time the caller was expected to * write to its log. * * <p>Specifying multiple values will maintain separate summary statistics * about each value. For example: * <pre>{@code * helper.record(1, 0); * LogAction action = helper.record(3, 100); * action.getStats(0); // == 2 * action.getStats(1); // == 50 * }</pre> * * @param values The values about which to maintain summary information. Every * time this method is called, the same number of values must * be specified. * @return A LogAction indicating whether or not the caller should write to * its log. */ public synchronized LogAction record(double... values) { return record(DEFAULT_RECORDER_NAME, timer.monotonicNow(), values); } /** * Record some set of values at the specified time into this helper. This can * be useful to avoid fetching the current time twice if the caller has * already done so for other purposes. This additionally allows the caller to * specify a name for this recorder. When multiple names are used, one is * denoted as the primary recorder. Only recorders named as the primary * will trigger logging; other names not matching the primary can <i>only</i> * be triggered by following the primary. This is used to coordinate multiple * logging points. A primary can be set via the * {@link #LogThrottlingHelper(long, String)} constructor. If no primary * is set in the constructor, then the first recorder name used becomes the * primary. * * If multiple names are used, they maintain entirely different sets of values * and summary information. For example: * <pre>{@code * // Initialize "pre" as the primary recorder name * LogThrottlingHelper helper = new LogThrottlingHelper(1000, "pre"); * LogAction preLog = helper.record("pre", Time.monotonicNow()); * if (preLog.shouldLog()) { * // ... * } * double eventsProcessed = ... // perform some action * LogAction postLog = * helper.record("post", Time.monotonicNow(), eventsProcessed); * if (postLog.shouldLog()) { * // ... * // Can use postLog.getStats(0) to access eventsProcessed information * } * }</pre> * Since "pre" is the primary recorder name, logging to "pre" will trigger a * log action if enough time has elapsed. This will indicate that "post" * should log as well. This ensures that "post" is always logged in the same * iteration as "pre", yet each one is able to maintain its own summary * information. * * <p>Other behavior is the same as {@link #record(double...)}. * * @param recorderName The name of the recorder. This is used to check if the * current recorder is the primary. Other names are * arbitrary and are only used to differentiate between * distinct recorders. * @param currentTimeMs The current time. * @param values The values to log. * @return The LogAction for the specified recorder. * * @see #record(double...) */ public synchronized LogAction record(String recorderName, long currentTimeMs, double... values) { if (primaryRecorderName == null) { primaryRecorderName = recorderName; } LoggingAction currentLog = currentLogs.get(recorderName); if (currentLog == null || currentLog.hasLogged()) { currentLog = new LoggingAction(values.length); if (!currentLogs.containsKey(recorderName)) { // Always log newly created loggers currentLog.setShouldLog(); } currentLogs.put(recorderName, currentLog); } currentLog.recordValues(values); if (primaryRecorderName.equals(recorderName) && currentTimeMs - minLogPeriodMs >= lastLogTimestampMs) { lastLogTimestampMs = currentTimeMs; currentLogs.replaceAll((key, log) -> { LoggingAction newLog = log; if (log.hasLogged()) { // create a fresh log since the old one has already been logged newLog = new LoggingAction(log.getValueCount()); } newLog.setShouldLog(); return newLog; }); } if (currentLog.shouldLog()) { currentLog.setHasLogged(); return currentLog; } else { return DO_NOT_LOG; } } /** * Return the summary information for given index. * * @param recorderName The name of the recorder. * @param idx The index value. * @return The summary information. */ public synchronized SummaryStatistics getCurrentStats(String recorderName, int idx) { LoggingAction currentLog = currentLogs.get(recorderName); if (currentLog != null) { return currentLog.getStats(idx); } return null; } /** * Helper function to create a message about how many log statements were * suppressed in the provided log action. If no statements were suppressed, * this returns an empty string. The message has the format (without quotes): * * <p>' (suppressed logging <i>{suppression_count}</i> times)'</p> * * @param action The log action to produce a message about. * @return A message about suppression within this action. */ public static String getLogSupressionMessage(LogAction action) { if (action.getCount() > 1) { return " (suppressed logging " + (action.getCount() - 1) + " times)"; } else { return ""; } } @VisibleForTesting public synchronized void reset() { primaryRecorderName = null; currentLogs.clear(); lastLogTimestampMs = Long.MIN_VALUE; } /** * A standard log action which keeps track of all of the values which have * been logged. This is also used for internal bookkeeping via its private * fields and methods; it will maintain whether or not it is ready to be * logged ({@link #shouldLog()}) as well as whether or not it has been * returned for logging yet ({@link #hasLogged()}). */ private static
LogAction
java
google__dagger
javatests/dagger/functional/membersinject/ChildOfStringArray.java
{ "start": 646, "end": 721 }
class ____ extends MembersInjectGenericParent<String[]> { }
ChildOfStringArray
java
google__guice
core/test/com/google/inject/internal/MultibinderTest.java
{ "start": 36390, "end": 46280 }
class ____ { private final String string; @SuppressWarnings("unused") // Found by reflection public StringGrabber(@Named("A_string") String string) { this.string = string; } @SuppressWarnings("unused") // Found by reflection public StringGrabber(@Named("B_string") String string, int unused) { this.string = string; } @Override public int hashCode() { return string.hashCode(); } @Override public boolean equals(Object obj) { return (obj instanceof StringGrabber) && ((StringGrabber) obj).string.equals(string); } @Override public String toString() { return "StringGrabber(" + string + ")"; } static Set<String> values(Iterable<StringGrabber> grabbers) { Set<String> result = new HashSet<>(); for (StringGrabber grabber : grabbers) { result.add(grabber.string); } return result; } } public void testModuleOverrideRepeatedInstallsAndMultibindings_toConstructor() { TypeLiteral<Set<StringGrabber>> setOfStringGrabber = new TypeLiteral<Set<StringGrabber>>() {}; Module ab = new AbstractModule() { @Override protected void configure() { Key<String> aKey = Key.get(String.class, Names.named("A_string")); Key<String> bKey = Key.get(String.class, Names.named("B_string")); bind(aKey).toInstance("A"); bind(bKey).toInstance("B"); bind(Integer.class).toInstance(0); // used to disambiguate constructors Multibinder<StringGrabber> multibinder = Multibinder.newSetBinder(binder(), StringGrabber.class); try { multibinder .addBinding() .toConstructor(StringGrabber.class.getConstructor(String.class)); multibinder .addBinding() .toConstructor(StringGrabber.class.getConstructor(String.class, int.class)); } catch (NoSuchMethodException e) { fail("No such method: " + e.getMessage()); } } }; // Guice guarantees this assertion, as the same module cannot be installed twice. assertEquals( ImmutableSet.of("A", "B"), StringGrabber.values( Guice.createInjector(ab, ab).getInstance(Key.get(setOfStringGrabber)))); // Guice will only guarantee this assertion if Multibinder ensures the bindings match. Injector injector = Guice.createInjector(ab, Modules.override(ab).with(ab)); assertEquals( ImmutableSet.of("A", "B"), StringGrabber.values(injector.getInstance(Key.get(setOfStringGrabber)))); } /** * Unscoped bindings should not conflict, whether they were bound with no explicit scope, or * explicitly bound in {@link Scopes#NO_SCOPE}. */ public void testDuplicateUnscopedBindings() { Module singleBinding = new AbstractModule() { @Override protected void configure() { bind(Integer.class).to(Key.get(Integer.class, named("A"))); bind(Integer.class).to(Key.get(Integer.class, named("A"))).in(Scopes.NO_SCOPE); } @Provides @Named("A") int provideInteger() { return 5; } }; Module multibinding = new AbstractModule() { @Override protected void configure() { Multibinder<Integer> multibinder = Multibinder.newSetBinder(binder(), Integer.class); multibinder.addBinding().to(Key.get(Integer.class, named("A"))); multibinder.addBinding().to(Key.get(Integer.class, named("A"))).in(Scopes.NO_SCOPE); } }; assertEquals(5, (int) Guice.createInjector(singleBinding).getInstance(Integer.class)); assertEquals( ImmutableSet.of(5), Guice.createInjector(singleBinding, multibinding).getInstance(Key.get(setOfInteger))); } /** Ensure key hash codes are fixed at injection time, not binding time. */ public void testKeyHashCodesFixedAtInjectionTime() { Module ab = new AbstractModule() { @Override protected void configure() { Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings); List<String> list = Lists.newArrayList(); multibinder.addBinding().toInstance(list); list.add("A"); list.add("B"); } }; Injector injector = Guice.createInjector(ab); for (Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet()) { Key<?> bindingKey = entry.getKey(); Key<?> clonedKey; if (bindingKey.getAnnotation() != null) { clonedKey = bindingKey.ofType(bindingKey.getTypeLiteral()); } else if (bindingKey.getAnnotationType() != null) { clonedKey = bindingKey.ofType(bindingKey.getTypeLiteral()); } else { clonedKey = Key.get(bindingKey.getTypeLiteral()); } assertEquals(bindingKey, clonedKey); assertEquals( "Incorrect hashcode for " + bindingKey + " -> " + entry.getValue(), bindingKey.hashCode(), clonedKey.hashCode()); } } /** Ensure bindings do not rehash their keys once returned from {@link Elements#getElements}. */ public void testBindingKeysFixedOnReturnFromGetElements() { final List<String> list = Lists.newArrayList(); Module ab = new AbstractModule() { @Override protected void configure() { Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings); multibinder.addBinding().toInstance(list); list.add("A"); list.add("B"); } }; InstanceBinding<?> binding = Elements.getElements(ab).stream() .filter(InstanceBinding.class::isInstance) .map(InstanceBinding.class::cast) .collect(onlyElement()); Key<?> keyBefore = binding.getKey(); assertEquals(listOfStrings, keyBefore.getTypeLiteral()); list.add("C"); Key<?> keyAfter = binding.getKey(); assertSame(keyBefore, keyAfter); } /* * Verify through gratuitous mutation that key hashCode snapshots and whatnot happens at the right * times, by binding two lists that are different at injector creation, but compare equal when the * module is configured *and* when the set is instantiated. */ public void testConcurrentMutation_bindingsDiffentAtInjectorCreation() { // We initially bind two equal lists final List<String> list1 = Lists.newArrayList(); final List<String> list2 = Lists.newArrayList(); Module module = new AbstractModule() { @Override protected void configure() { Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings); multibinder.addBinding().toInstance(list1); multibinder.addBinding().toInstance(list2); } }; List<Element> elements = Elements.getElements(module); // Now we change the lists so they no longer match, and create the injector. list1.add("A"); list2.add("B"); Injector injector = Guice.createInjector(Elements.getModule(elements)); // Now we change the lists so they compare equal again, and create the set. list1.add(1, "B"); list2.add(0, "A"); try { injector.getInstance(Key.get(setOfListOfStrings)); fail(); } catch (ProvisionException e) { assertEquals(1, e.getErrorMessages().size()); assertContains(e.getMessage(), "Duplicate elements found in Multibinder Set<List<String>>."); } // Finally, we change the lists again so they are once more different, and ensure the set // contains both. list1.remove("A"); list2.remove("B"); Set<List<String>> set = injector.getInstance(Key.get(setOfListOfStrings)); assertEquals(ImmutableSet.of(ImmutableList.of("A"), ImmutableList.of("B")), set); } /* * Verify through gratuitous mutation that key hashCode snapshots and whatnot happen at the right * times, by binding two lists that compare equal at injector creation, but are different when the * module is configured *and* when the set is instantiated. */ public void testConcurrentMutation_bindingsSameAtInjectorCreation() { // We initially bind two distinct lists final List<String> list1 = Lists.newArrayList("A"); final List<String> list2 = Lists.newArrayList("B"); Module module = new AbstractModule() { @Override protected void configure() { Multibinder<List<String>> multibinder = Multibinder.newSetBinder(binder(), listOfStrings); multibinder.addBinding().toInstance(list1); multibinder.addBinding().toInstance(list2); } }; List<Element> elements = Elements.getElements(module); // Now we change the lists so they compare equal, and create the injector. list1.add(1, "B"); list2.add(0, "A"); Injector injector = Guice.createInjector(Elements.getModule(elements)); // Now we change the lists again so they are once more different, and create the set. list1.remove("A"); list2.remove("B"); Set<List<String>> set = injector.getInstance(Key.get(setOfListOfStrings)); // The set will contain just one of the two lists. // (In fact, it will be the first one we bound, but we don't promise that, so we won't test it.) assertTrue( ImmutableSet.of(ImmutableList.of("A")).equals(set) || ImmutableSet.of(ImmutableList.of("B")).equals(set)); } @BindingAnnotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) private static @
StringGrabber
java
apache__avro
lang/java/mapred/src/main/java/org/apache/avro/mapred/tether/TetherPartitioner.java
{ "start": 1115, "end": 1898 }
class ____ implements Partitioner<TetherData, NullWritable> { private static final ThreadLocal<Integer> CACHE = new ThreadLocal<>(); private Schema schema; @Override public void configure(JobConf job) { schema = AvroJob.getMapOutputSchema(job); } static void setNextPartition(int newValue) { CACHE.set(newValue); } @Override public int getPartition(TetherData key, NullWritable value, int numPartitions) { Integer result = CACHE.get(); if (result != null) // return cached value return result; ByteBuffer b = key.buffer(); int p = b.position(); int hashCode = BinaryData.hashCode(b.array(), p, b.limit() - p, schema); if (hashCode < 0) hashCode = -hashCode; return hashCode % numPartitions; } }
TetherPartitioner
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/inheritance/classrolesallowed/ClassRolesAllowedInterfaceWithPath_SecurityOnBase.java
{ "start": 1430, "end": 2159 }
interface ____ { @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + CLASS_ROLES_ALLOWED_PATH) String classPathOnInterface_ImplOnBase_ImplMethodWithPath_ClassRolesAllowed(JsonObject array); @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + INTERFACE_METHOD_WITH_PATH + CLASS_ROLES_ALLOWED_PATH) String classPathOnInterface_ImplOnBase_InterfaceMethodWithPath_ClassRolesAllowed(JsonObject array); @Path(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_BASE + CLASS_ROLES_ALLOWED_PATH) ClassRolesAllowedSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnBase_ClassRolesAllowed(); }
ClassRolesAllowedInterfaceWithPath_SecurityOnBase
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java
{ "start": 162088, "end": 162406 }
class ____ implements ITypeConverter<Short> { @Override public Short convert(final String value) { return Short.valueOf(value); } } /** Converts text to an {@code Integer} by delegating to {@link Integer#valueOf(String)}.*/ static
ShortConverter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StringFormatWithLiteralTest.java
{ "start": 11165, "end": 11419 }
class ____ { String test() { return String.format("hello %s", "['world']"); } } """) .addOutputLines( "ExampleClass.java", """ public
ExampleClass