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
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldHavePermittedSubclasses_create_Test.java
{ "start": 1091, "end": 2131 }
class ____ { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldHavePermittedSubclasses(ShouldHavePermittedSubclasses_create_Test.class, array(String.class, Number.class), list(Number.class)); // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting%n" + " org.assertj.core.error.ShouldHavePermittedSubclasses_create_Test%n" + "to have these permitted subclasses:%n" + " [java.lang.String, java.lang.Number]%n" + "but the following ones were not found:%n" + " [java.lang.Number]")); } }
ShouldHavePermittedSubclasses_create_Test
java
apache__camel
dsl/camel-jbang/camel-jbang-plugin-generate/src/main/java/org/apache/camel/dsl/jbang/core/commands/generate/CodeSchemaGenerator.java
{ "start": 2952, "end": 4867 }
class ____ (e.g., 'org.hl7.fhir.r4.model.Patient')", arity = "1") private String fullyQualifiedName; @CommandLine.Option(names = { "--camel-version" }, description = "Camel version to use") private String camelVersion; @CommandLine.Option(names = { "--output" }, description = "Output file path (default: stdout)") private String outputFile; @CommandLine.Option(names = { "--verbose" }, description = "Enable verbose logging") private boolean verbose; @CommandLine.Option(names = { "--download" }, defaultValue = "true", description = "Whether to allow automatic downloading JAR dependencies (over the internet)") boolean download = true; @CommandLine.Option(names = { "--repo", "--repos" }, description = "Additional maven repositories (Use commas to separate multiple repositories)") String repositories; public CodeSchemaGenerator(CamelJBangMain main) { super(main); } @Override public Integer doCall() throws Exception { try { if (camelVersion == null) { camelVersion = new DefaultCamelCatalog().getCatalogVersion(); } if (verbose) { printer().println("Generating JSON Schema for component: " + camelComponent); printer().println("Class: " + fullyQualifiedName); printer().println("Camel version: " + camelVersion); } // Validate inputs if (camelComponent == null || camelComponent.trim().isEmpty()) { printer().printErr("Error: Camel component name cannot be empty"); return 4; } if (fullyQualifiedName == null || fullyQualifiedName.trim().isEmpty()) { printer().printErr("Error: Fully qualified
name
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/TaskManagerInfo.java
{ "start": 1247, "end": 2669 }
interface ____ { /** * Get the instanceId of this task manager. * * @return the instanceId */ InstanceID getInstanceId(); /** * Get the taskExecutorConnection. * * @return the taskExecutorConnection */ TaskExecutorConnection getTaskExecutorConnection(); /** * Get allocated slots information. * * @return allocated slots information mapped by its allocationId */ Map<AllocationID, TaskManagerSlotInformation> getAllocatedSlots(); /** * Get the available resource. * * @return the available resource */ ResourceProfile getAvailableResource(); /** * Get the total resource. * * @return the total resource */ ResourceProfile getTotalResource(); /** * Get the default slot resource profile. * * @return the default slot resource profile */ ResourceProfile getDefaultSlotResourceProfile(); /** * Get the default number of slots. * * @return the default number of slots */ int getDefaultNumSlots(); /** * Get the timestamp when the last time becoming idle. * * @return the timestamp when the last time becoming idle */ long getIdleSince(); /** * Check whether this task manager is idle. * * @return whether this task manager is idle */ boolean isIdle(); }
TaskManagerInfo
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/rest/cat/RestCatTrainedModelsActionTests.java
{ "start": 957, "end": 3988 }
class ____ extends ESTestCase { public void testBuildTableAccumulatedStats() { var action = new RestCatTrainedModelsAction(true); // GetTrainedModelsStatsActionResponseTests var deployment1 = new GetTrainedModelsStatsAction.Response.TrainedModelStats( "id1", new TrainedModelSizeStats(100, 200), GetTrainedModelsStatsActionResponseTests.randomIngestStats(), 2, null, null ); var deployment2 = new GetTrainedModelsStatsAction.Response.TrainedModelStats( "id1", new TrainedModelSizeStats(1, 2), GetTrainedModelsStatsActionResponseTests.randomIngestStats(), 2, null, null ); var dataframeConfig = DataFrameAnalyticsConfigTests.createRandom("dataframe1"); var configs = List.of( TrainedModelConfigTests.createTestInstance(deployment1.getModelId()).setTags(List.of(dataframeConfig.getId())).build() ); var table = action.buildTable(new FakeRestRequest(), List.of(deployment1, deployment2), configs, List.of(dataframeConfig)); assertThat(table.getRows().get(0).get(0).value, is(deployment1.getModelId())); // pipeline count assertThat(table.getRows().get(0).get(9).value, is(4)); // ingest count assertThat( table.getRows().get(0).get(10).value, is(deployment1.getIngestStats().totalStats().ingestCount() + deployment2.getIngestStats().totalStats().ingestCount()) ); // ingest time in millis assertThat( table.getRows().get(0).get(11).value, is( deployment1.getIngestStats().totalStats().ingestTimeInMillis() + deployment2.getIngestStats() .totalStats() .ingestTimeInMillis() ) ); // ingest current assertThat( table.getRows().get(0).get(12).value, is(deployment1.getIngestStats().totalStats().ingestCurrent() + deployment2.getIngestStats().totalStats().ingestCurrent()) ); // ingest failed count assertThat( table.getRows().get(0).get(13).value, is( deployment1.getIngestStats().totalStats().ingestFailedCount() + deployment2.getIngestStats() .totalStats() .ingestFailedCount() ) ); assertThat(table.getRows().get(0).get(14).value, is(dataframeConfig.getId())); assertThat(table.getRows().get(0).get(15).value, is(dataframeConfig.getCreateTime())); assertThat(table.getRows().get(0).get(16).value, is(Strings.arrayToCommaDelimitedString(dataframeConfig.getSource().getIndex()))); assertThat( table.getRows().get(0).get(17).value, dataframeConfig.getAnalysis() == null ? nullValue() : is(dataframeConfig.getAnalysis().getWriteableName()) ); } }
RestCatTrainedModelsActionTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/CustomDeserializersTest.java
{ "start": 1344, "end": 1778 }
class ____<T> extends StdDeserializer<T> { final T value; public DummyDeserializer(T v, Class<T> cls) { super(cls); value = v; } @Override public T deserialize(JsonParser p, DeserializationContext ctxt) { // need to skip, if structured... p.skipChildren(); return value; } } static
DummyDeserializer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateTest.java
{ "start": 8264, "end": 8428 }
class ____ extends InheritanceRootEntity { } @Entity(name = "InheritanceSecondChildEntity") @PrimaryKeyJoinColumn(name = "ID") public static
InheritanceChildEntity
java
google__dagger
javatests/dagger/internal/codegen/BindsMissingDelegateValidationTest.java
{ "start": 5426, "end": 5913 }
class ____ {", " @Binds @IntoSet abstract Object bindObject(NotBound notBound);", " }", "}"); CompilerTests.daggerCompiler(component) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining("test.C.NotBound cannot be provided") .onSource(component) .onLineContaining("
TestModule
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AbstractAsyncThreadContextTestBase.java
{ "start": 2638, "end": 3193 }
class ____ { private static final int LINE_COUNT = 130; private static TestProperties props; @BeforeEach public void beforeEach() { ThreadContext.clearAll(); } @BeforeAll public static void beforeClass() { props.setProperty("log4j2.enableThreadlocals", true); props.setProperty("log4j2.asyncLoggerRingBufferSize", 128); // minimum ringbuffer size props.setProperty("log4j2.asyncLoggerConfigRingBufferSize", 128); // minimum ringbuffer size } protected
AbstractAsyncThreadContextTestBase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/locking/OptimisticLockTypeDirtyWithLazyOneToOneTest.java
{ "start": 4118, "end": 4867 }
class ____ { @Id Long id; @Column String name; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) Address address; public Person() { } public Person(Long id, String name, Address address) { this.id = id; this.name = name; this.address = address; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } @Entity(name = "Address") @OptimisticLocking(type = OptimisticLockType.DIRTY) @DynamicUpdate public static
Person
java
redisson__redisson
redisson-quarkus/redisson-quarkus-30/cache/runtime/src/main/java/io/quarkus/cache/redisson/runtime/RedissonCache.java
{ "start": 765, "end": 1166 }
interface ____ extends Cache { <K, V> Uni<V> put(K key, V value); <K, V> Uni<V> putIfAbsent(K key, V value); <K, V> Uni<V> putIfExists(K key, V value); <K, V> Uni<Boolean> fastPut(K key, V value); <K, V> Uni<Boolean> fastPutIfAbsent(K key, V value); <K, V> Uni<Boolean> fastPutIfExists(K key, V value); <K, V> Uni<V> getOrDefault(K key, V defaultValue); }
RedissonCache
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/util/DualClass.java
{ "start": 1830, "end": 2577 }
class ____ expected value belongs to */ public Class<E> expected() { return expected; } public boolean hasNoExpected() { return expected == null; } public String actualDescription() { return actual == null ? "" : actual.getName(); } public String expectedDescription() { return expected == null ? "" : expected.getName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DualClass<?, ?> dualClass = (DualClass<?, ?>) o; return Objects.equals(actual, dualClass.actual) && Objects.equals(expected, dualClass.expected); } @Override public int hashCode() { return hash(actual, expected); } }
whose
java
apache__flink
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/functions/TimedOutPartialMatchHandler.java
{ "start": 1421, "end": 1813 }
interface ____<IN> { /** * Called for every timed out partial match (due to {@link * org.apache.flink.cep.pattern.Pattern#within(Duration)}). It enables custom handling, e.g. one * can emit the timed out results through a side output: * * <pre>{@code * private final OutputTag<T> timedOutPartialMatchesTag = ... * * private
TimedOutPartialMatchHandler
java
apache__camel
components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/NoopTracingStrategy.java
{ "start": 1090, "end": 1424 }
class ____ implements InterceptStrategy { @Override public Processor wrapProcessorInInterceptors( CamelContext camelContext, NamedNode processorDefinition, Processor target, Processor nextTarget) throws Exception { return new DelegateAsyncProcessor(target); } }
NoopTracingStrategy
java
google__dagger
dagger-android-processor/main/java/dagger/android/processor/AndroidMapKeys.java
{ "start": 788, "end": 994 }
class ____ { /** * If {@code mapKey} is {@code AndroidInjectionKey}, returns the string value for the map key. If * it's {@link dagger.multibindings.ClassKey}, returns the fully-qualified
AndroidMapKeys
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/TestLogLongTimeTransaction.java
{ "start": 999, "end": 2383 }
class ____ extends TestCase { private DruidDataSource dataSource; private MockDriver driver; protected void setUp() throws Exception { driver = new MockDriver() { protected ResultSet executeQuery(MockStatement stmt, String sql) throws SQLException { try { Thread.sleep(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return super.executeQuery(stmt, sql); } }; dataSource = new DruidDataSource(); dataSource.setDriver(driver); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setFilters("stat,trace,log4j,encoding"); dataSource.setTransactionThresholdMillis(1); } protected void tearDown() throws Exception { dataSource.close(); assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); } public void test_0() throws Exception { Connection conn = dataSource.getConnection(); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 1"); rs.next(); rs.close(); stmt.close(); conn.commit(); conn.close(); } }
TestLogLongTimeTransaction
java
apache__camel
components/camel-http/src/generated/java/org/apache/camel/component/http/HttpEndpointConfigurer.java
{ "start": 731, "end": 26042 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { HttpEndpoint target = (HttpEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "authbearertoken": case "authBearerToken": target.setAuthBearerToken(property(camelContext, java.lang.String.class, value)); return true; case "authdomain": case "authDomain": target.setAuthDomain(property(camelContext, java.lang.String.class, value)); return true; case "authhost": case "authHost": target.setAuthHost(property(camelContext, java.lang.String.class, value)); return true; case "authmethod": case "authMethod": target.setAuthMethod(property(camelContext, java.lang.String.class, value)); return true; case "authpassword": case "authPassword": target.setAuthPassword(property(camelContext, java.lang.String.class, value)); return true; case "authusername": case "authUsername": target.setAuthUsername(property(camelContext, java.lang.String.class, value)); return true; case "authenticationpreemptive": case "authenticationPreemptive": target.setAuthenticationPreemptive(property(camelContext, boolean.class, value)); return true; case "bridgeendpoint": case "bridgeEndpoint": target.setBridgeEndpoint(property(camelContext, boolean.class, value)); return true; case "clearexpiredcookies": case "clearExpiredCookies": target.setClearExpiredCookies(property(camelContext, boolean.class, value)); return true; case "clientbuilder": case "clientBuilder": target.setClientBuilder(property(camelContext, org.apache.hc.client5.http.impl.classic.HttpClientBuilder.class, value)); return true; case "clientconnectionmanager": case "clientConnectionManager": target.setClientConnectionManager(property(camelContext, org.apache.hc.client5.http.io.HttpClientConnectionManager.class, value)); return true; case "connectionclose": case "connectionClose": target.setConnectionClose(property(camelContext, boolean.class, value)); return true; case "connectionsperroute": case "connectionsPerRoute": target.setConnectionsPerRoute(property(camelContext, int.class, value)); return true; case "contenttypecharsetenabled": case "contentTypeCharsetEnabled": target.setContentTypeCharsetEnabled(property(camelContext, boolean.class, value)); return true; case "cookiehandler": case "cookieHandler": target.setCookieHandler(property(camelContext, org.apache.camel.http.base.cookie.CookieHandler.class, value)); return true; case "cookiestore": case "cookieStore": target.setCookieStore(property(camelContext, org.apache.hc.client5.http.cookie.CookieStore.class, value)); return true; case "copyheaders": case "copyHeaders": target.setCopyHeaders(property(camelContext, boolean.class, value)); return true; case "customhostheader": case "customHostHeader": target.setCustomHostHeader(property(camelContext, java.lang.String.class, value)); return true; case "deletewithbody": case "deleteWithBody": target.setDeleteWithBody(property(camelContext, boolean.class, value)); return true; case "disablestreamcache": case "disableStreamCache": target.setDisableStreamCache(property(camelContext, boolean.class, value)); return true; case "followredirects": case "followRedirects": target.setFollowRedirects(property(camelContext, boolean.class, value)); return true; case "getwithbody": case "getWithBody": target.setGetWithBody(property(camelContext, boolean.class, value)); return true; case "headerfilterstrategy": case "headerFilterStrategy": target.setHeaderFilterStrategy(property(camelContext, org.apache.camel.spi.HeaderFilterStrategy.class, value)); return true; case "httpactivitylistener": case "httpActivityListener": target.setHttpActivityListener(property(camelContext, org.apache.camel.component.http.HttpActivityListener.class, value)); return true; case "httpclient": case "httpClient": target.setHttpClient(property(camelContext, org.apache.hc.client5.http.classic.HttpClient.class, value)); return true; case "httpclientconfigurer": case "httpClientConfigurer": target.setHttpClientConfigurer(property(camelContext, org.apache.camel.component.http.HttpClientConfigurer.class, value)); return true; case "httpclientoptions": case "httpClientOptions": target.setHttpClientOptions(property(camelContext, java.util.Map.class, value)); return true; case "httpconnectionoptions": case "httpConnectionOptions": target.setHttpConnectionOptions(property(camelContext, java.util.Map.class, value)); return true; case "httpcontext": case "httpContext": target.setHttpContext(property(camelContext, org.apache.hc.core5.http.protocol.HttpContext.class, value)); return true; case "httpmethod": case "httpMethod": target.setHttpMethod(property(camelContext, org.apache.camel.http.common.HttpMethods.class, value)); return true; case "ignoreresponsebody": case "ignoreResponseBody": target.setIgnoreResponseBody(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "loghttpactivity": case "logHttpActivity": target.setLogHttpActivity(property(camelContext, boolean.class, value)); return true; case "maxtotalconnections": case "maxTotalConnections": target.setMaxTotalConnections(property(camelContext, int.class, value)); return true; case "multipartupload": case "multipartUpload": target.setMultipartUpload(property(camelContext, boolean.class, value)); return true; case "multipartuploadname": case "multipartUploadName": target.setMultipartUploadName(property(camelContext, java.lang.String.class, value)); return true; case "oauth2bodyauthentication": case "oauth2BodyAuthentication": target.setOauth2BodyAuthentication(property(camelContext, boolean.class, value)); return true; case "oauth2cachetokens": case "oauth2CacheTokens": target.setOauth2CacheTokens(property(camelContext, boolean.class, value)); return true; case "oauth2cachedtokensdefaultexpiryseconds": case "oauth2CachedTokensDefaultExpirySeconds": target.setOauth2CachedTokensDefaultExpirySeconds(property(camelContext, long.class, value)); return true; case "oauth2cachedtokensexpirationmarginseconds": case "oauth2CachedTokensExpirationMarginSeconds": target.setOauth2CachedTokensExpirationMarginSeconds(property(camelContext, long.class, value)); return true; case "oauth2clientid": case "oauth2ClientId": target.setOauth2ClientId(property(camelContext, java.lang.String.class, value)); return true; case "oauth2clientsecret": case "oauth2ClientSecret": target.setOauth2ClientSecret(property(camelContext, java.lang.String.class, value)); return true; case "oauth2resourceindicator": case "oauth2ResourceIndicator": target.setOauth2ResourceIndicator(property(camelContext, java.lang.String.class, value)); return true; case "oauth2scope": case "oauth2Scope": target.setOauth2Scope(property(camelContext, java.lang.String.class, value)); return true; case "oauth2tokenendpoint": case "oauth2TokenEndpoint": target.setOauth2TokenEndpoint(property(camelContext, java.lang.String.class, value)); return true; case "okstatuscoderange": case "okStatusCodeRange": target.setOkStatusCodeRange(property(camelContext, java.lang.String.class, value)); return true; case "preservehostheader": case "preserveHostHeader": target.setPreserveHostHeader(property(camelContext, boolean.class, value)); return true; case "proxyauthdomain": case "proxyAuthDomain": target.setProxyAuthDomain(property(camelContext, java.lang.String.class, value)); return true; case "proxyauthhost": case "proxyAuthHost": target.setProxyAuthHost(property(camelContext, java.lang.String.class, value)); return true; case "proxyauthmethod": case "proxyAuthMethod": target.setProxyAuthMethod(property(camelContext, java.lang.String.class, value)); return true; case "proxyauthnthost": case "proxyAuthNtHost": target.setProxyAuthNtHost(property(camelContext, java.lang.String.class, value)); return true; case "proxyauthpassword": case "proxyAuthPassword": target.setProxyAuthPassword(property(camelContext, java.lang.String.class, value)); return true; case "proxyauthport": case "proxyAuthPort": target.setProxyAuthPort(property(camelContext, int.class, value)); return true; case "proxyauthscheme": case "proxyAuthScheme": target.setProxyAuthScheme(property(camelContext, java.lang.String.class, value)); return true; case "proxyauthusername": case "proxyAuthUsername": target.setProxyAuthUsername(property(camelContext, java.lang.String.class, value)); return true; case "proxyhost": case "proxyHost": target.setProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "proxyport": case "proxyPort": target.setProxyPort(property(camelContext, int.class, value)); return true; case "skipcontrolheaders": case "skipControlHeaders": target.setSkipControlHeaders(property(camelContext, boolean.class, value)); return true; case "skiprequestheaders": case "skipRequestHeaders": target.setSkipRequestHeaders(property(camelContext, boolean.class, value)); return true; case "skipresponseheaders": case "skipResponseHeaders": target.setSkipResponseHeaders(property(camelContext, boolean.class, value)); return true; case "sslcontextparameters": case "sslContextParameters": target.setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true; case "throwexceptiononfailure": case "throwExceptionOnFailure": target.setThrowExceptionOnFailure(property(camelContext, boolean.class, value)); return true; case "usesystemproperties": case "useSystemProperties": target.setUseSystemProperties(property(camelContext, boolean.class, value)); return true; case "useragent": case "userAgent": target.setUserAgent(property(camelContext, java.lang.String.class, value)); return true; case "x509hostnameverifier": case "x509HostnameVerifier": target.setX509HostnameVerifier(property(camelContext, javax.net.ssl.HostnameVerifier.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "authbearertoken": case "authBearerToken": return java.lang.String.class; case "authdomain": case "authDomain": return java.lang.String.class; case "authhost": case "authHost": return java.lang.String.class; case "authmethod": case "authMethod": return java.lang.String.class; case "authpassword": case "authPassword": return java.lang.String.class; case "authusername": case "authUsername": return java.lang.String.class; case "authenticationpreemptive": case "authenticationPreemptive": return boolean.class; case "bridgeendpoint": case "bridgeEndpoint": return boolean.class; case "clearexpiredcookies": case "clearExpiredCookies": return boolean.class; case "clientbuilder": case "clientBuilder": return org.apache.hc.client5.http.impl.classic.HttpClientBuilder.class; case "clientconnectionmanager": case "clientConnectionManager": return org.apache.hc.client5.http.io.HttpClientConnectionManager.class; case "connectionclose": case "connectionClose": return boolean.class; case "connectionsperroute": case "connectionsPerRoute": return int.class; case "contenttypecharsetenabled": case "contentTypeCharsetEnabled": return boolean.class; case "cookiehandler": case "cookieHandler": return org.apache.camel.http.base.cookie.CookieHandler.class; case "cookiestore": case "cookieStore": return org.apache.hc.client5.http.cookie.CookieStore.class; case "copyheaders": case "copyHeaders": return boolean.class; case "customhostheader": case "customHostHeader": return java.lang.String.class; case "deletewithbody": case "deleteWithBody": return boolean.class; case "disablestreamcache": case "disableStreamCache": return boolean.class; case "followredirects": case "followRedirects": return boolean.class; case "getwithbody": case "getWithBody": return boolean.class; case "headerfilterstrategy": case "headerFilterStrategy": return org.apache.camel.spi.HeaderFilterStrategy.class; case "httpactivitylistener": case "httpActivityListener": return org.apache.camel.component.http.HttpActivityListener.class; case "httpclient": case "httpClient": return org.apache.hc.client5.http.classic.HttpClient.class; case "httpclientconfigurer": case "httpClientConfigurer": return org.apache.camel.component.http.HttpClientConfigurer.class; case "httpclientoptions": case "httpClientOptions": return java.util.Map.class; case "httpconnectionoptions": case "httpConnectionOptions": return java.util.Map.class; case "httpcontext": case "httpContext": return org.apache.hc.core5.http.protocol.HttpContext.class; case "httpmethod": case "httpMethod": return org.apache.camel.http.common.HttpMethods.class; case "ignoreresponsebody": case "ignoreResponseBody": return boolean.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "loghttpactivity": case "logHttpActivity": return boolean.class; case "maxtotalconnections": case "maxTotalConnections": return int.class; case "multipartupload": case "multipartUpload": return boolean.class; case "multipartuploadname": case "multipartUploadName": return java.lang.String.class; case "oauth2bodyauthentication": case "oauth2BodyAuthentication": return boolean.class; case "oauth2cachetokens": case "oauth2CacheTokens": return boolean.class; case "oauth2cachedtokensdefaultexpiryseconds": case "oauth2CachedTokensDefaultExpirySeconds": return long.class; case "oauth2cachedtokensexpirationmarginseconds": case "oauth2CachedTokensExpirationMarginSeconds": return long.class; case "oauth2clientid": case "oauth2ClientId": return java.lang.String.class; case "oauth2clientsecret": case "oauth2ClientSecret": return java.lang.String.class; case "oauth2resourceindicator": case "oauth2ResourceIndicator": return java.lang.String.class; case "oauth2scope": case "oauth2Scope": return java.lang.String.class; case "oauth2tokenendpoint": case "oauth2TokenEndpoint": return java.lang.String.class; case "okstatuscoderange": case "okStatusCodeRange": return java.lang.String.class; case "preservehostheader": case "preserveHostHeader": return boolean.class; case "proxyauthdomain": case "proxyAuthDomain": return java.lang.String.class; case "proxyauthhost": case "proxyAuthHost": return java.lang.String.class; case "proxyauthmethod": case "proxyAuthMethod": return java.lang.String.class; case "proxyauthnthost": case "proxyAuthNtHost": return java.lang.String.class; case "proxyauthpassword": case "proxyAuthPassword": return java.lang.String.class; case "proxyauthport": case "proxyAuthPort": return int.class; case "proxyauthscheme": case "proxyAuthScheme": return java.lang.String.class; case "proxyauthusername": case "proxyAuthUsername": return java.lang.String.class; case "proxyhost": case "proxyHost": return java.lang.String.class; case "proxyport": case "proxyPort": return int.class; case "skipcontrolheaders": case "skipControlHeaders": return boolean.class; case "skiprequestheaders": case "skipRequestHeaders": return boolean.class; case "skipresponseheaders": case "skipResponseHeaders": return boolean.class; case "sslcontextparameters": case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class; case "throwexceptiononfailure": case "throwExceptionOnFailure": return boolean.class; case "usesystemproperties": case "useSystemProperties": return boolean.class; case "useragent": case "userAgent": return java.lang.String.class; case "x509hostnameverifier": case "x509HostnameVerifier": return javax.net.ssl.HostnameVerifier.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { HttpEndpoint target = (HttpEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "authbearertoken": case "authBearerToken": return target.getAuthBearerToken(); case "authdomain": case "authDomain": return target.getAuthDomain(); case "authhost": case "authHost": return target.getAuthHost(); case "authmethod": case "authMethod": return target.getAuthMethod(); case "authpassword": case "authPassword": return target.getAuthPassword(); case "authusername": case "authUsername": return target.getAuthUsername(); case "authenticationpreemptive": case "authenticationPreemptive": return target.isAuthenticationPreemptive(); case "bridgeendpoint": case "bridgeEndpoint": return target.isBridgeEndpoint(); case "clearexpiredcookies": case "clearExpiredCookies": return target.isClearExpiredCookies(); case "clientbuilder": case "clientBuilder": return target.getClientBuilder(); case "clientconnectionmanager": case "clientConnectionManager": return target.getClientConnectionManager(); case "connectionclose": case "connectionClose": return target.isConnectionClose(); case "connectionsperroute": case "connectionsPerRoute": return target.getConnectionsPerRoute(); case "contenttypecharsetenabled": case "contentTypeCharsetEnabled": return target.isContentTypeCharsetEnabled(); case "cookiehandler": case "cookieHandler": return target.getCookieHandler(); case "cookiestore": case "cookieStore": return target.getCookieStore(); case "copyheaders": case "copyHeaders": return target.isCopyHeaders(); case "customhostheader": case "customHostHeader": return target.getCustomHostHeader(); case "deletewithbody": case "deleteWithBody": return target.isDeleteWithBody(); case "disablestreamcache": case "disableStreamCache": return target.isDisableStreamCache(); case "followredirects": case "followRedirects": return target.isFollowRedirects(); case "getwithbody": case "getWithBody": return target.isGetWithBody(); case "headerfilterstrategy": case "headerFilterStrategy": return target.getHeaderFilterStrategy(); case "httpactivitylistener": case "httpActivityListener": return target.getHttpActivityListener(); case "httpclient": case "httpClient": return target.getHttpClient(); case "httpclientconfigurer": case "httpClientConfigurer": return target.getHttpClientConfigurer(); case "httpclientoptions": case "httpClientOptions": return target.getHttpClientOptions(); case "httpconnectionoptions": case "httpConnectionOptions": return target.getHttpConnectionOptions(); case "httpcontext": case "httpContext": return target.getHttpContext(); case "httpmethod": case "httpMethod": return target.getHttpMethod(); case "ignoreresponsebody": case "ignoreResponseBody": return target.isIgnoreResponseBody(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "loghttpactivity": case "logHttpActivity": return target.isLogHttpActivity(); case "maxtotalconnections": case "maxTotalConnections": return target.getMaxTotalConnections(); case "multipartupload": case "multipartUpload": return target.isMultipartUpload(); case "multipartuploadname": case "multipartUploadName": return target.getMultipartUploadName(); case "oauth2bodyauthentication": case "oauth2BodyAuthentication": return target.isOauth2BodyAuthentication(); case "oauth2cachetokens": case "oauth2CacheTokens": return target.isOauth2CacheTokens(); case "oauth2cachedtokensdefaultexpiryseconds": case "oauth2CachedTokensDefaultExpirySeconds": return target.getOauth2CachedTokensDefaultExpirySeconds(); case "oauth2cachedtokensexpirationmarginseconds": case "oauth2CachedTokensExpirationMarginSeconds": return target.getOauth2CachedTokensExpirationMarginSeconds(); case "oauth2clientid": case "oauth2ClientId": return target.getOauth2ClientId(); case "oauth2clientsecret": case "oauth2ClientSecret": return target.getOauth2ClientSecret(); case "oauth2resourceindicator": case "oauth2ResourceIndicator": return target.getOauth2ResourceIndicator(); case "oauth2scope": case "oauth2Scope": return target.getOauth2Scope(); case "oauth2tokenendpoint": case "oauth2TokenEndpoint": return target.getOauth2TokenEndpoint(); case "okstatuscoderange": case "okStatusCodeRange": return target.getOkStatusCodeRange(); case "preservehostheader": case "preserveHostHeader": return target.isPreserveHostHeader(); case "proxyauthdomain": case "proxyAuthDomain": return target.getProxyAuthDomain(); case "proxyauthhost": case "proxyAuthHost": return target.getProxyAuthHost(); case "proxyauthmethod": case "proxyAuthMethod": return target.getProxyAuthMethod(); case "proxyauthnthost": case "proxyAuthNtHost": return target.getProxyAuthNtHost(); case "proxyauthpassword": case "proxyAuthPassword": return target.getProxyAuthPassword(); case "proxyauthport": case "proxyAuthPort": return target.getProxyAuthPort(); case "proxyauthscheme": case "proxyAuthScheme": return target.getProxyAuthScheme(); case "proxyauthusername": case "proxyAuthUsername": return target.getProxyAuthUsername(); case "proxyhost": case "proxyHost": return target.getProxyHost(); case "proxyport": case "proxyPort": return target.getProxyPort(); case "skipcontrolheaders": case "skipControlHeaders": return target.isSkipControlHeaders(); case "skiprequestheaders": case "skipRequestHeaders": return target.isSkipRequestHeaders(); case "skipresponseheaders": case "skipResponseHeaders": return target.isSkipResponseHeaders(); case "sslcontextparameters": case "sslContextParameters": return target.getSslContextParameters(); case "throwexceptiononfailure": case "throwExceptionOnFailure": return target.isThrowExceptionOnFailure(); case "usesystemproperties": case "useSystemProperties": return target.isUseSystemProperties(); case "useragent": case "userAgent": return target.getUserAgent(); case "x509hostnameverifier": case "x509HostnameVerifier": return target.getX509HostnameVerifier(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "httpclientoptions": case "httpClientOptions": return java.lang.Object.class; case "httpconnectionoptions": case "httpConnectionOptions": return java.lang.Object.class; default: return null; } } }
HttpEndpointConfigurer
java
alibaba__druid
core/src/test/java/com/alibaba/druid/proxy/demo/Demo1.java
{ "start": 828, "end": 1762 }
class ____ extends TestCase { public void test_0() throws Exception { JdbcStatManager.getInstance().reset(); // 重置计数器 Assert.assertEquals(0, JdbcStatManager.getInstance().getConnectionStat().getConnectCount()); Assert.assertEquals(0, JdbcStatManager.getInstance().getConnectionStat().getCloseCount()); String url = "jdbc:wrap-jdbc:filters=default:name=preCallTest:jdbc:derby:memory:Demo1;create=true"; Connection conn = DriverManager.getConnection(url); Assert.assertEquals(1, JdbcStatManager.getInstance().getConnectionStat().getConnectCount()); Assert.assertEquals(0, JdbcStatManager.getInstance().getConnectionStat().getCloseCount()); conn.close(); Assert.assertEquals(1, JdbcStatManager.getInstance().getConnectionStat().getConnectCount()); Assert.assertEquals(1, JdbcStatManager.getInstance().getConnectionStat().getCloseCount()); } }
Demo1
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/DefaultJaxRsDenyAllImplMethodSecuredTest.java
{ "start": 163, "end": 468 }
class ____ extends AbstractImplMethodSecuredTest { @RegisterExtension static QuarkusUnitTest runner = getRunner("quarkus.security.jaxrs.deny-unannotated-endpoints=true"); @Override protected boolean denyAllUnannotated() { return true; } }
DefaultJaxRsDenyAllImplMethodSecuredTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/store/records/TestRouterState.java
{ "start": 1753, "end": 5410 }
class ____ { private static final String ADDRESS = "address"; private static final String VERSION = "version"; private static final String COMPILE_INFO = "compileInfo"; private static final long START_TIME = 100; private static final long DATE_MODIFIED = 200; private static final long DATE_CREATED = 300; private static final long FILE_RESOLVER_VERSION = 500; private static final RouterServiceState STATE = RouterServiceState.RUNNING; private RouterState generateRecord() { RouterState record = RouterState.newInstance(ADDRESS, START_TIME, STATE); record.setVersion(VERSION); record.setCompileInfo(COMPILE_INFO); record.setDateCreated(DATE_CREATED); record.setDateModified(DATE_MODIFIED); StateStoreVersion version = StateStoreVersion.newInstance(); version.setMountTableVersion(FILE_RESOLVER_VERSION); record.setStateStoreVersion(version); return record; } private void validateRecord(RouterState record) throws IOException { assertEquals(ADDRESS, record.getAddress()); assertEquals(START_TIME, record.getDateStarted()); assertEquals(STATE, record.getStatus()); assertEquals(COMPILE_INFO, record.getCompileInfo()); assertEquals(VERSION, record.getVersion()); StateStoreVersion version = record.getStateStoreVersion(); assertEquals(FILE_RESOLVER_VERSION, version.getMountTableVersion()); } @Test public void testGetterSetter() throws IOException { RouterState record = generateRecord(); validateRecord(record); } @Test public void testSerialization() throws IOException { RouterState record = generateRecord(); StateStoreSerializer serializer = StateStoreSerializer.getSerializer(); String serializedString = serializer.serializeString(record); RouterState newRecord = serializer.deserialize(serializedString, RouterState.class); validateRecord(newRecord); } @Test public void testStateStoreResilience() throws Exception { StateStoreService service = new StateStoreService(); Configuration conf = new Configuration(); conf.setClass(RBFConfigKeys.FEDERATION_STORE_DRIVER_CLASS, MockStateStoreDriver.class, StateStoreDriver.class); conf.setBoolean(RBFConfigKeys.DFS_ROUTER_METRICS_ENABLE, false); service.init(conf); MockStateStoreDriver driver = (MockStateStoreDriver) service.getDriver(); driver.clearAll(); // Add two records for block1 driver.put(MembershipState.newInstance("routerId", "ns1", "ns1-ha1", "cluster1", "block1", "rpc1", "service1", "lifeline1", "https", "nn01", FederationNamenodeServiceState.ACTIVE, false), false, false); driver.put(MembershipState.newInstance("routerId", "ns1", "ns1-ha2", "cluster1", "block1", "rpc2", "service2", "lifeline2", "https", "nn02", FederationNamenodeServiceState.STANDBY, false), false, false); // load the cache service.loadDriver(); MembershipNamenodeResolver resolver = new MembershipNamenodeResolver(conf, service); service.refreshCaches(true); // look up block1 List<? extends FederationNamenodeContext> result = resolver.getNamenodesForBlockPoolId("block1"); assertEquals(2, result.size()); // cause io errors and then reload the cache driver.setGiveErrors(true); long previousUpdate = service.getCacheUpdateTime(); service.refreshCaches(true); assertEquals(previousUpdate, service.getCacheUpdateTime()); // make sure the old cache is still there result = resolver.getNamenodesForBlockPoolId("block1"); assertEquals(2, result.size()); service.stop(); } }
TestRouterState
java
google__guava
android/guava/src/com/google/common/collect/EmptyImmutableSetMultimap.java
{ "start": 950, "end": 1271 }
class ____ extends ImmutableSetMultimap<Object, Object> { static final EmptyImmutableSetMultimap INSTANCE = new EmptyImmutableSetMultimap(); private EmptyImmutableSetMultimap() { super(ImmutableMap.of(), 0, null); } /* * TODO(b/242884182): Figure out why this helps produce the same
EmptyImmutableSetMultimap
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UndefinedEqualsTest.java
{ "start": 14492, "end": 14933 }
class ____ { void f(PriorityQueue a, PriorityQueue b) { a.equals(b); } } """) .doTest(); } @Test public void charSequenceFix() { BugCheckerRefactoringTestHelper.newInstance(UndefinedEquals.class, getClass()) .addInputLines( "Test.java", """ import static com.google.common.truth.Truth.assertThat;
Test
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MinioComponentBuilderFactory.java
{ "start": 31267, "end": 38978 }
class ____ extends AbstractComponentBuilder<MinioComponent> implements MinioComponentBuilder { @Override protected MinioComponent buildConcreteComponent() { return new MinioComponent(); } private org.apache.camel.component.minio.MinioConfiguration getOrCreateConfiguration(MinioComponent component) { if (component.getConfiguration() == null) { component.setConfiguration(new org.apache.camel.component.minio.MinioConfiguration()); } return component.getConfiguration(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "autoCreateBucket": getOrCreateConfiguration((MinioComponent) component).setAutoCreateBucket((boolean) value); return true; case "configuration": ((MinioComponent) component).setConfiguration((org.apache.camel.component.minio.MinioConfiguration) value); return true; case "endpoint": getOrCreateConfiguration((MinioComponent) component).setEndpoint((java.lang.String) value); return true; case "minioClient": getOrCreateConfiguration((MinioComponent) component).setMinioClient((io.minio.MinioClient) value); return true; case "objectLock": getOrCreateConfiguration((MinioComponent) component).setObjectLock((boolean) value); return true; case "policy": getOrCreateConfiguration((MinioComponent) component).setPolicy((java.lang.String) value); return true; case "proxyPort": getOrCreateConfiguration((MinioComponent) component).setProxyPort((java.lang.Integer) value); return true; case "region": getOrCreateConfiguration((MinioComponent) component).setRegion((java.lang.String) value); return true; case "secure": getOrCreateConfiguration((MinioComponent) component).setSecure((boolean) value); return true; case "autoCloseBody": getOrCreateConfiguration((MinioComponent) component).setAutoCloseBody((boolean) value); return true; case "bridgeErrorHandler": ((MinioComponent) component).setBridgeErrorHandler((boolean) value); return true; case "bypassGovernanceMode": getOrCreateConfiguration((MinioComponent) component).setBypassGovernanceMode((boolean) value); return true; case "deleteAfterRead": getOrCreateConfiguration((MinioComponent) component).setDeleteAfterRead((boolean) value); return true; case "delimiter": getOrCreateConfiguration((MinioComponent) component).setDelimiter((java.lang.String) value); return true; case "destinationBucketName": getOrCreateConfiguration((MinioComponent) component).setDestinationBucketName((java.lang.String) value); return true; case "destinationObjectName": getOrCreateConfiguration((MinioComponent) component).setDestinationObjectName((java.lang.String) value); return true; case "includeBody": getOrCreateConfiguration((MinioComponent) component).setIncludeBody((boolean) value); return true; case "includeFolders": getOrCreateConfiguration((MinioComponent) component).setIncludeFolders((boolean) value); return true; case "includeUserMetadata": getOrCreateConfiguration((MinioComponent) component).setIncludeUserMetadata((boolean) value); return true; case "includeVersions": getOrCreateConfiguration((MinioComponent) component).setIncludeVersions((boolean) value); return true; case "length": getOrCreateConfiguration((MinioComponent) component).setLength((long) value); return true; case "matchETag": getOrCreateConfiguration((MinioComponent) component).setMatchETag((java.lang.String) value); return true; case "maxConnections": getOrCreateConfiguration((MinioComponent) component).setMaxConnections((int) value); return true; case "maxMessagesPerPoll": getOrCreateConfiguration((MinioComponent) component).setMaxMessagesPerPoll((int) value); return true; case "modifiedSince": getOrCreateConfiguration((MinioComponent) component).setModifiedSince((java.time.ZonedDateTime) value); return true; case "moveAfterRead": getOrCreateConfiguration((MinioComponent) component).setMoveAfterRead((boolean) value); return true; case "notMatchETag": getOrCreateConfiguration((MinioComponent) component).setNotMatchETag((java.lang.String) value); return true; case "objectName": getOrCreateConfiguration((MinioComponent) component).setObjectName((java.lang.String) value); return true; case "offset": getOrCreateConfiguration((MinioComponent) component).setOffset((long) value); return true; case "prefix": getOrCreateConfiguration((MinioComponent) component).setPrefix((java.lang.String) value); return true; case "recursive": getOrCreateConfiguration((MinioComponent) component).setRecursive((boolean) value); return true; case "startAfter": getOrCreateConfiguration((MinioComponent) component).setStartAfter((java.lang.String) value); return true; case "unModifiedSince": getOrCreateConfiguration((MinioComponent) component).setUnModifiedSince((java.time.ZonedDateTime) value); return true; case "useVersion1": getOrCreateConfiguration((MinioComponent) component).setUseVersion1((boolean) value); return true; case "versionId": getOrCreateConfiguration((MinioComponent) component).setVersionId((java.lang.String) value); return true; case "deleteAfterWrite": getOrCreateConfiguration((MinioComponent) component).setDeleteAfterWrite((boolean) value); return true; case "keyName": getOrCreateConfiguration((MinioComponent) component).setKeyName((java.lang.String) value); return true; case "lazyStartProducer": ((MinioComponent) component).setLazyStartProducer((boolean) value); return true; case "operation": getOrCreateConfiguration((MinioComponent) component).setOperation((org.apache.camel.component.minio.MinioOperations) value); return true; case "pojoRequest": getOrCreateConfiguration((MinioComponent) component).setPojoRequest((boolean) value); return true; case "storageClass": getOrCreateConfiguration((MinioComponent) component).setStorageClass((java.lang.String) value); return true; case "autowiredEnabled": ((MinioComponent) component).setAutowiredEnabled((boolean) value); return true; case "customHttpClient": getOrCreateConfiguration((MinioComponent) component).setCustomHttpClient((okhttp3.OkHttpClient) value); return true; case "healthCheckConsumerEnabled": ((MinioComponent) component).setHealthCheckConsumerEnabled((boolean) value); return true; case "healthCheckProducerEnabled": ((MinioComponent) component).setHealthCheckProducerEnabled((boolean) value); return true; case "accessKey": getOrCreateConfiguration((MinioComponent) component).setAccessKey((java.lang.String) value); return true; case "secretKey": getOrCreateConfiguration((MinioComponent) component).setSecretKey((java.lang.String) value); return true; case "serverSideEncryption": getOrCreateConfiguration((MinioComponent) component).setServerSideEncryption((io.minio.ServerSideEncryption) value); return true; case "serverSideEncryptionCustomerKey": getOrCreateConfiguration((MinioComponent) component).setServerSideEncryptionCustomerKey((io.minio.ServerSideEncryptionCustomerKey) value); return true; default: return false; } } } }
MinioComponentBuilderImpl
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java
{ "start": 1584, "end": 15876 }
class ____ { /** * The UTC time zone (often referred to as GMT). * This is private as it is mutable. */ private static final TimeZone UTC_TIME_ZONE = FastTimeZone.getGmtTimeZone(); /** * ISO 8601 formatter for date-time without time zone. * * <p> * The format used is {@code yyyy-MM-dd'T'HH:mm:ss}. This format uses the * default TimeZone in effect at the time of loading DateFormatUtils class. * </p> * * @since 3.5 */ public static final FastDateFormat ISO_8601_EXTENDED_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); /** * @deprecated - as of 4.0, ISO_DATETIME_FORMAT will be replaced by ISO_8601_EXTENDED_DATETIME_FORMAT. */ @Deprecated public static final FastDateFormat ISO_DATETIME_FORMAT = ISO_8601_EXTENDED_DATETIME_FORMAT; /** * ISO 8601 formatter for date-time with time zone. * * <p> * The format used is {@code yyyy-MM-dd'T'HH:mm:ssZZ}. This format uses the * default TimeZone in effect at the time of loading DateFormatUtils class. * </p> * * @since 3.5 */ public static final FastDateFormat ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZZ"); /** * @deprecated - as of 4.0, ISO_DATETIME_TIME_ZONE_FORMAT will be replaced by ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT. */ @Deprecated public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT = ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT; /** * ISO 8601 formatter for date without time zone. * * <p> * The format used is {@code yyyy-MM-dd}. This format uses the * default TimeZone in effect at the time of loading DateFormatUtils class. * </p> * * @since 3.5 */ public static final FastDateFormat ISO_8601_EXTENDED_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd"); /** * @deprecated - as of 4.0, ISO_DATE_FORMAT will be replaced by ISO_8601_EXTENDED_DATE_FORMAT. */ @Deprecated public static final FastDateFormat ISO_DATE_FORMAT = ISO_8601_EXTENDED_DATE_FORMAT; /** * ISO 8601-like formatter for date with time zone. * * <p> * The format used is {@code yyyy-MM-ddZZ}. This pattern does not comply * with the formal ISO 8601 specification as the standard does not allow * a time zone without a time. This format uses the default TimeZone in * effect at the time of loading DateFormatUtils class. * </p> * * @deprecated - as of 4.0, ISO_DATE_TIME_ZONE_FORMAT will be removed. */ @Deprecated public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-ddZZ"); /** * Non-compliant formatter for time without time zone (ISO 8601 does not * prefix 'T' for standalone time value). * * <p> * The format used is {@code 'T'HH:mm:ss}. This format uses the default * TimeZone in effect at the time of loading DateFormatUtils class. * </p> * * @deprecated - as of 4.0, ISO_TIME_FORMAT will be removed. */ @Deprecated public static final FastDateFormat ISO_TIME_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ss"); /** * Non-compliant formatter for time with time zone (ISO 8601 does not * prefix 'T' for standalone time value). * * <p> * The format used is {@code 'T'HH:mm:ssZZ}. This format uses the default * TimeZone in effect at the time of loading DateFormatUtils class. * </p> * * @deprecated - as of 4.0, ISO_TIME_TIME_ZONE_FORMAT will be removed. */ @Deprecated public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ssZZ"); /** * ISO 8601 formatter for time without time zone. * * <p> * The format used is {@code HH:mm:ss}. This format uses the default * TimeZone in effect at the time of loading DateFormatUtils class. * </p> * * @since 3.5 */ public static final FastDateFormat ISO_8601_EXTENDED_TIME_FORMAT = FastDateFormat.getInstance("HH:mm:ss"); /** * @deprecated - as of 4.0, ISO_TIME_NO_T_FORMAT will be replaced by ISO_8601_EXTENDED_TIME_FORMAT. */ @Deprecated public static final FastDateFormat ISO_TIME_NO_T_FORMAT = ISO_8601_EXTENDED_TIME_FORMAT; /** * ISO 8601 formatter for time with time zone. * * <p> * The format used is {@code HH:mm:ssZZ}. This format uses the default * TimeZone in effect at the time of loading DateFormatUtils class. * </p> * * @since 3.5 */ public static final FastDateFormat ISO_8601_EXTENDED_TIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("HH:mm:ssZZ"); /** * @deprecated - as of 4.0, ISO_TIME_NO_T_TIME_ZONE_FORMAT will be replaced by ISO_8601_EXTENDED_TIME_TIME_ZONE_FORMAT. */ @Deprecated public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT = ISO_8601_EXTENDED_TIME_TIME_ZONE_FORMAT; /** * SMTP (and probably other) date headers. * * <p> * The format used is {@code EEE, dd MMM yyyy HH:mm:ss Z} in US locale. * This format uses the default TimeZone in effect at the time of loading * DateFormatUtils class. * </p> */ public static final FastDateFormat SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); /** * Formats a calendar into a specific pattern. The TimeZone from the calendar * will be used for formatting. * * @param calendar the calendar to format, not null. * @param pattern the pattern to use to format the calendar, not null. * @return the formatted calendar. * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(final Calendar calendar, final String pattern) { return format(calendar, pattern, getTimeZone(calendar), null); } /** * Formats a calendar into a specific pattern in a locale. The TimeZone from the calendar * will be used for formatting. * * @param calendar the calendar to format, not null. * @param pattern the pattern to use to format the calendar, not null. * @param locale the locale to use, may be {@code null}. * @return the formatted calendar. * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(final Calendar calendar, final String pattern, final Locale locale) { return format(calendar, pattern, getTimeZone(calendar), locale); } /** * Formats a calendar into a specific pattern in a time zone. * * @param calendar the calendar to format, not null. * @param pattern the pattern to use to format the calendar, not null. * @param timeZone the time zone to use, may be {@code null}. * @return the formatted calendar. * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(final Calendar calendar, final String pattern, final TimeZone timeZone) { return format(calendar, pattern, timeZone, null); } /** * Formats a calendar into a specific pattern in a time zone and locale. * * @param calendar the calendar to format, not null. * @param pattern the pattern to use to format the calendar, not null. * @param timeZone the time zone to use, may be {@code null}. * @param locale the locale to use, may be {@code null}. * @return the formatted calendar. * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(final Calendar calendar, final String pattern, final TimeZone timeZone, final Locale locale) { final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); return df.format(calendar); } /** * Formats a date/time into a specific pattern. * * @param date the date to format, not null. * @param pattern the pattern to use to format the date, not null. * @return the formatted date. */ public static String format(final Date date, final String pattern) { return format(date, pattern, null, null); } /** * Formats a date/time into a specific pattern in a locale. * * @param date the date to format, not null. * @param pattern the pattern to use to format the date, not null. * @param locale the locale to use, may be {@code null}. * @return the formatted date. */ public static String format(final Date date, final String pattern, final Locale locale) { return format(date, pattern, null, locale); } /** * Formats a date/time into a specific pattern in a time zone. * * @param date the date to format, not null. * @param pattern the pattern to use to format the date, not null. * @param timeZone the time zone to use, may be {@code null}. * @return the formatted date. */ public static String format(final Date date, final String pattern, final TimeZone timeZone) { return format(date, pattern, timeZone, null); } /** * Formats a date/time into a specific pattern in a time zone and locale. * * @param date the date to format, not null. * @param pattern the pattern to use to format the date, not null, not null. * @param timeZone the time zone to use, may be {@code null}. * @param locale the locale to use, may be {@code null}. * @return the formatted date. */ public static String format(final Date date, final String pattern, final TimeZone timeZone, final Locale locale) { final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); return df.format(date); } /** * Formats a date/time into a specific pattern. * * @param millis the date to format expressed in milliseconds. * @param pattern the pattern to use to format the date, not null. * @return the formatted date. */ public static String format(final long millis, final String pattern) { return format(new Date(millis), pattern, null, null); } /** * Formats a date/time into a specific pattern in a locale. * * @param millis the date to format expressed in milliseconds. * @param pattern the pattern to use to format the date, not null. * @param locale the locale to use, may be {@code null}. * @return the formatted date. */ public static String format(final long millis, final String pattern, final Locale locale) { return format(new Date(millis), pattern, null, locale); } /** * Formats a date/time into a specific pattern in a time zone. * * @param millis the time expressed in milliseconds. * @param pattern the pattern to use to format the date, not null. * @param timeZone the time zone to use, may be {@code null}. * @return the formatted date. */ public static String format(final long millis, final String pattern, final TimeZone timeZone) { return format(new Date(millis), pattern, timeZone, null); } /** * Formats a date/time into a specific pattern in a time zone and locale. * * @param millis the date to format expressed in milliseconds. * @param pattern the pattern to use to format the date, not null. * @param timeZone the time zone to use, may be {@code null}. * @param locale the locale to use, may be {@code null}. * @return the formatted date. */ public static String format(final long millis, final String pattern, final TimeZone timeZone, final Locale locale) { return format(new Date(millis), pattern, timeZone, locale); } /** * Formats a date/time into a specific pattern using the UTC time zone. * * @param date the date to format, not null. * @param pattern the pattern to use to format the date, not null. * @return the formatted date. */ public static String formatUTC(final Date date, final String pattern) { return format(date, pattern, UTC_TIME_ZONE, null); } /** * Formats a date/time into a specific pattern using the UTC time zone. * * @param date the date to format, not null. * @param pattern the pattern to use to format the date, not null. * @param locale the locale to use, may be {@code null}. * @return the formatted date. */ public static String formatUTC(final Date date, final String pattern, final Locale locale) { return format(date, pattern, UTC_TIME_ZONE, locale); } /** * Formats a date/time into a specific pattern using the UTC time zone. * * @param millis the date to format expressed in milliseconds. * @param pattern the pattern to use to format the date, not null. * @return the formatted date. */ public static String formatUTC(final long millis, final String pattern) { return format(new Date(millis), pattern, UTC_TIME_ZONE, null); } /** * Formats a date/time into a specific pattern using the UTC time zone. * * @param millis the date to format expressed in milliseconds. * @param pattern the pattern to use to format the date, not null. * @param locale the locale to use, may be {@code null}. * @return the formatted date. */ public static String formatUTC(final long millis, final String pattern, final Locale locale) { return format(new Date(millis), pattern, UTC_TIME_ZONE, locale); } private static TimeZone getTimeZone(final Calendar calendar) { return calendar == null ? null : calendar.getTimeZone(); } /** * DateFormatUtils instances should NOT be constructed in standard programming. * * <p>This constructor is public to permit tools that require a JavaBean instance * to operate.</p> * * @deprecated TODO Make private in 4.0. */ @Deprecated public DateFormatUtils() { // empty } }
DateFormatUtils
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/authentication/AuthenticationManagerFactoryBean.java
{ "start": 1887, "end": 3912 }
class ____ implements FactoryBean<AuthenticationManager>, BeanFactoryAware { private BeanFactory bf; private ObservationRegistry observationRegistry = ObservationRegistry.NOOP; public static final String MISSING_BEAN_ERROR_MESSAGE = "Did you forget to add a global <authentication-manager> element " + "to your configuration (with child <authentication-provider> elements)? Alternatively you can use the " + "authentication-manager-ref attribute on your <http> and <global-method-security> elements."; @Override public AuthenticationManager getObject() throws Exception { try { return (AuthenticationManager) this.bf.getBean(BeanIds.AUTHENTICATION_MANAGER); } catch (NoSuchBeanDefinitionException ex) { if (!BeanIds.AUTHENTICATION_MANAGER.equals(ex.getBeanName())) { throw ex; } UserDetailsService uds = this.bf.getBeanProvider(UserDetailsService.class).getIfUnique(); if (uds == null) { throw new NoSuchBeanDefinitionException(BeanIds.AUTHENTICATION_MANAGER, MISSING_BEAN_ERROR_MESSAGE); } DaoAuthenticationProvider provider = new DaoAuthenticationProvider(uds); PasswordEncoder passwordEncoder = this.bf.getBeanProvider(PasswordEncoder.class).getIfUnique(); if (passwordEncoder != null) { provider.setPasswordEncoder(passwordEncoder); } provider.afterPropertiesSet(); ProviderManager manager = new ProviderManager(Arrays.asList(provider)); if (this.observationRegistry.isNoop()) { return manager; } return new ObservationAuthenticationManager(this.observationRegistry, manager); } } @Override public Class<? extends AuthenticationManager> getObjectType() { return ProviderManager.class; } @Override public boolean isSingleton() { return true; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.bf = beanFactory; } public void setObservationRegistry(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } }
AuthenticationManagerFactoryBean
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
{ "start": 66351, "end": 66517 }
interface ____ { String pattern(); } /** * Mock of {@code org.springframework.context.annotation.ComponentScan}. */ @Retention(RetentionPolicy.RUNTIME) @
Filter
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/mapping/KeyValue.java
{ "start": 576, "end": 797 }
interface ____ extends Value { ForeignKey createForeignKeyOfEntity(String entityName, List<Column> referencedColumns); ForeignKey createForeignKeyOfEntity(String entityName); boolean isCascadeDeleteEnabled();
KeyValue
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
{ "start": 3286, "end": 5417 }
class ____ extends PatternStrategy { private final int field; private final Locale locale; private final Map<String, Integer> lKeyValues; /** * Constructs a Strategy that parses a Text field * * @param field The Calendar field * @param definingCalendar The Calendar to use * @param locale The Locale to use */ CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) { this.field = field; this.locale = LocaleUtils.toLocale(locale); final StringBuilder regex = new StringBuilder(); regex.append("((?iu)"); lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex); regex.setLength(regex.length() - 1); regex.append(")"); createPattern(regex); } /** * {@inheritDoc} */ @Override void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) { final String lowerCase = value.toLowerCase(locale); Integer iVal = lKeyValues.get(lowerCase); if (iVal == null) { // match missing the optional trailing period iVal = lKeyValues.get(lowerCase + '.'); } // LANG-1669: Mimic fix done in OpenJDK 17 to resolve issue with parsing newly supported day periods added in OpenJDK 16 if (Calendar.AM_PM != this.field || iVal <= 1) { calendar.set(field, iVal.intValue()); } } /** * Converts this instance to a handy debug string. * * @since 3.12.0 */ @Override public String toString() { return "CaseInsensitiveTextStrategy [field=" + field + ", locale=" + locale + ", lKeyValues=" + lKeyValues + ", pattern=" + pattern + "]"; } } /** * A strategy that copies the static or quoted field in the parsing pattern */ private static final
CaseInsensitiveTextStrategy
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/TimestampUtcAsJdbcTimestampJdbcType.java
{ "start": 933, "end": 3819 }
class ____ implements JdbcType { public static final TimestampUtcAsJdbcTimestampJdbcType INSTANCE = new TimestampUtcAsJdbcTimestampJdbcType(); private static final Calendar UTC_CALENDAR = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); public TimestampUtcAsJdbcTimestampJdbcType() { } @Override public int getJdbcTypeCode() { return Types.TIMESTAMP; } @Override public int getDefaultSqlTypeCode() { return SqlTypes.TIMESTAMP_UTC; } @Override public String getFriendlyName() { return "TIMESTAMP_UTC"; } @Override public String toString() { return "TimestampUtcDescriptor"; } @Override public <T> JavaType<T> getJdbcRecommendedJavaTypeMapping( Integer length, Integer scale, TypeConfiguration typeConfiguration) { return typeConfiguration.getJavaTypeRegistry().getDescriptor( Instant.class ); } @Override public Class<?> getPreferredJavaTypeClass(WrapperOptions options) { return Instant.class; } @Override public <T> JdbcLiteralFormatter<T> getJdbcLiteralFormatter(JavaType<T> javaType) { return new JdbcLiteralFormatterTemporal<>( javaType, TemporalType.TIMESTAMP ); } @Override public <X> ValueBinder<X> getBinder(final JavaType<X> javaType) { return new BasicBinder<>( javaType, this ) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { final Instant instant = javaType.unwrap( value, Instant.class, options ); st.setTimestamp( index, Timestamp.from( instant ), UTC_CALENDAR ); } @Override protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException { final Instant instant = javaType.unwrap( value, Instant.class, options ); st.setTimestamp( name, Timestamp.from( instant ), UTC_CALENDAR ); } }; } @Override public <X> ValueExtractor<X> getExtractor(final JavaType<X> javaType) { return new BasicExtractor<>( javaType, this ) { @Override protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException { final Timestamp timestamp = rs.getTimestamp( paramIndex, UTC_CALENDAR ); return javaType.wrap( timestamp == null ? null : timestamp.toInstant(), options ); } @Override protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { final Timestamp timestamp = statement.getTimestamp( index, UTC_CALENDAR ); return javaType.wrap( timestamp == null ? null : timestamp.toInstant(), options ); } @Override protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { final Timestamp timestamp = statement.getTimestamp( name, UTC_CALENDAR ); return javaType.wrap( timestamp == null ? null : timestamp.toInstant(), options ); } }; } }
TimestampUtcAsJdbcTimestampJdbcType
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/ManagedChannelImplBuilder.java
{ "start": 8669, "end": 29027 }
class ____ implements ChannelBuilderDefaultPortProvider { @Override public int getDefaultPort() { return GrpcUtil.DEFAULT_PORT_SSL; } } private final ClientTransportFactoryBuilder clientTransportFactoryBuilder; private final ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider; /** * Creates a new managed channel builder with a target string, which can be either a valid {@link * io.grpc.NameResolver}-compliant URI, or an authority string. Transport implementors must * provide client transport factory builder, and may set custom channel default port provider. */ public ManagedChannelImplBuilder(String target, ClientTransportFactoryBuilder clientTransportFactoryBuilder, @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) { this(target, null, null, clientTransportFactoryBuilder, channelBuilderDefaultPortProvider); } /** * Creates a new managed channel builder with a target string, which can be either a valid {@link * io.grpc.NameResolver}-compliant URI, or an authority string. Transport implementors must * provide client transport factory builder, and may set custom channel default port provider. * * @param channelCreds The ChannelCredentials provided by the user. These may be used when * creating derivative channels. */ public ManagedChannelImplBuilder( String target, @Nullable ChannelCredentials channelCreds, @Nullable CallCredentials callCreds, ClientTransportFactoryBuilder clientTransportFactoryBuilder, @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) { this.target = checkNotNull(target, "target"); this.channelCredentials = channelCreds; this.callCredentials = callCreds; this.clientTransportFactoryBuilder = checkNotNull(clientTransportFactoryBuilder, "clientTransportFactoryBuilder"); this.directServerAddress = null; if (channelBuilderDefaultPortProvider != null) { this.channelBuilderDefaultPortProvider = channelBuilderDefaultPortProvider; } else { this.channelBuilderDefaultPortProvider = new ManagedChannelDefaultPortProvider(); } // TODO(dnvindhya): Move configurator to all the individual builders InternalConfiguratorRegistry.configureChannelBuilder(this); } /** * Returns a target string for the SocketAddress. It is only used as a placeholder, because * DirectAddressNameResolverProvider will not actually try to use it. However, it must be a valid * URI. */ @VisibleForTesting static String makeTargetStringForDirectAddress(SocketAddress address) { try { return new URI(DIRECT_ADDRESS_SCHEME, "", "/" + address, null).toString(); } catch (URISyntaxException e) { // It should not happen. throw new RuntimeException(e); } } /** * Creates a new managed channel builder with the given server address, authority string of the * channel. Transport implementors must provide client transport factory builder, and may set * custom channel default port provider. */ public ManagedChannelImplBuilder(SocketAddress directServerAddress, String authority, ClientTransportFactoryBuilder clientTransportFactoryBuilder, @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) { this(directServerAddress, authority, null, null, clientTransportFactoryBuilder, channelBuilderDefaultPortProvider); } /** * Creates a new managed channel builder with the given server address, authority string of the * channel. Transport implementors must provide client transport factory builder, and may set * custom channel default port provider. * * @param channelCreds The ChannelCredentials provided by the user. These may be used when * creating derivative channels. */ public ManagedChannelImplBuilder(SocketAddress directServerAddress, String authority, @Nullable ChannelCredentials channelCreds, @Nullable CallCredentials callCreds, ClientTransportFactoryBuilder clientTransportFactoryBuilder, @Nullable ChannelBuilderDefaultPortProvider channelBuilderDefaultPortProvider) { this.target = makeTargetStringForDirectAddress(directServerAddress); this.channelCredentials = channelCreds; this.callCredentials = callCreds; this.clientTransportFactoryBuilder = checkNotNull(clientTransportFactoryBuilder, "clientTransportFactoryBuilder"); this.directServerAddress = directServerAddress; NameResolverRegistry reg = new NameResolverRegistry(); reg.register(new DirectAddressNameResolverProvider(directServerAddress, authority)); this.nameResolverRegistry = reg; if (channelBuilderDefaultPortProvider != null) { this.channelBuilderDefaultPortProvider = channelBuilderDefaultPortProvider; } else { this.channelBuilderDefaultPortProvider = new ManagedChannelDefaultPortProvider(); } // TODO(dnvindhya): Move configurator to all the individual builders InternalConfiguratorRegistry.configureChannelBuilder(this); } @Override public ManagedChannelImplBuilder directExecutor() { return executor(MoreExecutors.directExecutor()); } @Override public ManagedChannelImplBuilder executor(Executor executor) { if (executor != null) { this.executorPool = new FixedObjectPool<>(executor); } else { this.executorPool = DEFAULT_EXECUTOR_POOL; } return this; } @Override public ManagedChannelImplBuilder offloadExecutor(Executor executor) { if (executor != null) { this.offloadExecutorPool = new FixedObjectPool<>(executor); } else { this.offloadExecutorPool = DEFAULT_EXECUTOR_POOL; } return this; } @Override public ManagedChannelImplBuilder intercept(List<ClientInterceptor> interceptors) { this.interceptors.addAll(interceptors); return this; } @Override public ManagedChannelImplBuilder intercept(ClientInterceptor... interceptors) { return intercept(Arrays.asList(interceptors)); } @Override protected ManagedChannelImplBuilder interceptWithTarget(InterceptorFactory factory) { // Add a placeholder instance to the interceptor list, and replace it with a real instance // during build(). this.interceptors.add(new InterceptorFactoryWrapper(factory)); return this; } @Override public ManagedChannelImplBuilder addTransportFilter(ClientTransportFilter hook) { transportFilters.add(checkNotNull(hook, "transport filter")); return this; } @Deprecated @Override public ManagedChannelImplBuilder nameResolverFactory(NameResolver.Factory resolverFactory) { Preconditions.checkState(directServerAddress == null, "directServerAddress is set (%s), which forbids the use of NameResolverFactory", directServerAddress); if (resolverFactory != null) { NameResolverRegistry reg = new NameResolverRegistry(); if (resolverFactory instanceof NameResolverProvider) { reg.register((NameResolverProvider) resolverFactory); } else { reg.register(new NameResolverFactoryToProviderFacade(resolverFactory)); } this.nameResolverRegistry = reg; } else { this.nameResolverRegistry = NameResolverRegistry.getDefaultRegistry(); } return this; } ManagedChannelImplBuilder nameResolverRegistry(NameResolverRegistry resolverRegistry) { this.nameResolverRegistry = resolverRegistry; return this; } @Override public ManagedChannelImplBuilder defaultLoadBalancingPolicy(String policy) { Preconditions.checkState(directServerAddress == null, "directServerAddress is set (%s), which forbids the use of load-balancing policy", directServerAddress); Preconditions.checkArgument(policy != null, "policy cannot be null"); this.defaultLbPolicy = policy; return this; } @Override public ManagedChannelImplBuilder decompressorRegistry(DecompressorRegistry registry) { if (registry != null) { this.decompressorRegistry = registry; } else { this.decompressorRegistry = DEFAULT_DECOMPRESSOR_REGISTRY; } return this; } @Override public ManagedChannelImplBuilder compressorRegistry(CompressorRegistry registry) { if (registry != null) { this.compressorRegistry = registry; } else { this.compressorRegistry = DEFAULT_COMPRESSOR_REGISTRY; } return this; } @Override public ManagedChannelImplBuilder userAgent(@Nullable String userAgent) { this.userAgent = userAgent; return this; } @Override public ManagedChannelImplBuilder overrideAuthority(String authority) { this.authorityOverride = checkAuthority(authority); return this; } @Override public ManagedChannelImplBuilder idleTimeout(long value, TimeUnit unit) { checkArgument(value > 0, "idle timeout is %s, but must be positive", value); // We convert to the largest unit to avoid overflow if (unit.toDays(value) >= IDLE_MODE_MAX_TIMEOUT_DAYS) { // This disables idle mode this.idleTimeoutMillis = ManagedChannelImpl.IDLE_TIMEOUT_MILLIS_DISABLE; } else { this.idleTimeoutMillis = Math.max(unit.toMillis(value), IDLE_MODE_MIN_TIMEOUT_MILLIS); } return this; } @Override public ManagedChannelImplBuilder maxRetryAttempts(int maxRetryAttempts) { this.maxRetryAttempts = maxRetryAttempts; return this; } @Override public ManagedChannelImplBuilder maxHedgedAttempts(int maxHedgedAttempts) { this.maxHedgedAttempts = maxHedgedAttempts; return this; } @Override public ManagedChannelImplBuilder retryBufferSize(long bytes) { checkArgument(bytes > 0L, "retry buffer size must be positive"); retryBufferSize = bytes; return this; } @Override public ManagedChannelImplBuilder perRpcBufferLimit(long bytes) { checkArgument(bytes > 0L, "per RPC buffer limit must be positive"); perRpcBufferLimit = bytes; return this; } @Override public ManagedChannelImplBuilder disableRetry() { retryEnabled = false; return this; } @Override public ManagedChannelImplBuilder enableRetry() { retryEnabled = true; return this; } @Override public ManagedChannelImplBuilder setBinaryLog(BinaryLog binlog) { this.binlog = binlog; return this; } @Override public ManagedChannelImplBuilder maxTraceEvents(int maxTraceEvents) { checkArgument(maxTraceEvents >= 0, "maxTraceEvents must be non-negative"); this.maxTraceEvents = maxTraceEvents; return this; } @Override public ManagedChannelImplBuilder proxyDetector(@Nullable ProxyDetector proxyDetector) { this.proxyDetector = proxyDetector; return this; } @Override public ManagedChannelImplBuilder defaultServiceConfig(@Nullable Map<String, ?> serviceConfig) { // TODO(notcarl): use real parsing defaultServiceConfig = checkMapEntryTypes(serviceConfig); return this; } @Nullable private static Map<String, ?> checkMapEntryTypes(@Nullable Map<?, ?> map) { if (map == null) { return null; } // Not using ImmutableMap.Builder because of extra guava dependency for Android. Map<String, Object> parsedMap = new LinkedHashMap<>(); for (Map.Entry<?, ?> entry : map.entrySet()) { checkArgument( entry.getKey() instanceof String, "The key of the entry '%s' is not of String type", entry); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value == null) { parsedMap.put(key, null); } else if (value instanceof Map) { parsedMap.put(key, checkMapEntryTypes((Map<?, ?>) value)); } else if (value instanceof List) { parsedMap.put(key, checkListEntryTypes((List<?>) value)); } else if (value instanceof String) { parsedMap.put(key, value); } else if (value instanceof Double) { parsedMap.put(key, value); } else if (value instanceof Boolean) { parsedMap.put(key, value); } else { throw new IllegalArgumentException( "The value of the map entry '" + entry + "' is of type '" + value.getClass() + "', which is not supported"); } } return Collections.unmodifiableMap(parsedMap); } private static List<?> checkListEntryTypes(List<?> list) { List<Object> parsedList = new ArrayList<>(list.size()); for (Object value : list) { if (value == null) { parsedList.add(null); } else if (value instanceof Map) { parsedList.add(checkMapEntryTypes((Map<?, ?>) value)); } else if (value instanceof List) { parsedList.add(checkListEntryTypes((List<?>) value)); } else if (value instanceof String) { parsedList.add(value); } else if (value instanceof Double) { parsedList.add(value); } else if (value instanceof Boolean) { parsedList.add(value); } else { throw new IllegalArgumentException( "The entry '" + value + "' is of type '" + value.getClass() + "', which is not supported"); } } return Collections.unmodifiableList(parsedList); } @Override public <X> ManagedChannelImplBuilder setNameResolverArg(NameResolver.Args.Key<X> key, X value) { if (nameResolverCustomArgs == null) { nameResolverCustomArgs = new IdentityHashMap<>(); } nameResolverCustomArgs.put(checkNotNull(key, "key"), checkNotNull(value, "value")); return this; } @SuppressWarnings("unchecked") // This cast is safe because of setNameResolverArg()'s signature. void copyAllNameResolverCustomArgsTo(NameResolver.Args.Builder dest) { if (nameResolverCustomArgs != null) { for (Map.Entry<NameResolver.Args.Key<?>, Object> entry : nameResolverCustomArgs.entrySet()) { dest.setArg((NameResolver.Args.Key<Object>) entry.getKey(), entry.getValue()); } } } @Override public ManagedChannelImplBuilder disableServiceConfigLookUp() { this.lookUpServiceConfig = false; return this; } /** * Disable or enable stats features. Enabled by default. * * <p>For the current release, calling {@code setStatsEnabled(true)} may have a side effect that * disables retry. */ public void setStatsEnabled(boolean value) { statsEnabled = value; } /** * Disable or enable stats recording for RPC upstarts. Effective only if {@link * #setStatsEnabled} is set to true. Enabled by default. */ public void setStatsRecordStartedRpcs(boolean value) { recordStartedRpcs = value; } /** * Disable or enable stats recording for RPC completions. Effective only if {@link * #setStatsEnabled} is set to true. Enabled by default. */ public void setStatsRecordFinishedRpcs(boolean value) { recordFinishedRpcs = value; } /** * Disable or enable real-time metrics recording. Effective only if {@link #setStatsEnabled} is * set to true. Disabled by default. */ public void setStatsRecordRealTimeMetrics(boolean value) { recordRealTimeMetrics = value; } public void setStatsRecordRetryMetrics(boolean value) { recordRetryMetrics = value; } /** * Disable or enable tracing features. Enabled by default. */ public void setTracingEnabled(boolean value) { tracingEnabled = value; } /** * Verifies the authority is valid. */ @VisibleForTesting String checkAuthority(String authority) { if (authorityCheckerDisabled) { return authority; } return GrpcUtil.checkAuthority(authority); } /** Disable the check whether the authority is valid. */ public ManagedChannelImplBuilder disableCheckAuthority() { authorityCheckerDisabled = true; return this; } /** Enable previously disabled authority check. */ public ManagedChannelImplBuilder enableCheckAuthority() { authorityCheckerDisabled = false; return this; } @Override protected ManagedChannelImplBuilder addMetricSink(MetricSink metricSink) { metricSinks.add(checkNotNull(metricSink, "metric sink")); return this; } @Override public ManagedChannel build() { ClientTransportFactory clientTransportFactory = clientTransportFactoryBuilder.buildClientTransportFactory(); ResolvedNameResolver resolvedResolver = getNameResolverProvider( target, nameResolverRegistry, clientTransportFactory.getSupportedSocketAddressTypes()); return new ManagedChannelOrphanWrapper(new ManagedChannelImpl( this, clientTransportFactory, resolvedResolver.targetUri, resolvedResolver.provider, new ExponentialBackoffPolicy.Provider(), SharedResourcePool.forResource(GrpcUtil.SHARED_CHANNEL_EXECUTOR), GrpcUtil.STOPWATCH_SUPPLIER, getEffectiveInterceptors(resolvedResolver.targetUri.toString()), TimeProvider.SYSTEM_TIME_PROVIDER)); } // Temporarily disable retry when stats or tracing is enabled to avoid breakage, until we know // what should be the desired behavior for retry + stats/tracing. // TODO(zdapeng): FIX IT @VisibleForTesting List<ClientInterceptor> getEffectiveInterceptors(String computedTarget) { List<ClientInterceptor> effectiveInterceptors = new ArrayList<>(this.interceptors.size()); for (ClientInterceptor interceptor : this.interceptors) { if (interceptor instanceof InterceptorFactoryWrapper) { InterceptorFactory factory = ((InterceptorFactoryWrapper) interceptor).factory; interceptor = factory.newInterceptor(computedTarget); if (interceptor == null) { throw new NullPointerException("Factory returned null interceptor: " + factory); } } effectiveInterceptors.add(interceptor); } boolean disableImplicitCensus = InternalConfiguratorRegistry.wasSetConfiguratorsCalled(); if (disableImplicitCensus) { return effectiveInterceptors; } if (statsEnabled) { ClientInterceptor statsInterceptor = null; if (GET_CLIENT_INTERCEPTOR_METHOD != null) { try { statsInterceptor = (ClientInterceptor) GET_CLIENT_INTERCEPTOR_METHOD .invoke( null, recordStartedRpcs, recordFinishedRpcs, recordRealTimeMetrics, recordRetryMetrics); } catch (IllegalAccessException e) { log.log(Level.FINE, "Unable to apply census stats", e); } catch (InvocationTargetException e) { log.log(Level.FINE, "Unable to apply census stats", e); } } if (statsInterceptor != null) { // First interceptor runs last (see ClientInterceptors.intercept()), so that no // other interceptor can override the tracer factory we set in CallOptions. effectiveInterceptors.add(0, statsInterceptor); } } if (tracingEnabled) { ClientInterceptor tracingInterceptor = null; try { Class<?> censusTracingAccessor = Class.forName("io.grpc.census.InternalCensusTracingAccessor"); Method getClientInterceptroMethod = censusTracingAccessor.getDeclaredMethod("getClientInterceptor"); tracingInterceptor = (ClientInterceptor) getClientInterceptroMethod.invoke(null); } catch (ClassNotFoundException e) { // Replace these separate catch statements with multicatch when Android min-API >= 19 log.log(Level.FINE, "Unable to apply census stats", e); } catch (NoSuchMethodException e) { log.log(Level.FINE, "Unable to apply census stats", e); } catch (IllegalAccessException e) { log.log(Level.FINE, "Unable to apply census stats", e); } catch (InvocationTargetException e) { log.log(Level.FINE, "Unable to apply census stats", e); } if (tracingInterceptor != null) { effectiveInterceptors.add(0, tracingInterceptor); } } return effectiveInterceptors; } /** * Returns a default port to {@link NameResolver} for use in cases where the target string doesn't * include a port. The default implementation returns {@link GrpcUtil#DEFAULT_PORT_SSL}. */ int getDefaultPort() { return channelBuilderDefaultPortProvider.getDefaultPort(); } @VisibleForTesting static
ManagedChannelDefaultPortProvider
java
spring-projects__spring-security
acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
{ "start": 1378, "end": 5307 }
class ____ { private static final Long DEFAULT_IDENTIFIER = 999L; private static final BigInteger BIGINT_IDENTIFIER = new BigInteger("999"); private static final String DEFAULT_IDENTIFIER_AS_STRING = DEFAULT_IDENTIFIER.toString(); @Mock private ResultSet resultSet; @Mock private ConversionService conversionService; private AclClassIdUtils aclClassIdUtils; @BeforeEach public void setUp() { this.aclClassIdUtils = new AclClassIdUtils(); } @Test public void shouldReturnLongIfIdentifierIsLong() throws SQLException { Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfIdentifierIsBigInteger() throws SQLException { Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(BIGINT_IDENTIFIER, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfClassIdTypeIsNull() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn(null); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfNoClassIdTypeColumn() throws SQLException { given(this.resultSet.getString("class_id_type")).willThrow(SQLException.class); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfTypeClassNotFound() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn("com.example.UnknownType"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongEvenIfCustomConversionServiceDoesNotSupportLongConversion() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn("java.lang.Long"); given(this.conversionService.canConvert(String.class, Long.class)).willReturn(false); this.aclClassIdUtils.setConversionService(this.conversionService); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongWhenLongClassIdType() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn("java.lang.Long"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnUUIDWhenUUIDClassIdType() throws SQLException { UUID identifier = UUID.randomUUID(); given(this.resultSet.getString("class_id_type")).willReturn("java.util.UUID"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(identifier.toString(), this.resultSet); assertThat(newIdentifier).isEqualTo(identifier); } @Test public void shouldReturnStringWhenStringClassIdType() throws SQLException { String identifier = "MY_STRING_IDENTIFIER"; given(this.resultSet.getString("class_id_type")).willReturn("java.lang.String"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(identifier, this.resultSet); assertThat(newIdentifier).isEqualTo(identifier); } @Test public void shouldNotAcceptNullConversionServiceInConstruction() { assertThatIllegalArgumentException().isThrownBy(() -> new AclClassIdUtils(null)); } @Test public void shouldNotAcceptNullConversionServiceInSetter() { assertThatIllegalArgumentException().isThrownBy(() -> this.aclClassIdUtils.setConversionService(null)); } }
AclClassIdUtilsTests
java
quarkusio__quarkus
extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiBuildTimeExcludedClassTestCase.java
{ "start": 2619, "end": 2813 }
class ____ { @GET public String endpoint() { return ""; } } @Path("/bar-profile-enabled") @IfBuildProfile("bar") public static
IfBuildProfileTest
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharacterConverter.java
{ "start": 920, "end": 1003 }
class ____ convert {@link String} to {@link Character} * * @since 2.7.6 */ public
to
java
alibaba__nacos
console/src/main/java/com/alibaba/nacos/console/config/ConsoleModuleStateBuilder.java
{ "start": 895, "end": 1498 }
class ____ extends AbstractConsoleModuleStateBuilder { public static final String CONSOLE_MODULE = "console"; private static final String CONSOLE_UI_ENABLED = "console_ui_enabled"; @Override public ModuleState build() { ModuleState result = new ModuleState(CONSOLE_MODULE); try { boolean consoleUiEnabled = EnvUtil.getProperty("nacos.console.ui.enabled", Boolean.class, true); result.newState(CONSOLE_UI_ENABLED, consoleUiEnabled); } catch (Exception ignored) { } return result; } }
ConsoleModuleStateBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/NoDefaultOptimisticLockAnnotationTest.java
{ "start": 660, "end": 1685 }
class ____ { private static SQLStatementInspector statementInspector; private static int consumerId; @BeforeEach public void setUp(EntityManagerFactoryScope scope) { statementInspector = scope.getCollectingStatementInspector(); scope.inTransaction( em -> { Consumer consumer = new Consumer(); em.persist( consumer ); consumerId = consumer.getId(); ConsumerItem item1 = new ConsumerItem(); item1.setConsumer( consumer ); em.persist( item1 ); ConsumerItem item2 = new ConsumerItem(); item2.setConsumer( consumer ); em.persist( item2 ); } ); } @Test void test(EntityManagerFactoryScope scope) { statementInspector.clear(); scope.inTransaction( em -> { Consumer consumer = em.find( Consumer.class, consumerId ); ConsumerItem inventory = new ConsumerItem(); inventory.setConsumer( consumer ); consumer.getConsumerItems().add( inventory ); } ); statementInspector.assertIsInsert( 1 ); statementInspector.assertNoUpdate(); } }
NoDefaultOptimisticLockAnnotationTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/FloatTest.java
{ "start": 143, "end": 2093 }
class ____ extends TestCase { public void test_0() throws Exception { Assert.assertEquals("null", JSON.toJSONString(Float.NaN)); Assert.assertEquals("null", JSON.toJSONString(Double.NaN)); Assert.assertEquals("null", JSON.toJSONString(Float.POSITIVE_INFINITY)); Assert.assertEquals("null", JSON.toJSONString(Float.NEGATIVE_INFINITY)); Assert.assertEquals("null", JSON.toJSONString(Double.NaN)); Assert.assertEquals("null", JSON.toJSONString(Double.POSITIVE_INFINITY)); Assert.assertEquals("null", JSON.toJSONString(Double.NEGATIVE_INFINITY)); Assert.assertEquals("null", JSON.toJSONString(new Float(Float.NaN))); Assert.assertEquals("null", JSON.toJSONString(new Double(Double.NaN))); //Assert.assertEquals("{\"f1\":null,\"f2\":null}", JSON.toJSONString(new Bean())); //Assert.assertEquals("{\"f1\":null,\"f2\":null}", JSON.toJSONString(new Bean(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))); //Assert.assertEquals("{\"f1\":null,\"f2\":null}", JSON.toJSONString(new Bean(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))); Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean())).get("f1")); Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean())).get("f2")); Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))).get("f1")); Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))).get("f2")); Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))).get("f1")); Assert.assertEquals(null, JSON.parseObject(JSON.toJSONString(new Bean(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))).get("f2")); } public static
FloatTest
java
google__error-prone
test_helpers/src/main/java/com/google/errorprone/FileObjects.java
{ "start": 1361, "end": 1663 }
class ____ {@link JavaFileObject}s. */ public static ImmutableList<JavaFileObject> forResources(Class<?> clazz, String... fileNames) { return stream(fileNames) .map(fileName -> forResource(clazz, fileName)) .collect(toImmutableList()); } /** Loads a resource of the provided
into
java
quarkusio__quarkus
extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/JaxRsResourceImplementor.java
{ "start": 1610, "end": 2970 }
class ____ { private static final Logger LOGGER = Logger.getLogger(JaxRsResourceImplementor.class); private static final String OPENAPI_TAG_ANNOTATION = "org.eclipse.microprofile.openapi.annotations.tags.Tag"; private static final String WITH_SESSION_ON_DEMAND_ANNOTATION = "io.quarkus.hibernate.reactive.panache.common.WithSessionOnDemand"; private final List<MethodImplementor> methodImplementors; JaxRsResourceImplementor(Capabilities capabilities) { this.methodImplementors = Arrays.asList(new GetMethodImplementor(capabilities), new ListMethodImplementor(capabilities), new CountMethodImplementor(capabilities), new AddMethodImplementor(capabilities), new UpdateMethodImplementor(capabilities), new DeleteMethodImplementor(capabilities), new UserMethodsWithAnnotationsImplementor(capabilities), // The list hal endpoint needs to be added for both resteasy classic and resteasy reactive // because the pagination links are programmatically added. new ListHalMethodImplementor(capabilities)); } /** * Implement a JAX-RS resource with a following structure. * * <pre> * {@code * &#64;Path("/my-entities') * public
JaxRsResourceImplementor
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/validators/OperatorsAreFinal.java
{ "start": 788, "end": 2902 }
class ____ { File directoryOf(String baseClassName) throws Exception { File f = TestHelper.findSource("Flowable"); if (f == null) { return null; } String parent = f.getParentFile().getParentFile().getAbsolutePath().replace('\\', '/'); if (!parent.endsWith("/")) { parent += "/"; } parent += "internal/operators/" + baseClassName.toLowerCase() + "/"; return new File(parent); } void check(String baseClassName) throws Exception { File f = directoryOf(baseClassName); if (f == null) { return; } StringBuilder e = new StringBuilder(); File[] files = f.listFiles(); if (files != null) { for (File g : files) { if (g.getName().startsWith(baseClassName) && g.getName().endsWith(".java")) { String className = "io.reactivex.rxjava3.internal.operators." + baseClassName.toLowerCase() + "." + g.getName().replace(".java", ""); Class<?> clazz = Class.forName(className); if ((clazz.getModifiers() & Modifier.FINAL) == 0 && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { e.append("java.lang.RuntimeException: ").append(className).append(" is not final\r\n"); e.append(" at ").append(className).append(" (").append(g.getName()).append(":14)\r\n\r\n"); } } } } if (e.length() != 0) { System.out.println(e); throw new AssertionError(e.toString()); } } @Test public void flowable() throws Exception { check("Flowable"); } @Test public void observable() throws Exception { check("Observable"); } @Test public void single() throws Exception { check("Single"); } @Test public void completable() throws Exception { check("Completable"); } @Test public void maybe() throws Exception { check("Maybe"); } }
OperatorsAreFinal
java
spring-projects__spring-security
messaging/src/main/java/org/springframework/security/messaging/util/matcher/OrMessageMatcher.java
{ "start": 960, "end": 1818 }
class ____<T> extends AbstractMessageMatcherComposite<T> { /** * Creates a new instance * @param messageMatchers the {@link MessageMatcher} instances to try */ public OrMessageMatcher(List<MessageMatcher<T>> messageMatchers) { super(messageMatchers); } /** * Creates a new instance * @param messageMatchers the {@link MessageMatcher} instances to try */ @SafeVarargs public OrMessageMatcher(MessageMatcher<T>... messageMatchers) { super(messageMatchers); } @Override public boolean matches(Message<? extends T> message) { for (MessageMatcher<T> matcher : getMessageMatchers()) { this.logger.debug(LogMessage.format("Trying to match using %s", matcher)); if (matcher.matches(message)) { this.logger.debug("matched"); return true; } } this.logger.debug("No matches found"); return false; } }
OrMessageMatcher
java
apache__kafka
storage/src/main/java/org/apache/kafka/storage/internals/log/FetchPartitionStatus.java
{ "start": 927, "end": 1119 }
class ____ log offset metadata and fetch info for a topic partition. */ public record FetchPartitionStatus( LogOffsetMetadata startOffsetMetadata, PartitionData fetchInfo ) { }
containing
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openai/OpenAiStreamingProcessor.java
{ "start": 3667, "end": 7336 }
class ____ extends DelegatingProcessor<Deque<ServerSentEvent>, InferenceServiceResults.Result> { private static final Logger log = LogManager.getLogger(OpenAiStreamingProcessor.class); private static final String FAILED_TO_FIND_FIELD_TEMPLATE = "Failed to find required field [%s] in OpenAI chat completions response"; private static final String CHOICES_FIELD = "choices"; private static final String DELTA_FIELD = "delta"; private static final String CONTENT_FIELD = "content"; private static final String DONE_MESSAGE = "[done]"; @Override protected void next(Deque<ServerSentEvent> item) throws Exception { var parserConfig = XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE); var results = parseEvent(item, OpenAiStreamingProcessor::parse, parserConfig); if (results.isEmpty()) { upstream().request(1); } else { downstream().onNext(new StreamingChatCompletionResults.Results(results)); } } public static Stream<StreamingChatCompletionResults.Result> parse(XContentParserConfiguration parserConfig, ServerSentEvent event) { if (DONE_MESSAGE.equalsIgnoreCase(event.data())) { return Stream.empty(); } try (XContentParser jsonParser = XContentFactory.xContent(XContentType.JSON).createParser(parserConfig, event.data())) { moveToFirstToken(jsonParser); XContentParser.Token token = jsonParser.currentToken(); ensureExpectedToken(XContentParser.Token.START_OBJECT, token, jsonParser); positionParserAtTokenAfterField(jsonParser, CHOICES_FIELD, FAILED_TO_FIND_FIELD_TEMPLATE); return parseList(jsonParser, parser -> { ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser); positionParserAtTokenAfterField(parser, DELTA_FIELD, FAILED_TO_FIND_FIELD_TEMPLATE); var currentToken = parser.currentToken(); ensureExpectedToken(XContentParser.Token.START_OBJECT, currentToken, parser); currentToken = parser.nextToken(); // continue until the end of delta while (currentToken != null && currentToken != XContentParser.Token.END_OBJECT) { if (currentToken == XContentParser.Token.START_OBJECT || currentToken == XContentParser.Token.START_ARRAY) { parser.skipChildren(); } if (currentToken == XContentParser.Token.FIELD_NAME && parser.currentName().equals(CONTENT_FIELD)) { parser.nextToken(); ensureExpectedToken(XContentParser.Token.VALUE_STRING, parser.currentToken(), parser); var content = parser.text(); consumeUntilObjectEnd(parser); // end delta consumeUntilObjectEnd(parser); // end choices return content; } currentToken = parser.nextToken(); } consumeUntilObjectEnd(parser); // end choices return ""; // stopped }).stream().filter(Objects::nonNull).filter(Predicate.not(String::isEmpty)).map(StreamingChatCompletionResults.Result::new); } catch (IOException e) { throw new ElasticsearchStatusException( "Failed to parse event from inference provider: {}", RestStatus.INTERNAL_SERVER_ERROR, e, event ); } } }
OpenAiStreamingProcessor
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/GenericFlatVectorReaders.java
{ "start": 1009, "end": 3588 }
interface ____ { FlatVectorsReader getReader(String formatName, boolean useDirectIO) throws IOException; } private record FlatVectorsReaderKey(String formatName, boolean useDirectIO) { private FlatVectorsReaderKey(Field field) { this(field.rawVectorFormatName(), field.useDirectIOReads()); } @Override public String toString() { return formatName + (useDirectIO ? " with Direct IO" : ""); } } private final Map<FlatVectorsReaderKey, FlatVectorsReader> readers = new HashMap<>(); private final Map<Integer, FlatVectorsReader> readersForFields = new HashMap<>(); public void loadField(int fieldNumber, Field field, LoadFlatVectorsReader loadReader) throws IOException { FlatVectorsReaderKey key = new FlatVectorsReaderKey(field); FlatVectorsReader reader = readers.get(key); if (reader == null) { reader = loadReader.getReader(field.rawVectorFormatName(), field.useDirectIOReads()); if (reader == null) { throw new IllegalStateException("Cannot find flat vector format: " + field.rawVectorFormatName()); } readers.put(key, reader); } readersForFields.put(fieldNumber, reader); } public FlatVectorsReader getReaderForField(int fieldNumber) { FlatVectorsReader reader = readersForFields.get(fieldNumber); if (reader == null) { throw new IllegalArgumentException("Invalid field number [" + fieldNumber + "]"); } return reader; } public Collection<FlatVectorsReader> allReaders() { return Collections.unmodifiableCollection(readers.values()); } public GenericFlatVectorReaders getMergeInstance() throws IOException { GenericFlatVectorReaders mergeReaders = new GenericFlatVectorReaders(); // link the original instance with the merge instance Map<FlatVectorsReader, FlatVectorsReader> mergeInstances = new IdentityHashMap<>(); for (var reader : readers.entrySet()) { FlatVectorsReader mergeInstance = reader.getValue().getMergeInstance(); mergeInstances.put(reader.getValue(), mergeInstance); mergeReaders.readers.put(reader.getKey(), mergeInstance); } // link up the fields to the merge readers for (var field : readersForFields.entrySet()) { mergeReaders.readersForFields.put(field.getKey(), mergeInstances.get(field.getValue())); } return mergeReaders; } }
LoadFlatVectorsReader
java
google__guice
core/test/com/google/inject/TypeConversionTest.java
{ "start": 14415, "end": 14620 }
class ____ extends AbstractModule { @Override protected void configure() { convertToTypes(Matchers.only(TypeLiteral.get(Date.class)), mockTypeConverter(new Date())); } }
Ambiguous1Module
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/FSQueueMetricsForCustomResources.java
{ "start": 1020, "end": 1179 }
class ____ a main entry-point for any kind of metrics for * custom resources. * It provides increase and decrease methods for all types of metrics. */ public
is
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/narayana/quarkus/TSRTest.java
{ "start": 1593, "end": 7924 }
enum ____ { AGROAL, HIBERNATE, OTHER }; private static final List<String> synchronizationCallbacks = new ArrayList<>(); @BeforeEach public void before() { synchronizationCallbacks.clear(); } @Test public void test() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException { tm.begin(); RestAssured.given() .when() .body("{\"name\" : \"Pear\"}") .contentType("application/json") .post("/fruits") .then() .statusCode(201); // register a synchronization that registers more synchronizations during the beforeCompletion callback tsr.registerInterposedSynchronization(new Synchronization() { @Override public void beforeCompletion() { synchronizationCallbacks.add(SYNCH_TYPES.OTHER.name()); // Add another synchronization belonging to the same "category". // This registration should succeed since it belongs to the same group that's currently being processed. // But note that adding one for a group that has already finished should fail (but we cannot test that // here since the other groups belong to different packages, ie hibernate and agroal). tsr.registerInterposedSynchronization(new NormalSynchronization()); } @Override public void afterCompletion(int status) { } }); // cause ARC to register a callback for transaction lifecycle events (see ObservingBean), but since ARC // uses a session synchronization this should *not* result in an interposed synchronization being registered event.fire("commit"); tm.commit(); /* * Check that the two normal synchronizations added by this test were invoked. * The actual list is maintained by {@code AgroalOrderedLastSynchronizationList} * and it will also include interposed synchronizations added by hibernate * and Agroal as a result of calling the above hibernate query. * If you want to verify that the order is correct then run the test under * the control of a debugger and look at the order of the list maintained * by the AgroalOrderedLastSynchronizationList class. */ Assertions.assertEquals(2, synchronizationCallbacks.size()); Assertions.assertEquals(SYNCH_TYPES.OTHER.name(), synchronizationCallbacks.get(0)); Assertions.assertEquals(SYNCH_TYPES.OTHER.name(), synchronizationCallbacks.get(1)); } @Test public void testException() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException { final String MESSAGE = "testException from synchronization"; final NormalSynchronization normalSynchronization = new NormalSynchronization(); tm.begin(); RestAssured.given() .when() .body("{\"name\" : \"Orange\"}") // use a different fruit from the other tests in this suite .contentType("application/json") .post("/fruits") .then() .statusCode(201); // register a synchronization that registers more synchronizations during the beforeCompletion callback tsr.registerInterposedSynchronization(new Synchronization() { @Override public void beforeCompletion() { synchronizationCallbacks.add(SYNCH_TYPES.OTHER.name()); // Add another synchronization belonging to the same "category". // This registration should succeed since it belongs to the same group that's currently being processed. // But note that adding one for a group that has already finished should fail (but we cannot test that // here since the other groups belong to different packages, ie hibernate and agroal). tsr.registerInterposedSynchronization(normalSynchronization); // throw an exception to verify that the other beforeCompletion synchronizations still execute throw new RuntimeException(MESSAGE); } @Override public void afterCompletion(int status) { } }); try { tm.commit(); Assertions.fail("Expected commit to throw an exception"); } catch (RollbackException | HeuristicMixedException | HeuristicRollbackException | SecurityException | IllegalStateException | SystemException e) { Assertions.assertNotNull(e.getCause(), "expected exception cause to be present"); Assertions.assertTrue(e.getCause().getMessage().endsWith(MESSAGE), "expected a different exception message"); // the synchronization registered a synchronization (the variable normalSynchronization) // just before it threw the exception so now check that it was still called: Assertions.assertTrue(normalSynchronization.wasInvoked(), "the synchronization registered before the exception should have ran"); /* * Check that the two normal synchronizations added by this test were invoked. * The actual list is maintained by {@code AgroalOrderedLastSynchronizationList} * and it will also include interposed synchronizations added by hibernate * and Agroal as a result of calling the above hibernate query. * If you want to verify that the order is correct then run the test under * the control of a debugger and look at the order of the list maintained * by the AgroalOrderedLastSynchronizationList class. */ Assertions.assertEquals(2, synchronizationCallbacks.size()); Assertions.assertEquals(SYNCH_TYPES.OTHER.name(), synchronizationCallbacks.get(0)); Assertions.assertEquals(SYNCH_TYPES.OTHER.name(), synchronizationCallbacks.get(1)); } } @ApplicationScoped static
SYNCH_TYPES
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/TestPropertySource.java
{ "start": 13821, "end": 13968 }
class ____ * <em>inherit</em> inlined properties defined by a superclass or enclosing * class. Specifically, the inlined properties for a test
will
java
apache__flink
flink-core/src/main/java/org/apache/flink/configuration/ExternalResourceOptions.java
{ "start": 1514, "end": 4094 }
class ____ the external resource to use. This is used as a suffix in an * actual config. */ public static final String EXTERNAL_RESOURCE_DRIVER_FACTORY_SUFFIX = "driver-factory.class"; /** The suffix of custom config options' prefix for the external resource. */ public static final String EXTERNAL_RESOURCE_DRIVER_PARAM_SUFFIX = "param."; /** * The naming pattern of custom config options for the external resource. This is used as a * suffix. */ private static final String EXTERNAL_RESOURCE_DRIVER_PARAM_PATTERN_SUFFIX = EXTERNAL_RESOURCE_DRIVER_PARAM_SUFFIX + "<param>"; /** * The prefix for all external resources configs. Has to be combined with a resource name and * the configs mentioned below. */ private static final String EXTERNAL_RESOURCE_PREFIX = "external-resource"; /** * List of the resource_name of all external resources with delimiter ";", e.g. "gpu;fpga" for * two external resource gpu and fpga. The resource_name will be used to splice related config * options for external resource. Only the resource_name defined here will go into effect in * external resource framework. * * <p>Example: * * <pre>{@code * external-resources = gpu;fpga * * external-resource.gpu.driver-factory.class: org.apache.flink.externalresource.gpu.GPUDriverFactory * external-resource.gpu.amount: 2 * external-resource.gpu.param.type: nvidia * * external-resource.fpga.driver-factory.class: org.apache.flink.externalresource.fpga.FPGADriverFactory * external-resource.fpga.amount: 1 * }</pre> */ public static final ConfigOption<List<String>> EXTERNAL_RESOURCE_LIST = key("external-resources") .stringType() .asList() .defaultValues() .withDescription( "List of the <resource_name> of all external resources with delimiter \";\", e.g. \"gpu;fpga\" " + "for two external resource gpu and fpga. The <resource_name> will be used to splice related config options for " + "external resource. Only the <resource_name> defined here will go into effect by external resource framework. " + "Do not set the <resource_name> to '" + NONE + "', which is preserved internally"); /** * Defines the factory
of
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/DefaultQueueResourceRoundingStrategy.java
{ "start": 1318, "end": 2102 }
class ____ implements QueueResourceRoundingStrategy { private final ResourceUnitCapacityType lastCapacityType; public DefaultQueueResourceRoundingStrategy( ResourceUnitCapacityType[] capacityTypePrecedence) { if (capacityTypePrecedence.length == 0) { throw new IllegalArgumentException("Capacity type precedence collection is empty"); } lastCapacityType = capacityTypePrecedence[capacityTypePrecedence.length - 1]; } @Override public double getRoundedResource(double resourceValue, QueueCapacityVectorEntry capacityVectorEntry) { if (capacityVectorEntry.getVectorResourceType().equals(lastCapacityType)) { return Math.round(resourceValue); } else { return Math.floor(resourceValue); } } }
DefaultQueueResourceRoundingStrategy
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclass/JoinedSubclassWithImplicitDiscriminatorTest.java
{ "start": 1552, "end": 3734 }
class ____ { @Test public void metadataAssertions(SessionFactoryScope scope) { EntityPersister p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Dog.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister dogPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( AnnotatedDiscriminatorColumn.DEFAULT_DISCRIMINATOR_TYPE, dogPersister.getDiscriminatorType().getName() ); assertEquals( AnnotatedDiscriminatorColumn.DEFAULT_DISCRIMINATOR_COLUMN_NAME, dogPersister.getDiscriminatorColumnName() ); assertEquals( "Dog", dogPersister.getDiscriminatorValue() ); p = scope.getSessionFactory().getMappingMetamodel().getEntityDescriptor(Cat.class.getName()); assertNotNull( p ); final JoinedSubclassEntityPersister catPersister = assertTyping( JoinedSubclassEntityPersister.class, p ); assertEquals( AnnotatedDiscriminatorColumn.DEFAULT_DISCRIMINATOR_TYPE, catPersister.getDiscriminatorType().getName() ); assertEquals( AnnotatedDiscriminatorColumn.DEFAULT_DISCRIMINATOR_COLUMN_NAME, catPersister.getDiscriminatorColumnName() ); assertEquals( "Cat", catPersister.getDiscriminatorValue() ); } @Test public void basicUsageTest(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new Cat( 1 ) ); session.persist( new Dog( 2 ) ); } ); scope.inTransaction( session -> { session.createQuery( "from Animal" ).list(); Cat cat = session.get( Cat.class, 1 ); assertNotNull( cat ); session.remove( cat ); Dog dog = session.get( Dog.class, 2 ); assertNotNull( dog ); session.remove( dog ); } ); } public <T> T assertTyping(Class<T> expectedType, Object value) { if ( !expectedType.isInstance( value ) ) { fail( String.format( "Expecting value of type [%s], but found [%s]", expectedType.getName(), value == null ? "<null>" : value ) ); } return (T) value; } @Entity(name = "Animal") @Table(name = "animal") @Inheritance(strategy = InheritanceType.JOINED) public static abstract
JoinedSubclassWithImplicitDiscriminatorTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java
{ "start": 41950, "end": 42096 }
class ____ { @OneToOne private EntityA identicallyNamedAssociation; private EmbeddableB embeddable; } @Embeddable
EntityB
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsComposedOnSingleAnnotatedElementTests.java
{ "start": 1422, "end": 6762 }
class ____ { // See SPR-13486 @Test void inheritedStrategyMultipleComposedAnnotationsOnClass() { assertInheritedStrategyBehavior(MultipleComposedCachesClass.class); } @Test void inheritedStrategyMultipleInheritedComposedAnnotationsOnSuperclass() { assertInheritedStrategyBehavior(SubMultipleComposedCachesClass.class); } @Test void inheritedStrategyMultipleNoninheritedComposedAnnotationsOnClass() { MergedAnnotations annotations = MergedAnnotations.from( MultipleNoninheritedComposedCachesClass.class, SearchStrategy.INHERITED_ANNOTATIONS); assertThat(stream(annotations, "value")).containsExactly("noninheritedCache1", "noninheritedCache2"); } @Test void inheritedStrategyMultipleNoninheritedComposedAnnotationsOnSuperclass() { MergedAnnotations annotations = MergedAnnotations.from( SubMultipleNoninheritedComposedCachesClass.class, SearchStrategy.INHERITED_ANNOTATIONS); assertThat(annotations.stream(Cacheable.class)).isEmpty(); } @Test void inheritedStrategyComposedPlusLocalAnnotationsOnClass() { assertInheritedStrategyBehavior(ComposedPlusLocalCachesClass.class); } @Test void inheritedStrategyMultipleComposedAnnotationsOnInterface() { MergedAnnotations annotations = MergedAnnotations.from( MultipleComposedCachesOnInterfaceClass.class, SearchStrategy.INHERITED_ANNOTATIONS); assertThat(annotations.stream(Cacheable.class)).isEmpty(); } @Test void inheritedStrategyMultipleComposedAnnotationsOnMethod() throws Exception { assertInheritedStrategyBehavior( getClass().getDeclaredMethod("multipleComposedCachesMethod")); } @Test void inheritedStrategyComposedPlusLocalAnnotationsOnMethod() throws Exception { assertInheritedStrategyBehavior( getClass().getDeclaredMethod("composedPlusLocalCachesMethod")); } private void assertInheritedStrategyBehavior(AnnotatedElement element) { MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.INHERITED_ANNOTATIONS); assertThat(stream(annotations, "key")).containsExactly("fooKey", "barKey"); assertThat(stream(annotations, "value")).containsExactly("fooCache", "barCache"); } @Test void typeHierarchyStrategyMultipleComposedAnnotationsOnClass() { assertTypeHierarchyStrategyBehavior(MultipleComposedCachesClass.class); } @Test void typeHierarchyStrategyMultipleInheritedComposedAnnotationsOnSuperclass() { assertTypeHierarchyStrategyBehavior(SubMultipleComposedCachesClass.class); } @Test void typeHierarchyStrategyMultipleNoninheritedComposedAnnotationsOnClass() { MergedAnnotations annotations = MergedAnnotations.from( MultipleNoninheritedComposedCachesClass.class, SearchStrategy.TYPE_HIERARCHY); assertThat(stream(annotations, "value")).containsExactly("noninheritedCache1", "noninheritedCache2"); } @Test void typeHierarchyStrategyMultipleNoninheritedComposedAnnotationsOnSuperclass() { MergedAnnotations annotations = MergedAnnotations.from( SubMultipleNoninheritedComposedCachesClass.class, SearchStrategy.TYPE_HIERARCHY); assertThat(stream(annotations, "value")).containsExactly("noninheritedCache1", "noninheritedCache2"); } @Test void typeHierarchyStrategyComposedPlusLocalAnnotationsOnClass() { assertTypeHierarchyStrategyBehavior(ComposedPlusLocalCachesClass.class); } @Test void typeHierarchyStrategyMultipleComposedAnnotationsOnInterface() { assertTypeHierarchyStrategyBehavior(MultipleComposedCachesOnInterfaceClass.class); } @Test void typeHierarchyStrategyComposedCacheOnInterfaceAndLocalCacheOnClass() { assertTypeHierarchyStrategyBehavior( ComposedCacheOnInterfaceAndLocalCacheClass.class); } @Test void typeHierarchyStrategyMultipleComposedAnnotationsOnMethod() throws Exception { assertTypeHierarchyStrategyBehavior( getClass().getDeclaredMethod("multipleComposedCachesMethod")); } @Test void typeHierarchyStrategyComposedPlusLocalAnnotationsOnMethod() throws Exception { assertTypeHierarchyStrategyBehavior( getClass().getDeclaredMethod("composedPlusLocalCachesMethod")); } @Test void typeHierarchyStrategyMultipleComposedAnnotationsOnBridgeMethod() { assertTypeHierarchyStrategyBehavior(getBridgeMethod()); } private void assertTypeHierarchyStrategyBehavior(AnnotatedElement element) { MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY); assertThat(stream(annotations, "key")).containsExactly("fooKey", "barKey"); assertThat(stream(annotations, "value")).containsExactly("fooCache", "barCache"); } Method getBridgeMethod() { List<Method> methods = new ArrayList<>(); ReflectionUtils.doWithLocalMethods(StringGenericParameter.class, method -> { if ("getFor".equals(method.getName())) { methods.add(method); } }); Method bridgeMethod = methods.get(0).getReturnType() == Object.class ? methods.get(0) : methods.get(1); assertThat(bridgeMethod.isBridge()).isTrue(); return bridgeMethod; } private Stream<String> stream(MergedAnnotations annotations, String attributeName) { return annotations.stream(Cacheable.class).map( annotation -> annotation.getString(attributeName)); } // @formatter:off @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @
MergedAnnotationsComposedOnSingleAnnotatedElementTests
java
apache__hadoop
hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/MKNOD3Response.java
{ "start": 1095, "end": 2667 }
class ____ extends NFS3Response { private final FileHandle objFileHandle; private final Nfs3FileAttributes objPostOpAttr; private final WccData dirWcc; public MKNOD3Response(int status) { this(status, null, null, new WccData(null, null)); } public MKNOD3Response(int status, FileHandle handle, Nfs3FileAttributes attrs, WccData dirWcc) { super(status); this.objFileHandle = handle; this.objPostOpAttr = attrs; this.dirWcc = dirWcc; } public FileHandle getObjFileHandle() { return objFileHandle; } public Nfs3FileAttributes getObjPostOpAttr() { return objPostOpAttr; } public WccData getDirWcc() { return dirWcc; } public static MKNOD3Response deserialize(XDR xdr) { int status = xdr.readInt(); FileHandle objFileHandle = new FileHandle(); Nfs3FileAttributes objPostOpAttr = null; WccData dirWcc; if (status == Nfs3Status.NFS3_OK) { xdr.readBoolean(); objFileHandle.deserialize(xdr); xdr.readBoolean(); objPostOpAttr = Nfs3FileAttributes.deserialize(xdr); } dirWcc = WccData.deserialize(xdr); return new MKNOD3Response(status, objFileHandle, objPostOpAttr, dirWcc); } @Override public XDR serialize(XDR out, int xid, Verifier verifier) { super.serialize(out, xid, verifier); if (this.getStatus() == Nfs3Status.NFS3_OK) { out.writeBoolean(true); objFileHandle.serialize(out); out.writeBoolean(true); objPostOpAttr.serialize(out); } dirWcc.serialize(out); return out; } }
MKNOD3Response
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/SelfAlwaysReturnsThisTest.java
{ "start": 1259, "end": 1636 }
class ____ { public Builder self() { return this; } } """) .expectUnchanged() .doTest(); } @Test public void selfReturnsThis_withCast() { helper .addInputLines( "Builder.java", """ package com.google.frobber; public final
Builder
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/text/package-info.java
{ "start": 1246, "end": 1999 }
class ____ * substituting variables within a String named {@link org.apache.commons.lang3.text.StrSubstitutor} and a replacement for {@link java.util.StringTokenizer} * named {@link org.apache.commons.lang3.text.StrTokenizer}. While somewhat ungainly, the {@code Str} prefix has been used to ensure we don't clash with any * current or future standard Java classes. * </p> * <p> * <strong>Deprecated</strong>: As of <a href="https://commons.apache.org/proper/commons-lang/changes-report.html#a3.6">3.6</a>, use the Apache Commons Text * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/package-summary.html"> text package</a>. * </p> * * @since 2.1 */ package org.apache.commons.lang3.text;
for
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SpringWsComponentBuilderFactory.java
{ "start": 1414, "end": 1930 }
interface ____ { /** * Spring WebService (camel-spring-ws) * Access external web services as a client or expose your own web services. * * Category: webservice * Since: 2.6 * Maven coordinates: org.apache.camel:camel-spring-ws * * @return the dsl builder */ static SpringWsComponentBuilder springWs() { return new SpringWsComponentBuilderImpl(); } /** * Builder for the Spring WebService component. */
SpringWsComponentBuilderFactory
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteAction.java
{ "start": 1730, "end": 10253 }
class ____ extends AbstractPathAction { private final PathSorter pathSorter; private final boolean testMode; private final ScriptCondition scriptCondition; /** * Creates a new DeleteAction that starts scanning for files to delete from the specified base path. * * @param basePath base path from where to start scanning for files to delete. * @param followSymbolicLinks whether to follow symbolic links. Default is false. * @param maxDepth The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 * means that only the starting file is visited, unless denied by the security manager. A value of * MAX_VALUE may be used to indicate that all levels should be visited. * @param testMode if true, files are not deleted but instead a message is printed to the <a * href="https://logging.apache.org/log4j/2.x/manual/status-logger.html">status logger</a> * at INFO level. Users can use this to do a dry run to test if their configuration works as expected. * @param sorter sorts * @param pathConditions an array of path filters (if more than one, they all need to accept a path before it is * deleted). * @param scriptCondition */ DeleteAction( final String basePath, final boolean followSymbolicLinks, final int maxDepth, final boolean testMode, final PathSorter sorter, final PathCondition[] pathConditions, final ScriptCondition scriptCondition, final StrSubstitutor subst) { super(basePath, followSymbolicLinks, maxDepth, pathConditions, subst); this.testMode = testMode; this.pathSorter = Objects.requireNonNull(sorter, "sorter"); this.scriptCondition = scriptCondition; if (scriptCondition == null && (pathConditions == null || pathConditions.length == 0)) { LOGGER.error("Missing Delete conditions: unconditional Delete not supported"); throw new IllegalArgumentException("Unconditional Delete not supported"); } } /* * (non-Javadoc) * * @see org.apache.logging.log4j.core.appender.rolling.action.AbstractPathAction#execute() */ @Override public boolean execute() throws IOException { return scriptCondition != null ? executeScript() : super.execute(); } private boolean executeScript() throws IOException { final List<PathWithAttributes> selectedForDeletion = callScript(); if (selectedForDeletion == null) { LOGGER.trace("Script returned null list (no files to delete)"); return true; } deleteSelectedFiles(selectedForDeletion); return true; } private List<PathWithAttributes> callScript() throws IOException { final List<PathWithAttributes> sortedPaths = getSortedPaths(); trace("Sorted paths:", sortedPaths); final List<PathWithAttributes> result = scriptCondition.selectFilesToDelete(getBasePath(), sortedPaths); return result; } private void deleteSelectedFiles(final List<PathWithAttributes> selectedForDeletion) throws IOException { trace("Paths the script selected for deletion:", selectedForDeletion); for (final PathWithAttributes pathWithAttributes : selectedForDeletion) { final Path path = pathWithAttributes == null ? null : pathWithAttributes.getPath(); if (isTestMode()) { LOGGER.info("Deleting {} (TEST MODE: file not actually deleted)", path); } else { delete(path); } } } /** * Deletes the specified file. * * @param path the file to delete * @throws IOException if a problem occurred deleting the file */ protected void delete(final Path path) throws IOException { LOGGER.trace("Deleting {}", path); Files.deleteIfExists(path); } /* * (non-Javadoc) * * @see org.apache.logging.log4j.core.appender.rolling.action.AbstractPathAction#execute(FileVisitor) */ @Override public boolean execute(final FileVisitor<Path> visitor) throws IOException { final List<PathWithAttributes> sortedPaths = getSortedPaths(); trace("Sorted paths:", sortedPaths); for (final PathWithAttributes element : sortedPaths) { try { visitor.visitFile(element.getPath(), element.getAttributes()); } catch (final IOException ioex) { LOGGER.error("Error in post-rollover Delete when visiting {}", element.getPath(), ioex); visitor.visitFileFailed(element.getPath(), ioex); } } // TODO return (visitor.success || ignoreProcessingFailure) return true; // do not abort rollover even if processing failed } private void trace(final String label, final List<PathWithAttributes> sortedPaths) { LOGGER.trace(label); for (final PathWithAttributes pathWithAttributes : sortedPaths) { LOGGER.trace(pathWithAttributes); } } /** * Returns a sorted list of all files up to maxDepth under the basePath. * * @return a sorted list of files * @throws IOException */ List<PathWithAttributes> getSortedPaths() throws IOException { final SortingVisitor sort = new SortingVisitor(pathSorter); super.execute(sort); final List<PathWithAttributes> sortedPaths = sort.getSortedPaths(); return sortedPaths; } /** * Returns {@code true} if files are not deleted even when all conditions accept a path, {@code false} otherwise. * * @return {@code true} if files are not deleted even when all conditions accept a path, {@code false} otherwise */ public boolean isTestMode() { return testMode; } @Override protected FileVisitor<Path> createFileVisitor(final Path visitorBaseDir, final List<PathCondition> conditions) { return new DeletingVisitor(visitorBaseDir, conditions, testMode); } /** * Create a DeleteAction. * * @param basePath base path from where to start scanning for files to delete. * @param followLinks whether to follow symbolic links. Default is false. * @param maxDepth The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 * means that only the starting file is visited, unless denied by the security manager. A value of * MAX_VALUE may be used to indicate that all levels should be visited. * @param testMode if true, files are not deleted but instead a message is printed to the * <a href="https://logging.apache.org/log4j/2.x/manual/status-logger.html">status logger</a> * at INFO level. Users can use this to do a dry run to test if their configuration works as expected. * Default is false. * @param sorterParameter a plugin implementing the {@link PathSorter} interface * @param pathConditions an array of path conditions (if more than one, they all need to accept a path before it is * deleted). * @param config The Configuration. * @return A DeleteAction. */ @PluginFactory public static DeleteAction createDeleteAction( // @formatter:off @PluginAttribute("basePath") final String basePath, @PluginAttribute(value = "followLinks") final boolean followLinks, @PluginAttribute(value = "maxDepth", defaultInt = 1) final int maxDepth, @PluginAttribute(value = "testMode") final boolean testMode, @PluginElement("PathSorter") final PathSorter sorterParameter, @PluginElement("PathConditions") final PathCondition[] pathConditions, @PluginElement("ScriptCondition") final ScriptCondition scriptCondition, @PluginConfiguration final Configuration config) { // @formatter:on final PathSorter sorter = sorterParameter == null ? new PathSortByModificationTime(true) : sorterParameter; return new DeleteAction( basePath, followLinks, maxDepth, testMode, sorter, pathConditions, scriptCondition, config.getStrSubstitutor()); } }
DeleteAction
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/service/QuarkusRuntimeInitDialectResolver.java
{ "start": 554, "end": 872 }
class ____ implements DialectResolver { private final Dialect dialect; public QuarkusRuntimeInitDialectResolver(Dialect dialect) { this.dialect = dialect; } @Override public Dialect resolveDialect(DialectResolutionInfo info) { return dialect; } }
QuarkusRuntimeInitDialectResolver
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/Base64Variant.java
{ "start": 776, "end": 31682 }
enum ____ { /** * Padding is not allowed in Base64 content being read (finding something * that looks like padding at the end of content results in an exception) */ PADDING_FORBIDDEN, /** * Padding is required in Base64 content being read * (missing padding for incomplete ending quartet results in an exception) */ PADDING_REQUIRED, /** * Padding is allowed but not required in Base64 content being read: no * exception thrown based on existence or absence, as long as proper * padding characters are used. */ PADDING_ALLOWED } private final static int INT_SPACE = 0x20; // We'll only serialize name private static final long serialVersionUID = 1L; /** * Placeholder used by "no padding" variant, to be used when a character * value is needed. */ protected final static char PADDING_CHAR_NONE = '\0'; /** * Marker used to denote ascii characters that do not correspond * to a 6-bit value (in this variant), and is not used as a padding * character. */ public final static int BASE64_VALUE_INVALID = -1; /** * Marker used to denote ascii character (in decoding table) that * is the padding character using this variant (if any). */ public final static int BASE64_VALUE_PADDING = -2; /* /********************************************************** /* Encoding/decoding tables /********************************************************** */ /** * Decoding table used for base 64 decoding. */ private final transient int[] _asciiToBase64 = new int[128]; /** * Encoding table used for base 64 decoding when output is done * as characters. */ private final transient char[] _base64ToAsciiC = new char[64]; /** * Alternative encoding table used for base 64 decoding when output is done * as ascii bytes. */ private final transient byte[] _base64ToAsciiB = new byte[64]; /* /********************************************************** /* Other configuration /********************************************************** */ /** * Symbolic name of variant; used for diagnostics/debugging. *<p> * Note that this is the only non-transient field; used when reading * back from serialized state. *<p> * Also: must not be private, accessed from `BaseVariants` */ final String _name; /** * Character used for padding, if any ({@link #PADDING_CHAR_NONE} if not). */ private final char _paddingChar; /** * Maximum number of encoded base64 characters to output during encoding * before adding a linefeed, if line length is to be limited * ({@link java.lang.Integer#MAX_VALUE} if not limited). *<p> * Note: for some output modes (when writing attributes) linefeeds may * need to be avoided, and this value ignored. */ private final int _maxLineLength; /** * Whether this variant uses padding when writing out content or not. * * @since 2.12 */ private final boolean _writePadding; /** * Whether padding characters should be required or not while decoding * * @since 2.12 */ private final PaddingReadBehaviour _paddingReadBehaviour; /* /********************************************************** /* Life-cycle /********************************************************** */ public Base64Variant(String name, String base64Alphabet, boolean writePadding, char paddingChar, int maxLineLength) { _name = name; _writePadding = writePadding; _paddingChar = paddingChar; _maxLineLength = maxLineLength; // Ok and then we need to create codec tables. // First the main encoding table: int alphaLen = base64Alphabet.length(); if (alphaLen != 64) { throw new IllegalArgumentException("Base64Alphabet length must be exactly 64 (was "+alphaLen+")"); } // And then secondary encoding table and decoding table: base64Alphabet.getChars(0, alphaLen, _base64ToAsciiC, 0); Arrays.fill(_asciiToBase64, BASE64_VALUE_INVALID); for (int i = 0; i < alphaLen; ++i) { char alpha = _base64ToAsciiC[i]; _base64ToAsciiB[i] = (byte) alpha; _asciiToBase64[alpha] = i; } // Plus if we use padding, add that in too if (writePadding) { _asciiToBase64[paddingChar] = BASE64_VALUE_PADDING; } // By default, require padding on input if written on output; do not // accept if padding not written _paddingReadBehaviour = writePadding ? PaddingReadBehaviour.PADDING_REQUIRED : PaddingReadBehaviour.PADDING_FORBIDDEN; } /** * "Copy constructor" that can be used when the base alphabet is identical * to one used by another variant except for the maximum line length * (and obviously, name). * * @param base Variant to use for settings not specific by other parameters * @param name Name of this variant * @param maxLineLength Maximum length (in characters) of lines to output before * using linefeed */ public Base64Variant(Base64Variant base, String name, int maxLineLength) { this(base, name, base._writePadding, base._paddingChar, maxLineLength); } /** * "Copy constructor" that can be used when the base alphabet is identical * to one used by another variant, but other details (padding, maximum * line length) differ * * @param base Variant to use for settings not specific by other parameters * @param name Name of this variant * @param writePadding Whether variant will use padding when encoding * @param paddingChar Padding character used for encoding, excepted on reading, if any * @param maxLineLength Maximum length (in characters) of lines to output before * using linefeed */ public Base64Variant(Base64Variant base, String name, boolean writePadding, char paddingChar, int maxLineLength) { this(base, name, writePadding, paddingChar, base._paddingReadBehaviour, maxLineLength); } private Base64Variant(Base64Variant base, String name, boolean writePadding, char paddingChar, PaddingReadBehaviour paddingReadBehaviour, int maxLineLength) { _name = name; byte[] srcB = base._base64ToAsciiB; System.arraycopy(srcB, 0, this._base64ToAsciiB, 0, srcB.length); char[] srcC = base._base64ToAsciiC; System.arraycopy(srcC, 0, this._base64ToAsciiC, 0, srcC.length); int[] srcV = base._asciiToBase64; System.arraycopy(srcV, 0, this._asciiToBase64, 0, srcV.length); _writePadding = writePadding; _paddingChar = paddingChar; _maxLineLength = maxLineLength; _paddingReadBehaviour = paddingReadBehaviour; } private Base64Variant(Base64Variant base, PaddingReadBehaviour paddingReadBehaviour) { this(base, base._name, base._writePadding, base._paddingChar, paddingReadBehaviour, base._maxLineLength); } /** * @return Base64Variant which does not require padding on read * * @since 2.12 */ public Base64Variant withPaddingAllowed() { return withReadPadding(PaddingReadBehaviour.PADDING_ALLOWED); } /** * @return Base64Variant which requires padding on read * @since 2.12 */ public Base64Variant withPaddingRequired() { return withReadPadding(PaddingReadBehaviour.PADDING_REQUIRED); } /** * @return Base64Variant which does not accept padding on read * @since 2.12 */ public Base64Variant withPaddingForbidden() { return withReadPadding(PaddingReadBehaviour.PADDING_FORBIDDEN); } /** * @param readPadding Padding read behavior desired * * @return Instance with desired padding read behavior setting (this * if already has setting; new instance otherwise) * * @since 2.12 */ public Base64Variant withReadPadding(PaddingReadBehaviour readPadding) { return (readPadding == _paddingReadBehaviour) ? this : new Base64Variant(this, readPadding); } /** * @param writePadding Determines if padding is output on write or not * * @return Base64Variant which writes padding or not depending on writePadding * * @since 2.12 */ public Base64Variant withWritePadding(boolean writePadding) { return (writePadding == _writePadding) ? this : new Base64Variant(this, _name, writePadding, _paddingChar, _maxLineLength); } /* /********************************************************** /* Serializable overrides /********************************************************** */ // 26-Oct-2020, tatu: Much more complicated with 2.12 as it is // possible to create differently configured instances. // Need to start with name to regenerate tables etc but then // handle overrides protected Object readResolve() { Base64Variant base = Base64Variants.valueOf(_name); if ((_writePadding != base._writePadding) || (_paddingChar != base._paddingChar) || (_paddingReadBehaviour != base._paddingReadBehaviour) || (_maxLineLength != base._maxLineLength) ) { return new Base64Variant(base, _name, _writePadding, _paddingChar, _paddingReadBehaviour, _maxLineLength); } return base; } /* /********************************************************** /* Public accessors /********************************************************** */ @Override public String getName() { return _name; } /** * @return True if this Base64 encoding will <b>write</b> padding on output * (note: before Jackson 2.12 also dictated whether padding was accepted on read) */ public boolean usesPadding() { return _writePadding; } /** * @return {@code True} if this variant requires padding on content decoded; {@code false} if not. * * @since 2.12 */ public boolean requiresPaddingOnRead() { return _paddingReadBehaviour == PaddingReadBehaviour.PADDING_REQUIRED; } /** * @return {@code True} if this variant accepts padding on content decoded; {@code false} if not. * * @since 2.12 */ public boolean acceptsPaddingOnRead() { return _paddingReadBehaviour != PaddingReadBehaviour.PADDING_FORBIDDEN; } public boolean usesPaddingChar(char c) { return c == _paddingChar; } public boolean usesPaddingChar(int ch) { return ch == _paddingChar; } /** * @return Indicator on how this Base64 encoding will handle possible padding * in content when reading. * * @since 2.12 */ public PaddingReadBehaviour paddingReadBehaviour() { return _paddingReadBehaviour; } public char getPaddingChar() { return _paddingChar; } public byte getPaddingByte() { return (byte)_paddingChar; } public int getMaxLineLength() { return _maxLineLength; } /* /********************************************************** /* Decoding support /********************************************************** */ /** * @param c Character to decode * * @return 6-bit decoded value, if valid character; */ public int decodeBase64Char(char c) { int ch = c; return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } public int decodeBase64Char(int ch) { return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; } public int decodeBase64Byte(byte b) { int ch = b; // note: cast retains sign, so it's from -128 to +127 if (ch < 0) { return BASE64_VALUE_INVALID; } return _asciiToBase64[ch]; } /* /********************************************************** /* Encoding support /********************************************************** */ public char encodeBase64BitsAsChar(int value) { // Let's assume caller has done necessary checks; this // method must be fast and inlinable return _base64ToAsciiC[value]; } /** * Method that encodes given right-aligned (LSB) 24-bit value * into 4 base64 characters, stored in given result buffer. * Caller must ensure there is sufficient space for 4 encoded characters * at specified position. * * @param b24 3-byte value to encode * @param buffer Output buffer to append characters to * @param outPtr Starting position within {@code buffer} to append encoded characters * * @return Pointer in output buffer after appending 4 encoded characters */ public int encodeBase64Chunk(int b24, char[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiC[(b24 >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiC[(b24 >> 12) & 0x3F]; buffer[outPtr++] = _base64ToAsciiC[(b24 >> 6) & 0x3F]; buffer[outPtr++] = _base64ToAsciiC[b24 & 0x3F]; return outPtr; } public void encodeBase64Chunk(StringBuilder sb, int b24) { sb.append(_base64ToAsciiC[(b24 >> 18) & 0x3F]); sb.append(_base64ToAsciiC[(b24 >> 12) & 0x3F]); sb.append(_base64ToAsciiC[(b24 >> 6) & 0x3F]); sb.append(_base64ToAsciiC[b24 & 0x3F]); } /** * Method that outputs partial chunk (which only encodes one * or two bytes of data). Data given is still aligned same as if * it as full data; that is, missing data is at the "right end" * (LSB) of int. * * @param bits 24-bit chunk containing 1 or 2 bytes to encode * @param outputBytes Number of input bytes to encode (either 1 or 2) * @param buffer Output buffer to append characters to * @param outPtr Starting position within {@code buffer} to append encoded characters * * @return Pointer in output buffer after appending encoded characters (2, 3 or 4) */ public int encodeBase64Partial(int bits, int outputBytes, char[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiC[(bits >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiC[(bits >> 12) & 0x3F]; if (usesPadding()) { buffer[outPtr++] = (outputBytes == 2) ? _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar; buffer[outPtr++] = _paddingChar; } else { if (outputBytes == 2) { buffer[outPtr++] = _base64ToAsciiC[(bits >> 6) & 0x3F]; } } return outPtr; } public void encodeBase64Partial(StringBuilder sb, int bits, int outputBytes) { sb.append(_base64ToAsciiC[(bits >> 18) & 0x3F]); sb.append(_base64ToAsciiC[(bits >> 12) & 0x3F]); if (usesPadding()) { sb.append((outputBytes == 2) ? _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar); sb.append(_paddingChar); } else { if (outputBytes == 2) { sb.append(_base64ToAsciiC[(bits >> 6) & 0x3F]); } } } public byte encodeBase64BitsAsByte(int value) { // As with above, assuming it is 6-bit value return _base64ToAsciiB[value]; } /** * Method that encodes given right-aligned (LSB) 24-bit value * into 4 base64 bytes (ascii), stored in given result buffer. * * @param b24 3-byte value to encode * @param buffer Output buffer to append characters (as bytes) to * @param outPtr Starting position within {@code buffer} to append encoded characters * * @return Pointer in output buffer after appending 4 encoded characters */ public int encodeBase64Chunk(int b24, byte[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiB[(b24 >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiB[(b24 >> 12) & 0x3F]; buffer[outPtr++] = _base64ToAsciiB[(b24 >> 6) & 0x3F]; buffer[outPtr++] = _base64ToAsciiB[b24 & 0x3F]; return outPtr; } /** * Method that outputs partial chunk (which only encodes one * or two bytes of data). Data given is still aligned same as if * it as full data; that is, missing data is at the "right end" * (LSB) of int. * * @param bits 24-bit chunk containing 1 or 2 bytes to encode * @param outputBytes Number of input bytes to encode (either 1 or 2) * @param buffer Output buffer to append characters to * @param outPtr Starting position within {@code buffer} to append encoded characters * * @return Pointer in output buffer after appending encoded characters (2, 3 or 4) */ public int encodeBase64Partial(int bits, int outputBytes, byte[] buffer, int outPtr) { buffer[outPtr++] = _base64ToAsciiB[(bits >> 18) & 0x3F]; buffer[outPtr++] = _base64ToAsciiB[(bits >> 12) & 0x3F]; if (usesPadding()) { byte pb = (byte) _paddingChar; buffer[outPtr++] = (outputBytes == 2) ? _base64ToAsciiB[(bits >> 6) & 0x3F] : pb; buffer[outPtr++] = pb; } else { if (outputBytes == 2) { buffer[outPtr++] = _base64ToAsciiB[(bits >> 6) & 0x3F]; } } return outPtr; } /* /********************************************************** /* Convenience conversion methods for String to/from bytes use case /********************************************************** */ /** * Convenience method for converting given byte array as base64 encoded * String using this variant's settings. * Resulting value is "raw", that is, not enclosed in double-quotes. * * @param input Byte array to encode * * @return Base64 encoded String of encoded {@code input} bytes, not surrounded by quotes */ public String encode(byte[] input) { return encode(input, false); } /** * Convenience method for converting given byte array as base64 encoded String * using this variant's settings, optionally enclosed in double-quotes. * Linefeeds added, if needed, are expressed as 2-character JSON (and Java source) * escape sequence of backslash + `n`. * * @param input Byte array to encode * @param addQuotes Whether to surround resulting value in double quotes or not * * @return Base64 encoded String of encoded {@code input} bytes, possibly * surrounded by quotes (if {@code addQuotes} enabled) */ public String encode(byte[] input, boolean addQuotes) { final int inputEnd = input.length; final StringBuilder sb = new StringBuilder(inputEnd + (inputEnd >> 2) + (inputEnd >> 3)); if (addQuotes) { sb.append('"'); } int chunksBeforeLF = getMaxLineLength() >> 2; // Ok, first we loop through all full triplets of data: int inputPtr = 0; int safeInputEnd = inputEnd-3; // to get only full triplets while (inputPtr <= safeInputEnd) { // First, mash 3 bytes into lsb of 32-bit int int b24 = (input[inputPtr++]) << 8; b24 |= (input[inputPtr++]) & 0xFF; b24 = (b24 << 8) | ((input[inputPtr++]) & 0xFF); encodeBase64Chunk(sb, b24); if (--chunksBeforeLF <= 0) { // note: must quote in JSON value, so not really useful... sb.append('\\'); sb.append('n'); chunksBeforeLF = getMaxLineLength() >> 2; } } // And then we may have 1 or 2 leftover bytes to encode int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 if (inputLeft > 0) { // yes, but do we have room for output? int b24 = (input[inputPtr++]) << 16; if (inputLeft == 2) { b24 |= ((input[inputPtr++]) & 0xFF) << 8; } encodeBase64Partial(sb, b24, inputLeft); } if (addQuotes) { sb.append('"'); } return sb.toString(); } /** * Convenience method for converting given byte array as base64 encoded String * using this variant's settings, optionally enclosed in double-quotes. * Linefeed character to use is passed explicitly. * * @param input Byte array to encode * @param addQuotes Whether to surround resulting value in double quotes or not * @param linefeed Linefeed to use for encoded content * * @return Base64 encoded String of encoded {@code input} bytes */ public String encode(byte[] input, boolean addQuotes, String linefeed) { final int inputEnd = input.length; final StringBuilder sb = new StringBuilder(inputEnd + (inputEnd >> 2) + (inputEnd >> 3)); if (addQuotes) { sb.append('"'); } int chunksBeforeLF = getMaxLineLength() >> 2; int inputPtr = 0; int safeInputEnd = inputEnd-3; while (inputPtr <= safeInputEnd) { int b24 = (input[inputPtr++]) << 8; b24 |= (input[inputPtr++]) & 0xFF; b24 = (b24 << 8) | ((input[inputPtr++]) & 0xFF); encodeBase64Chunk(sb, b24); if (--chunksBeforeLF <= 0) { sb.append(linefeed); chunksBeforeLF = getMaxLineLength() >> 2; } } int inputLeft = inputEnd - inputPtr; if (inputLeft > 0) { int b24 = (input[inputPtr++]) << 16; if (inputLeft == 2) { b24 |= ((input[inputPtr++]) & 0xFF) << 8; } encodeBase64Partial(sb, b24, inputLeft); } if (addQuotes) { sb.append('"'); } return sb.toString(); } /** * Convenience method for decoding contents of a Base64-encoded String, * using this variant's settings. * * @param input Base64-encoded input String to decode * * @return Byte array of decoded contents * * @throws IllegalArgumentException if input is not valid base64 encoded data */ public byte[] decode(String input) throws IllegalArgumentException { try (ByteArrayBuilder b = new ByteArrayBuilder()) { decode(input, b); return b.toByteArray(); } } /** * Convenience method for decoding contents of a Base64-encoded String, * using this variant's settings * and appending decoded binary data using provided {@link ByteArrayBuilder}. *<p> * NOTE: builder will NOT be reset before decoding (nor cleared afterwards); * assumption is that caller will ensure it is given in proper state, and * used as appropriate afterwards. * * @param str Input to decode * @param builder Builder used for assembling decoded content * * @throws IllegalArgumentException if input is not valid base64 encoded data */ public void decode(String str, ByteArrayBuilder builder) throws IllegalArgumentException { int ptr = 0; int len = str.length(); main_loop: while (true) { // first, we'll skip preceding white space, if any char ch; do { if (ptr >= len) { break main_loop; } ch = str.charAt(ptr++); } while (ch <= INT_SPACE); int bits = decodeBase64Char(ch); if (bits < 0) { _reportInvalidBase64(ch, 0, null); } int decodedData = bits; // then second base64 char; can't get padding yet, nor ws if (ptr >= len) { _reportBase64EOF(); } ch = str.charAt(ptr++); bits = decodeBase64Char(ch); if (bits < 0) { _reportInvalidBase64(ch, 1, null); } decodedData = (decodedData << 6) | bits; // third base64 char; can be padding, but not ws if (ptr >= len) { // but as per [JACKSON-631] can be end-of-input, iff padding is not required if (!requiresPaddingOnRead()) { decodedData >>= 4; builder.append(decodedData); break; } _reportBase64EOF(); } ch = str.charAt(ptr++); bits = decodeBase64Char(ch); // First branch: can get padding (-> 1 byte) if (bits < 0) { if (bits != Base64Variant.BASE64_VALUE_PADDING) { _reportInvalidBase64(ch, 2, null); } if (!acceptsPaddingOnRead()) { _reportBase64UnexpectedPadding(); } // Ok, must get padding if (ptr >= len) { _reportBase64EOF(); } ch = str.charAt(ptr++); if (!usesPaddingChar(ch)) { _reportInvalidBase64(ch, 3, "expected padding character '"+getPaddingChar()+"'"); } // Got 12 bits, only need 8, need to shift decodedData >>= 4; builder.append(decodedData); continue; } // Nope, 2 or 3 bytes decodedData = (decodedData << 6) | bits; // fourth and last base64 char; can be padding, but not ws if (ptr >= len) { // but as per [JACKSON-631] can be end-of-input, iff padding on read is not required if (!requiresPaddingOnRead()) { decodedData >>= 2; builder.appendTwoBytes(decodedData); break; } _reportBase64EOF(); } ch = str.charAt(ptr++); bits = decodeBase64Char(ch); if (bits < 0) { if (bits != Base64Variant.BASE64_VALUE_PADDING) { _reportInvalidBase64(ch, 3, null); } if (!acceptsPaddingOnRead()) { _reportBase64UnexpectedPadding(); } decodedData >>= 2; builder.appendTwoBytes(decodedData); } else { // otherwise, our triple is now complete decodedData = (decodedData << 6) | bits; builder.appendThreeBytes(decodedData); } } } /* /********************************************************** /* Overridden standard methods /********************************************************** */ @Override public String toString() { return _name; } @Override public boolean equals(Object o) { // identity comparison should be fine // 26-Oct-2020, tatu: ... not any more with 2.12 if (o == this) return true; if (o == null || o.getClass() != getClass()) return false; Base64Variant other = (Base64Variant) o; return (other._paddingChar == _paddingChar) && (other._maxLineLength == _maxLineLength) && (other._writePadding == _writePadding) && (other._paddingReadBehaviour == _paddingReadBehaviour) && (_name.equals(other._name)) ; } @Override public int hashCode() { return _name.hashCode(); } /* /********************************************************** /* Internal helper methods /********************************************************** */ /** * @param ch Character to report on * @param bindex Relative index within base64 character unit; between 0 * and 3 (as unit has exactly 4 characters) * @param msg Base message to use for exception */ protected void _reportInvalidBase64(char ch, int bindex, String msg) throws IllegalArgumentException { String base; if (ch <= INT_SPACE) { base = "Illegal white space character (code 0x"+Integer.toHexString(ch)+") as character #"+(bindex+1)+" of 4-char base64 unit: can only used between units"; } else if (usesPaddingChar(ch)) { base = "Unexpected padding character ('"+getPaddingChar()+"') as character #"+(bindex+1)+" of 4-char base64 unit: padding only legal as 3rd or 4th character"; } else if (!Character.isDefined(ch) || Character.isISOControl(ch)) { // Not sure if we can really get here... ? (most illegal xml chars are caught at lower level) base = "Illegal character (code 0x"+Integer.toHexString(ch)+") in base64 content"; } else { base = "Illegal character '"+ch+"' (code 0x"+Integer.toHexString(ch)+") in base64 content"; } if (msg != null) { base = base + ": " + msg; } throw new IllegalArgumentException(base); } protected void _reportBase64EOF() throws IllegalArgumentException { throw new IllegalArgumentException(missingPaddingMessage()); } protected void _reportBase64UnexpectedPadding() throws IllegalArgumentException { throw new IllegalArgumentException(unexpectedPaddingMessage()); } /** * Helper method that will construct a message to use in exceptions for cases where input ends * prematurely in place where padding is not expected. * * @return Exception message for indicating "unexpected padding" case * * @since 2.12 */ protected String unexpectedPaddingMessage() { return String.format("Unexpected end of base64-encoded String: base64 variant '%s' expects no padding at the end while decoding. This Base64Variant might have been incorrectly configured", getName()); } /** * Helper method that will construct a message to use in exceptions for cases where input ends * prematurely in place where padding would be expected. * * @return Exception message for indicating "missing padding" case */ public String missingPaddingMessage() { // !!! TODO: why is this 'public'? return String.format("Unexpected end of base64-encoded String: base64 variant '%s' expects padding (one or more '%c' characters) at the end. This Base64Variant might have been incorrectly configured", getName(), getPaddingChar()); } }
PaddingReadBehaviour
java
elastic__elasticsearch
x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/AnnotationIndexIT.java
{ "start": 2076, "end": 19617 }
class ____ extends MlSingleNodeTestCase { @Override protected Settings nodeSettings() { Settings.Builder newSettings = Settings.builder(); newSettings.put(super.nodeSettings()); newSettings.put(XPackSettings.SECURITY_ENABLED.getKey(), false); newSettings.put(XPackSettings.WATCHER_ENABLED.getKey(), false); return newSettings.build(); } public void testNotCreatedWhenNoOtherMlIndices() { // Ask a few times to increase the chance of failure if the .ml-annotations index is created when no other ML index exists for (int i = 0; i < 10; ++i) { assertFalse(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(0, numberOfAnnotationsAliases()); } } public void testCreatedWhenAfterOtherMlIndex() throws Exception { // Creating a document in the .ml-notifications-000002 index should cause .ml-annotations // to be created, as it should get created as soon as any other ML index exists Set<Boolean> includeNodeInfoValues = Set.of(true, false); includeNodeInfoValues.forEach(includeNodeInfo -> { createNotification(includeNodeInfo); try { assertBusy(() -> { assertTrue(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(2, numberOfAnnotationsAliases()); }); } catch (Exception e) { throw new RuntimeException(e); } }); } public void testReindexingWithNodeInfo() throws Exception { // Creating a document in the .ml-notifications-000002 index should cause .ml-annotations // to be created, as it should get created as soon as any other ML index exists createNotification(true); assertBusy(() -> { assertTrue(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(2, numberOfAnnotationsAliases()); }); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, true)) .actionGet(); String reindexedIndexName = ".reindexed-v7-ml-annotations-6"; createReindexedIndex(reindexedIndexName); IndicesAliasesRequestBuilder indicesAliasesRequestBuilder = indicesAdmin().prepareAliases( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT ) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.READ_ALIAS_NAME).isHidden(true) ) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.WRITE_ALIAS_NAME).isHidden(true) ) .addAliasAction(IndicesAliasesRequest.AliasActions.removeIndex().index(AnnotationIndex.LATEST_INDEX_NAME)) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.LATEST_INDEX_NAME).isHidden(true) ); indicesAdmin().aliases(indicesAliasesRequestBuilder.request()).actionGet(); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, false)) .actionGet(); // Ask a few times to increase the chance of failure if the .ml-annotations index is created when no other ML index exists for (int i = 0; i < 10; ++i) { assertFalse(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertTrue(annotationsIndexExists(reindexedIndexName)); // Aliases should be read, write and original name assertEquals(3, numberOfAnnotationsAliases()); } } public void testReindexingWithoutNodeInfo() throws Exception { // Creating a document in the .ml-notifications-000002 index should cause .ml-annotations // to be created, as it should get created as soon as any other ML index exists createNotification(false); assertBusy(() -> { assertTrue(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(2, numberOfAnnotationsAliases()); }); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, true)) .actionGet(); String reindexedIndexName = ".reindexed-v7-ml-annotations-6"; createReindexedIndex(reindexedIndexName); IndicesAliasesRequestBuilder indicesAliasesRequestBuilder = indicesAdmin().prepareAliases( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT ) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.READ_ALIAS_NAME).isHidden(true) ) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.WRITE_ALIAS_NAME).isHidden(true) ) .addAliasAction(IndicesAliasesRequest.AliasActions.removeIndex().index(AnnotationIndex.LATEST_INDEX_NAME)) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.LATEST_INDEX_NAME).isHidden(true) ); indicesAdmin().aliases(indicesAliasesRequestBuilder.request()).actionGet(); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, false)) .actionGet(); // Ask a few times to increase the chance of failure if the .ml-annotations index is created when no other ML index exists for (int i = 0; i < 10; ++i) { assertFalse(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertTrue(annotationsIndexExists(reindexedIndexName)); // Aliases should be read, write and original name assertEquals(3, numberOfAnnotationsAliases()); } } public void testReindexingWithLostAliasesWithNodeInfo() throws Exception { // Creating a document in the .ml-notifications-000002 index should cause .ml-annotations // to be created, as it should get created as soon as any other ML index exists createNotification(true); assertBusy(() -> { assertTrue(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(2, numberOfAnnotationsAliases()); }); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, true)) .actionGet(); String reindexedIndexName = ".reindexed-v7-ml-annotations-6"; createReindexedIndex(reindexedIndexName); IndicesAliasesRequestBuilder indicesAliasesRequestBuilder = indicesAdmin().prepareAliases( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT ) // The difference compared to the standard reindexing test is that the read and write aliases are not correctly set up. // The annotations index maintenance code should add them back. .addAliasAction(IndicesAliasesRequest.AliasActions.removeIndex().index(AnnotationIndex.LATEST_INDEX_NAME)) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.LATEST_INDEX_NAME).isHidden(true) ); indicesAdmin().aliases(indicesAliasesRequestBuilder.request()).actionGet(); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, false)) .actionGet(); assertBusy(() -> { assertFalse(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertTrue(annotationsIndexExists(reindexedIndexName)); // Aliases should be read, write and original name assertEquals(3, numberOfAnnotationsAliases()); }); } public void testReindexingWithLostAliasesWithoutNodeInfo() throws Exception { // Creating a document in the .ml-notifications-000002 index should cause .ml-annotations // to be created, as it should get created as soon as any other ML index exists createNotification(false); assertBusy(() -> { assertTrue(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(2, numberOfAnnotationsAliases()); }); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, true)) .actionGet(); String reindexedIndexName = ".reindexed-v7-ml-annotations-6"; createReindexedIndex(reindexedIndexName); IndicesAliasesRequestBuilder indicesAliasesRequestBuilder = indicesAdmin().prepareAliases( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT ) // The difference compared to the standard reindexing test is that the read and write aliases are not correctly set up. // The annotations index maintenance code should add them back. .addAliasAction(IndicesAliasesRequest.AliasActions.removeIndex().index(AnnotationIndex.LATEST_INDEX_NAME)) .addAliasAction( IndicesAliasesRequest.AliasActions.add().index(reindexedIndexName).alias(AnnotationIndex.LATEST_INDEX_NAME).isHidden(true) ); indicesAdmin().aliases(indicesAliasesRequestBuilder.request()).actionGet(); client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, false)) .actionGet(); assertBusy(() -> { assertFalse(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertTrue(annotationsIndexExists(reindexedIndexName)); // Aliases should be read, write and original name assertEquals(3, numberOfAnnotationsAliases()); }); } public void testAliasesMovedFromOldToNew() throws Exception { // Create an old annotations index with both read and write aliases pointing at it. String oldIndex = randomFrom(AnnotationIndex.OLD_INDEX_NAMES); CreateIndexRequest createIndexRequest = new CreateIndexRequest(oldIndex).mapping(AnnotationIndex.annotationsMapping()) .settings( Settings.builder() .put(IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS, "0-1") .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, "1") .put(IndexMetadata.SETTING_INDEX_HIDDEN, true) ) .alias(new Alias(AnnotationIndex.READ_ALIAS_NAME).isHidden(true)) .alias(new Alias(AnnotationIndex.WRITE_ALIAS_NAME).isHidden(true)); client().execute(TransportCreateIndexAction.TYPE, createIndexRequest).actionGet(); // Because the old annotations index name began with .ml, it will trigger the new annotations index to be created. // When this happens the read alias should be changed to cover both indices, and the write alias should be // switched to only point at the new index. assertBusy(() -> { assertTrue(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); Map<String, List<AliasMetadata>> aliases = indicesAdmin().prepareGetAliases( TEST_REQUEST_TIMEOUT, AnnotationIndex.READ_ALIAS_NAME, AnnotationIndex.WRITE_ALIAS_NAME ).setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN_CLOSED_HIDDEN).get().getAliases(); assertNotNull(aliases); List<String> indicesWithReadAlias = new ArrayList<>(); for (var entry : aliases.entrySet()) { for (AliasMetadata aliasMetadata : entry.getValue()) { switch (aliasMetadata.getAlias()) { case AnnotationIndex.WRITE_ALIAS_NAME -> assertThat(entry.getKey(), is(AnnotationIndex.LATEST_INDEX_NAME)); case AnnotationIndex.READ_ALIAS_NAME -> indicesWithReadAlias.add(entry.getKey()); default -> fail("Found unexpected alias " + aliasMetadata.getAlias() + " on index " + entry.getKey()); } } } assertThat(indicesWithReadAlias, containsInAnyOrder(oldIndex, AnnotationIndex.LATEST_INDEX_NAME)); }); } public void testNotCreatedWhenAfterOtherMlIndexAndUpgradeInProgress() throws Exception { client().execute(SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, true)) .actionGet(); try { // Creating a document in the .ml-notifications-000002 index would normally cause .ml-annotations // to be created, but in this case it shouldn't as we're doing an upgrade Set<Boolean> includeNodeInfoValues = Set.of(true, false); includeNodeInfoValues.forEach(includeNodeInfo -> { createNotification(includeNodeInfo); try { assertBusy(() -> { assertHitCount(client().search(new SearchRequest(".ml-notifications*")), 1); assertFalse(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(0, numberOfAnnotationsAliases()); }); } catch (Exception e) { throw new RuntimeException(e); } }); } finally { client().execute( SetUpgradeModeAction.INSTANCE, new SetUpgradeModeAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, false) ).actionGet(); } } public void testNotCreatedWhenAfterOtherMlIndexAndResetInProgress() throws Exception { client().execute(SetResetModeAction.INSTANCE, SetResetModeActionRequest.enabled(TEST_REQUEST_TIMEOUT)).actionGet(); try { IndexRequest stateDoc = new IndexRequest(".ml-state"); stateDoc.source(Collections.singletonMap("state", "blah")); DocWriteResponse indexResponse = client().index(stateDoc).actionGet(); assertEquals(RestStatus.CREATED, indexResponse.status()); // Creating the .ml-state index would normally cause .ml-annotations // to be created, but in this case it shouldn't as we're doing a reset assertBusy(() -> { assertHitCount(client().search(new SearchRequest(".ml-state")), 1); assertFalse(annotationsIndexExists(AnnotationIndex.LATEST_INDEX_NAME)); assertEquals(0, numberOfAnnotationsAliases()); }); } finally { client().execute(SetResetModeAction.INSTANCE, SetResetModeActionRequest.disabled(TEST_REQUEST_TIMEOUT, true)).actionGet(); } } private boolean annotationsIndexExists(String expectedName) { GetIndexResponse getIndexResponse = indicesAdmin().prepareGetIndex(TEST_REQUEST_TIMEOUT) .setIndices(AnnotationIndex.LATEST_INDEX_NAME) .setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN) .get(); return Arrays.asList(getIndexResponse.getIndices()).contains(expectedName); } private int numberOfAnnotationsAliases() { int count = 0; Map<String, List<AliasMetadata>> aliases = indicesAdmin().prepareGetAliases( TEST_REQUEST_TIMEOUT, AnnotationIndex.READ_ALIAS_NAME, AnnotationIndex.WRITE_ALIAS_NAME, AnnotationIndex.LATEST_INDEX_NAME ).setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN_CLOSED_HIDDEN).get().getAliases(); if (aliases != null) { for (var aliasList : aliases.values()) { for (AliasMetadata aliasMetadata : aliasList) { assertThat("Annotations aliases should be hidden but are not: " + aliases, aliasMetadata.isHidden(), is(true)); } count += aliasList.size(); } } return count; } private void createReindexedIndex(String reindexedIndexName) { CreateIndexRequest createIndexRequest = new CreateIndexRequest(reindexedIndexName).mapping(AnnotationIndex.annotationsMapping()) .settings( Settings.builder() .put(IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS, "0-1") .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, "1") .put(IndexMetadata.SETTING_INDEX_HIDDEN, true) ); indicesAdmin().create(createIndexRequest).actionGet(); // At this point the upgrade assistant would reindex the old index into the new index but there's // no point in this test as there's nothing in the old index. } private void createNotification(boolean includeNodeInfo) { AnomalyDetectionAuditor auditor = new AnomalyDetectionAuditor( client(), getInstanceFromNode(ClusterService.class), TestIndexNameExpressionResolver.newInstance(), includeNodeInfo ); auditor.info("whatever", "blah"); } }
AnnotationIndexIT
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/rest/action/cat/RestShardsAction.java
{ "start": 2863, "end": 26572 }
class ____ extends AbstractCatAction { @Override public List<Route> routes() { return List.of(new Route(GET, "/_cat/shards"), new Route(GET, "/_cat/shards/{index}")); } @Override public String getName() { return "cat_shards_action"; } @Override public boolean allowSystemIndexAccessByDefault() { return true; } @Override protected void documentation(StringBuilder sb) { sb.append("/_cat/shards\n"); sb.append("/_cat/shards/{index}\n"); } @Override public RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) { final String[] indices = Strings.splitStringByCommaToArray(request.param("index")); final var clusterStateRequest = new ClusterStateRequest(getMasterNodeTimeout(request)); clusterStateRequest.clear().nodes(true).routingTable(true).indices(indices).indicesOptions(IndicesOptions.strictExpandHidden()); return channel -> { final var clusterStateFuture = new ListenableFuture<ClusterStateResponse>(); client.admin().cluster().state(clusterStateRequest, clusterStateFuture); client.admin() .indices() .stats( new IndicesStatsRequest().all().indices(indices).indicesOptions(IndicesOptions.strictExpandHidden()), new RestResponseListener<Table>(channel) { @Override public RestResponse buildResponse(Table table) throws Exception { return RestTable.buildResponse(table, channel); } }.delegateFailure( (delegate, indicesStatsResponse) -> clusterStateFuture.addListener( delegate.map(clusterStateResponse -> buildTable(request, clusterStateResponse, indicesStatsResponse)) ) ) ); }; } @Override protected Table getTableWithHeader(final RestRequest request) { Table table = new Table(); table.startHeaders() .addCell("index", "default:true;alias:i,idx;desc:index name") .addCell("shard", "default:true;alias:s,sh;desc:shard name") .addCell("prirep", "alias:p,pr,primaryOrReplica;default:true;desc:primary or replica") .addCell("state", "default:true;alias:st;desc:shard state") .addCell("docs", "alias:d,dc;text-align:right;desc:number of docs in shard") .addCell("store", "alias:sto;text-align:right;desc:store size of shard (how much disk it uses)") .addCell("dataset", "text-align:right;desc:total size of dataset") .addCell("ip", "default:true;desc:ip of node where it lives") .addCell("id", "default:false;desc:unique id of node where it lives") .addCell("node", "default:true;alias:n;desc:name of node where it lives"); if (request.getRestApiVersion() == RestApiVersion.V_8) { table.addCell("sync_id", "alias:sync_id;default:false;desc:sync id"); } table.addCell("unassigned.reason", "alias:ur;default:false;desc:reason shard became unassigned"); table.addCell("unassigned.at", "alias:ua;default:false;desc:time shard became unassigned (UTC)"); table.addCell("unassigned.for", "alias:uf;default:false;text-align:right;desc:time has been unassigned"); table.addCell("unassigned.details", "alias:ud;default:false;desc:additional details as to why the shard became unassigned"); table.addCell("recoverysource.type", "alias:rs;default:false;desc:recovery source type"); table.addCell("completion.size", "alias:cs,completionSize;default:false;text-align:right;desc:size of completion"); table.addCell("fielddata.memory_size", "alias:fm,fielddataMemory;default:false;text-align:right;desc:used fielddata cache"); table.addCell("fielddata.evictions", "alias:fe,fielddataEvictions;default:false;text-align:right;desc:fielddata evictions"); table.addCell("query_cache.memory_size", "alias:qcm,queryCacheMemory;default:false;text-align:right;desc:used query cache"); table.addCell("query_cache.evictions", "alias:qce,queryCacheEvictions;default:false;text-align:right;desc:query cache evictions"); table.addCell("flush.total", "alias:ft,flushTotal;default:false;text-align:right;desc:number of flushes"); table.addCell("flush.total_time", "alias:ftt,flushTotalTime;default:false;text-align:right;desc:time spent in flush"); table.addCell("get.current", "alias:gc,getCurrent;default:false;text-align:right;desc:number of current get ops"); table.addCell("get.time", "alias:gti,getTime;default:false;text-align:right;desc:time spent in get"); table.addCell("get.total", "alias:gto,getTotal;default:false;text-align:right;desc:number of get ops"); table.addCell("get.exists_time", "alias:geti,getExistsTime;default:false;text-align:right;desc:time spent in successful gets"); table.addCell("get.exists_total", "alias:geto,getExistsTotal;default:false;text-align:right;desc:number of successful gets"); table.addCell("get.missing_time", "alias:gmti,getMissingTime;default:false;text-align:right;desc:time spent in failed gets"); table.addCell("get.missing_total", "alias:gmto,getMissingTotal;default:false;text-align:right;desc:number of failed gets"); table.addCell( "indexing.delete_current", "alias:idc,indexingDeleteCurrent;default:false;text-align:right;desc:number of current deletions" ); table.addCell("indexing.delete_time", "alias:idti,indexingDeleteTime;default:false;text-align:right;desc:time spent in deletions"); table.addCell("indexing.delete_total", "alias:idto,indexingDeleteTotal;default:false;text-align:right;desc:number of delete ops"); table.addCell( "indexing.index_current", "alias:iic,indexingIndexCurrent;default:false;text-align:right;desc:number of current indexing ops" ); table.addCell("indexing.index_time", "alias:iiti,indexingIndexTime;default:false;text-align:right;desc:time spent in indexing"); table.addCell("indexing.index_total", "alias:iito,indexingIndexTotal;default:false;text-align:right;desc:number of indexing ops"); table.addCell( "indexing.index_failed", "alias:iif,indexingIndexFailed;default:false;text-align:right;desc:number of failed indexing ops" ); table.addCell( "indexing.index_failed_due_to_version_conflict", "alias:iifvc,indexingIndexFailedDueToVersionConflict;default:false;text-align:right;" + "desc:number of failed indexing ops due to version conflict" ); table.addCell("merges.current", "alias:mc,mergesCurrent;default:false;text-align:right;desc:number of current merges"); table.addCell( "merges.current_docs", "alias:mcd,mergesCurrentDocs;default:false;text-align:right;desc:number of current merging docs" ); table.addCell("merges.current_size", "alias:mcs,mergesCurrentSize;default:false;text-align:right;desc:size of current merges"); table.addCell("merges.total", "alias:mt,mergesTotal;default:false;text-align:right;desc:number of completed merge ops"); table.addCell("merges.total_docs", "alias:mtd,mergesTotalDocs;default:false;text-align:right;desc:docs merged"); table.addCell("merges.total_size", "alias:mts,mergesTotalSize;default:false;text-align:right;desc:size merged"); table.addCell("merges.total_time", "alias:mtt,mergesTotalTime;default:false;text-align:right;desc:time spent in merges"); table.addCell("refresh.total", "alias:rto,refreshTotal;default:false;text-align:right;desc:total refreshes"); table.addCell("refresh.time", "alias:rti,refreshTime;default:false;text-align:right;desc:time spent in refreshes"); table.addCell("refresh.external_total", "alias:rto,refreshTotal;default:false;text-align:right;desc:total external refreshes"); table.addCell( "refresh.external_time", "alias:rti,refreshTime;default:false;text-align:right;desc:time spent in external refreshes" ); table.addCell( "refresh.listeners", "alias:rli,refreshListeners;default:false;text-align:right;desc:number of pending refresh listeners" ); table.addCell("search.fetch_current", "alias:sfc,searchFetchCurrent;default:false;text-align:right;desc:current fetch phase ops"); table.addCell("search.fetch_time", "alias:sfti,searchFetchTime;default:false;text-align:right;desc:time spent in fetch phase"); table.addCell("search.fetch_total", "alias:sfto,searchFetchTotal;default:false;text-align:right;desc:total fetch ops"); table.addCell("search.open_contexts", "alias:so,searchOpenContexts;default:false;text-align:right;desc:open search contexts"); table.addCell("search.query_current", "alias:sqc,searchQueryCurrent;default:false;text-align:right;desc:current query phase ops"); table.addCell("search.query_time", "alias:sqti,searchQueryTime;default:false;text-align:right;desc:time spent in query phase"); table.addCell("search.query_total", "alias:sqto,searchQueryTotal;default:false;text-align:right;desc:total query phase ops"); table.addCell("search.scroll_current", "alias:scc,searchScrollCurrent;default:false;text-align:right;desc:open scroll contexts"); table.addCell( "search.scroll_time", "alias:scti,searchScrollTime;default:false;text-align:right;desc:time scroll contexts held open" ); table.addCell("search.scroll_total", "alias:scto,searchScrollTotal;default:false;text-align:right;desc:completed scroll contexts"); table.addCell("segments.count", "alias:sc,segmentsCount;default:false;text-align:right;desc:number of segments"); table.addCell("segments.memory", "alias:sm,segmentsMemory;default:false;text-align:right;desc:memory used by segments"); table.addCell( "segments.index_writer_memory", "alias:siwm,segmentsIndexWriterMemory;default:false;text-align:right;desc:memory used by index writer" ); table.addCell( "segments.version_map_memory", "alias:svmm,segmentsVersionMapMemory;default:false;text-align:right;desc:memory used by version map" ); table.addCell( "segments.fixed_bitset_memory", "alias:sfbm,fixedBitsetMemory;default:false;text-align:right;desc:memory used by fixed bit sets for nested object" + " field types and type filters for types referred in _parent fields" ); table.addCell("seq_no.max", "alias:sqm,maxSeqNo;default:false;text-align:right;desc:max sequence number"); table.addCell("seq_no.local_checkpoint", "alias:sql,localCheckpoint;default:false;text-align:right;desc:local checkpoint"); table.addCell("seq_no.global_checkpoint", "alias:sqg,globalCheckpoint;default:false;text-align:right;desc:global checkpoint"); table.addCell("warmer.current", "alias:wc,warmerCurrent;default:false;text-align:right;desc:current warmer ops"); table.addCell("warmer.total", "alias:wto,warmerTotal;default:false;text-align:right;desc:total warmer ops"); table.addCell("warmer.total_time", "alias:wtt,warmerTotalTime;default:false;text-align:right;desc:time spent in warmers"); table.addCell("path.data", "alias:pd,dataPath;default:false;text-align:right;desc:shard data path"); table.addCell("path.state", "alias:ps,statsPath;default:false;text-align:right;desc:shard state path"); table.addCell( "bulk.total_operations", "alias:bto,bulkTotalOperations;default:false;text-align:right;desc:number of bulk shard ops" ); table.addCell("bulk.total_time", "alias:btti,bulkTotalTime;default:false;text-align:right;desc:time spend in shard bulk"); table.addCell( "bulk.total_size_in_bytes", "alias:btsi,bulkTotalSizeInBytes;default:false;text-align:right;desc:total size in bytes of shard bulk" ); table.addCell("bulk.avg_time", "alias:bati,bulkAvgTime;default:false;text-align:right;desc:average time spend in shard bulk"); table.addCell( "bulk.avg_size_in_bytes", "alias:basi,bulkAvgSizeInBytes;default:false;text-align:right;desc:avg size in bytes of shard bulk" ); table.addCell( "dense_vector.value_count", "alias:dvc,denseVectorCount;default:false;text-align:right;desc:number of indexed dense vectors in shard" ); table.addCell( "sparse_vector.value_count", "alias:svc,sparseVectorCount;default:false;text-align:right;desc:number of indexed sparse vectors in shard" ); table.endHeaders(); return table; } private static <S, T> Object getOrNull(S stats, Function<S, T> accessor, Function<T, Object> func) { if (stats != null) { T t = accessor.apply(stats); if (t != null) { return func.apply(t); } } return null; } // package private for testing Table buildTable(RestRequest request, ClusterStateResponse state, IndicesStatsResponse stats) { Table table = getTableWithHeader(request); for (ShardRouting shard : state.getState().routingTable().allShardsIterator()) { ShardStats shardStats = stats.asMap().get(shard); CommonStats commonStats = null; CommitStats commitStats = null; if (shardStats != null) { commonStats = shardStats.getStats(); commitStats = shardStats.getCommitStats(); } table.startRow(); table.addCell(shard.getIndexName()); table.addCell(shard.id()); if (shard.primary()) { table.addCell("p"); } else { table.addCell("r"); } table.addCell(shard.state()); table.addCell(getOrNull(commonStats, CommonStats::getDocs, DocsStats::getCount)); table.addCell(getOrNull(commonStats, CommonStats::getStore, StoreStats::size)); table.addCell(getOrNull(commonStats, CommonStats::getStore, StoreStats::totalDataSetSize)); if (shard.assignedToNode()) { String ip = state.getState().nodes().get(shard.currentNodeId()).getHostAddress(); String nodeId = shard.currentNodeId(); StringBuilder name = new StringBuilder(); name.append(state.getState().nodes().get(shard.currentNodeId()).getName()); if (shard.relocating()) { String reloIp = state.getState().nodes().get(shard.relocatingNodeId()).getHostAddress(); String reloNme = state.getState().nodes().get(shard.relocatingNodeId()).getName(); String reloNodeId = shard.relocatingNodeId(); name.append(" -> "); name.append(reloIp); name.append(" "); name.append(reloNodeId); name.append(" "); name.append(reloNme); } table.addCell(ip); table.addCell(nodeId); table.addCell(name); } else { table.addCell(null); table.addCell(null); table.addCell(null); } if (request.getRestApiVersion() == RestApiVersion.V_8) { table.addCell(null); } if (shard.unassignedInfo() != null) { table.addCell(shard.unassignedInfo().reason()); Instant unassignedTime = Instant.ofEpochMilli(shard.unassignedInfo().unassignedTimeMillis()); table.addCell(UnassignedInfo.DATE_TIME_FORMATTER.format(unassignedTime)); table.addCell( TimeValue.timeValueMillis(Math.max(0, System.currentTimeMillis() - shard.unassignedInfo().unassignedTimeMillis())) ); table.addCell(shard.unassignedInfo().details()); } else { table.addCell(null); table.addCell(null); table.addCell(null); table.addCell(null); } if (shard.recoverySource() != null) { table.addCell(shard.recoverySource().getType().toString().toLowerCase(Locale.ROOT)); } else { table.addCell(null); } table.addCell(getOrNull(commonStats, CommonStats::getCompletion, CompletionStats::getSize)); table.addCell(getOrNull(commonStats, CommonStats::getFieldData, FieldDataStats::getMemorySize)); table.addCell(getOrNull(commonStats, CommonStats::getFieldData, FieldDataStats::getEvictions)); table.addCell(getOrNull(commonStats, CommonStats::getQueryCache, QueryCacheStats::getMemorySize)); table.addCell(getOrNull(commonStats, CommonStats::getQueryCache, QueryCacheStats::getEvictions)); table.addCell(getOrNull(commonStats, CommonStats::getFlush, FlushStats::getTotal)); table.addCell(getOrNull(commonStats, CommonStats::getFlush, FlushStats::getTotalTime)); table.addCell(getOrNull(commonStats, CommonStats::getGet, GetStats::current)); table.addCell(getOrNull(commonStats, CommonStats::getGet, GetStats::getTime)); table.addCell(getOrNull(commonStats, CommonStats::getGet, GetStats::getCount)); table.addCell(getOrNull(commonStats, CommonStats::getGet, GetStats::getExistsTime)); table.addCell(getOrNull(commonStats, CommonStats::getGet, GetStats::getExistsCount)); table.addCell(getOrNull(commonStats, CommonStats::getGet, GetStats::getMissingTime)); table.addCell(getOrNull(commonStats, CommonStats::getGet, GetStats::getMissingCount)); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getDeleteCurrent())); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getDeleteTime())); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getDeleteCount())); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getIndexCurrent())); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getIndexTime())); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getIndexCount())); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getIndexFailedCount())); table.addCell(getOrNull(commonStats, CommonStats::getIndexing, i -> i.getTotal().getIndexFailedDueToVersionConflictCount())); table.addCell(getOrNull(commonStats, CommonStats::getMerge, MergeStats::getCurrent)); table.addCell(getOrNull(commonStats, CommonStats::getMerge, MergeStats::getCurrentNumDocs)); table.addCell(getOrNull(commonStats, CommonStats::getMerge, MergeStats::getCurrentSize)); table.addCell(getOrNull(commonStats, CommonStats::getMerge, MergeStats::getTotal)); table.addCell(getOrNull(commonStats, CommonStats::getMerge, MergeStats::getTotalNumDocs)); table.addCell(getOrNull(commonStats, CommonStats::getMerge, MergeStats::getTotalSize)); table.addCell(getOrNull(commonStats, CommonStats::getMerge, MergeStats::getTotalTime)); table.addCell(getOrNull(commonStats, CommonStats::getRefresh, RefreshStats::getTotal)); table.addCell(getOrNull(commonStats, CommonStats::getRefresh, RefreshStats::getTotalTime)); table.addCell(getOrNull(commonStats, CommonStats::getRefresh, RefreshStats::getExternalTotal)); table.addCell(getOrNull(commonStats, CommonStats::getRefresh, RefreshStats::getExternalTotalTime)); table.addCell(getOrNull(commonStats, CommonStats::getRefresh, RefreshStats::getListeners)); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getFetchCurrent())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getFetchTime())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getFetchCount())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, SearchStats::getOpenContexts)); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getQueryCurrent())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getQueryTime())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getQueryCount())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getScrollCurrent())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getScrollTime())); table.addCell(getOrNull(commonStats, CommonStats::getSearch, i -> i.getTotal().getScrollCount())); table.addCell(getOrNull(commonStats, CommonStats::getSegments, SegmentsStats::getCount)); table.addCell(getOrNull(commonStats, CommonStats::getSegments, ss -> ByteSizeValue.ZERO)); table.addCell(getOrNull(commonStats, CommonStats::getSegments, SegmentsStats::getIndexWriterMemory)); table.addCell(getOrNull(commonStats, CommonStats::getSegments, SegmentsStats::getVersionMapMemory)); table.addCell(getOrNull(commonStats, CommonStats::getSegments, SegmentsStats::getBitsetMemory)); table.addCell(getOrNull(shardStats, ShardStats::getSeqNoStats, SeqNoStats::getMaxSeqNo)); table.addCell(getOrNull(shardStats, ShardStats::getSeqNoStats, SeqNoStats::getLocalCheckpoint)); table.addCell(getOrNull(shardStats, ShardStats::getSeqNoStats, SeqNoStats::getGlobalCheckpoint)); table.addCell(getOrNull(commonStats, CommonStats::getWarmer, WarmerStats::current)); table.addCell(getOrNull(commonStats, CommonStats::getWarmer, WarmerStats::total)); table.addCell(getOrNull(commonStats, CommonStats::getWarmer, WarmerStats::totalTime)); table.addCell(getOrNull(shardStats, ShardStats::getDataPath, s -> s)); table.addCell(getOrNull(shardStats, ShardStats::getStatePath, s -> s)); table.addCell(getOrNull(commonStats, CommonStats::getBulk, BulkStats::getTotalOperations)); table.addCell(getOrNull(commonStats, CommonStats::getBulk, BulkStats::getTotalTime)); table.addCell(getOrNull(commonStats, CommonStats::getBulk, BulkStats::getTotalSizeInBytes)); table.addCell(getOrNull(commonStats, CommonStats::getBulk, BulkStats::getAvgTime)); table.addCell(getOrNull(commonStats, CommonStats::getBulk, BulkStats::getAvgSizeInBytes)); table.addCell(getOrNull(commonStats, CommonStats::getDenseVectorStats, DenseVectorStats::getValueCount)); table.addCell(getOrNull(commonStats, CommonStats::getSparseVectorStats, SparseVectorStats::getValueCount)); table.endRow(); } return table; } }
RestShardsAction
java
apache__flink
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/pattern/Quantifier.java
{ "start": 6170, "end": 6383 }
enum ____ { STRICT, SKIP_TILL_NEXT, SKIP_TILL_ANY, NOT_FOLLOW, NOT_NEXT } /** Describe the times this {@link Pattern} can occur. */ public static
ConsumingStrategy
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/constructor/nestedsource/source/Artist.java
{ "start": 253, "end": 558 }
class ____ { private final String name; private final Label label; public Artist(String name, Label label) { this.name = name; this.label = label; } public String getName() { return name; } public Label getLabel() { return label; } }
Artist
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/huggingface/request/rerank/HuggingFaceRerankRequestTests.java
{ "start": 3355, "end": 3480 }
class ____ fake the auth implementation to avoid static mocking of {@link HuggingFaceRerankRequest} */ private static
to
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoBuilderCompilationTest.java
{ "start": 19763, "end": 20075 }
interface ____"); } @Test public void methodNotStatic() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "foo.bar.Baz", "package foo.bar;", "", "import com.google.auto.value.AutoBuilder;", "", "public
Builder
java
apache__camel
components/camel-ai/camel-tensorflow-serving/src/main/java/org/apache/camel/component/tensorflow/serving/TensorFlowServingConstants.java
{ "start": 970, "end": 2271 }
interface ____ { @Metadata(description = "The target of the client. See: https://grpc.github.io/grpc-java/javadoc/io/grpc/Grpc.html#newChannelBuilder%28java.lang.String,io.grpc.ChannelCredentials%29", javaType = "String") String TARGET = "CamelTensorFlowServingTarget"; @Metadata(description = "The credentials of the client.", javaType = "io.grpc.ChannelCredentials") String CREDENTIALS = "CamelTensorFlowServingCredentials"; @Metadata(description = "Required servable name.", javaType = "String") String MODEL_NAME = "CamelTensorFlowServingModelName"; @Metadata(description = "Optional choice of which version of the model to use. Use this specific version number.", javaType = "long") String MODEL_VERSION = "CamelTensorFlowServingModelVersion"; @Metadata(description = "Optional choice of which version of the model to use. Use the version associated with the given label.", javaType = "String") String MODEL_VERSION_LABEL = "CamelTensorFlowServingModelVersionLabel"; @Metadata(description = "A named signature to evaluate. If unspecified, the default signature will be used.", javaType = "String") String SIGNATURE_NAME = "CamelTensorFlowServingSignatureName"; }
TensorFlowServingConstants
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/text/translate/OctalUnescaperTest.java
{ "start": 1100, "end": 3322 }
class ____ extends AbstractLangTest { @Test void testBetween() { final OctalUnescaper oue = new OctalUnescaper(); //.between("1", "377"); String input = "\\45"; String result = oue.translate(input); assertEquals("\45", result, "Failed to unescape octal characters via the between method"); input = "\\377"; result = oue.translate(input); assertEquals("\377", result, "Failed to unescape octal characters via the between method"); input = "\\377 and"; result = oue.translate(input); assertEquals("\377 and", result, "Failed to unescape octal characters via the between method"); input = "\\378 and"; result = oue.translate(input); assertEquals("\37" + "8 and", result, "Failed to unescape octal characters via the between method"); input = "\\378"; result = oue.translate(input); assertEquals("\37" + "8", result, "Failed to unescape octal characters via the between method"); input = "\\1"; result = oue.translate(input); assertEquals("\1", result, "Failed to unescape octal characters via the between method"); input = "\\036"; result = oue.translate(input); assertEquals("\036", result, "Failed to unescape octal characters via the between method"); input = "\\0365"; result = oue.translate(input); assertEquals("\036" + "5", result, "Failed to unescape octal characters via the between method"); input = "\\003"; result = oue.translate(input); assertEquals("\003", result, "Failed to unescape octal characters via the between method"); input = "\\0003"; result = oue.translate(input); assertEquals("\000" + "3", result, "Failed to unescape octal characters via the between method"); input = "\\279"; result = oue.translate(input); assertEquals("\279", result, "Failed to unescape octal characters via the between method"); input = "\\999"; result = oue.translate(input); assertEquals("\\999", result, "Failed to ignore an out of range octal character via the between method"); } }
OctalUnescaperTest
java
apache__logging-log4j2
log4j-api-test/src/main/java/org/apache/logging/log4j/test/ThreadContextHolder.java
{ "start": 1235, "end": 2796 }
class ____ { private final Map<String, String> immutableContext; private final ContextStack immutableStack; private final boolean restoreContext; private final boolean restoreStack; /** * Constructs a new holder initialized with an immutable copy of the ThreadContext stack and map. * * @param restoreContext * @param restoreStack */ public ThreadContextHolder(final boolean restoreContext, final boolean restoreStack) { this.restoreContext = restoreContext; this.restoreStack = restoreStack; this.immutableContext = restoreContext ? ThreadContext.getImmutableContext() : null; this.immutableStack = restoreStack ? ThreadContext.getImmutableStack() : null; } /** * Restores the ThreadContext stack and map based on the values saved in the constructor. */ public void restore() { if (restoreStack) { ThreadContext.setStack(immutableStack); } if (restoreContext) { // TODO LOG4J2-1517 Add ThreadContext.setContext(Map<String, String>) // Use: // ThreadContext.setContext(immutableContext); // Instead of: ThreadContext.clearMap(); ThreadContext.putAll(immutableContext); // // or: // ThreadContext.clearMap(); // for (Map.Entry<String, String> entry : immutableContext.entrySet()) { // ThreadContext.put(entry.getKey(), entry.getValue()); // } } } }
ThreadContextHolder
java
quarkusio__quarkus
extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/grpc/GrpcTracingClientInterceptor.java
{ "start": 4018, "end": 4992 }
class ____<ReqT, RespT> extends ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT> { private final Context spanContext; private final GrpcRequest grpcRequest; protected TracingClientCall(final ClientCall<ReqT, RespT> delegate, final Context spanContext, final GrpcRequest grpcRequest) { super(delegate); this.spanContext = spanContext; this.grpcRequest = grpcRequest; } @Override public void start(final Listener<RespT> responseListener, final Metadata headers) { GrpcRequest clientRequest = GrpcRequest.client(grpcRequest.getMethodDescriptor(), headers); openTelemetry.getPropagators().getTextMapPropagator().inject(spanContext, clientRequest, GrpcTextMapSetter.INSTANCE); super.start(new TracingClientCallListener<>(responseListener, spanContext, clientRequest), headers); } } }
TracingClientCall
java
google__guava
android/guava-tests/test/com/google/common/reflect/TypeTokenSubtypeTest.java
{ "start": 20104, "end": 20142 }
class ____ SubtypeTester. private
using
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/http/sendfile/Http2SendFileTest.java
{ "start": 595, "end": 940 }
class ____ extends HttpSendFileTest { @Override protected HttpServerOptions createBaseServerOptions() { return Http2TestBase.createHttp2ServerOptions(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST); } @Override protected HttpClientOptions createBaseClientOptions() { return Http2TestBase.createHttp2ClientOptions(); } }
Http2SendFileTest
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelStartupRecorderAction.java
{ "start": 1666, "end": 5622 }
class ____ extends ActionWatchCommand { @CommandLine.Parameters(description = "Name or pid of running Camel integration", arity = "0..1") String name = "*"; @CommandLine.Option(names = { "--sort" }, completionCandidates = DurationTypeCompletionCandidates.class, description = "Sort by duration, or type") String sort; private volatile long pid; public CamelStartupRecorderAction(CamelJBangMain main) { super(main); } @Override public Integer doWatchCall() throws Exception { List<Row> rows = new ArrayList<>(); List<Long> pids = findPids(name); if (pids.isEmpty()) { return 0; } else if (pids.size() > 1) { printer().println("Name or pid " + name + " matches " + pids.size() + " running Camel integrations. Specify a name or PID that matches exactly one."); return 0; } this.pid = pids.get(0); // ensure output file is deleted before executing action Path outputFile = getOutputFile(Long.toString(pid)); PathUtils.deleteFile(outputFile); JsonObject root = new JsonObject(); root.put("action", "startup-recorder"); Path f = getActionFile(Long.toString(pid)); try { Files.writeString(f, root.toJson()); } catch (Exception e) { // ignore } JsonObject jo = waitForOutputFile(outputFile); if (jo != null) { JsonArray arr = (JsonArray) jo.get("steps"); for (int i = 0; arr != null && i < arr.size(); i++) { JsonObject o = (JsonObject) arr.get(i); Row row = new Row(); row.id = o.getInteger("id"); row.parentId = o.getInteger("parentId"); row.level = o.getInteger("level"); row.name = o.getString("name"); row.type = o.getString("type"); row.description = o.getString("description"); row.duration = o.getLong("duration"); rows.add(row); } } // sort rows rows.sort(this::sortRow); if (!rows.isEmpty()) { printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, rows, Arrays.asList( new Column().header("DURATION").dataAlign(HorizontalAlign.RIGHT).with(this::getDuration), new Column().header("TYPE").dataAlign(HorizontalAlign.LEFT).with(r -> r.type), new Column().header("STEP (END)").dataAlign(HorizontalAlign.LEFT) .maxWidth(80, OverflowBehaviour.ELLIPSIS_RIGHT) .with(this::getStep)))); } // delete output file after use PathUtils.deleteFile(outputFile); return 0; } private String getStep(Row r) { String pad = StringHelper.padString(r.level); String out = r.description; if (r.name != null && !r.name.equals("null")) { out = String.format("%s(%s)", r.description, r.name); } return pad + out; } private String getDuration(Row r) { if (r.duration > 0) { return Long.toString(r.duration); } return ""; } protected int sortRow(Row o1, Row o2) { String s = sort != null ? sort : ""; int negate = 1; if (s.startsWith("-")) { s = s.substring(1); negate = -1; } switch (s) { case "duration": return Long.compare(o1.duration, o2.duration) * negate; case "type": return o1.type.compareToIgnoreCase(o2.type) * negate; default: return 0; } } protected JsonObject waitForOutputFile(Path outputFile) { return getJsonObject(outputFile); } private static
CamelStartupRecorderAction
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/JndiCloser.java
{ "start": 974, "end": 1061 }
class ____ separate from {@link Closer} because JNDI is not in Android. */ public final
is
java
micronaut-projects__micronaut-core
discovery-core/src/main/java/io/micronaut/discovery/metadata/ServiceInstanceMetadataContributor.java
{ "start": 1032, "end": 1341 }
interface ____ { /** * Contribute metadata to the given {@link ServiceInstance} prior to registration. * * @param instance The instance * @param metadata The metadata */ void contribute(ServiceInstance instance, Map<String, String> metadata); }
ServiceInstanceMetadataContributor
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/DataClassRowMapper.java
{ "start": 5353, "end": 5860 }
class ____ each row should be mapped to * @param conversionService the {@link ConversionService} for binding * JDBC values to bean properties, or {@code null} for none * @see #newInstance(Class) * @see #setConversionService */ public static <T> DataClassRowMapper<T> newInstance( Class<T> mappedClass, @Nullable ConversionService conversionService) { DataClassRowMapper<T> rowMapper = newInstance(mappedClass); rowMapper.setConversionService(conversionService); return rowMapper; } }
that
java
netty__netty
codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactoryTest.java
{ "start": 1259, "end": 2174 }
class ____ { @Test public void testUnsupportedVersion() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(); WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ch); ch.runPendingTasks(); Object msg = ch.readOutbound(); if (!(msg instanceof FullHttpResponse)) { fail("Got wrong response " + msg); } FullHttpResponse response = (FullHttpResponse) msg; assertEquals(HttpResponseStatus.UPGRADE_REQUIRED, response.status()); assertEquals(WebSocketVersion.V13.toHttpHeaderValue(), response.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION)); assertTrue(HttpUtil.isContentLengthSet(response)); assertEquals(0, HttpUtil.getContentLength(response)); ReferenceCountUtil.release(response); assertFalse(ch.finish()); } }
WebSocketServerHandshakerFactoryTest
java
apache__flink
flink-python/src/main/java/org/apache/flink/table/runtime/operators/python/aggregate/PythonStreamGroupTableAggregateOperator.java
{ "start": 1337, "end": 2928 }
class ____ extends AbstractPythonStreamGroupAggregateOperator { private static final long serialVersionUID = 1L; @VisibleForTesting protected static final String STREAM_GROUP_TABLE_AGGREGATE_URN = "flink:transform:stream_group_table_aggregate:v1"; public PythonStreamGroupTableAggregateOperator( Configuration config, RowType inputType, RowType outputType, PythonAggregateFunctionInfo[] aggregateFunctions, DataViewSpec[][] dataViewSpecs, int[] grouping, int indexOfCountStar, boolean generateUpdateBefore, long minRetentionTime, long maxRetentionTime) { super( config, inputType, outputType, aggregateFunctions, dataViewSpecs, grouping, indexOfCountStar, generateUpdateBefore, minRetentionTime, maxRetentionTime); } /** * Gets the proto representation of the Python user-defined table aggregate function to be * executed. */ @Override public FlinkFnApi.UserDefinedAggregateFunctions getUserDefinedFunctionsProto() { FlinkFnApi.UserDefinedAggregateFunctions.Builder builder = super.getUserDefinedFunctionsProto().toBuilder(); return builder.build(); } @Override public String getFunctionUrn() { return STREAM_GROUP_TABLE_AGGREGATE_URN; } }
PythonStreamGroupTableAggregateOperator
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/security/HttpUpgradeSelectAuthMechWithAnnotationTest.java
{ "start": 15349, "end": 15982 }
class ____ { @Inject CurrentIdentityAssociation currentIdentity; @OnOpen String open() { return "ready"; } @RolesAllowed("admin") @OnTextMessage String echo(String message) { return "sub-endpoint"; } @OnError String error(ForbiddenException t) { return "sub-endpoint:forbidden:" + currentIdentity.getIdentity().getPrincipal().getName(); } } } @BasicAuthentication @WebSocket(path = "/end") public static
SubEndpoint
java
google__dagger
javatests/dagger/functional/producers/monitoring/StubModule.java
{ "start": 821, "end": 1188 }
interface ____ {} private final StringStub server1; private final StringStub server2; StubModule(StringStub server1, StringStub server2) { this.server1 = server1; this.server2 = server2; } @Provides @ForServer1 StringStub server1() { return server1; } @Provides @ForServer2 StringStub server2() { return server2; } }
ForServer2
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fkcircularity/ClassB.java
{ "start": 444, "end": 476 }
class ____ extends ClassA { }
ClassB
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/DtUtilShell.java
{ "start": 9929, "end": 10876 }
class ____ extends SubCommand { public static final String REMOVE_USAGE = "dtutil remove -alias <alias> " + FORMAT_SUBSTRING + " filename..."; public static final String CANCEL_USAGE = "dtutil cancel -alias <alias> " + FORMAT_SUBSTRING + " filename..."; private boolean cancel = false; public Remove(boolean arg) { cancel = arg; } @Override public boolean validate() { if (alias == null) { LOG.error("-alias flag is not optional for remove or cancel"); return false; } return true; } @Override public void execute() throws Exception { for (File tokenFile : tokenFiles) { DtFileOperations.removeTokenFromFile( cancel, tokenFile, format, alias, getConf()); } } @Override public String getUsage() { if (cancel) { return CANCEL_USAGE; } return REMOVE_USAGE; } } private
Remove
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/transport/OutboundHandlerTests.java
{ "start": 2773, "end": 25973 }
class ____ extends ESTestCase { private final TestThreadPool threadPool = new TestThreadPool(getClass().getName()); private final TransportRequestOptions options = TransportRequestOptions.EMPTY; private final AtomicReference<Tuple<Header, BytesReference>> message = new AtomicReference<>(); private final BytesRefRecycler recycler = new BytesRefRecycler(PageCacheRecycler.NON_RECYCLING_INSTANCE); private InboundPipeline pipeline; private OutboundHandler handler; private FakeTcpChannel channel; private PlainActionFuture<Void> closeListener; private DiscoveryNode node; private Compression.Scheme compressionScheme; @Before public void setUp() throws Exception { super.setUp(); channel = new FakeTcpChannel(randomBoolean(), buildNewFakeTransportAddress().address(), buildNewFakeTransportAddress().address()); closeListener = new PlainActionFuture<>(); channel.addCloseListener(closeListener); TransportAddress transportAddress = buildNewFakeTransportAddress(); node = DiscoveryNodeUtils.create("", transportAddress); StatsTracker statsTracker = new StatsTracker(); compressionScheme = randomFrom(Compression.Scheme.DEFLATE, Compression.Scheme.LZ4); handler = new OutboundHandler( "node", TransportVersion.current(), statsTracker, threadPool, recycler, new HandlingTimeTracker(), false ); final LongSupplier millisSupplier = () -> TimeValue.nsecToMSec(System.nanoTime()); final InboundDecoder decoder = new InboundDecoder(this.recycler); final Supplier<CircuitBreaker> breaker = () -> new NoopCircuitBreaker("test"); final InboundAggregator aggregator = new InboundAggregator(breaker, (Predicate<String>) action -> true); pipeline = new InboundPipeline(statsTracker, millisSupplier, decoder, aggregator, (c, m) -> { try (BytesStreamOutput streamOutput = new BytesStreamOutput()) { Streams.copy(m.openOrGetStreamInput(), streamOutput); message.set(new Tuple<>(m.getHeader(), streamOutput.bytes())); } catch (IOException e) { throw new AssertionError(e); } }); } @After public void tearDown() throws Exception { ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS); super.tearDown(); } public void testSendRawBytes() { BytesArray bytesArray = new BytesArray("message".getBytes(StandardCharsets.UTF_8)); AtomicBoolean isSuccess = new AtomicBoolean(false); AtomicReference<Exception> exception = new AtomicReference<>(); ActionListener<Void> listener = ActionListener.wrap((v) -> isSuccess.set(true), exception::set); handler.sendBytes(channel, bytesArray, listener); BytesReference reference = channel.getMessageCaptor().get(); ActionListener<Void> sendListener = channel.getListenerCaptor().get(); if (randomBoolean()) { sendListener.onResponse(null); assertTrue(isSuccess.get()); assertNull(exception.get()); } else { IOException e = new IOException("failed"); sendListener.onFailure(e); assertFalse(isSuccess.get()); assertSame(e, exception.get()); } assertThat(reference, equalBytes(bytesArray)); } public void testSendRequest() throws IOException { ThreadContext threadContext = threadPool.getThreadContext(); String action = "handshake"; long requestId = randomLongBetween(0, 300); boolean isHandshake = randomBoolean(); TransportVersion version = isHandshake ? randomFrom(TransportHandshaker.ALLOWED_HANDSHAKE_VERSIONS) : TransportVersionUtils.randomCompatibleVersion(random()); boolean compress = randomBoolean(); String value = "message"; threadContext.putHeader("header", "header_value"); TestRequest request = new TestRequest(value); AtomicReference<DiscoveryNode> nodeRef = new AtomicReference<>(); AtomicLong requestIdRef = new AtomicLong(); AtomicReference<String> actionRef = new AtomicReference<>(); AtomicReference<TransportRequest> requestRef = new AtomicReference<>(); handler.setMessageListener(new TransportMessageListener() { @Override public void onRequestSent( DiscoveryNode node, long requestId, String action, TransportRequest request, TransportRequestOptions options ) { nodeRef.set(node); requestIdRef.set(requestId); actionRef.set(action); requestRef.set(request); } }); if (compress) { handler.sendRequest(node, channel, requestId, action, request, options, version, compressionScheme, isHandshake); } else { handler.sendRequest(node, channel, requestId, action, request, options, version, null, isHandshake); } BytesReference reference = channel.getMessageCaptor().get(); ActionListener<Void> sendListener = channel.getListenerCaptor().get(); if (randomBoolean()) { sendListener.onResponse(null); } else { sendListener.onFailure(new IOException("failed")); } assertEquals(node, nodeRef.get()); assertEquals(requestId, requestIdRef.get()); assertEquals(action, actionRef.get()); assertEquals(request, requestRef.get()); pipeline.handleBytes(channel, new ReleasableBytesReference(reference, () -> {})); final Tuple<Header, BytesReference> tuple = message.get(); final Header header = tuple.v1(); final TestRequest message = new TestRequest(tuple.v2().streamInput()); assertEquals(version, header.getVersion()); assertEquals(requestId, header.getRequestId()); assertTrue(header.isRequest()); assertFalse(header.isResponse()); if (isHandshake) { assertTrue(header.isHandshake()); } else { assertFalse(header.isHandshake()); } if (compress) { assertTrue(header.isCompressed()); } else { assertFalse(header.isCompressed()); } assertEquals(value, message.value); assertEquals("header_value", header.getHeaders().v1().get("header")); } public void testSendResponse() throws IOException { ThreadContext threadContext = threadPool.getThreadContext(); String action = "handshake"; long requestId = randomLongBetween(0, 300); boolean isHandshake = randomBoolean(); TransportVersion version = isHandshake ? randomFrom(TransportHandshaker.ALLOWED_HANDSHAKE_VERSIONS) : TransportVersionUtils.randomCompatibleVersion(random()); boolean compress = randomBoolean(); String value = "message"; threadContext.putHeader("header", "header_value"); TestResponse response = new TestResponse(value); AtomicLong requestIdRef = new AtomicLong(); AtomicReference<String> actionRef = new AtomicReference<>(); handler.setMessageListener(new TransportMessageListener() { @Override public void onResponseSent(long requestId, String action) { requestIdRef.set(requestId); actionRef.set(action); } }); if (compress) { handler.sendResponse(version, channel, requestId, action, response, compressionScheme, isHandshake, ResponseStatsConsumer.NONE); } else { handler.sendResponse(version, channel, requestId, action, response, null, isHandshake, ResponseStatsConsumer.NONE); } BytesReference reference = channel.getMessageCaptor().get(); ActionListener<Void> sendListener = channel.getListenerCaptor().get(); if (randomBoolean()) { sendListener.onResponse(null); } else { sendListener.onFailure(new IOException("failed")); } assertEquals(requestId, requestIdRef.get()); assertEquals(action, actionRef.get()); pipeline.handleBytes(channel, new ReleasableBytesReference(reference, () -> {})); final Tuple<Header, BytesReference> tuple = message.get(); final Header header = tuple.v1(); final TestResponse message = new TestResponse(tuple.v2().streamInput()); assertEquals(version, header.getVersion()); assertEquals(requestId, header.getRequestId()); assertFalse(header.isRequest()); assertTrue(header.isResponse()); if (isHandshake) { assertTrue(header.isHandshake()); } else { assertFalse(header.isHandshake()); } if (compress) { assertTrue(header.isCompressed()); } else { assertFalse(header.isCompressed()); } assertFalse(header.isError()); assertEquals(value, message.value); assertEquals("header_value", header.getHeaders().v1().get("header")); } public void testErrorResponse() throws IOException { ThreadContext threadContext = threadPool.getThreadContext(); TransportVersion version = TransportVersionUtils.randomCompatibleVersion(random()); String action = "not-a-handshake"; long requestId = randomLongBetween(0, 300); threadContext.putHeader("header", "header_value"); ElasticsearchException error = new ElasticsearchException("boom"); AtomicLong requestIdRef = new AtomicLong(); AtomicReference<String> actionRef = new AtomicReference<>(); AtomicReference<Exception> responseRef = new AtomicReference<>(); handler.setMessageListener(new TransportMessageListener() { @Override public void onResponseSent(long requestId, String action, Exception error) { requestIdRef.set(requestId); actionRef.set(action); responseRef.set(error); } }); handler.sendErrorResponse(version, channel, requestId, action, ResponseStatsConsumer.NONE, error); BytesReference reference = channel.getMessageCaptor().get(); ActionListener<Void> sendListener = channel.getListenerCaptor().get(); if (randomBoolean()) { sendListener.onResponse(null); } else { sendListener.onFailure(new IOException("failed")); } assertEquals(requestId, requestIdRef.get()); assertEquals(action, actionRef.get()); assertEquals(error, responseRef.get()); pipeline.handleBytes(channel, new ReleasableBytesReference(reference, () -> {})); final Tuple<Header, BytesReference> tuple = message.get(); final Header header = tuple.v1(); assertEquals(version, header.getVersion()); assertEquals(requestId, header.getRequestId()); assertFalse(header.isRequest()); assertTrue(header.isResponse()); assertFalse(header.isCompressed()); assertFalse(header.isHandshake()); assertTrue(header.isError()); RemoteTransportException remoteException = tuple.v2().streamInput().readException(); assertThat(remoteException.getCause(), instanceOf(ElasticsearchException.class)); assertEquals(remoteException.getCause().getMessage(), "boom"); assertThat( remoteException.getMessage(), allOf(containsString('[' + NetworkAddress.format(channel.getLocalAddress()) + ']'), containsString('[' + action + ']')) ); assertEquals("header_value", header.getHeaders().v1().get("header")); } public void testSendErrorAfterFailToSendResponse() throws Exception { TransportVersion version = TransportVersionUtils.randomCompatibleVersion(random()); String action = randomAlphaOfLength(10); long requestId = randomLongBetween(0, 300); var response = new ReleasbleTestResponse(randomAlphaOfLength(10)) { @Override public void writeTo(StreamOutput out) { throw new CircuitBreakingException("simulated cbe", CircuitBreaker.Durability.TRANSIENT); } }; AtomicLong requestIdRef = new AtomicLong(); AtomicReference<String> actionRef = new AtomicReference<>(); AtomicReference<Exception> exceptionRef = new AtomicReference<>(); handler.setMessageListener(new TransportMessageListener() { @Override public void onResponseSent(long requestId, String action) { assertNull(channel.getMessageCaptor().get()); assertThat(requestIdRef.get(), equalTo(0L)); requestIdRef.set(requestId); assertNull(actionRef.get()); actionRef.set(action); } @Override public void onResponseSent(long requestId, String action, Exception error) { assertNotNull(channel.getMessageCaptor().get()); assertThat(requestIdRef.get(), equalTo(requestId)); assertThat(actionRef.get(), equalTo(action)); exceptionRef.set(error); } }); Compression.Scheme compress = randomFrom(compressionScheme, null); try { handler.sendResponse(version, channel, requestId, action, response, compress, false, ResponseStatsConsumer.NONE); } finally { response.decRef(); } ActionListener<Void> sendListener = channel.getListenerCaptor().get(); if (randomBoolean()) { sendListener.onResponse(null); } else { sendListener.onFailure(new IOException("failed")); } assertEquals(requestId, requestIdRef.get()); assertEquals(action, actionRef.get()); assertThat(exceptionRef.get().getMessage(), equalTo("simulated cbe")); assertTrue(response.released.get()); BytesReference reference = channel.getMessageCaptor().get(); pipeline.handleBytes(channel, new ReleasableBytesReference(reference, () -> {})); try (StreamInput input = message.get().v2().streamInput()) { RemoteTransportException rme = input.readException(); assertThat(rme.getCause(), instanceOf(CircuitBreakingException.class)); assertThat(rme.getCause().getMessage(), equalTo("simulated cbe")); } assertTrue(channel.isOpen()); assertFalse(closeListener.isDone()); } public void testFailToSendResponseThenFailToSendError() { channel.close(); channel = new FakeTcpChannel(randomBoolean(), buildNewFakeTransportAddress().address(), buildNewFakeTransportAddress().address()) { @Override public void sendMessage(BytesReference reference, ActionListener<Void> listener) { throw new IllegalStateException("pipe broken"); } }; closeListener = new PlainActionFuture<>(); channel.addCloseListener(closeListener); TransportVersion version = TransportVersionUtils.randomVersion(); String action = randomAlphaOfLength(10); long requestId = randomLongBetween(0, 300); AtomicLong requestIdRef = new AtomicLong(); AtomicReference<String> actionRef = new AtomicReference<>(); AtomicReference<Exception> exceptionRef = new AtomicReference<>(); handler.setMessageListener(new TransportMessageListener() { @Override public void onResponseSent(long requestId, String action) { assertNull(channel.getMessageCaptor().get()); assertThat(requestIdRef.get(), equalTo(0L)); requestIdRef.set(requestId); assertNull(actionRef.get()); actionRef.set(action); } @Override public void onResponseSent(long requestId, String action, Exception error) { assertNull(channel.getMessageCaptor().get()); assertThat(requestIdRef.get(), equalTo(requestId)); assertThat(actionRef.get(), equalTo(action)); exceptionRef.set(error); } }); Compression.Scheme compress = randomFrom(compressionScheme, null); var response = new ReleasbleTestResponse(randomAlphaOfLength(10)) { @Override public void writeTo(StreamOutput out) { throw new CircuitBreakingException("simulated cbe", CircuitBreaker.Durability.TRANSIENT); } }; try { handler.sendResponse(version, channel, requestId, action, response, compress, false, ResponseStatsConsumer.NONE); } finally { response.decRef(); } assertEquals(requestId, requestIdRef.get()); assertEquals(action, actionRef.get()); assertThat(exceptionRef.get().getMessage(), equalTo("simulated cbe")); assertTrue(response.released.get()); assertNull(channel.getMessageCaptor().get()); assertNull(channel.getListenerCaptor().get()); assertFalse(channel.isOpen()); assertTrue(closeListener.isDone()); expectThrows(Exception.class, () -> closeListener.get()); } public void testFailToSendHandshakeResponse() { TransportVersion version = TransportVersionUtils.randomVersion(); String action = randomAlphaOfLength(10); long requestId = randomLongBetween(0, 300); var response = new ReleasbleTestResponse(randomAlphaOfLength(10)) { @Override public void writeTo(StreamOutput out) { throw new CircuitBreakingException("simulated", CircuitBreaker.Durability.TRANSIENT); } }; AtomicLong requestIdRef = new AtomicLong(); AtomicReference<String> actionRef = new AtomicReference<>(); handler.setMessageListener(new TransportMessageListener() { @Override public void onResponseSent(long requestId, String action) { assertNull(channel.getMessageCaptor().get()); assertThat(requestIdRef.get(), equalTo(0L)); requestIdRef.set(requestId); assertNull(actionRef.get()); actionRef.set(action); } @Override public void onResponseSent(long requestId, String action, Exception error) { throw new AssertionError("failing to send a handshake response should not send failure"); } }); Compression.Scheme compress = randomFrom(compressionScheme, null); try { handler.sendResponse(version, channel, requestId, action, response, compress, true, ResponseStatsConsumer.NONE); } finally { response.decRef(); } assertNull(channel.getMessageCaptor().get()); assertNull(channel.getListenerCaptor().get()); assertEquals(requestId, requestIdRef.get()); assertEquals(action, actionRef.get()); assertTrue(response.released.get()); assertFalse(channel.isOpen()); assertTrue(closeListener.isDone()); expectThrows(Exception.class, () -> closeListener.get()); } public void testFailToSendErrorResponse() { channel.close(); channel = new FakeTcpChannel(randomBoolean(), buildNewFakeTransportAddress().address(), buildNewFakeTransportAddress().address()) { @Override public void sendMessage(BytesReference reference, ActionListener<Void> listener) { throw new IllegalStateException("pipe broken"); } }; closeListener = new PlainActionFuture<>(); channel.addCloseListener(closeListener); TransportVersion version = TransportVersionUtils.randomVersion(); String action = randomAlphaOfLength(10); long requestId = randomLongBetween(0, 300); AtomicLong requestIdRef = new AtomicLong(); AtomicReference<String> actionRef = new AtomicReference<>(); AtomicReference<Exception> exceptionRef = new AtomicReference<>(); handler.setMessageListener(new TransportMessageListener() { @Override public void onResponseSent(long requestId, String action) { throw new AssertionError("must not be called"); } @Override public void onResponseSent(long requestId, String action, Exception error) { assertNull(channel.getMessageCaptor().get()); assertThat(requestIdRef.get(), equalTo(0L)); requestIdRef.set(requestId); assertNull(actionRef.get()); actionRef.set(action); assertNull(exceptionRef.get()); exceptionRef.set(error); } }); IOException exception = new IOException("file doesn't exist"); handler.sendErrorResponse(version, channel, requestId, action, ResponseStatsConsumer.NONE, exception); assertEquals(requestId, requestIdRef.get()); assertEquals(action, actionRef.get()); assertEquals(exception, exceptionRef.get()); assertFalse(channel.isOpen()); assertNull(channel.getMessageCaptor().get()); assertNull(channel.getListenerCaptor().get()); assertTrue(closeListener.isDone()); expectThrows(Exception.class, () -> closeListener.get()); } /** * This logger is mentioned in the docs by name, so we cannot rename it without adjusting the docs. Thus we fix the expected logger * name in this string constant rather than using {@code OutboundHandler.class.getCanonicalName()}. */ private static final String EXPECTED_LOGGER_NAME = "org.elasticsearch.transport.OutboundHandler"; public void testSlowLogOutboundMessage() throws Exception { handler.setSlowLogThreshold(TimeValue.timeValueMillis(5L)); try (var mockLog = MockLog.capture(OutboundHandler.class)) { mockLog.addExpectation( new MockLog.SeenEventExpectation("expected message", EXPECTED_LOGGER_NAME, Level.WARN, "sending transport message ") ); final int length = randomIntBetween(1, 100); final PlainActionFuture<Void> f = new PlainActionFuture<>(); handler.sendBytes(new FakeTcpChannel() { @Override public void sendMessage(BytesReference reference, ActionListener<Void> listener) { try { TimeUnit.SECONDS.sleep(1L); listener.onResponse(null); } catch (InterruptedException e) { listener.onFailure(e); } } }, new BytesArray(randomByteArrayOfLength(length)), f); f.get(); mockLog.assertAllExpectationsMatched(); } } static
OutboundHandlerTests
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/runtimefilter/GlobalRuntimeFilterBuilderOperatorTest.java
{ "start": 2011, "end": 8507 }
class ____ { @Test void testNormalInputAndNormalOutput() throws Exception { try (StreamTaskMailboxTestHarness<RowData> testHarness = createGlobalRuntimeFilterBuilderOperatorHarness(10)) { // process elements testHarness.processElement( new StreamRecord<RowData>( GenericRowData.of(5, BloomFilter.toBytes(createBloomFilter1())))); testHarness.processElement( new StreamRecord<RowData>( GenericRowData.of(5, BloomFilter.toBytes(createBloomFilter2())))); testHarness.processEvent(new EndOfData(StopMode.DRAIN), 0); // test the output Queue<Object> outputs = testHarness.getOutput(); assertThat(outputs.size()).isEqualTo(1); RowData outputRowData = ((StreamRecord<RowData>) outputs.poll()).getValue(); assertThat(outputRowData.getArity()).isEqualTo(2); int globalCount = outputRowData.getInt(0); BloomFilter globalBloomFilter = BloomFilter.fromBytes(outputRowData.getBinary(1)); assertThat(globalCount).isEqualTo(10); assertThat(globalBloomFilter.testHash("var1".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var2".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var3".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var4".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var5".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var6".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var7".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var8".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var9".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var10".hashCode())).isTrue(); assertThat(globalBloomFilter.testHash("var11".hashCode())).isFalse(); assertThat(globalBloomFilter.testHash("var12".hashCode())).isFalse(); assertThat(globalBloomFilter.testHash("var13".hashCode())).isFalse(); assertThat(globalBloomFilter.testHash("var14".hashCode())).isFalse(); assertThat(globalBloomFilter.testHash("var15".hashCode())).isFalse(); } } /** * Test the case that all input local runtime filters are normal, but the merged global filter * is over-max-row-count. */ @Test void testNormalInputAndOverMaxRowCountOutput() throws Exception { try (StreamTaskMailboxTestHarness<RowData> testHarness = createGlobalRuntimeFilterBuilderOperatorHarness(9)) { // process elements testHarness.processElement( new StreamRecord<RowData>( GenericRowData.of(5, BloomFilter.toBytes(createBloomFilter1())))); testHarness.processElement( new StreamRecord<RowData>( GenericRowData.of(5, BloomFilter.toBytes(createBloomFilter2())))); testHarness.processEvent(new EndOfData(StopMode.DRAIN), 0); // test the output Queue<Object> outputs = testHarness.getOutput(); assertThat(outputs.size()).isEqualTo(1); RowData outputRowData = ((StreamRecord<RowData>) outputs.poll()).getValue(); assertThat(outputRowData.getArity()).isEqualTo(2); int globalCount = outputRowData.getInt(0); assertThat(globalCount).isEqualTo(OVER_MAX_ROW_COUNT); assertThat(outputRowData.isNullAt(1)).isTrue(); } } /** Test the case that one of the input local runtime filters is over-max-row-count. */ @Test void testOverMaxRowCountInput() throws Exception { try (StreamTaskMailboxTestHarness<RowData> testHarness = createGlobalRuntimeFilterBuilderOperatorHarness(10)) { // process elements testHarness.processElement( new StreamRecord<RowData>( GenericRowData.of(5, BloomFilter.toBytes(createBloomFilter1())))); testHarness.processElement( new StreamRecord<RowData>(GenericRowData.of(OVER_MAX_ROW_COUNT, null))); testHarness.processEvent(new EndOfData(StopMode.DRAIN), 0); // test the output Queue<Object> outputs = testHarness.getOutput(); assertThat(outputs.size()).isEqualTo(1); RowData outputRowData = ((StreamRecord<RowData>) outputs.poll()).getValue(); assertThat(outputRowData.getArity()).isEqualTo(2); int globalCount = outputRowData.getInt(0); assertThat(globalCount).isEqualTo(OVER_MAX_ROW_COUNT); assertThat(outputRowData.isNullAt(1)).isTrue(); } } private static BloomFilter createBloomFilter1() { final BloomFilter bloomFilter1 = RuntimeFilterUtils.createOnHeapBloomFilter(10); bloomFilter1.addHash("var1".hashCode()); bloomFilter1.addHash("var2".hashCode()); bloomFilter1.addHash("var3".hashCode()); bloomFilter1.addHash("var4".hashCode()); bloomFilter1.addHash("var5".hashCode()); return bloomFilter1; } private static BloomFilter createBloomFilter2() { final BloomFilter bloomFilter2 = RuntimeFilterUtils.createOnHeapBloomFilter(10); bloomFilter2.addHash("var6".hashCode()); bloomFilter2.addHash("var7".hashCode()); bloomFilter2.addHash("var8".hashCode()); bloomFilter2.addHash("var9".hashCode()); bloomFilter2.addHash("var10".hashCode()); return bloomFilter2; } private static StreamTaskMailboxTestHarness<RowData> createGlobalRuntimeFilterBuilderOperatorHarness(int maxRowCount) throws Exception { final GlobalRuntimeFilterBuilderOperator operator = new GlobalRuntimeFilterBuilderOperator(maxRowCount); return new StreamTaskMailboxTestHarnessBuilder<>( OneInputStreamTask::new, InternalTypeInfo.ofFields(new IntType(), new BinaryType())) .setupOutputForSingletonOperatorChain(operator) .addInput(InternalTypeInfo.ofFields(new IntType(), new BinaryType())) .build(); } }
GlobalRuntimeFilterBuilderOperatorTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/SubQueryTest.java
{ "start": 7080, "end": 7170 }
class ____ { @Id @GeneratedValue public Integer id; public String leafName; } }
Leaf
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/BrokerStatsItem.java
{ "start": 863, "end": 1341 }
class ____ { private long sum; private double tps; private double avgpt; public long getSum() { return sum; } public void setSum(long sum) { this.sum = sum; } public double getTps() { return tps; } public void setTps(double tps) { this.tps = tps; } public double getAvgpt() { return avgpt; } public void setAvgpt(double avgpt) { this.avgpt = avgpt; } }
BrokerStatsItem
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringSetVariablesTest.java
{ "start": 1117, "end": 1808 }
class ____ extends ContextTestSupport { @Test public void testSetVariables() throws Exception { MockEndpoint resultEndpoint = getMockEndpoint("mock:b"); resultEndpoint.expectedBodiesReceived("World"); resultEndpoint.expectedVariableReceived("myVar", "Hello World"); resultEndpoint.expectedVariableReceived("myOtherVar", "Bye World"); sendBody("seda:a", "World"); resultEndpoint.assertIsSatisfied(); } @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringSetVariablesTest-context.xml"); } }
SpringSetVariablesTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/stats/CriteriaStatTest.java
{ "start": 1608, "end": 1772 }
class ____ { @Id private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } }
Employee
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/DeleteRecordsRequest.java
{ "start": 1304, "end": 1478 }
class ____ extends AbstractRequest { public static final long HIGH_WATERMARK = -1L; private final DeleteRecordsRequestData data; public static
DeleteRecordsRequest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/CharacterGetNumericValueTest.java
{ "start": 4433, "end": 4661 }
class ____ { void f() { // BUG: Diagnostic contains: CharacterGetNumericValue UCharacter.getNumericValue(41); } } """) .doTest(); } }
Test
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java
{ "start": 1121, "end": 1265 }
class ____ {@code Processor} implementations that bridge between * event-listener write APIs and Reactive Streams. * * <p>Specifically a base
for
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventImpl.java
{ "start": 20204, "end": 22579 }
class ____<T> implements Runnable { private ObserverMethod<? super T> observerMethod; private boolean isBeforeCompletion; private EventContext eventContext; private Status status; private static final Logger LOG = Logger.getLogger(DeferredEventNotification.class); DeferredEventNotification(ObserverMethod<? super T> observerMethod, EventContext eventContext, Status status) { this.observerMethod = observerMethod; this.isBeforeCompletion = observerMethod.getTransactionPhase().equals(TransactionPhase.BEFORE_COMPLETION); this.eventContext = eventContext; this.status = status; } public boolean isBeforeCompletion() { return isBeforeCompletion; } public Status getStatus() { return status; } @SuppressWarnings("unchecked") @Override public void run() { try { ManagedContext reqContext = Arc.requireContainer().requestContext(); if (reqContext.isActive()) { observerMethod.notify(eventContext); } else { try { reqContext.activate(); observerMethod.notify(eventContext); } finally { reqContext.terminate(); } } } catch (Exception e) { // swallow exception and log errors for every problematic OM LOG.errorf( "Failure occurred while notifying a transational %s for event of type %s " + "\n- please enable debug logging to see the full stack trace" + "\n %s", observerMethod, eventContext.getMetadata().getType().getTypeName(), e.getCause() != null && e.getMessage() != null ? "Cause: " + e.getCause() + " Message: " + e.getMessage() : "Exception caught: " + e); LOG.debugf(e, "Failure occurred while notifying a transational %s for event of type %s", observerMethod, eventContext.getMetadata().getType().getTypeName()); } } }
DeferredEventNotification
java
apache__flink
flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/messages/KvStateRequest.java
{ "start": 1507, "end": 3912 }
class ____ extends MessageBody { private final JobID jobId; private final String stateName; private final int keyHashCode; private final byte[] serializedKeyAndNamespace; public KvStateRequest( final JobID jobId, final String stateName, final int keyHashCode, final byte[] serializedKeyAndNamespace) { this.jobId = Preconditions.checkNotNull(jobId); this.stateName = Preconditions.checkNotNull(stateName); this.keyHashCode = keyHashCode; this.serializedKeyAndNamespace = Preconditions.checkNotNull(serializedKeyAndNamespace); } public JobID getJobId() { return jobId; } public String getStateName() { return stateName; } public int getKeyHashCode() { return keyHashCode; } public byte[] getSerializedKeyAndNamespace() { return serializedKeyAndNamespace; } @Override public byte[] serialize() { byte[] serializedStateName = stateName.getBytes(ConfigConstants.DEFAULT_CHARSET); // JobID + stateName + sizeOf(stateName) + hashCode + keyAndNamespace + // sizeOf(keyAndNamespace) final int size = JobID.SIZE + serializedStateName.length + Integer.BYTES + Integer.BYTES + serializedKeyAndNamespace.length + Integer.BYTES; return ByteBuffer.allocate(size) .putLong(jobId.getLowerPart()) .putLong(jobId.getUpperPart()) .putInt(serializedStateName.length) .put(serializedStateName) .putInt(keyHashCode) .putInt(serializedKeyAndNamespace.length) .put(serializedKeyAndNamespace) .array(); } @Override public String toString() { return "KvStateRequest{" + "jobId=" + jobId + ", stateName='" + stateName + '\'' + ", keyHashCode=" + keyHashCode + ", serializedKeyAndNamespace=" + Arrays.toString(serializedKeyAndNamespace) + '}'; } /** A {@link MessageDeserializer deserializer} for {@link KvStateRequest}. */ public static
KvStateRequest
java
spring-projects__spring-boot
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/InvalidConfigurationMetadataException.java
{ "start": 938, "end": 1238 }
class ____ extends RuntimeException { private final Diagnostic.Kind kind; public InvalidConfigurationMetadataException(String message, Diagnostic.Kind kind) { super(message); this.kind = kind; } public Diagnostic.Kind getKind() { return this.kind; } }
InvalidConfigurationMetadataException
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/filter/impl/Op.java
{ "start": 868, "end": 1103 }
class ____ { private String symbol; protected Op(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } public String toString() { return symbol; } }
Op
java
google__dagger
hilt-android/main/java/dagger/hilt/android/migration/OptionalInject.java
{ "start": 1368, "end": 1537 }
class ____ and don't use the Gradle plugin. * * <p>Example usage: * * <pre><code> * {@literal @}OptionalInject * {@literal @}AndroidEntryPoint * public final
directly
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isIn_Test.java
{ "start": 1297, "end": 2721 }
class ____ extends LocalDateTimeAssertBaseTest { @Test void should_pass_if_actual_is_in_dateTimes_as_string_array_parameter() { assertThat(REFERENCE).isIn(REFERENCE.toString(), AFTER.toString()); } @Test void should_fail_if_actual_is_not_in_dateTimes_as_string_array_parameter() { // WHEN ThrowingCallable code = () -> assertThat(REFERENCE).isIn(BEFORE.toString(), AFTER.toString()); // THEN assertThatAssertionErrorIsThrownBy(code).withMessage(shouldBeIn(REFERENCE, asList(BEFORE, AFTER)).create()); } @Test void should_fail_if_dateTimes_as_string_array_parameter_is_null() { // GIVEN String[] otherDateTimesAsString = null; // WHEN ThrowingCallable code = () -> assertThat(LocalDateTime.now()).isIn(otherDateTimesAsString); // THEN assertThatIllegalArgumentException().isThrownBy(code) .withMessage("The given LocalDateTime array should not be null"); } @Test void should_fail_if_dateTimes_as_string_array_parameter_is_empty() { // GIVEN String[] otherDateTimesAsString = new String[0]; // WHEN ThrowingCallable code = () -> assertThat(LocalDateTime.now()).isIn(otherDateTimesAsString); // THEN assertThatIllegalArgumentException().isThrownBy(code) .withMessage("The given LocalDateTime array should not be empty"); } }
LocalDateTimeAssert_isIn_Test
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/MultipleEmbeddedGenericsTest.java
{ "start": 7048, "end": 7516 }
class ____ extends GenericEntity<CustomerEmbeddableOne, CustomerEmbeddableTwo> { @Id @GeneratedValue private Long id; private String name; public Customer() { } public Customer(String name) { super( new CustomerEmbeddableOne( "1", 1 ), new CustomerEmbeddableTwo( "2", 2 ) ); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Embeddable public static
Customer
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryFactoryBeanUnitTests.java
{ "start": 4431, "end": 4642 }
class ____ implements Persistable<Long> { } /** * required to trick Mockito on invoking protected getRepository(Class<T> repositoryInterface, Optional<Object> * customImplementation */ private static
User
java
quarkusio__quarkus
extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcTenantConfig.java
{ "start": 952, "end": 4780 }
interface ____ extends OidcClientCommonConfig { /** * A unique tenant identifier. It can be set by {@code TenantConfigResolver} providers, which * resolve the tenant configuration dynamically. */ Optional<String> tenantId(); /** * If this tenant configuration is enabled. * * The default tenant is disabled if it is not configured but * a {@link TenantConfigResolver} that resolves tenant configurations is registered, * or named tenants are configured. * In this case, you do not need to disable the default tenant. */ @WithDefault("true") boolean tenantEnabled(); /** * The application type, which can be one of the following {@link ApplicationType} values. */ @ConfigDocDefault("service") Optional<ApplicationType> applicationType(); /** * The relative path or absolute URL of the OpenID Connect (OIDC) authorization endpoint, which authenticates * users. * You must set this property for `web-app` applications if OIDC discovery is disabled. * This property is ignored if OIDC discovery is enabled. */ Optional<String> authorizationPath(); /** * The relative path or absolute URL of the OIDC UserInfo endpoint. * You must set this property for `web-app` applications if OIDC discovery is disabled * and the `authentication.user-info-required` property is enabled. * This property is ignored if OIDC discovery is enabled. */ Optional<String> userInfoPath(); /** * Relative path or absolute URL of the OIDC RFC7662 introspection endpoint which can introspect both opaque and * JSON Web Token (JWT) tokens. * This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens must be verified * or 2) JWT tokens must be verified while the cached JWK verification set with no matching JWK is being refreshed. * This property is ignored if the discovery is enabled. */ Optional<String> introspectionPath(); /** * Relative path or absolute URL of the OIDC JSON Web Key Set (JWKS) endpoint which returns a JSON Web Key * Verification Set. * This property should be set if OIDC discovery is disabled and the local JWT verification is required. * This property is ignored if the discovery is enabled. */ Optional<String> jwksPath(); /** * Relative path or absolute URL of the OIDC end_session_endpoint. * This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the `web-app` applications is * required. * This property is ignored if the discovery is enabled. */ Optional<String> endSessionPath(); /** * The paths which must be secured by this tenant. Tenant with the most specific path wins. * Please see the xref:security-openid-connect-multitenancy.adoc#configure-tenant-paths[Configure tenant paths] * section of the OIDC multitenancy guide for explanation of allowed path patterns. * * @asciidoclet */ Optional<List<String>> tenantPaths(); /** * The public key for the local JWT token verification. * OIDC server connection is not created when this property is set. */ Optional<String> publicKey(); /** * Optional introspection endpoint-specific basic authentication configuration. * It must be configured only if the introspection is required * but OpenId Connect Provider does not support the OIDC client authentication configured with * {@link OidcCommonConfig#credentials} for its introspection endpoint. */ @ConfigDocSection IntrospectionCredentials introspectionCredentials(); /** * Optional introspection endpoint-specific authentication configuration. */
OidcTenantConfig
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googlevertexai/response/GoogleVertexAiCompletionResponseEntityTests.java
{ "start": 820, "end": 2889 }
class ____ extends ESTestCase { public void testFromResponse_Javadoc() throws IOException { var responseText = "I am sorry, I cannot summarize the text because I do not have access to the text you are referring to."; String responseJson = Strings.format(""" { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "%s" } ] }, "finishReason": "STOP", "avgLogprobs": -0.19326641248620074 } ], "usageMetadata": { "promptTokenCount": 71, "candidatesTokenCount": 23, "totalTokenCount": 94, "trafficType": "ON_DEMAND", "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 71 } ], "candidatesTokensDetails": [ { "modality": "TEXT", "tokenCount": 23 } ] }, "modelVersion": "gemini-2.0-flash-001", "createTime": "2025-05-28T15:08:20.049493Z", "responseId": "5CY3aNWCA6mm4_UPr-zduAE" } """, responseText); var parsedResults = GoogleVertexAiCompletionResponseEntity.fromResponse( mock(Request.class), new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ); assert parsedResults instanceof ChatCompletionResults; var results = (ChatCompletionResults) parsedResults; assertThat(results.isStreaming(), is(false)); assertThat(results.results().size(), is(1)); assertThat(results.results().get(0).content(), is(responseText)); } }
GoogleVertexAiCompletionResponseEntityTests
java
spring-projects__spring-boot
loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/Runner.java
{ "start": 891, "end": 2609 }
class ____ { private final PrintStream out; private final List<Command> commands = new ArrayList<>(); private final HelpCommand help; Runner(PrintStream out, Context context, List<Command> commands) { this.out = out; this.commands.addAll(commands); this.help = new HelpCommand(context, commands); this.commands.add(this.help); } void run(String... args) { run(dequeOf(args)); } private void run(Deque<String> args) { if (!args.isEmpty()) { String commandName = args.removeFirst(); Command command = Command.find(this.commands, commandName); if (command != null) { runCommand(command, args); return; } printError("Unknown command \"" + commandName + "\""); } this.help.run(this.out, args); } private void runCommand(Command command, Deque<String> args) { if (command.isDeprecated()) { printWarning("This command is deprecated. " + command.getDeprecationMessage()); } try { command.run(this.out, args); } catch (UnknownOptionException ex) { printError("Unknown option \"" + ex.getMessage() + "\" for the " + command.getName() + " command"); this.help.printCommandHelp(this.out, command, false); } catch (MissingValueException ex) { printError("Option \"" + ex.getMessage() + "\" for the " + command.getName() + " command requires a value"); this.help.printCommandHelp(this.out, command, false); } } private void printWarning(String message) { this.out.println("Warning: " + message); this.out.println(); } private void printError(String message) { this.out.println("Error: " + message); this.out.println(); } private Deque<String> dequeOf(String... args) { return new ArrayDeque<>(Arrays.asList(args)); } }
Runner