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
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/singletable/Address.java
{ "start": 186, "end": 296 }
class ____ { public String entityName; public String street; public String state; public String zip; }
Address
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/stats/outlierdetection/TimingStatsTests.java
{ "start": 641, "end": 1779 }
class ____ extends AbstractBWCSerializationTestCase<TimingStats> { private boolean lenient; @Before public void chooseLenient() { lenient = randomBoolean(); } @Override protected boolean supportsUnknownFields() { return lenient; } @Override protected TimingStats mutateInstanceForVersion(TimingStats instance, TransportVersion version) { return instance; } @Override protected TimingStats doParseInstance(XContentParser parser) throws IOException { return TimingStats.fromXContent(parser, lenient); } @Override protected Writeable.Reader<TimingStats> instanceReader() { return TimingStats::new; } @Override protected TimingStats createTestInstance() { return createRandom(); } @Override protected TimingStats mutateInstance(TimingStats instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } public static TimingStats createRandom() { return new TimingStats(TimeValue.timeValueMillis(randomNonNegativeLong())); } }
TimingStatsTests
java
google__gson
gson/src/test/java/com/google/gson/VersionExclusionStrategyTest.java
{ "start": 3671, "end": 3823 }
class ____ { @Until(VERSION) @Keep public final int someField = 0; } @Since(VERSION) @Until(VERSION + 2) private static
MockClassUntil
java
elastic__elasticsearch
modules/repository-s3/src/internalClusterTest/java/org/elasticsearch/repositories/s3/S3BlobStoreRepositoryTests.java
{ "start": 32706, "end": 35145 }
class ____ extends S3RepositoryPlugin { public TestS3RepositoryPlugin(final Settings settings) { super(settings); } @Override public List<Setting<?>> getSettings() { final List<Setting<?>> settings = new ArrayList<>(super.getSettings()); settings.add(S3ClientSettings.DISABLE_CHUNKED_ENCODING); return settings; } @Override protected S3Repository createRepository( ProjectId projectId, RepositoryMetadata metadata, NamedXContentRegistry registry, ClusterService clusterService, BigArrays bigArrays, RecoverySettings recoverySettings, S3RepositoriesMetrics s3RepositoriesMetrics, SnapshotMetrics snapshotMetrics ) { return new S3Repository( projectId, metadata, registry, getService(), clusterService, bigArrays, recoverySettings, s3RepositoriesMetrics, snapshotMetrics ) { @Override public BlobStore blobStore() { return new BlobStoreWrapper(super.blobStore()) { @Override public BlobContainer blobContainer(final BlobPath path) { return new S3BlobContainer(path, (S3BlobStore) delegate()) { @Override long getLargeBlobThresholdInBytes() { return ByteSizeUnit.MB.toBytes(1L); } @Override long getMaxCopySizeBeforeMultipart() { // on my laptop 10K exercises this better but larger values should be fine for nightlies return ByteSizeUnit.MB.toBytes(1L); } @Override void ensureMultiPartUploadSize(long blobSize) {} }; } }; } }; } } @SuppressForbidden(reason = "this test uses a HttpHandler to emulate an S3 endpoint") protected
TestS3RepositoryPlugin
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/tenant/HibernateMultiTenantConnectionProvider.java
{ "start": 957, "end": 4363 }
class ____ extends AbstractMultiTenantConnectionProvider<String> { private static final Logger LOG = Logger.getLogger(HibernateMultiTenantConnectionProvider.class); private final String persistenceUnitName; private final Map<String, ConnectionProvider> providerMap = new ConcurrentHashMap<>(); public HibernateMultiTenantConnectionProvider(String persistenceUnitName) { this.persistenceUnitName = persistenceUnitName; } @Override protected ConnectionProvider getAnyConnectionProvider() { InstanceHandle<TenantResolver> tenantResolver = tenantResolver(persistenceUnitName); String tenantId; // Activate RequestScope if the TenantResolver is @RequestScoped or @SessionScoped ManagedContext requestContext = Arc.container().requestContext(); Class<? extends Annotation> tenantScope = tenantResolver.getBean().getScope(); boolean requiresRequestScope = (tenantScope == RequestScoped.class || tenantScope == SessionScoped.class); boolean forceRequestActivation = (!requestContext.isActive() && requiresRequestScope); try { if (forceRequestActivation) { requestContext.activate(); } tenantId = tenantResolver.get().getDefaultTenantId(); } finally { if (forceRequestActivation) { requestContext.deactivate(); } } if (tenantId == null) { throw new IllegalStateException("Method 'TenantResolver.getDefaultTenantId()' returned a null value. " + "This violates the contract of the interface!"); } return selectConnectionProvider(tenantId); } @Override protected ConnectionProvider selectConnectionProvider(final String tenantIdentifier) { LOG.debugv("selectConnectionProvider(persistenceUnitName={0}, tenantIdentifier={1})", persistenceUnitName, tenantIdentifier); ConnectionProvider provider = providerMap.get(tenantIdentifier); if (provider == null) { final ConnectionProvider connectionProvider = resolveConnectionProvider(persistenceUnitName, tenantIdentifier); providerMap.put(tenantIdentifier, connectionProvider); return connectionProvider; } return provider; } private static ConnectionProvider resolveConnectionProvider(String persistenceUnitName, String tenantIdentifier) { LOG.debugv("resolveConnectionProvider(persistenceUnitName={0}, tenantIdentifier={1})", persistenceUnitName, tenantIdentifier); // TODO when we switch to the non-legacy method, don't forget to update the definition of the default bean // of type DataSourceTenantConnectionResolver (add the @PersistenceUnitExtension qualifier to that bean) InjectableInstance<TenantConnectionResolver> instance = PersistenceUnitUtil .legacySingleExtensionInstanceForPersistenceUnit( TenantConnectionResolver.class, persistenceUnitName); if (instance.isUnsatisfied()) { throw new IllegalStateException( String.format( Locale.ROOT, "No instance of %1$s was found for persistence unit %2$s. " + "You need to create an implementation for this
HibernateMultiTenantConnectionProvider
java
quarkusio__quarkus
integration-tests/hibernate-validator/src/main/java/io/quarkus/it/hibernate/validator/groups/MyBeanWithGroups.java
{ "start": 251, "end": 1133 }
class ____ { @Null(groups = ValidationGroups.Post.class) @NotNull(groups = { ValidationGroups.Put.class, ValidationGroups.Get.class, ValidationGroups.Delete.class }) private Long id; @NotNull private String name; @AssertFalse(groups = { ValidationGroups.Post.class, ValidationGroups.Put.class, ValidationGroups.Get.class }) @AssertTrue(groups = ValidationGroups.Delete.class) private boolean deleted; public MyBeanWithGroups() { } 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 boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } }
MyBeanWithGroups
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmanager/ExecutionPlanStoreUtil.java
{ "start": 1072, "end": 1515 }
interface ____ { /** * Get the name in external storage from job id. * * @param jobId job id * @return Key name in ConfigMap or child path name in ZooKeeper */ String jobIDToName(JobID jobId); /** * Get the job id from name. * * @param name Key name in ConfigMap or child path name in ZooKeeper * @return parsed job id. */ JobID nameToJobID(String name); }
ExecutionPlanStoreUtil
java
quarkusio__quarkus
extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/StaticTenantResolver.java
{ "start": 786, "end": 3212 }
class ____ { private static final Logger LOG = Logger.getLogger(StaticTenantResolver.class); private final TenantResolver[] staticTenantResolvers; private final IssuerBasedTenantResolver issuerBasedTenantResolver; StaticTenantResolver(TenantConfigBean tenantConfigBean, String rootPath, boolean resolveTenantsWithIssuer, Instance<TenantResolver> tenantResolverInstance) { List<TenantResolver> staticTenantResolvers = new ArrayList<>(); // STATIC TENANT RESOLVERS BY PRIORITY: // 0. annotation based resolver // 1. custom tenant resolver if (tenantResolverInstance.isResolvable()) { if (tenantResolverInstance.isAmbiguous()) { throw new IllegalStateException("Multiple " + TenantResolver.class + " beans registered"); } staticTenantResolvers.add(tenantResolverInstance.get()); } // 2. path-matching tenant resolver var pathMatchingTenantResolver = PathMatchingTenantResolver.of(tenantConfigBean.getStaticTenantsConfig(), rootPath, tenantConfigBean.getDefaultTenant()); if (pathMatchingTenantResolver != null) { staticTenantResolvers.add(pathMatchingTenantResolver); } // 3. default static tenant resolver if (!tenantConfigBean.getStaticTenantsConfig().isEmpty()) { staticTenantResolvers.add(new DefaultStaticTenantResolver(tenantConfigBean)); } this.staticTenantResolvers = staticTenantResolvers.toArray(new TenantResolver[0]); // 4. issuer-based tenant resolver if (resolveTenantsWithIssuer) { this.issuerBasedTenantResolver = IssuerBasedTenantResolver.of( tenantConfigBean.getStaticTenantsConfig(), tenantConfigBean.getDefaultTenant()); } else { this.issuerBasedTenantResolver = null; } } Uni<String> resolve(RoutingContext context) { for (TenantResolver resolver : staticTenantResolvers) { final String tenantId = resolver.resolve(context); if (tenantId != null) { return Uni.createFrom().item(tenantId); } } if (issuerBasedTenantResolver != null) { return issuerBasedTenantResolver.resolveTenant(context); } return Uni.createFrom().nullItem(); } private static final
StaticTenantResolver
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/EqualsIncompatibleTypeTest.java
{ "start": 14006, "end": 14195 }
interface ____ extends Second<Fourth> {} void testing(Third third, Fourth fourth) { // BUG: Diagnostic contains: Third and Fourth boolean equals = third.equals(fourth); }
Fourth
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/args/HandshakeRequestArgumentTest.java
{ "start": 630, "end": 1297 }
class ____ { @RegisterExtension public static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot(root -> { root.addClasses(XTest.class, WSClient.class); }); @Inject Vertx vertx; @TestHTTPResource("xtest") URI testUri; @Test void testArgument() { WSClient client = WSClient.create(vertx).connect(new WebSocketConnectOptions().addHeader("X-Test", "fool"), testUri); client.waitForMessages(1); assertEquals("fool", client.getLastMessage().toString()); } @WebSocket(path = "/xtest") public static
HandshakeRequestArgumentTest
java
quarkusio__quarkus
test-framework/arquillian/src/main/java/io/quarkus/arquillian/QuarkusDeployableContainer.java
{ "start": 2429, "end": 3500 }
class ____ implements DeployableContainer<QuarkusConfiguration> { private static final Logger LOGGER = Logger.getLogger(QuarkusDeployableContainer.class); @Inject @DeploymentScoped private InstanceProducer<QuarkusDeployment> deployment; @Inject @DeploymentScoped private InstanceProducer<Path> deploymentLocation; @Inject private Instance<TestClass> testClass; static Object testInstance; static ClassLoader old; private QuarkusConfiguration configuration; @Override public Class<QuarkusConfiguration> getConfigurationClass() { return QuarkusConfiguration.class; } @Override public void setup(QuarkusConfiguration configuration) { this.configuration = configuration; } @SuppressWarnings("rawtypes") @Override public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException { old = Thread.currentThread().getContextClassLoader(); if (testClass.get() == null) { throw new IllegalStateException("Test
QuarkusDeployableContainer
java
redisson__redisson
redisson-micronaut/redisson-micronaut-20/src/main/java/org/redisson/micronaut/session/RedissonHttpSessionConfiguration.java
{ "start": 1078, "end": 2960 }
enum ____ {WRITE_BEHIND, AFTER_REQUEST} private String keyPrefix = ""; private Codec codec; private UpdateMode updateMode = UpdateMode.AFTER_REQUEST; private boolean broadcastSessionUpdates = false; public boolean isBroadcastSessionUpdates() { return broadcastSessionUpdates; } /** * Defines broadcasting of session updates across all micronaut services. * * @param broadcastSessionUpdates - if true then session changes are broadcasted. */ public void setBroadcastSessionUpdates(boolean broadcastSessionUpdates) { this.broadcastSessionUpdates = broadcastSessionUpdates; } public UpdateMode getUpdateMode() { return updateMode; } /** * Defines session attributes update mode. * <p> * WRITE_BEHIND - session changes stored asynchronously. * AFTER_REQUEST - session changes stored only on io.micronaut.session.SessionStore#save(io.micronaut.session.Session) method invocation. * <p> * Default is AFTER_REQUEST. * * @param updateMode - mode value */ public void setUpdateMode(UpdateMode updateMode) { this.updateMode = updateMode; } public Codec getCodec() { return codec; } /** * Redis data codec applied to session values. * Default is Kryo5Codec codec * * @see org.redisson.client.codec.Codec * @see org.redisson.codec.Kryo5Codec * * @param codec - data codec * @return config */ public void setCodec(Codec codec) { this.codec = codec; } public String getKeyPrefix() { return keyPrefix; } /** * Defines string prefix applied to all objects stored in Redis. * * @param keyPrefix - key prefix value */ public void setKeyPrefix(String keyPrefix) { this.keyPrefix = keyPrefix; } }
UpdateMode
java
quarkusio__quarkus
extensions/resteasy-classic/rest-client-config/runtime/src/main/java/io/quarkus/restclient/config/RestClientsBuildTimeConfig.java
{ "start": 1461, "end": 1823 }
interface ____ bean of the configured scope. */ Optional<String> scope(); /** * If true, the extension will automatically remove the trailing slash in the paths if any. * This property is not applicable to the RESTEasy Client. */ @WithName("removes-trailing-slash") @WithDefault("true") boolean removesTrailingSlash();
a
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/http/PoolOptions.java
{ "start": 838, "end": 7446 }
class ____ { /** * The default maximum number of HTTP/1 connections a client will pool = 5 */ public static final int DEFAULT_MAX_POOL_SIZE = 5; /** * The default maximum number of connections an HTTP/2 client will pool = 1 */ public static final int DEFAULT_HTTP2_MAX_POOL_SIZE = 1; /** * Default max wait queue size = -1 (unbounded) */ public static final int DEFAULT_MAX_WAIT_QUEUE_SIZE = -1; /** * Default maximum pooled connection lifetime = 0 (no maximum) */ public static final int DEFAULT_MAXIMUM_LIFETIME = 0; /** * Default maximum pooled connection lifetime unit = seconds */ public static final TimeUnit DEFAULT_MAXIMUM_LIFETIME_TIME_UNIT = TimeUnit.SECONDS; /** * Default pool cleaner period = 1000 ms (1 second) */ public static final int DEFAULT_POOL_CLEANER_PERIOD = 1000; /** * Default pool event loop size = 0 (reuse current event-loop) */ public static final int DEFAULT_POOL_EVENT_LOOP_SIZE = 0; private int http1MaxSize; private int http2MaxSize; private int maxLifetime; private TimeUnit maxLifetimeUnit; private int cleanerPeriod; private int eventLoopSize; private int maxWaitQueueSize; /** * Default constructor */ public PoolOptions() { http1MaxSize = DEFAULT_MAX_POOL_SIZE; http2MaxSize = DEFAULT_HTTP2_MAX_POOL_SIZE; maxLifetime = DEFAULT_MAXIMUM_LIFETIME; maxLifetimeUnit = DEFAULT_MAXIMUM_LIFETIME_TIME_UNIT; cleanerPeriod = DEFAULT_POOL_CLEANER_PERIOD; eventLoopSize = DEFAULT_POOL_EVENT_LOOP_SIZE; maxWaitQueueSize = DEFAULT_MAX_WAIT_QUEUE_SIZE; } /** * Copy constructor * * @param other the options to copy */ public PoolOptions(PoolOptions other) { this.http1MaxSize = other.http1MaxSize; this.http2MaxSize = other.http2MaxSize; maxLifetime = other.maxLifetime; maxLifetimeUnit = other.maxLifetimeUnit; this.cleanerPeriod = other.cleanerPeriod; this.eventLoopSize = other.eventLoopSize; this.maxWaitQueueSize = other.maxWaitQueueSize; } /** * Constructor to create an options from JSON * * @param json the JSON */ public PoolOptions(JsonObject json) { PoolOptionsConverter.fromJson(json, this); } /** * Get the maximum pool size for HTTP/1.x connections * * @return the maximum pool size */ public int getHttp1MaxSize() { return http1MaxSize; } /** * Set the maximum pool size for HTTP/1.x connections * * @param http1MaxSize the maximum pool size * @return a reference to this, so the API can be used fluently */ public PoolOptions setHttp1MaxSize(int http1MaxSize) { if (http1MaxSize < 1) { throw new IllegalArgumentException("maxPoolSize must be > 0"); } this.http1MaxSize = http1MaxSize; return this; } /** * Get the maximum pool size for HTTP/2 connections * * @return the maximum pool size */ public int getHttp2MaxSize() { return http2MaxSize; } /** * Set the maximum pool size for HTTP/2 connections * * @param max the maximum pool size * @return a reference to this, so the API can be used fluently */ public PoolOptions setHttp2MaxSize(int max) { if (max < 1) { throw new IllegalArgumentException("http2MaxPoolSize must be > 0"); } this.http2MaxSize = max; return this; } /** * @return the pooled connection max lifetime unit */ public TimeUnit getMaxLifetimeUnit() { return maxLifetimeUnit; } /** * Establish a max lifetime unit for pooled connections. * * @param maxLifetimeUnit pooled connection max lifetime unit * @return a reference to this, so the API can be used fluently */ public PoolOptions setMaxLifetimeUnit(TimeUnit maxLifetimeUnit) { this.maxLifetimeUnit = maxLifetimeUnit; return this; } /** * @return pooled connection max lifetime */ public int getMaxLifetime() { return maxLifetime; } /** * Establish a max lifetime for pooled connections, a value of zero disables the maximum lifetime. * * @param maxLifetime the pool connection max lifetime * @return a reference to this, so the API can be used fluently */ public PoolOptions setMaxLifetime(int maxLifetime) { if (maxLifetime < 0) { throw new IllegalArgumentException("maxLifetime must be >= 0"); } this.maxLifetime = maxLifetime; return this; } /** * @return the connection pool cleaner period in ms. */ public int getCleanerPeriod() { return cleanerPeriod; } /** * Set the connection pool cleaner period in milli seconds, a non positive value disables expiration checks and connections * will remain in the pool until they are closed. * * @param cleanerPeriod the pool cleaner period * @return a reference to this, so the API can be used fluently */ public PoolOptions setCleanerPeriod(int cleanerPeriod) { this.cleanerPeriod = cleanerPeriod; return this; } /** * @return the max number of event-loop a pool will use, the default value is {@code 0} which implies * to reuse the current event-loop */ public int getEventLoopSize() { return eventLoopSize; } /** * Set the number of event-loop the pool use. * * <ul> * <li>when the size is {@code 0}, the client pool will use the current event-loop</li> * <li>otherwise the client will create and use its own event loop</li> * </ul> * * The default size is {@code 0}. * * @param eventLoopSize the new size * @return a reference to this, so the API can be used fluently */ public PoolOptions setEventLoopSize(int eventLoopSize) { Arguments.require(eventLoopSize >= 0, "poolEventLoopSize must be >= 0"); this.eventLoopSize = eventLoopSize; return this; } /** * Set the maximum requests allowed in the wait queue, any requests beyond the max size will result in * a ConnectionPoolTooBusyException. If the value is set to a negative number then the queue will be unbounded. * @param maxWaitQueueSize the maximum number of waiting requests * @return a reference to this, so the API can be used fluently */ public PoolOptions setMaxWaitQueueSize(int maxWaitQueueSize) { this.maxWaitQueueSize = maxWaitQueueSize; return this; } /** * Returns the maximum wait queue size * @return the maximum wait queue size */ public int getMaxWaitQueueSize() { return maxWaitQueueSize; } public JsonObject toJson() { JsonObject json = new JsonObject(); PoolOptionsConverter.toJson(this, json); return json; } }
PoolOptions
java
quarkusio__quarkus
extensions/reactive-routes/deployment/src/test/java/io/quarkus/vertx/web/mutiny/SSEMultiRouteWithContentTypeTest.java
{ "start": 5322, "end": 9355 }
class ____ { @Route(path = "hello", produces = EVENT_STREAM) Multi<String> hello() { return Multi.createFrom().item("Hello world!"); } @Route(path = "hellos", produces = EVENT_STREAM) Multi<String> hellos() { return Multi.createFrom().items("hello", "world", "!"); } @Route(path = "no-hello", produces = EVENT_STREAM) Multi<String> noHello() { return Multi.createFrom().empty(); } @Route(path = "hello-and-fail", produces = EVENT_STREAM) Multi<String> helloAndFail() { return Multi.createBy().concatenating().streams( Multi.createFrom().item("Hello"), Multi.createFrom().failure(() -> new IOException("boom"))); } @Route(path = "buffer", produces = EVENT_STREAM) Multi<Buffer> buffer() { return Multi.createFrom().item(Buffer.buffer("Buffer")); } @Route(path = "buffers", produces = EVENT_STREAM) Multi<Buffer> buffers() { return Multi.createFrom() .items(Buffer.buffer("Buffer"), Buffer.buffer("Buffer"), Buffer.buffer("Buffer.")); } @Route(path = "mutiny-buffer", produces = EVENT_STREAM) Multi<io.vertx.mutiny.core.buffer.Buffer> bufferMutiny() { return Multi.createFrom().items(io.vertx.mutiny.core.buffer.Buffer.buffer("Buffer"), io.vertx.mutiny.core.buffer.Buffer.buffer("Mutiny")); } @Route(path = "void", produces = EVENT_STREAM) Multi<Void> multiVoid() { return Multi.createFrom().range(0, 200).onItem().ignore(); } @Route(path = "/people", produces = EVENT_STREAM) Multi<Person> people() { return Multi.createFrom().items( new Person("superman", 1), new Person("batman", 2), new Person("spiderman", 3)); } @Route(path = "/people-as-event", produces = EVENT_STREAM) Multi<PersonAsEvent> peopleAsEvent() { return Multi.createFrom().items( new PersonAsEvent("superman", 1), new PersonAsEvent("batman", 2), new PersonAsEvent("spiderman", 3)); } @Route(path = "/people-as-event-without-id", produces = EVENT_STREAM) Multi<PersonAsEventWithoutId> peopleAsEventWithoutId() { return Multi.createFrom().items( new PersonAsEventWithoutId("superman", 1), new PersonAsEventWithoutId("batman", 2), new PersonAsEventWithoutId("spiderman", 3)); } @Route(path = "/people-as-event-without-event", produces = EVENT_STREAM) Multi<PersonAsEventWithoutEvent> peopleAsEventWithoutEvent() { return Multi.createFrom().items( new PersonAsEventWithoutEvent("superman", 1), new PersonAsEventWithoutEvent("batman", 2), new PersonAsEventWithoutEvent("spiderman", 3)); } @Route(path = "/people-content-type", produces = EVENT_STREAM) Multi<Person> peopleWithContentType(RoutingContext context) { context.response().putHeader("content-type", "text/event-stream;charset=utf-8"); return Multi.createFrom().items( new Person("superman", 1), new Person("batman", 2), new Person("spiderman", 3)); } @Route(path = "/failure", produces = EVENT_STREAM) Multi<Person> fail() { return Multi.createFrom().failure(new IOException("boom")); } @Route(path = "/sync-failure", produces = EVENT_STREAM) Multi<Person> failSync() { throw new IllegalStateException("boom"); } @Route(path = "/null", produces = EVENT_STREAM) Multi<String> uniNull() { return null; } } static
SimpleBean
java
apache__dubbo
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.java
{ "start": 10989, "end": 11589 }
class ____ { private final BiConsumer<Long, Number> consumerFunc; private final Number initValue; public Action(BiConsumer<Long, Number> consumerFunc, Number initValue) { this.consumerFunc = consumerFunc; this.initValue = initValue; } public void run(Long responseTime) { consumerFunc.accept(responseTime, initValue); } } @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation return samplesChanged.compareAndSet(true, false); } }
Action
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/LeaderElectionDriverFactory.java
{ "start": 912, "end": 1475 }
interface ____ { /** * Creates a {@link LeaderElectionDriver} for the given leader contender description. Moreover, * it registers the given leader election listener with the service. * * @param leaderElectionListener listener for the callbacks of the {@link LeaderElectionDriver} * @return created {@link LeaderElectionDriver} instance * @throws Exception if the creation fails */ LeaderElectionDriver create(LeaderElectionDriver.Listener leaderElectionListener) throws Exception; }
LeaderElectionDriverFactory
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/validation/SpiModelBindingGraphConverter.java
{ "start": 22308, "end": 23807 }
class ____ extends DaggerProcessingEnv { private final XProcessingEnv env; public static DaggerProcessingEnv from(XProcessingEnv env) { return new DaggerProcessingEnvImpl(env); } DaggerProcessingEnvImpl(XProcessingEnv env) { this.env = env; } @Override public ProcessingEnvironment javac() { checkIsJavac(backend()); return toJavac(env); } @Override public SymbolProcessorEnvironment ksp() { checkIsKsp(backend()); return toKS(env); } @Override public Resolver resolver() { return toKSResolver(env); } @Override public DaggerProcessingEnv.Backend backend() { return getBackend(env); } } private static void checkIsJavac(DaggerProcessingEnv.Backend backend) { checkState( backend == DaggerProcessingEnv.Backend.JAVAC, "Expected JAVAC backend but was: %s", backend); } private static void checkIsKsp(DaggerProcessingEnv.Backend backend) { checkState( backend == DaggerProcessingEnv.Backend.KSP, "Expected KSP backend but was: %s", backend); } private static DaggerProcessingEnv.Backend getBackend(XProcessingEnv env) { switch (env.getBackend()) { case JAVAC: return DaggerProcessingEnv.Backend.JAVAC; case KSP: return DaggerProcessingEnv.Backend.KSP; } throw new AssertionError(String.format("Unexpected backend %s", env.getBackend())); } private static final
DaggerProcessingEnvImpl
java
quarkusio__quarkus
extensions/keycloak-authorization/runtime/src/main/java/io/quarkus/keycloak/pep/runtime/KeycloakPolicyEnforcerTenantConfigBuilder.java
{ "start": 24257, "end": 25270 }
class ____ { private final PathConfigBuilder builder; private String method; private String[] scopes; private ScopeEnforcementMode scopesEnforcementMode; private MethodConfigBuilder(PathConfigBuilder builder) { this.builder = builder; } public MethodConfigBuilder method(String method) { this.method = method; return this; } public MethodConfigBuilder scopes(String... scopes) { this.scopes = scopes; return this; } public MethodConfigBuilder scopesEnforcementMode(ScopeEnforcementMode scopesEnforcementMode) { this.scopesEnforcementMode = scopesEnforcementMode; return this; } public PathConfigBuilder build() { Objects.requireNonNull(method); builder.method(method, scopesEnforcementMode, scopes == null ? new String[] {} : scopes); return builder; } } }
MethodConfigBuilder
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_3100/Issue3131.java
{ "start": 198, "end": 625 }
class ____ extends TestCase { public void test_for_issue() throws Exception { List orgs = new ArrayList(); UserOrg org = new UserOrg("111","222" ); orgs.add(org); String s = JSON.toJSONString(new Orgs("111", orgs)); System.out.println(s); Orgs userOrgs = JSON.parseObject(s, Orgs.class); System.out.println(JSON.toJSONString(userOrgs)); } public static
Issue3131
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/DataInputBuffer.java
{ "start": 1743, "end": 4374 }
class ____ extends ByteArrayInputStream { public Buffer() { super(new byte[] {}); } public void reset(byte[] input, int start, int length) { this.buf = input; this.count = start+length; this.mark = start; this.pos = start; } public byte[] getData() { return buf; } public int getPosition() { return pos; } public int getLength() { return count; } /* functions below comes verbatim from hive.common.io.NonSyncByteArrayInputStream */ /** * {@inheritDoc} */ @Override public int read() { return (pos < count) ? (buf[pos++] & 0xff) : -1; } /** * {@inheritDoc} */ @Override public int read(byte[] b, int off, int len) { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } if (pos >= count) { return -1; } if (pos + len > count) { len = count - pos; } if (len <= 0) { return 0; } System.arraycopy(buf, pos, b, off, len); pos += len; return len; } /** * {@inheritDoc} */ @Override public long skip(long n) { if (pos + n > count) { n = count - pos; } if (n < 0) { return 0; } pos += n; return n; } /** * {@inheritDoc} */ @Override public int available() { return count - pos; } } private Buffer buffer; /** Constructs a new empty buffer. */ public DataInputBuffer() { this(new Buffer()); } private DataInputBuffer(Buffer buffer) { super(buffer); this.buffer = buffer; } /** * Resets the data that the buffer reads. * * @param input input. * @param length length. */ public void reset(byte[] input, int length) { buffer.reset(input, 0, length); } /** * Resets the data that the buffer reads. * * @param input input. * @param start start. * @param length length. */ public void reset(byte[] input, int start, int length) { buffer.reset(input, start, length); } public byte[] getData() { return buffer.getData(); } /** * Returns the current position in the input. * * @return position. */ public int getPosition() { return buffer.getPosition(); } /** * Returns the index one greater than the last valid character in the input * stream buffer. * * @return length. */ public int getLength() { return buffer.getLength(); } }
Buffer
java
apache__camel
components/camel-aws/camel-aws2-eventbridge/src/main/java/org/apache/camel/component/aws2/eventbridge/EventbridgeConfiguration.java
{ "start": 1153, "end": 9506 }
class ____ implements Cloneable { private String eventbusName = "default"; @UriParam @Metadata(label = "advanced", autowired = true) private EventBridgeClient eventbridgeClient; @UriParam(label = "security", secret = true) private String accessKey; @UriParam(label = "security", secret = true) private String secretKey; @UriParam(label = "security", secret = true) private String sessionToken; @UriParam @Metadata(required = true, defaultValue = "putRule") private EventbridgeOperations operation = EventbridgeOperations.putRule; @UriParam(label = "proxy", enums = "HTTP,HTTPS", defaultValue = "HTTPS") private Protocol proxyProtocol = Protocol.HTTPS; @UriParam(label = "proxy") private String proxyHost; @UriParam(label = "proxy") private Integer proxyPort; @UriParam(enums = "ap-south-2,ap-south-1,eu-south-1,eu-south-2,us-gov-east-1,me-central-1,il-central-1,ca-central-1,eu-central-1,us-iso-west-1,eu-central-2,eu-isoe-west-1,us-west-1,us-west-2,af-south-1,eu-north-1,eu-west-3,eu-west-2,eu-west-1,ap-northeast-3,ap-northeast-2,ap-northeast-1,me-south-1,sa-east-1,ap-east-1,cn-north-1,ca-west-1,us-gov-west-1,ap-southeast-1,ap-southeast-2,us-iso-east-1,ap-southeast-3,ap-southeast-4,us-east-1,us-east-2,cn-northwest-1,us-isob-east-1,aws-global,aws-cn-global,aws-us-gov-global,aws-iso-global,aws-iso-b-global") private String region; @UriParam private boolean pojoRequest; @UriParam(label = "security") private boolean trustAllCertificates; @UriParam @Metadata(supportFileReference = true) private String eventPatternFile; @UriParam private boolean overrideEndpoint; @UriParam private String uriEndpointOverride; @UriParam(label = "security") private boolean useDefaultCredentialsProvider; @UriParam(label = "security") private boolean useProfileCredentialsProvider; @UriParam(label = "security") private boolean useSessionCredentials; @UriParam(label = "security") private String profileCredentialsName; public EventBridgeClient getEventbridgeClient() { return eventbridgeClient; } /** * To use an existing configured AWS Eventbridge client */ public void setEventbridgeClient(EventBridgeClient eventbridgeClient) { this.eventbridgeClient = eventbridgeClient; } public String getAccessKey() { return accessKey; } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getSessionToken() { return sessionToken; } /** * Amazon AWS Session Token used when the user needs to assume an IAM role */ public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } public EventbridgeOperations getOperation() { return operation; } /** * The operation to perform */ public void setOperation(EventbridgeOperations operation) { this.operation = operation; } public Protocol getProxyProtocol() { return proxyProtocol; } /** * To define a proxy protocol when instantiating the Eventbridge client */ public void setProxyProtocol(Protocol proxyProtocol) { this.proxyProtocol = proxyProtocol; } public String getProxyHost() { return proxyHost; } /** * To define a proxy host when instantiating the Eventbridge client */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } /** * To define a proxy port when instantiating the Eventbridge client */ public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getRegion() { return region; } /** * The region in which the Eventbridge client needs to work. When using this parameter, the configuration will * expect the lowercase name of the region (for example, ap-east-1) You'll need to use the name * Region.EU_WEST_1.id() */ public void setRegion(String region) { this.region = region; } public boolean isPojoRequest() { return pojoRequest; } /** * If we want to use a POJO request as body or not */ public void setPojoRequest(boolean pojoRequest) { this.pojoRequest = pojoRequest; } public boolean isTrustAllCertificates() { return trustAllCertificates; } /** * If we want to trust all certificates in case of overriding the endpoint */ public void setTrustAllCertificates(boolean trustAllCertificates) { this.trustAllCertificates = trustAllCertificates; } public String getEventPatternFile() { return eventPatternFile; } /** * EventPattern File */ public void setEventPatternFile(String eventPatternFile) { this.eventPatternFile = eventPatternFile; } public String getEventbusName() { return eventbusName; } /** * The eventbus name, the default value is default, and this means it will be the AWS event bus of your account. */ public void setEventbusName(String eventbusName) { this.eventbusName = eventbusName; } public boolean isOverrideEndpoint() { return overrideEndpoint; } /** * Set the need for overriding the endpoint. This option needs to be used in combination with the * uriEndpointOverride option */ public void setOverrideEndpoint(boolean overrideEndpoint) { this.overrideEndpoint = overrideEndpoint; } public String getUriEndpointOverride() { return uriEndpointOverride; } /** * Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option */ public void setUriEndpointOverride(String uriEndpointOverride) { this.uriEndpointOverride = uriEndpointOverride; } /** * Set whether the Eventbridge client should expect to load credentials through a default credentials provider or to * expect static credentials to be passed in. */ public void setUseDefaultCredentialsProvider(Boolean useDefaultCredentialsProvider) { this.useDefaultCredentialsProvider = useDefaultCredentialsProvider; } public Boolean isUseDefaultCredentialsProvider() { return useDefaultCredentialsProvider; } public boolean isUseProfileCredentialsProvider() { return useProfileCredentialsProvider; } /** * Set whether the Eventbridge client should expect to load credentials through a profile credentials provider. */ public void setUseProfileCredentialsProvider(boolean useProfileCredentialsProvider) { this.useProfileCredentialsProvider = useProfileCredentialsProvider; } public boolean isUseSessionCredentials() { return useSessionCredentials; } /** * Set whether the Eventbridge client should expect to use Session Credentials. This is useful in a situation in * which the user needs to assume an IAM role for doing operations in Eventbridge. */ public void setUseSessionCredentials(boolean useSessionCredentials) { this.useSessionCredentials = useSessionCredentials; } public String getProfileCredentialsName() { return profileCredentialsName; } /** * If using a profile credentials provider this parameter will set the profile name */ public void setProfileCredentialsName(String profileCredentialsName) { this.profileCredentialsName = profileCredentialsName; } // ************************************************* // // ************************************************* public EventbridgeConfiguration copy() { try { return (EventbridgeConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
EventbridgeConfiguration
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/indices/analysis/IncorrectSetupStablePluginsTests.java
{ "start": 6465, "end": 6809 }
class ____ implements CharFilterFactory { @Override public Reader create(Reader reader) { return new ReplaceCharToNumber(reader, "#", 3); } @Override public Reader normalize(Reader reader) { return new ReplaceCharToNumber(reader, "#", 3); } } }
AbstractCharFilterFactory
java
apache__camel
components/camel-debezium/camel-debezium-common/camel-debezium-common-component/src/test/java/org/apache/camel/component/debezium/DebeziumConsumerTest.java
{ "start": 1781, "end": 7339 }
class ____ extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(DebeziumConsumerTest.class); private static final int NUMBER_OF_LINES = 5; private static final String DEFAULT_DATA_TESTING_FOLDER = "target/data"; private static final Path TEST_FILE_PATH = createTestingPath("camel-debezium-test-file-input.txt").toAbsolutePath(); private static final Path TEST_OFFSET_STORE_PATH = createTestingPath("camel-debezium-test-offset-store.txt").toAbsolutePath(); private static final String DEFAULT_TOPIC_NAME = "test_name_dummy"; private static final String DEFAULT_ROUTE_ID = "foo"; private File inputFile; private File offsetStore; private int linesAdded; @EndpointInject("mock:result") private MockEndpoint to; @BeforeEach public void beforeEach() { linesAdded = 0; inputFile = createTestingFile(TEST_FILE_PATH); offsetStore = createTestingFile(TEST_OFFSET_STORE_PATH); } @AfterEach public void afterEach() { // clean all data files deletePath(TEST_FILE_PATH); deletePath(TEST_OFFSET_STORE_PATH); } @AfterAll public static void afterClass() { // make sure to clean all data files deletePath(TEST_FILE_PATH); deletePath(TEST_OFFSET_STORE_PATH); } @Test void camelShouldConsumeDebeziumMessages() throws Exception { // add initial lines to the file appendLinesToSource(NUMBER_OF_LINES); // assert exchanges to.expectedMessageCount(linesAdded); to.expectedHeaderReceived(DebeziumConstants.HEADER_IDENTIFIER, DEFAULT_TOPIC_NAME); to.expectedBodiesReceivedInAnyOrder("message-1", "message-2", "message-3", "message-4", "message-5"); // verify the first records if they being consumed to.assertIsSatisfied(50); // send another batch appendLinesToSource(NUMBER_OF_LINES); // assert exchanges again to.expectedMessageCount(linesAdded); to.expectedHeaderReceived(DebeziumConstants.HEADER_IDENTIFIER, DEFAULT_TOPIC_NAME); to.assertIsSatisfied(50); } @Test void camelShouldContinueConsumeDebeziumMessagesWhenRouteIsOffline() throws Exception { // add initial lines to the file appendLinesToSource(NUMBER_OF_LINES); // assert exchanges to.expectedMessageCount(linesAdded); // verify the first records if they being consumed to.assertIsSatisfied(50); // assert when route if off to.reset(); // stop route context.getRouteController().stopRoute(DEFAULT_ROUTE_ID); // send a batch while the route is off appendLinesToSource(NUMBER_OF_LINES); // start route again context.getRouteController().startRoute(DEFAULT_ROUTE_ID); // assert exchange messages after restarting, it should continue using the offset file to.expectedMessageCount(NUMBER_OF_LINES); to.expectedHeaderReceived(DebeziumConstants.HEADER_IDENTIFIER, DEFAULT_TOPIC_NAME); to.expectedBodiesReceivedInAnyOrder("message-6", "message-7", "message-8", "message-9", "message-10"); to.assertIsSatisfied(50); } @Override protected CamelContext createCamelContext() throws Exception { final CamelContext context = super.createCamelContext(); final DebeziumComponent component = new DebeziumTestComponent(context); component.setConfiguration(initConfiguration()); context.addComponent("debezium", component); context.disableJMX(); return context; } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("debezium:dummy") .to(to); } }; } private static Path createTestingPath(final String relativePath) { return Paths.get(DEFAULT_DATA_TESTING_FOLDER, relativePath).toAbsolutePath(); } private static File createTestingFile(final Path relativePath) { return IoUtil.createFile(relativePath.toAbsolutePath()); } private static void deletePath(final Path path) { try { IoUtil.delete(path); } catch (IOException e) { LOG.error("Unable to delete {}", path.toAbsolutePath(), e); } } private EmbeddedDebeziumConfiguration initConfiguration() { final FileConnectorEmbeddedDebeziumConfiguration configuration = new FileConnectorEmbeddedDebeziumConfiguration(); configuration.setName("test_name_dummy"); configuration.setTopicConfig(DEFAULT_TOPIC_NAME); configuration.setOffsetStorageFileName(TEST_OFFSET_STORE_PATH.toAbsolutePath().toString()); configuration.setTestFilePath(TEST_FILE_PATH); configuration.setOffsetFlushIntervalMs(0); return configuration; } private void appendLinesToSource(int numberOfLines) throws IOException { CharSequence[] lines = new CharSequence[numberOfLines]; for (int i = 0; i != numberOfLines; ++i) { lines[i] = generateLine(linesAdded + i + 1); } java.nio.file.Files.write(inputFile.toPath(), Collect.arrayListOf(lines), StandardCharsets.UTF_8, StandardOpenOption.APPEND); linesAdded += numberOfLines; } private String generateLine(int lineNumber) { return "message-" + lineNumber; } }
DebeziumConsumerTest
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/classrolesallowed/ClassRolesAllowedBaseResourceWithoutPath_OnInterface_SecurityOnParent.java
{ "start": 81, "end": 254 }
class ____ extends ClassRolesAllowedParentResourceWithoutPath_PathOnInterface_SecurityOnParent { }
ClassRolesAllowedBaseResourceWithoutPath_OnInterface_SecurityOnParent
java
apache__flink
flink-rpc/flink-rpc-core/src/test/java/org/apache/flink/runtime/concurrent/ClassLoadingUtilsTest.java
{ "start": 1299, "end": 4286 }
class ____ { private static final ClassLoader TEST_CLASS_LOADER = new URLClassLoader(new URL[0], ClassLoadingUtilsTest.class.getClassLoader()); @Test void testRunnableWithContextClassLoader() throws Exception { final CompletableFuture<ClassLoader> contextClassLoader = new CompletableFuture<>(); Runnable runnable = () -> contextClassLoader.complete(Thread.currentThread().getContextClassLoader()); final Runnable wrappedRunnable = ClassLoadingUtils.withContextClassLoader(runnable, TEST_CLASS_LOADER); // the runnable should only be wrapped, not run immediately assertThat(contextClassLoader).isNotDone(); wrappedRunnable.run(); assertThat(contextClassLoader.get()).isSameAs(TEST_CLASS_LOADER); } @Test void testExecutorWithContextClassLoader() throws Exception { final Executor wrappedExecutor = ClassLoadingUtils.withContextClassLoader( Executors.newDirectExecutorService(), TEST_CLASS_LOADER); final CompletableFuture<ClassLoader> contextClassLoader = new CompletableFuture<>(); Runnable runnable = () -> contextClassLoader.complete(Thread.currentThread().getContextClassLoader()); wrappedExecutor.execute(runnable); assertThat(contextClassLoader.get()).isSameAs(TEST_CLASS_LOADER); } @Test void testRunRunnableWithContextClassLoader() throws Exception { final CompletableFuture<ClassLoader> contextClassLoader = new CompletableFuture<>(); ThrowingRunnable<Exception> runnable = () -> contextClassLoader.complete(Thread.currentThread().getContextClassLoader()); ClassLoadingUtils.runWithContextClassLoader(runnable, TEST_CLASS_LOADER); assertThat(contextClassLoader.get()).isSameAs(TEST_CLASS_LOADER); } @Test void testRunSupplierWithContextClassLoader() throws Exception { SupplierWithException<ClassLoader, Exception> runnable = () -> Thread.currentThread().getContextClassLoader(); final ClassLoader contextClassLoader = ClassLoadingUtils.runWithContextClassLoader(runnable, TEST_CLASS_LOADER); assertThat(contextClassLoader).isSameAs(TEST_CLASS_LOADER); } @Test void testGuardCompletionWithContextClassLoader() throws Exception { final CompletableFuture<Void> originalFuture = new CompletableFuture<>(); final CompletableFuture<Void> guardedFuture = ClassLoadingUtils.guardCompletionWithContextClassLoader( originalFuture, TEST_CLASS_LOADER); final CompletableFuture<ClassLoader> contextClassLoader = guardedFuture.thenApply(ignored -> Thread.currentThread().getContextClassLoader()); originalFuture.complete(null); assertThat(contextClassLoader.get()).isSameAs(TEST_CLASS_LOADER); } }
ClassLoadingUtilsTest
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/ListSerializerUpgradeTest.java
{ "start": 1391, "end": 2335 }
class ____ extends TypeSerializerUpgradeTestBase<List<String>, List<String>> { private static final String SPEC_NAME = "list-serializer"; public Collection<TestSpecification<?, ?>> createTestSpecifications(FlinkVersion flinkVersion) throws Exception { ArrayList<TestSpecification<?, ?>> testSpecifications = new ArrayList<>(); testSpecifications.add( new TestSpecification<>( SPEC_NAME, flinkVersion, ListSerializerSetup.class, ListSerializerVerifier.class)); return testSpecifications; } // ---------------------------------------------------------------------------------------------- // Specification for "list-serializer" // ---------------------------------------------------------------------------------------------- /** * This
ListSerializerUpgradeTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DirectInvocationOnMockTest.java
{ "start": 9982, "end": 10437 }
class ____ { public Object test() { Test test = mock(Test.class); given((Object) test.test()).willReturn(null); return null; } } """) .doTest(); } @Test public void finalMethodInvoked_noFinding() { helper .addSourceLines( "Test.java", """ import static org.mockito.Mockito.mock;
Test
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialDisjointGeoPointDocValuesAndSourceGridEvaluator.java
{ "start": 1181, "end": 4216 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(SpatialDisjointGeoPointDocValuesAndSourceGridEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator encodedPoints; private final EvalOperator.ExpressionEvaluator gridIds; private final DataType gridType; private final DriverContext driverContext; private Warnings warnings; public SpatialDisjointGeoPointDocValuesAndSourceGridEvaluator(Source source, EvalOperator.ExpressionEvaluator encodedPoints, EvalOperator.ExpressionEvaluator gridIds, DataType gridType, DriverContext driverContext) { this.source = source; this.encodedPoints = encodedPoints; this.gridIds = gridIds; this.gridType = gridType; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (LongBlock encodedPointsBlock = (LongBlock) encodedPoints.eval(page)) { try (LongBlock gridIdsBlock = (LongBlock) gridIds.eval(page)) { return eval(page.getPositionCount(), encodedPointsBlock, gridIdsBlock); } } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += encodedPoints.baseRamBytesUsed(); baseRamBytesUsed += gridIds.baseRamBytesUsed(); return baseRamBytesUsed; } public BooleanBlock eval(int positionCount, LongBlock encodedPointsBlock, LongBlock gridIdsBlock) { try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { boolean allBlocksAreNulls = true; if (!encodedPointsBlock.isNull(p)) { allBlocksAreNulls = false; } if (!gridIdsBlock.isNull(p)) { allBlocksAreNulls = false; } if (allBlocksAreNulls) { result.appendNull(); continue position; } try { SpatialDisjoint.processGeoPointDocValuesAndSourceGrid(result, p, encodedPointsBlock, gridIdsBlock, this.gridType); } catch (IllegalArgumentException | IOException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } @Override public String toString() { return "SpatialDisjointGeoPointDocValuesAndSourceGridEvaluator[" + "encodedPoints=" + encodedPoints + ", gridIds=" + gridIds + ", gridType=" + gridType + "]"; } @Override public void close() { Releasables.closeExpectNoException(encodedPoints, gridIds); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
SpatialDisjointGeoPointDocValuesAndSourceGridEvaluator
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/config/model/ConfigListenerInfoTest.java
{ "start": 1005, "end": 2260 }
class ____ { private ObjectMapper mapper; private ConfigListenerInfo configListenerInfo; @BeforeEach void setUp() { mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); configListenerInfo = new ConfigListenerInfo(); configListenerInfo.setQueryType(ConfigListenerInfo.QUERY_TYPE_CONFIG); configListenerInfo.setListenersStatus(Collections.singletonMap("1.1.1.1", "testMd5")); } @Test public void testSerialize() throws Exception { String json = mapper.writeValueAsString(configListenerInfo); assertTrue(json.contains("\"queryType\":\"config\"")); assertTrue(json.contains("\"listenersStatus\":{\"1.1.1.1\":\"testMd5\"}")); } @Test public void testDeserialize() throws Exception { String json = "{\"queryType\":\"config\",\"listenersStatus\":{\"1.1.1.1\":\"testMd5\"}}"; ConfigListenerInfo configListenerInfo = mapper.readValue(json, ConfigListenerInfo.class); assertEquals(ConfigListenerInfo.QUERY_TYPE_CONFIG, configListenerInfo.getQueryType()); assertEquals("testMd5", configListenerInfo.getListenersStatus().get("1.1.1.1")); } }
ConfigListenerInfoTest
java
quarkusio__quarkus
extensions/reactive-routes/deployment/src/main/java/io/quarkus/vertx/web/deployment/ReactiveRoutesProcessor.java
{ "start": 76658, "end": 78208 }
class ____ TCCL b1.set(result, b1.invokeVirtual(Methods.JSON_OBJECT_MAP_TO, bodyAsJson, Const.of(classDescOf(paramType)))); }); return result; } }).build()); // Add injector for failures injectors.add(ParameterInjector.builder().targetHandlerType(Route.HandlerType.FAILURE) .match(new TriPredicate<Type, Set<AnnotationInstance>, IndexView>() { @Override public boolean test(Type paramType, Set<AnnotationInstance> paramAnnotations, IndexView index) { return isThrowable(paramType, index) && !Annotations.contains(paramAnnotations, DotNames.BODY); } }).valueProvider(new ValueProvider() { @Override public Expr get(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext, BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) { // we can cast here, because we already checked if the failure is assignable to the param // (see the beginning of `generateInvoke()`) return bc.cast(bc.invokeInterface(Methods.FAILURE, routingContext), classDescOf(methodParam.type())); } }).build()); return injectors; } private static
from
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationContext.java
{ "start": 1614, "end": 2916 }
class ____ implements OAuth2AuthenticationContext { private final Map<Object, Object> context; private OAuth2AccessTokenAuthenticationContext(Map<Object, Object> context) { this.context = Collections.unmodifiableMap(new HashMap<>(context)); } @SuppressWarnings("unchecked") @Nullable @Override public <V> V get(Object key) { return hasKey(key) ? (V) this.context.get(key) : null; } @Override public boolean hasKey(Object key) { Assert.notNull(key, "key cannot be null"); return this.context.containsKey(key); } /** * Returns the {@link OAuth2AccessTokenResponse.Builder access token response * builder}. * @return the {@link OAuth2AccessTokenResponse.Builder} */ public OAuth2AccessTokenResponse.Builder getAccessTokenResponse() { return get(OAuth2AccessTokenResponse.Builder.class); } /** * Constructs a new {@link Builder} with the provided * {@link OAuth2AccessTokenAuthenticationToken}. * @param authentication the {@link OAuth2AccessTokenAuthenticationToken} * @return the {@link Builder} */ public static Builder with(OAuth2AccessTokenAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OAuth2AccessTokenAuthenticationContext}. */ public static final
OAuth2AccessTokenAuthenticationContext
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1600/Issue1603_map.java
{ "start": 566, "end": 681 }
class ____ { public final Map<String, Object> values = Collections.emptyMap(); } public static
Model_1
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromRunnableTest.java
{ "start": 1265, "end": 6095 }
class ____ extends RxJavaTest { @Test public void fromRunnable() { final AtomicInteger atomicInteger = new AtomicInteger(); Flowable.fromRunnable(new Runnable() { @Override public void run() { atomicInteger.incrementAndGet(); } }) .test() .assertResult(); assertEquals(1, atomicInteger.get()); } @Test public void fromRunnableTwice() { final AtomicInteger atomicInteger = new AtomicInteger(); Runnable run = new Runnable() { @Override public void run() { atomicInteger.incrementAndGet(); } }; Flowable.fromRunnable(run) .test() .assertResult(); assertEquals(1, atomicInteger.get()); Flowable.fromRunnable(run) .test() .assertResult(); assertEquals(2, atomicInteger.get()); } @Test public void fromRunnableInvokesLazy() { final AtomicInteger atomicInteger = new AtomicInteger(); Flowable<Object> source = Flowable.fromRunnable(new Runnable() { @Override public void run() { atomicInteger.incrementAndGet(); } }); assertEquals(0, atomicInteger.get()); source .test() .assertResult(); assertEquals(1, atomicInteger.get()); } @Test public void fromRunnableThrows() { Flowable.fromRunnable(new Runnable() { @Override public void run() { throw new UnsupportedOperationException(); } }) .test() .assertFailure(UnsupportedOperationException.class); } @SuppressWarnings("unchecked") @Test public void callable() throws Throwable { final int[] counter = { 0 }; Flowable<Void> m = Flowable.fromRunnable(new Runnable() { @Override public void run() { counter[0]++; } }); assertTrue(m.getClass().toString(), m instanceof Supplier); assertNull(((Supplier<Void>)m).get()); assertEquals(1, counter[0]); } @Test public void noErrorLoss() throws Exception { List<Throwable> errors = TestHelper.trackPluginErrors(); try { final CountDownLatch cdl1 = new CountDownLatch(1); final CountDownLatch cdl2 = new CountDownLatch(1); TestSubscriber<Object> ts = Flowable.fromRunnable(new Runnable() { @Override public void run() { cdl1.countDown(); try { cdl2.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); throw new TestException(e); } } }).subscribeOn(Schedulers.single()).test(); assertTrue(cdl1.await(5, TimeUnit.SECONDS)); ts.cancel(); int timeout = 10; while (timeout-- > 0 && errors.isEmpty()) { Thread.sleep(100); } TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void disposedUpfront() throws Throwable { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run) .test(1L, true) .assertEmpty(); verify(run, never()).run(); } @Test public void cancelWhileRunning() { final TestSubscriber<Object> ts = new TestSubscriber<>(); Flowable.fromRunnable(new Runnable() { @Override public void run() { ts.cancel(); } }) .subscribeWith(ts) .assertEmpty(); assertTrue(ts.isCancelled()); } @Test public void asyncFused() throws Throwable { TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); ts.setInitialFusionMode(QueueFuseable.ASYNC); Runnable action = mock(Runnable.class); Flowable.fromRunnable(action) .subscribe(ts); ts.assertFusionMode(QueueFuseable.ASYNC) .assertResult(); verify(action).run(); } @Test public void syncFusedRejected() throws Throwable { TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); ts.setInitialFusionMode(QueueFuseable.SYNC); Runnable action = mock(Runnable.class); Flowable.fromRunnable(action) .subscribe(ts); ts.assertFusionMode(QueueFuseable.NONE) .assertResult(); verify(action).run(); } }
FlowableFromRunnableTest
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/PropertyMapping.java
{ "start": 1498, "end": 1853 }
class ____ { * } * </pre> will result in a {@literal my.example.name} property being added with the value * {@literal "Spring"}. * <p> * * @author Phillip Webb * @since 4.0.0 * @see AnnotationsPropertySource * @see TestPropertySource */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented public @
MyTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/metrics/ReporterSetupTest.java
{ "start": 15418, "end": 15625 }
class ____ implements MetricReporterFactory { @Override public MetricReporter createMetricReporter(Properties config) { throw new RuntimeException(); } } }
FailingFactory
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 253189, "end": 253410 }
class ____ { private int age; public Person3(String name, int age) { this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public static
Person3
java
grpc__grpc-java
android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java
{ "start": 7809, "end": 8010 }
class ____ the server implementation of the service XdsUpdateHealthService. * <pre> * A service to remotely control health status of an xDS test server. * </pre> */ public static abstract
for
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/parser/SQLParserUtils.java
{ "start": 23191, "end": 42865 }
interface ____ { Object eval(SQLExpr expr); } public static String replaceBackQuote(String sql, DbType dbType) { int i = sql.indexOf('`'); if (i == -1) { return sql; } char[] chars = sql.toCharArray(); Lexer lexer = SQLParserUtils.createLexer(sql, dbType); int len = chars.length; int off = 0; for_: for (; ; ) { lexer.nextToken(); int p0, p1; char c0, c1; switch (lexer.token) { case IDENTIFIER: p0 = lexer.startPos + off; p1 = lexer.pos - 1 + off; c0 = chars[p0]; c1 = chars[p1]; if (c0 == '`' && c1 == '`') { if (p1 - p0 > 2 && chars[p0 + 1] == '\'' && chars[p1 - 1] == '\'') { System.arraycopy(chars, p0 + 1, chars, p0, p1 - p0 - 1); System.arraycopy(chars, p1 + 1, chars, p1 - 1, chars.length - p1 - 1); len -= 2; off -= 2; } else { chars[p0] = '"'; chars[p1] = '"'; } } break; case EOF: case ERROR: break for_; default: break; } } return new String(chars, 0, len); } public static String addBackQuote(String sql, DbType dbType) { if (StringUtils.isEmpty(sql)) { return sql; } SQLStatementParser parser = createSQLStatementParser(sql, dbType); StringBuilder buf = new StringBuilder(sql.length() + 20); SQLASTOutputVisitor out = SQLUtils.createOutputVisitor(buf, DbType.mysql); out.config(VisitorFeature.OutputNameQuote, true); SQLType sqlType = getSQLType(sql, dbType); if (sqlType == SQLType.INSERT) { parser.config(SQLParserFeature.InsertReader, true); SQLInsertStatement stmt = (SQLInsertStatement) parser.parseStatement(); int startPos = parser.getLexer().startPos; stmt.accept(out); if (stmt.getQuery() == null) { buf.append(' '); buf.append(sql, startPos, sql.length()); } } else { SQLStatement stmt = parser.parseStatement(); stmt.accept(out); } return buf.toString(); } public static List<String> split(String sql, DbType dbType) { if (dbType == null) { dbType = DbType.other; } { Lexer lexer = createLexer(sql, dbType); lexer.nextToken(); boolean script = false; if (dbType == DbType.odps && lexer.token == Token.VARIANT) { script = true; } if (script) { return Collections.singletonList(sql); } } List list = new ArrayList(); Lexer lexer = createLexer(sql, dbType); lexer.config(SQLParserFeature.SkipComments, false); lexer.config(SQLParserFeature.KeepComments, true); boolean set = false, paiOrJar = false; int start = 0; Token token = lexer.token; for (; lexer.token != Token.EOF; ) { if (token == Token.SEMI) { int len = lexer.startPos - start; if (len > 0) { String lineSql = sql.substring(start, lexer.startPos); lineSql = lineSql.trim(); if (!lineSql.isEmpty()) { list.add(lineSql); } } start = lexer.startPos + 1; set = false; } else if (token == Token.CREATE) { lexer.nextToken(); if (lexer.token == Token.FUNCTION || lexer.identifierEquals("FUNCTION")) { lexer.nextToken(); lexer.nextToken(); if (lexer.token == Token.AS) { lexer.nextToken(); if (lexer.token == Token.LITERAL_CHARS) { lexer.nextToken(); token = lexer.token; continue; } } lexer.startPos = sql.length(); break; } token = lexer.token; continue; } else if (set && token == Token.EQ && dbType == DbType.odps) { lexer.nextTokenForSet(); token = lexer.token; continue; } if (lexer.identifierEquals("USING")) { lexer.nextToken(); if (lexer.identifierEquals("jar")) { lexer.nextToken(); } } if (lexer.token == Token.SET) { set = true; } if (lexer.identifierEquals("ADD") && (dbType == DbType.hive || dbType == DbType.odps || dbType == DbType.spark)) { lexer.nextToken(); if (lexer.identifierEquals("JAR")) { lexer.nextPath(); } } else { lexer.nextToken(); } token = lexer.token; } if (start != sql.length() && token != Token.SEMI) { int end = lexer.startPos; if (end > sql.length()) { end = sql.length(); } String splitSql = sql.substring(start, end).trim(); if (!paiOrJar) { splitSql = removeComment(splitSql, dbType).trim(); } else { if (splitSql.endsWith(";")) { splitSql = splitSql.substring(0, splitSql.length() - 1).trim(); } } if (!splitSql.isEmpty()) { list.add(splitSql); } } return list; } public static List<String> splitAndRemoveComment(String sql, DbType dbType) { if (dbType == null) { dbType = DbType.other; } boolean containsCommentAndSemi = false; { Lexer lexer = createLexer(sql, dbType); lexer.config(SQLParserFeature.SkipComments, false); lexer.config(SQLParserFeature.KeepComments, true); while (lexer.token != Token.EOF) { if (lexer.token == Token.LINE_COMMENT || lexer.token == Token.MULTI_LINE_COMMENT || lexer.token == Token.SEMI) { containsCommentAndSemi = true; break; } lexer.nextToken(); } if (!containsCommentAndSemi) { return Collections.singletonList(sql); } } { Lexer lexer = createLexer(sql, dbType); lexer.nextToken(); boolean script = false; if (dbType == DbType.odps && lexer.token == Token.VARIANT) { script = true; } if (script || lexer.identifierEquals("pai") || lexer.identifierEquals("jar") || lexer.identifierEquals("copy")) { return Collections.singletonList(sql); } } List list = new ArrayList(); Lexer lexer = createLexer(sql, dbType); lexer.config(SQLParserFeature.SkipComments, false); lexer.config(SQLParserFeature.KeepComments, true); lexer.nextToken(); boolean set = false, paiOrJar = false; int start = 0; Token preToken = null; int prePos = 0; Token token = lexer.token; Token startToken = lexer.token; while (token == Token.LINE_COMMENT || token == Token.MULTI_LINE_COMMENT) { lexer.nextToken(); token = lexer.token; startToken = token; start = lexer.startPos; } for (int tokens = 1; lexer.token != Token.EOF; ) { if (token == Token.SEMI) { int len = lexer.startPos - start; if (len > 0) { String lineSql = sql.substring(start, lexer.startPos); String splitSql = set ? removeLeftComment(lineSql, dbType) : removeComment(lineSql, dbType ).trim(); if (!splitSql.isEmpty()) { list.add(splitSql); } } lexer.nextToken(); token = lexer.token; start = lexer.startPos; startToken = token; set = false; tokens = token == Token.LINE_COMMENT || token == Token.MULTI_LINE_COMMENT ? 0 : 1; continue; } else if (token == Token.MULTI_LINE_COMMENT) { int len = lexer.startPos - start; if (len > 0) { String splitSql = removeComment( sql.substring(start, lexer.startPos), dbType ).trim(); if (!splitSql.isEmpty()) { list.add(splitSql); } } lexer.nextToken(); token = lexer.token; start = lexer.startPos; startToken = token; tokens = token == Token.LINE_COMMENT || token == Token.MULTI_LINE_COMMENT ? 0 : 1; continue; } else if (token == Token.CREATE) { lexer.nextToken(); if (lexer.token == Token.FUNCTION || lexer.identifierEquals("FUNCTION")) { lexer.nextToken(); lexer.nextToken(); if (lexer.token == Token.AS) { lexer.nextToken(); if (lexer.token == Token.LITERAL_CHARS) { lexer.nextToken(); token = lexer.token; continue; } } lexer.startPos = sql.length(); break; } token = lexer.token; continue; } else if (set && token == Token.EQ && dbType == DbType.odps) { lexer.nextTokenForSet(); token = lexer.token; continue; } else if (dbType == DbType.odps && (preToken == null || preToken == Token.LINE_COMMENT || preToken == Token.SEMI) && (lexer.identifierEquals("pai") || lexer.identifierEquals("jar") || lexer.identifierEquals("copy"))) { lexer.scanLineArgument(); paiOrJar = true; } if (lexer.identifierEquals("USING")) { lexer.nextToken(); if (lexer.identifierEquals("jar")) { lexer.nextToken(); } } if (lexer.token == Token.SET) { set = true; } prePos = lexer.pos; if (lexer.identifierEquals("ADD") && (dbType == DbType.hive || dbType == DbType.odps || dbType == DbType.spark)) { lexer.nextToken(); if (lexer.identifierEquals("JAR")) { lexer.nextPath(); } } else { lexer.nextToken(); } preToken = token; token = lexer.token; if (token == Token.LINE_COMMENT && tokens == 0) { start = lexer.pos; startToken = token; } if (token != Token.LINE_COMMENT && token != Token.MULTI_LINE_COMMENT && token != Token.SEMI) { tokens++; } } if (start != sql.length() && token != Token.SEMI) { int end = lexer.startPos; if (end > sql.length()) { end = sql.length(); } String splitSql = sql.substring(start, end).trim(); if (!paiOrJar) { splitSql = removeComment(splitSql, dbType).trim(); } else { if (splitSql.endsWith(";")) { splitSql = splitSql.substring(0, splitSql.length() - 1).trim(); } } if (!splitSql.isEmpty()) { list.add(splitSql); } } return list; } public static String removeLeftComment(String sql, DbType dbType) { if (dbType == null) { dbType = DbType.other; } sql = sql.trim(); if (sql.startsWith("jar")) { return sql; } boolean containsComment = false; { Lexer lexer = createLexer(sql, dbType); lexer.config(SQLParserFeature.SkipComments, false); lexer.config(SQLParserFeature.KeepComments, true); while (lexer.token != Token.EOF) { if (lexer.token == Token.LINE_COMMENT || lexer.token == Token.MULTI_LINE_COMMENT) { containsComment = true; break; } lexer.nextToken(); } if (!containsComment) { return sql; } } StringBuilder sb = new StringBuilder(); Lexer lexer = createLexer(sql, dbType); lexer.config(SQLParserFeature.SkipComments, false); lexer.config(SQLParserFeature.KeepComments, true); lexer.nextToken(); int start = 0; for (; lexer.token != Token.EOF; lexer.nextToken()) { if (lexer.token == Token.LINE_COMMENT || lexer.token == Token.MULTI_LINE_COMMENT) { continue; } start = lexer.startPos; break; } if (start != sql.length()) { sb.append(sql.substring(start, sql.length())); } return sb.toString(); } public static String removeComment(String sql, DbType dbType) { if (dbType == null) { dbType = DbType.other; } sql = sql.trim(); if (sql.startsWith("jar") || sql.startsWith("JAR")) { return sql; } if ((sql.startsWith("pai") || sql.startsWith("PAI")) && sql.indexOf(';') == -1) { return sql; } boolean containsComment = false; { Lexer lexer = createLexer(sql, dbType); lexer.config(SQLParserFeature.SkipComments, false); lexer.config(SQLParserFeature.KeepComments, true); while (lexer.token != Token.EOF) { if (lexer.token == Token.LINE_COMMENT || lexer.token == Token.MULTI_LINE_COMMENT) { containsComment = true; break; } lexer.nextToken(); } if (!containsComment) { return sql; } } StringBuilder sb = new StringBuilder(); Lexer lexer = createLexer(sql, dbType); lexer.config(SQLParserFeature.SkipComments, false); lexer.config(SQLParserFeature.KeepComments, true); int start = 0; Token token = lexer.token; for (; lexer.token != Token.EOF; ) { if (token == Token.LINE_COMMENT) { int len = lexer.startPos - start; if (len > 0) { sb.append(sql.substring(start, lexer.startPos)); } start = lexer.startPos + lexer.stringVal().length(); if (lexer.startPos > 1 && lexer.text.charAt(lexer.startPos - 1) == '\n') { while (start + 1 < lexer.text.length() && lexer.text.charAt(start) == '\n') { start = start + 1; } } } else if (token == Token.MULTI_LINE_COMMENT) { int len = lexer.startPos - start; if (len > 0) { sb.append(sql.substring(start, lexer.startPos)); } start = lexer.startPos + lexer.stringVal().length(); } if (lexer.identifierEquals("ADD")) { lexer.nextToken(); if (lexer.identifierEquals("JAR")) { lexer.nextPath(); } } else { lexer.nextToken(); } token = lexer.token; } if (start != sql.length() && token != Token.LINE_COMMENT && token != Token.MULTI_LINE_COMMENT) { sb.append(sql.substring(start, sql.length())); } return sb.toString(); } public static List<String> getTables(String sql, DbType dbType) { Set<String> tables = new LinkedHashSet<>(); boolean set = false; Lexer lexer = createLexer(sql, dbType); lexer.nextToken(); SQLExprParser exprParser; switch (dbType) { case odps: exprParser = new OdpsExprParser(lexer); break; case mysql: exprParser = new MySqlExprParser(lexer); break; default: exprParser = new SQLExprParser(lexer); break; } for_: for (; lexer.token != Token.EOF; ) { switch (lexer.token) { case CREATE: case DROP: case ALTER: set = false; lexer.nextToken(); if (lexer.token == Token.TABLE) { lexer.nextToken(); if (lexer.token == Token.IF) { lexer.nextToken(); if (lexer.token == Token.NOT) { lexer.nextToken(); } if (lexer.token == Token.EXISTS) { lexer.nextToken(); } } SQLName name = exprParser.name(); tables.add(name.toString()); if (lexer.token == Token.AS) { lexer.nextToken(); } } continue for_; case FROM: case JOIN: lexer.nextToken(); if (lexer.token != Token.LPAREN && lexer.token != Token.VALUES ) { SQLName name = exprParser.name(); tables.add(name.toString()); } continue for_; case SEMI: set = false; break; case SET: set = true; break; case EQ: if (set && dbType == DbType.odps) { lexer.nextTokenForSet(); continue for_; } break; default: break; } lexer.nextToken(); } return new ArrayList<>(tables); } }
SimpleValueEvalHandler
java
square__javapoet
src/test/java/com/squareup/javapoet/TypeSpecTest.java
{ "start": 86081, "end": 88010 }
class ____ {\n" + " private static final String FOO;\n" + "\n" + " static {\n" + " FOO = \"FOO\";\n" + " }\n" + " static {\n" + " FOO = \"staticFoo\";\n" + " }\n" + "\n" + " private String foo;\n" + "\n" + " {\n" + " foo = \"FOO\";\n" + " }\n" + " {\n" + " foo = \"instanceFoo\";\n" + " }\n" + "\n" + " Taco() {\n" + " }\n" + "\n" + " @Override\n" + " public String toString() {\n" + " return FOO;\n" + " }\n" + "}\n"); } @Test public void initializerBlockUnsupportedExceptionOnInterface() { TypeSpec.Builder interfaceBuilder = TypeSpec.interfaceBuilder("Taco"); try { interfaceBuilder.addInitializerBlock(CodeBlock.builder().build()); fail("Exception expected"); } catch (UnsupportedOperationException e) { } } @Test public void initializerBlockUnsupportedExceptionOnAnnotation() { TypeSpec.Builder annotationBuilder = TypeSpec.annotationBuilder("Taco"); try { annotationBuilder.addInitializerBlock(CodeBlock.builder().build()); fail("Exception expected"); } catch (UnsupportedOperationException e) { } } @Test public void lineWrapping() { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("call"); methodBuilder.addCode("$[call("); for (int i = 0; i < 32; i++) { methodBuilder.addParameter(String.class, "s" + i); methodBuilder.addCode(i > 0 ? ",$W$S" : "$S", i); } methodBuilder.addCode(");$]\n"); TypeSpec taco = TypeSpec.classBuilder("Taco") .addMethod(methodBuilder.build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.String;\n" + "\n" + "
Taco
java
apache__camel
components/camel-google/camel-google-bigquery/src/test/java/org/apache/camel/component/google/bigquery/unit/sql/GoogleBigQuerySQLProducerBaseTest.java
{ "start": 1626, "end": 3478 }
class ____ extends CamelTestSupport { protected GoogleBigQuerySQLEndpoint endpoint = mock(GoogleBigQuerySQLEndpoint.class); protected GoogleBigQuerySQLProducer producer; protected String sql; protected String projectId = "testProjectId"; protected GoogleBigQuerySQLConfiguration configuration = new GoogleBigQuerySQLConfiguration(); protected BigQuery bigquery; protected TableResult tableResult; protected Job job; protected JobStatistics.QueryStatistics statistics; protected QueryJobConfiguration jobConfiguration; protected GoogleBigQuerySQLProducer createAndStartProducer() { configuration.setProjectId(projectId); configuration.setQueryString(sql); GoogleBigQuerySQLProducer sqlProducer = new GoogleBigQuerySQLProducer(bigquery, endpoint, configuration); sqlProducer.start(); return sqlProducer; } protected void setupBigqueryMock() throws Exception { bigquery = mock(BigQuery.class); tableResult = mock(TableResult.class); job = mock(Job.class); statistics = mock(JobStatistics.QueryStatistics.class); jobConfiguration = mock(QueryJobConfiguration.class); when(bigquery.query(any(QueryJobConfiguration.class), any(JobId.class))).thenReturn(tableResult); when(bigquery.create(any(JobInfo.class))).thenReturn(job); when(bigquery.getJob(any(JobId.class))).thenReturn(job); when(job.waitFor()).thenReturn(job); when(job.getQueryResults()).thenReturn(tableResult); when(job.getStatistics()).thenReturn(statistics); when(job.<QueryJobConfiguration> getConfiguration()).thenReturn(jobConfiguration); when(statistics.getNumDmlAffectedRows()).thenReturn(1L); when(jobConfiguration.getQuery()).thenReturn(sql); } }
GoogleBigQuerySQLProducerBaseTest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/rolemapping/PutRoleMappingRequest.java
{ "start": 1592, "end": 6498 }
class ____ extends LegacyActionRequest implements WriteRequest<PutRoleMappingRequest> { private String name = null; private boolean enabled = true; private List<String> roles = Collections.emptyList(); private List<TemplateRoleName> roleTemplates = Collections.emptyList(); private RoleMapperExpression rules = null; private Map<String, Object> metadata = Collections.emptyMap(); private RefreshPolicy refreshPolicy = RefreshPolicy.IMMEDIATE; public PutRoleMappingRequest(StreamInput in) throws IOException { super(in); this.name = in.readString(); this.enabled = in.readBoolean(); this.roles = in.readStringCollectionAsList(); this.roleTemplates = in.readCollectionAsList(TemplateRoleName::new); this.rules = ExpressionParser.readExpression(in); this.metadata = in.readGenericMap(); this.refreshPolicy = RefreshPolicy.readFrom(in); } public PutRoleMappingRequest() {} @Override public ActionRequestValidationException validate() { return validate(true); } public ActionRequestValidationException validate(boolean validateMetadata) { ActionRequestValidationException validationException = null; if (name == null) { validationException = addValidationError("role-mapping name is missing", validationException); } if (roles.isEmpty() && roleTemplates.isEmpty()) { validationException = addValidationError("role-mapping roles or role-templates are missing", validationException); } if (roles.size() > 0 && roleTemplates.size() > 0) { validationException = addValidationError("role-mapping cannot have both roles and role-templates", validationException); } if (rules == null) { validationException = addValidationError("role-mapping rules are missing", validationException); } if (validateMetadata && MetadataUtils.containsReservedMetadata(metadata)) { if (metadata.containsKey(READ_ONLY_ROLE_MAPPING_METADATA_FLAG)) { validationException = addValidationError( "metadata contains [" + READ_ONLY_ROLE_MAPPING_METADATA_FLAG + "] flag. You cannot create or update role-mappings with a read-only flag", validationException ); } else { validationException = addValidationError( "metadata keys may not start with [" + MetadataUtils.RESERVED_PREFIX + "]", validationException ); } } return validationException; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<String> getRoles() { return Collections.unmodifiableList(roles); } public List<TemplateRoleName> getRoleTemplates() { return Collections.unmodifiableList(roleTemplates); } public void setRoles(List<String> roles) { this.roles = new ArrayList<>(roles); } public void setRoleTemplates(List<TemplateRoleName> templates) { this.roleTemplates = new ArrayList<>(templates); } public RoleMapperExpression getRules() { return rules; } public void setRules(RoleMapperExpression expression) { this.rules = expression; } @Override public PutRoleMappingRequest setRefreshPolicy(RefreshPolicy refreshPolicy) { this.refreshPolicy = refreshPolicy; return this; } /** * Should this request trigger a refresh ({@linkplain RefreshPolicy#IMMEDIATE}, the default), * wait for a refresh ({@linkplain RefreshPolicy#WAIT_UNTIL}), or proceed ignore refreshes * entirely ({@linkplain RefreshPolicy#NONE}). */ @Override public RefreshPolicy getRefreshPolicy() { return refreshPolicy; } public void setMetadata(Map<String, Object> metadata) { this.metadata = Objects.requireNonNull(metadata); } public Map<String, Object> getMetadata() { return metadata; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(name); out.writeBoolean(enabled); out.writeStringCollection(roles); out.writeCollection(roleTemplates); ExpressionParser.writeExpression(rules, out); out.writeGenericMap(metadata); refreshPolicy.writeTo(out); } public ExpressionRoleMapping getMapping() { return new ExpressionRoleMapping(name, rules, roles, roleTemplates, metadata, enabled); } }
PutRoleMappingRequest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/injection/guice/spi/InstanceBinding.java
{ "start": 885, "end": 1243 }
interface ____<T> extends Binding<T> { /** * Returns the user-supplied instance. */ T getInstance(); /** * Returns the field and method injection points of the instance, injected at injector-creation * time only. * * @return a possibly empty set */ Set<InjectionPoint> getInjectionPoints(); }
InstanceBinding
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/flattened/FlattenedFieldMapper.java
{ "start": 5468, "end": 5841 }
class ____ extends FieldMapper { public static final String CONTENT_TYPE = "flattened"; public static final String KEYED_FIELD_SUFFIX = "._keyed"; public static final String KEYED_IGNORED_VALUES_FIELD_SUFFIX = "._keyed._ignored"; public static final String TIME_SERIES_DIMENSIONS_ARRAY_PARAM = "time_series_dimensions"; private static
FlattenedFieldMapper
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLDropTriggerStatement.java
{ "start": 844, "end": 2126 }
class ____ extends SQLStatementImpl implements SQLDropStatement, SQLReplaceable { private SQLName name; private boolean ifExists; public SQLDropTriggerStatement() { } public SQLDropTriggerStatement(DbType dbType) { super(dbType); } public SQLName getName() { return name; } public void setName(SQLName name) { this.name = name; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, name); } visitor.endVisit(this); } @Override public List<SQLObject> getChildren() { List<SQLObject> children = new ArrayList<SQLObject>(); if (name != null) { children.add(name); } return children; } public boolean isIfExists() { return ifExists; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } public boolean replace(SQLExpr expr, SQLExpr target) { if (name == expr) { setName((SQLName) target); return true; } return false; } @Override public DDLObjectType getDDLObjectType() { return DDLObjectType.TRIGGER; } }
SQLDropTriggerStatement
java
apache__camel
components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonObjectListSplitTest.java
{ "start": 1106, "end": 1763 }
class ____ extends CamelTestSupport { @Test public void testJackson() throws InterruptedException { getMockEndpoint("mock:result").expectedMessageCount(2); getMockEndpoint("mock:result").expectedMessagesMatches(body().isInstanceOf(DummyObject.class)); template.sendBody("direct:start", "[{\"dummy\": \"value1\"}, {\"dummy\": \"value2\"}]"); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // you can specify the pojo
JacksonObjectListSplitTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/results/internal/dynamic/DynamicFetchBuilder.java
{ "start": 304, "end": 463 }
interface ____ extends FetchBuilder, NativeQuery.ReturnProperty { DynamicFetchBuilder cacheKeyInstance(); List<String> getColumnAliases(); }
DynamicFetchBuilder
java
spring-projects__spring-framework
spring-context-support/src/main/java/org/springframework/scheduling/quartz/JobDetailFactoryBean.java
{ "start": 1470, "end": 1779 }
class ____ the Spring bean name as job name, * and the Quartz default group ("DEFAULT") as job group if not specified. * * @author Juergen Hoeller * @since 3.1 * @see #setName * @see #setGroup * @see org.springframework.beans.factory.BeanNameAware * @see org.quartz.Scheduler#DEFAULT_GROUP */ public
uses
java
google__dagger
javatests/artifacts/hilt-android/simple/app/src/sharedTest/java/dagger/hilt/android/simple/Injection1Test.java
{ "start": 1865, "end": 2076 }
interface ____ { @Provides @Named(APPLICATION_QUALIFIER) static String provideString() { return APPLICATION_VALUE; } } @Module @InstallIn(ActivityComponent.class)
TestApplicationModule
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/validation/annotation/ValidationAnnotationUtils.java
{ "start": 838, "end": 1023 }
class ____ handling validation annotations. * Mainly for internal use within the framework. * * @author Christoph Dreis * @author Juergen Hoeller * @since 5.3.7 */ public abstract
for
java
quarkusio__quarkus
independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/core/AbstractResteasyReactiveContext.java
{ "start": 718, "end": 14922 }
class ____<T extends AbstractResteasyReactiveContext<T, H>, H extends RestHandler<T>> implements Runnable, Closeable, ResteasyReactiveCallbackContext { protected static final Logger log = Logger.getLogger(AbstractResteasyReactiveContext.class); protected static final Logger logWebApplicationExceptions = Logger.getLogger(WebApplicationException.class.getSimpleName()); protected H[] handlers; protected H[] abortHandlerChain; protected int position; protected Throwable throwable; private boolean suspended = false; private volatile boolean requestScopeActivated = false; private boolean running = false; private volatile Executor executor; // ephemerally set by handlers to signal that we resume, it needs to be on this executor private volatile Executor lastExecutor; // contains the last executor which was provided during resume - needed to submit there if suspended again // This is used to store properties used in the various JAX-RS context objects, but it also stores some of the properties of this // object that are very infrequently accessed. This is done in order to cut down the size of this object in order to take advantage of better caching private Map<String, Object> properties; private final ThreadSetupAction requestContext; private ThreadSetupAction.ThreadState currentRequestScope; private List<CompletionCallback> completionCallbacks; private boolean abortHandlerChainStarted; private boolean closed = false; public AbstractResteasyReactiveContext(H[] handlerChain, H[] abortHandlerChain, ThreadSetupAction requestContext) { this.handlers = handlerChain; this.abortHandlerChain = abortHandlerChain; this.requestContext = requestContext; } public void suspend() { suspended = true; } public void resume() { resume((Executor) null); } public synchronized void resume(Throwable throwable) { resume(throwable, false); } public synchronized void resume(Throwable throwable, boolean keepTarget) { handleException(throwable, keepTarget); resume((Executor) null); } public synchronized void resume(Executor executor) { if (running) { this.executor = executor; if (executor == null) { suspended = false; } else { this.lastExecutor = executor; } } else { suspended = false; if (executor == null) { if (lastExecutor == null) { // TODO CES - Ugly Ugly hack! Executor ctxtExecutor = getContextExecutor(); if (ctxtExecutor == null) { // Won't use the TCCL. getEventLoop().execute(this); } else { // Use the TCCL. ctxtExecutor.execute(this); } } else { lastExecutor.execute(this); } } else { executor.execute(this); } } } public H[] getAbortHandlerChain() { return abortHandlerChain; } public T setAbortHandlerChain(H[] abortHandlerChain) { this.abortHandlerChain = abortHandlerChain; return (T) this; } public void close() { if (closed) { return; } closed = true; //TODO: do we even have any other resources to close? if (currentRequestScope != null) { currentRequestScope.close(); } onComplete(throwable); } public Throwable getThrowable() { return throwable; } protected abstract Executor getEventLoop(); public Executor getContextExecutor() { return null; } protected boolean isRequestScopeManagementRequired() { return true; } @Override public void run() { running = true; boolean processingSuspended = false; //if this is a blocking target we don't activate for the initial non-blocking part //unless there are pre-mapping filters as these may require CDI boolean disassociateRequestScope = false; boolean aborted = false; try { while (position < handlers.length) { int pos = position; position++; //increment before, as reset may reset it to zero try { invokeHandler(pos); if (suspended) { synchronized (this) { // as running is not volatile but instead read from inside the same monitor, // we write it from inside this monitor as well to ensure // that the read is visible regardless of the reading thread running = true; if (isRequestScopeManagementRequired()) { if (requestScopeActivated) { disassociateRequestScope = true; requestScopeActivated = false; } } else { requestScopeActivated = false; requestScopeDeactivated(); } if (suspended) { processingSuspended = true; return; } } } } catch (Throwable t) { aborted = abortHandlerChainStarted; if (t instanceof PreserveTargetException) { handleException(t.getCause(), true); } else { handleException(t, true); } if (aborted) { return; } else if (suspended) { log.error("Uncaught exception thrown when the request context is suspended. " + " Resuming the request to unlock processing the error." + " This may not be appropriate in your situation, please resume the request context when this exception is thrown. ", t); resume(t); } } } } catch (Throwable t) { handleUnrecoverableError(t); } finally { // we need to make sure we don't close the underlying stream in the event loop if the task // has been offloaded to the executor if ((position == handlers.length && !processingSuspended) || aborted) { if (requestScopeActivated) { requestScopeDeactivated(); currentRequestScope.deactivate(); } close(); } else { if (disassociateRequestScope) { requestScopeDeactivated(); currentRequestScope.deactivate(); } beginAsyncProcessing(); Executor exec = null; boolean resumed = false; synchronized (this) { running = false; if (this.executor != null) { //resume happened in the meantime suspended = false; exec = this.executor; // prevent future suspensions from re-submitting the task this.executor = null; } else if (!suspended) { resumed = true; } } if (exec != null) { //outside sync block exec.execute(this); } else if (resumed) { resume(); } } } } protected void invokeHandler(int pos) throws Exception { handlers[pos].handle((T) this); } protected void beginAsyncProcessing() { } protected void requestScopeDeactivated() { } /** * Ensures the CDI request scope is running when inside a handler chain */ public void requireCDIRequestScope() { if (requestScopeActivated) { return; } if (isRequestScopeManagementRequired()) { if (requestContext.isRequestContextActive()) { // req. context is already active, just reuse existing one currentRequestScope = requestContext.currentState(); } else { requestScopeActivated = true; if (currentRequestScope == null) { currentRequestScope = requestContext.activateInitial(); } else { currentRequestScope.activate(); } } } else { currentRequestScope = requestContext.currentState(); } handleRequestScopeActivation(); } /** * Captures the CDI request scope for use outside of handler chains. */ public ThreadSetupAction.ThreadState captureCDIRequestScope() { requireCDIRequestScope(); return currentRequestScope; } protected abstract void handleRequestScopeActivation(); /** * Restarts handler chain processing on a chain that does not target a specific resource * <p> * Generally used to abort processing. * * @param newHandlerChain The new handler chain */ public void restart(H[] newHandlerChain) { restart(newHandlerChain, false); } public void restart(H[] newHandlerChain, boolean keepTarget) { this.handlers = newHandlerChain; position = 0; restarted(keepTarget); } protected abstract void restarted(boolean keepTarget); public boolean isSuspended() { return suspended; } public T setSuspended(boolean suspended) { this.suspended = suspended; return (T) this; } public int getPosition() { return position; } public T setPosition(int position) { this.position = position; return (T) this; } public H[] getHandlers() { return handlers; } /** * If we are on the abort chain already, send a 500. If not, turn the throwable into * a response result and switch to the abort chain */ public void handleException(Throwable t) { handleException(t, false); } public void handleException(Throwable t, boolean keepSameTarget) { if (abortHandlerChainStarted) { log.debug("Attempting to handle unrecoverable exception", t); handleUnrecoverableError(unwrapException(t)); } else { this.throwable = unwrapException(t); if (t instanceof WebApplicationException) { logWebApplicationExceptions.trace("Restarting handler chain for exception exception", this.throwable); } else { log.trace("Restarting handler chain for exception exception", this.throwable); } abortHandlerChainStarted = true; restart(abortHandlerChain, keepSameTarget); } } protected Throwable unwrapException(Throwable t) { if (t instanceof UnwrappableException) { return t.getCause(); } return t; } protected abstract void handleUnrecoverableError(Throwable throwable); protected static final String CUSTOM_RR_PROPERTIES_PREFIX = "$RR$"; public Object getProperty(String name) { if (properties == null) { return null; } return properties.get(name); } public Collection<String> getPropertyNames() { if (properties == null) { return Collections.emptyList(); } Set<String> result = new HashSet<>(); for (String key : properties.keySet()) { if (key.startsWith(CUSTOM_RR_PROPERTIES_PREFIX)) { continue; } result.add(key); } return Collections.unmodifiableSet(result); } public void setProperty(String name, Object object) { if (object == null) { removeProperty(name); return; } if (properties == null) { synchronized (this) { if (properties == null) { properties = new ConcurrentHashMap<>(); } } } properties.put(name, object); } public void removeProperty(String name) { if (properties == null) { return; } properties.remove(name); } synchronized void onComplete(Throwable throwable) { if (completionCallbacks != null) { for (CompletionCallback callback : completionCallbacks) { callback.onComplete(throwable); } } } @Override public synchronized void registerCompletionCallback(CompletionCallback callback) { if (completionCallbacks == null) completionCallbacks = new ArrayList<>(); completionCallbacks.add(callback); } private static final String CONNECTION_CALLBACK_PROPERTY_KEY = CUSTOM_RR_PROPERTIES_PREFIX + "CONNECTION_CALLBACK"; @Override public synchronized void registerConnectionCallback(ConnectionCallback callback) { List<ConnectionCallback> connectionCallbacks = (List<ConnectionCallback>) getProperty(CONNECTION_CALLBACK_PROPERTY_KEY); if (connectionCallbacks == null) { connectionCallbacks = new ArrayList<>(); setProperty(CONNECTION_CALLBACK_PROPERTY_KEY, connectionCallbacks); } connectionCallbacks.add(callback); } public void setAbortHandlerChainStarted(boolean value) { abortHandlerChainStarted = value; } }
AbstractResteasyReactiveContext
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/bind/ArgumentBinder.java
{ "start": 2786, "end": 5351 }
interface ____<T> { /** * An empty but satisfied result. */ BindingResult EMPTY = Optional::empty; /** * An empty but unsatisfied result. */ BindingResult UNSATISFIED = new BindingResult() { @Override public Optional getValue() { return Optional.empty(); } @Override public boolean isSatisfied() { return false; } @Override public BindingResult flatMap(Function transform) { return this; } }; /** * @return The bound value */ Optional<T> getValue(); /** * @return The {@link ConversionError} instances that occurred */ default List<ConversionError> getConversionErrors() { return Collections.emptyList(); } /** * @return Was the binding requirement satisfied */ default boolean isSatisfied() { return getConversionErrors().isEmpty(); } /** * @return Is the value present and satisfied */ default boolean isPresentAndSatisfied() { return isSatisfied() && getValue().isPresent(); } /** * Obtains the value. Callers should call {@link #isPresentAndSatisfied()} first. * * @return The value */ @SuppressWarnings({"java:S3655", "OptionalGetWithoutIsPresent"}) default T get() { return getValue().get(); } /** * Transform the result, if present. * * @param transform The transformation function * @param <R> The type of the mapped result * @return The mapped result * @since 4.0.0 */ @Experimental @NonNull default <R> BindingResult<R> flatMap(@NonNull Function<T, BindingResult<R>> transform) { return new MappedBindingResult<>(this, transform); } /** * @param <R> The result type * @return An empty but satisfied result. * @since 4.0.0 */ static <R> BindingResult<R> empty() { return BindingResult.EMPTY; } /** * @param <R> The result type * @return An empty but unsatisfied result. * @since 4.0.0 */ static <R> BindingResult<R> unsatisfied() { return UNSATISFIED; } } }
BindingResult
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/nativex/feature/PreComputeFieldFeature.java
{ "start": 979, "end": 1309 }
class ____-time initialization. * * <p>It is possible to pass <pre style="code">-Dspring.native.precompute.log=verbose</pre> as a * <pre style="code">native-image</pre> compiler build argument to display detailed logs * about pre-computed fields.</p> * * @author Sebastien Deleuze * @author Phillip Webb * @since 6.0 */
build
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/repository/ConfigRowMapperInjector.java
{ "start": 9405, "end": 10306 }
class ____ implements RowMapper<ConfigInfoStateWrapper> { @Override public ConfigInfoStateWrapper mapRow(ResultSet rs, int rowNum) throws SQLException { ConfigInfoStateWrapper info = new ConfigInfoStateWrapper(); info.setDataId(rs.getString("data_id")); info.setGroup(rs.getString("group_id")); info.setTenant(rs.getString("tenant_id")); info.setLastModified(rs.getTimestamp("gmt_modified").getTime()); try { info.setMd5(rs.getString("md5")); } catch (SQLException e) { // ignore } try { info.setId(rs.getLong("id")); } catch (SQLException e) { // ignore } return info; } } public static final
ConfigInfoStateWrapperRowMapper
java
mockito__mockito
mockito-core/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java
{ "start": 3999, "end": 4077 }
class ____ extends TestBase { private static
ThreadsRunAllTestsHalfManualTest
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncScalarFunction.java
{ "start": 3959, "end": 4210 }
class ____ have a default constructor * and must be instantiable during runtime. Anonymous functions in Table API can only be persisted * if the function is not stateful (i.e. containing only transient and static fields). */ @PublicEvolving public
must
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ApplicationContextRunnerTests.java
{ "start": 1517, "end": 1655 }
class ____ extends AnnotationConfigApplicationContext implements AdditionalContextInterface { } }
TestAnnotationConfigApplicationContext
java
grpc__grpc-java
api/src/testFixtures/java/io/grpc/ServerRegistryAccessor.java
{ "start": 693, "end": 877 }
class ____ { private ServerRegistryAccessor() {} public static Iterable<Class<?>> getHardCodedClasses() { return ServerRegistry.getHardCodedClasses(); } }
ServerRegistryAccessor
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java
{ "start": 1770, "end": 24510 }
class ____ { final HttpHeaders headers = new HttpHeaders(); @Test void constructorUnwrapsReadonly() { headers.setContentType(MediaType.APPLICATION_JSON); HttpHeaders readOnly = HttpHeaders.readOnlyHttpHeaders(headers); assertThat(readOnly.getContentType()).isEqualTo(MediaType.APPLICATION_JSON); HttpHeaders writable = new HttpHeaders(readOnly); writable.setContentType(MediaType.TEXT_PLAIN); // content-type value is cached by ReadOnlyHttpHeaders assertThat(readOnly.getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(writable.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); // The HttpHeaders "copy constructor" creates an HttpHeaders instance // that mutates the state of the original HttpHeaders instance. assertThat(headers.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); } @Test void writableHttpHeadersUnwrapsMultiple() { HttpHeaders originalExchangeHeaders = HttpHeaders.readOnlyHttpHeaders(new HttpHeaders()); HttpHeaders firewallHeaders = new HttpHeaders(originalExchangeHeaders); HttpHeaders writeable = new HttpHeaders(firewallHeaders); writeable.setContentType(MediaType.APPLICATION_JSON); } @Test void copyOfCopiesHeaders() { headers.setContentType(MediaType.APPLICATION_JSON); headers.add("X-Project", "Spring"); headers.add("X-Project", "Framework"); HttpHeaders readOnly = HttpHeaders.readOnlyHttpHeaders(headers); assertThat(readOnly.getContentType()).isEqualTo(MediaType.APPLICATION_JSON); HttpHeaders writable = HttpHeaders.copyOf(readOnly); writable.setContentType(MediaType.TEXT_PLAIN); // content-type value is cached by ReadOnlyHttpHeaders assertThat(readOnly.getContentType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(writable.getContentType()).isEqualTo(MediaType.TEXT_PLAIN); assertThat(writable.get("X-Project")).contains("Spring", "Framework"); } @Test void getOrEmpty() { String key = "FOO"; assertThat(headers.get(key)).isNull(); assertThat(headers.getOrEmpty(key)).isEmpty(); headers.add(key, "bar"); assertThat(headers.getOrEmpty(key)).containsExactly("bar"); headers.remove(key); assertThat(headers.get(key)).isNull(); assertThat(headers.getOrEmpty(key)).isEmpty(); } @Test void getFirst() { headers.add(HttpHeaders.CACHE_CONTROL, "max-age=1000, public"); headers.add(HttpHeaders.CACHE_CONTROL, "s-maxage=1000"); assertThat(headers.getFirst(HttpHeaders.CACHE_CONTROL)).isEqualTo("max-age=1000, public"); } @Test void accept() { MediaType mediaType1 = new MediaType("text", "html"); MediaType mediaType2 = new MediaType("text", "plain"); List<MediaType> mediaTypes = new ArrayList<>(2); mediaTypes.add(mediaType1); mediaTypes.add(mediaType2); headers.setAccept(mediaTypes); assertThat(headers.getAccept()).as("Invalid Accept header").isEqualTo(mediaTypes); assertThat(headers.getFirst("Accept")).as("Invalid Accept header").isEqualTo("text/html, text/plain"); } @Test // SPR-9655 void acceptWithMultipleHeaderValues() { headers.add("Accept", "text/html"); headers.add("Accept", "text/plain"); List<MediaType> expected = Arrays.asList(new MediaType("text", "html"), new MediaType("text", "plain")); assertThat(headers.getAccept()).as("Invalid Accept header").isEqualTo(expected); } @Test // SPR-14506 void acceptWithMultipleCommaSeparatedHeaderValues() { headers.add("Accept", "text/html,text/pdf"); headers.add("Accept", "text/plain,text/csv"); List<MediaType> expected = Arrays.asList(new MediaType("text", "html"), new MediaType("text", "pdf"), new MediaType("text", "plain"), new MediaType("text", "csv")); assertThat(headers.getAccept()).as("Invalid Accept header").isEqualTo(expected); } @Test void acceptCharsets() { Charset charset1 = StandardCharsets.UTF_8; Charset charset2 = StandardCharsets.ISO_8859_1; List<Charset> charsets = new ArrayList<>(2); charsets.add(charset1); charsets.add(charset2); headers.setAcceptCharset(charsets); assertThat(headers.getAcceptCharset()).as("Invalid Accept header").isEqualTo(charsets); assertThat(headers.getFirst("Accept-Charset")).as("Invalid Accept header").isEqualTo("utf-8, iso-8859-1"); } @Test void acceptCharsetWildcard() { headers.set("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); assertThat(headers.getAcceptCharset()).as("Invalid Accept header").isEqualTo(Arrays.asList(StandardCharsets.ISO_8859_1, StandardCharsets.UTF_8)); } @Test void allow() { Set<HttpMethod> methods = new LinkedHashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.POST)); headers.setAllow(methods); assertThat(headers.getAllow()).as("Invalid Allow header").isEqualTo(methods); assertThat(headers.getFirst("Allow")).as("Invalid Allow header").isEqualTo("GET,POST"); } @Test void contentLength() { long length = 42L; headers.setContentLength(length); assertThat(headers.getContentLength()).as("Invalid Content-Length header").isEqualTo(length); assertThat(headers.getFirst("Content-Length")).as("Invalid Content-Length header").isEqualTo("42"); } @Test void setContentLengthWithNegativeValue() { assertThatIllegalArgumentException().isThrownBy(() -> headers.setContentLength(-1)); } @Test void getContentLengthReturnsMinusOneForAbsentHeader() { assertThat(headers.getContentLength()).isEqualTo(-1); } @Test void contentType() { MediaType contentType = new MediaType("text", "html", StandardCharsets.UTF_8); headers.setContentType(contentType); assertThat(headers.getContentType()).as("Invalid Content-Type header").isEqualTo(contentType); assertThat(headers.getFirst("Content-Type")).as("Invalid Content-Type header").isEqualTo("text/html;charset=UTF-8"); } @Test void location() { URI location = URI.create("https://www.example.com/hotels"); headers.setLocation(location); assertThat(headers.getLocation()).as("Invalid Location header").isEqualTo(location); assertThat(headers.getFirst("Location")).as("Invalid Location header").isEqualTo("https://www.example.com/hotels"); } @Test void eTag() { String eTag = "\"v2.6\""; headers.setETag(eTag); assertThat(headers.getETag()).as("Invalid ETag header").isEqualTo(eTag); assertThat(headers.getFirst("ETag")).as("Invalid ETag header").isEqualTo("\"v2.6\""); } @Test void host() { InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 8080); headers.setHost(host); assertThat(headers.getHost()).as("Invalid Host header").isEqualTo(host); assertThat(headers.getFirst("Host")).as("Invalid Host header").isEqualTo("localhost:8080"); } @Test void hostNoPort() { InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 0); headers.setHost(host); assertThat(headers.getHost()).as("Invalid Host header").isEqualTo(host); assertThat(headers.getFirst("Host")).as("Invalid Host header").isEqualTo("localhost"); } @Test void ipv6Host() { InetSocketAddress host = InetSocketAddress.createUnresolved("[::1]", 0); headers.setHost(host); assertThat(headers.getHost()).as("Invalid Host header").isEqualTo(host); assertThat(headers.getFirst("Host")).as("Invalid Host header").isEqualTo("[::1]"); } @Test // gh-33716 void hostDeletion() { InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 8080); headers.setHost(host); headers.setHost(null); assertThat(headers.getHost()).as("Host is not deleted").isEqualTo(null); assertThat(headers.getFirst("Host")).as("Host is not deleted").isEqualTo(null); } @Test void eTagWithoutQuotes() { headers.setETag("v2.6"); assertThat(headers.getETag()).isEqualTo("\"v2.6\""); } @Test void weakETagWithoutLeadingQuote() { headers.setETag("W/v2.6\""); assertThat(headers.getETag()).isEqualTo("\"W/v2.6\"\""); } @Test void ifMatch() { String ifMatch = "\"v2.6\""; headers.setIfMatch(ifMatch); assertThat(headers.getIfMatch()).containsExactly(ifMatch); assertThat(headers.getFirst("If-Match")).as("Invalid If-Match header").isEqualTo("\"v2.6\""); } @Test void ifMatchIllegalHeader() { headers.setIfMatch("Illegal"); assertThatIllegalArgumentException().isThrownBy(headers::getIfMatch); } @Test void ifMatchMultipleHeaders() { headers.add(HttpHeaders.IF_MATCH, "\"v2,0\""); headers.add(HttpHeaders.IF_MATCH, "W/\"v2,1\", \"v2,2\""); assertThat(headers.get(HttpHeaders.IF_MATCH)).containsExactly("\"v2,0\"", "W/\"v2,1\", \"v2,2\""); assertThat(headers.getIfMatch()).contains("\"v2,0\"", "W/\"v2,1\"", "\"v2,2\""); } @Test void ifNoneMatch() { String ifNoneMatch = "\"v2.6\""; headers.setIfNoneMatch(ifNoneMatch); assertThat(headers.getIfNoneMatch()).containsExactly(ifNoneMatch); assertThat(headers.getFirst("If-None-Match")).as("Invalid If-None-Match header").isEqualTo("\"v2.6\""); } @Test void ifNoneMatchWildCard() { String ifNoneMatch = "*"; headers.setIfNoneMatch(ifNoneMatch); assertThat(headers.getIfNoneMatch()).containsExactly(ifNoneMatch); assertThat(headers.getFirst("If-None-Match")).as("Invalid If-None-Match header").isEqualTo("*"); } @Test void ifNoneMatchList() { String ifNoneMatch1 = "\"v2.6\""; String ifNoneMatch2 = "\"v2.7\", \"v2.8\""; List<String> ifNoneMatchList = new ArrayList<>(2); ifNoneMatchList.add(ifNoneMatch1); ifNoneMatchList.add(ifNoneMatch2); headers.setIfNoneMatch(ifNoneMatchList); assertThat(headers.getIfNoneMatch()).contains("\"v2.6\"", "\"v2.7\"", "\"v2.8\""); assertThat(headers.getFirst("If-None-Match")).as("Invalid If-None-Match header").isEqualTo("\"v2.6\", \"v2.7\", \"v2.8\""); } @Test void date() { Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20); calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setDate(date); assertThat(headers.getDate()).as("Invalid Date header").isEqualTo(date); assertThat(headers.getFirst("date")).as("Invalid Date header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); // RFC 850 headers.set("Date", "Thu, 18 Dec 2008 10:20:00 GMT"); assertThat(headers.getDate()).as("Invalid Date header").isEqualTo(date); } @Test void dateInvalid() { headers.set("Date", "Foo Bar Baz"); assertThatIllegalArgumentException().isThrownBy(headers::getDate); } @Test void dateOtherLocale() { Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(new Locale("nl", "nl")); Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20); calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setDate(date); assertThat(headers.getFirst("date")).as("Invalid Date header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); assertThat(headers.getDate()).as("Invalid Date header").isEqualTo(date); } finally { Locale.setDefault(defaultLocale); } } @Test void lastModified() { Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20); calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setLastModified(date); assertThat(headers.getLastModified()).as("Invalid Last-Modified header").isEqualTo(date); assertThat(headers.getFirst("last-modified")).as("Invalid Last-Modified header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test void expiresLong() { Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20); calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setExpires(date); assertThat(headers.getExpires()).as("Invalid Expires header").isEqualTo(date); assertThat(headers.getFirst("expires")).as("Invalid Expires header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test void expiresZonedDateTime() { ZonedDateTime zonedDateTime = ZonedDateTime.of(2008, 12, 18, 10, 20, 0, 0, ZoneOffset.UTC); headers.setExpires(zonedDateTime); assertThat(headers.getExpires()).as("Invalid Expires header").isEqualTo(zonedDateTime.toInstant().toEpochMilli()); assertThat(headers.getFirst("expires")).as("Invalid Expires header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test // SPR-10648 (example is from INT-3063) void expiresInvalidDate() { headers.set("Expires", "-1"); assertThat(headers.getExpires()).isEqualTo(-1); } @Test void ifModifiedSince() { Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20); calendar.setTimeZone(TimeZone.getTimeZone("CET")); long date = calendar.getTimeInMillis(); headers.setIfModifiedSince(date); assertThat(headers.getIfModifiedSince()).as("Invalid If-Modified-Since header").isEqualTo(date); assertThat(headers.getFirst("if-modified-since")).as("Invalid If-Modified-Since header").isEqualTo("Thu, 18 Dec 2008 10:20:00 GMT"); } @Test // SPR-14144 void invalidIfModifiedSinceHeader() { headers.set(HttpHeaders.IF_MODIFIED_SINCE, "0"); assertThat(headers.getIfModifiedSince()).isEqualTo(-1); headers.set(HttpHeaders.IF_MODIFIED_SINCE, "-1"); assertThat(headers.getIfModifiedSince()).isEqualTo(-1); headers.set(HttpHeaders.IF_MODIFIED_SINCE, "XXX"); assertThat(headers.getIfModifiedSince()).isEqualTo(-1); } @Test void pragma() { String pragma = "no-cache"; headers.setPragma(pragma); assertThat(headers.getPragma()).as("Invalid Pragma header").isEqualTo(pragma); assertThat(headers.getFirst("pragma")).as("Invalid Pragma header").isEqualTo("no-cache"); } @Test void cacheControl() { headers.setCacheControl("no-cache"); assertThat(headers.getCacheControl()).as("Invalid Cache-Control header").isEqualTo("no-cache"); assertThat(headers.getFirst("cache-control")).as("Invalid Cache-Control header").isEqualTo("no-cache"); } @Test void cacheControlBuilder() { headers.setCacheControl(CacheControl.noCache()); assertThat(headers.getCacheControl()).as("Invalid Cache-Control header").isEqualTo("no-cache"); assertThat(headers.getFirst("cache-control")).as("Invalid Cache-Control header").isEqualTo("no-cache"); } @Test void cacheControlEmpty() { headers.setCacheControl(CacheControl.empty()); assertThat(headers.getCacheControl()).as("Invalid Cache-Control header").isNull(); assertThat(headers.getFirst("cache-control")).as("Invalid Cache-Control header").isNull(); } @Test void cacheControlAllValues() { headers.add(HttpHeaders.CACHE_CONTROL, "max-age=1000, public"); headers.add(HttpHeaders.CACHE_CONTROL, "s-maxage=1000"); assertThat(headers.getCacheControl()).isEqualTo("max-age=1000, public, s-maxage=1000"); } @Test void contentDisposition() { ContentDisposition disposition = headers.getContentDisposition(); assertThat(disposition).isNotNull(); assertThat(headers.getContentDisposition()).as("Invalid Content-Disposition header").isEqualTo(ContentDisposition.empty()); disposition = ContentDisposition.attachment().name("foo").filename("foo.txt").build(); headers.setContentDisposition(disposition); assertThat(headers.getContentDisposition()).as("Invalid Content-Disposition header").isEqualTo(disposition); } @Test // SPR-11917 void getAllowEmptySet() { headers.setAllow(Collections.emptySet()); assertThat(headers.getAllow()).isEmpty(); } @Test void accessControlAllowCredentials() { assertThat(headers.getAccessControlAllowCredentials()).isFalse(); headers.setAccessControlAllowCredentials(false); assertThat(headers.getAccessControlAllowCredentials()).isFalse(); headers.setAccessControlAllowCredentials(true); assertThat(headers.getAccessControlAllowCredentials()).isTrue(); } @Test void accessControlAllowHeaders() { List<String> allowedHeaders = headers.getAccessControlAllowHeaders(); assertThat(allowedHeaders).isEmpty(); headers.setAccessControlAllowHeaders(Arrays.asList("header1", "header2")); allowedHeaders = headers.getAccessControlAllowHeaders(); assertThat(Arrays.asList("header1", "header2")).isEqualTo(allowedHeaders); } @Test void accessControlAllowHeadersMultipleValues() { List<String> allowedHeaders = headers.getAccessControlAllowHeaders(); assertThat(allowedHeaders).isEmpty(); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "header1, header2"); headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "header3"); allowedHeaders = headers.getAccessControlAllowHeaders(); assertThat(allowedHeaders).isEqualTo(Arrays.asList("header1", "header2", "header3")); } @Test void accessControlAllowMethods() { List<HttpMethod> allowedMethods = headers.getAccessControlAllowMethods(); assertThat(allowedMethods).isEmpty(); headers.setAccessControlAllowMethods(Arrays.asList(HttpMethod.GET, HttpMethod.POST)); allowedMethods = headers.getAccessControlAllowMethods(); assertThat(Arrays.asList(HttpMethod.GET, HttpMethod.POST)).isEqualTo(allowedMethods); } @Test void accessControlAllowOrigin() { assertThat(headers.getAccessControlAllowOrigin()).isNull(); headers.setAccessControlAllowOrigin("*"); assertThat(headers.getAccessControlAllowOrigin()).isEqualTo("*"); } @Test void accessControlExposeHeaders() { List<String> exposedHeaders = headers.getAccessControlExposeHeaders(); assertThat(exposedHeaders).isEmpty(); headers.setAccessControlExposeHeaders(Arrays.asList("header1", "header2")); exposedHeaders = headers.getAccessControlExposeHeaders(); assertThat(Arrays.asList("header1", "header2")).isEqualTo(exposedHeaders); } @Test void accessControlMaxAge() { assertThat(headers.getAccessControlMaxAge()).isEqualTo(-1); headers.setAccessControlMaxAge(3600); assertThat(headers.getAccessControlMaxAge()).isEqualTo(3600); } @Test void accessControlRequestHeaders() { List<String> requestHeaders = headers.getAccessControlRequestHeaders(); assertThat(requestHeaders).isEmpty(); headers.setAccessControlRequestHeaders(Arrays.asList("header1", "header2")); requestHeaders = headers.getAccessControlRequestHeaders(); assertThat(Arrays.asList("header1", "header2")).isEqualTo(requestHeaders); } @Test void accessControlRequestMethod() { assertThat(headers.getAccessControlRequestMethod()).isNull(); headers.setAccessControlRequestMethod(HttpMethod.POST); assertThat(headers.getAccessControlRequestMethod()).isEqualTo(HttpMethod.POST); } @Test void acceptLanguage() { String headerValue = "fr-ch, fr;q=0.9, en-*;q=0.8, de;q=0.7, *-us;q=0.6, *;q=0.5"; headers.setAcceptLanguage(Locale.LanguageRange.parse(headerValue)); assertThat(headers.getFirst(HttpHeaders.ACCEPT_LANGUAGE)).isEqualTo(headerValue); List<Locale.LanguageRange> expectedRanges = List.of( new Locale.LanguageRange("fr-ch"), new Locale.LanguageRange("fr", 0.9), new Locale.LanguageRange("en-*", 0.8), new Locale.LanguageRange("de", 0.7), new Locale.LanguageRange("*-us", 0.6), new Locale.LanguageRange("*", 0.5) ); assertThat(headers.getAcceptLanguage()).isEqualTo(expectedRanges); assertThat(headers.getAcceptLanguageAsLocales()).containsExactly( Locale.forLanguageTag("fr-ch"), Locale.forLanguageTag("fr"), Locale.forLanguageTag("en"), Locale.forLanguageTag("de")); headers.setAcceptLanguageAsLocales(Collections.singletonList(Locale.FRANCE)); assertThat(headers.getAcceptLanguageAsLocales()).first().isEqualTo(Locale.FRANCE); } @Test // gh-32259 void acceptLanguageTrailingSemicolon() { String headerValue = "en-us,en;,nl;"; headers.set(HttpHeaders.ACCEPT_LANGUAGE, headerValue); assertThat(headers.getFirst(HttpHeaders.ACCEPT_LANGUAGE)).isEqualTo(headerValue); List<Locale.LanguageRange> expectedRanges = Arrays.asList( new Locale.LanguageRange("en-us"), new Locale.LanguageRange("en"), new Locale.LanguageRange("nl") ); assertThat(headers.getAcceptLanguage()).isEqualTo(expectedRanges); } @Test // SPR-15603 void acceptLanguageWithEmptyValue() { this.headers.set(HttpHeaders.ACCEPT_LANGUAGE, ""); assertThat(this.headers.getAcceptLanguageAsLocales()).isEqualTo(Collections.emptyList()); } @Test void contentLanguage() { headers.setContentLanguage(Locale.FRANCE); assertThat(headers.getContentLanguage()).isEqualTo(Locale.FRANCE); assertThat(headers.getFirst(HttpHeaders.CONTENT_LANGUAGE)).isEqualTo("fr-FR"); } @Test void contentLanguageSerialized() { headers.set(HttpHeaders.CONTENT_LANGUAGE, "de, en_CA"); assertThat(headers.getContentLanguage()).as("Expected one (first) locale").isEqualTo(Locale.GERMAN); } @Test void firstDate() { headers.setDate(HttpHeaders.DATE, 1496370120000L); assertThat(headers.getFirstDate(HttpHeaders.DATE)).isEqualTo(1496370120000L); headers.clear(); headers.add(HttpHeaders.DATE, "Fri, 02 Jun 2017 02:22:00 GMT"); headers.add(HttpHeaders.DATE, "Sat, 18 Dec 2010 10:20:00 GMT"); assertThat(headers.getFirstDate(HttpHeaders.DATE)).isEqualTo(1496370120000L); } @Test void firstZonedDateTime() { ZonedDateTime date = ZonedDateTime.of(2017, 6, 2, 2, 22, 0, 0, ZoneOffset.UTC); headers.setZonedDateTime(HttpHeaders.DATE, date); assertThat(headers.getFirst(HttpHeaders.DATE)).isEqualTo("Fri, 02 Jun 2017 02:22:00 GMT"); assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); headers.clear(); headers.add(HttpHeaders.DATE, "Fri, 02 Jun 2017 02:22:00 GMT"); headers.add(HttpHeaders.DATE, "Sat, 18 Dec 2010 10:20:00 GMT"); assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); assertThat(headers.get(HttpHeaders.DATE)).isEqualTo(Arrays.asList("Fri, 02 Jun 2017 02:22:00 GMT", "Sat, 18 Dec 2010 10:20:00 GMT")); // obsolete RFC 850 format headers.clear(); headers.set(HttpHeaders.DATE, "Friday, 02-Jun-17 02:22:00 GMT"); assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); // ANSI C's asctime() format headers.clear(); headers.set(HttpHeaders.DATE, "Fri Jun 02 02:22:00 2017"); assertThat(headers.getFirstZonedDateTime(HttpHeaders.DATE).isEqual(date)).isTrue(); } @Test void basicAuth() { String username = "foo"; String password = "bar"; headers.setBasicAuth(username, password); String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION); assertThat(authorization).isNotNull(); assertThat(authorization).startsWith("Basic "); byte[] result = Base64.getDecoder().decode(authorization.substring(6).getBytes(StandardCharsets.ISO_8859_1)); assertThat(new String(result, StandardCharsets.ISO_8859_1)).isEqualTo("foo:bar"); } @Test void basicAuthIllegalChar() { String username = "foo"; String password = "\u03BB"; assertThatIllegalArgumentException().isThrownBy(() -> headers.setBasicAuth(username, password)); } @Test void bearerAuth() { String token = "foo"; headers.setBearerAuth(token); String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION); assertThat(authorization).isEqualTo("Bearer foo"); } @Nested
HttpHeadersTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/component/DefaultDispatcherResourceManagerComponentFactory.java
{ "start": 4145, "end": 4257 }
class ____ implements the creation of the {@link DispatcherResourceManagerComponent} * components. */ public
which
java
elastic__elasticsearch
modules/repository-s3/src/main/java/org/elasticsearch/repositories/s3/HttpScheme.java
{ "start": 520, "end": 779 }
enum ____ { HTTP("http"), HTTPS("https"); private final String schemeString; HttpScheme(String schemeString) { this.schemeString = schemeString; } public String getSchemeString() { return schemeString; } }
HttpScheme
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationToken.java
{ "start": 1369, "end": 2271 }
class ____ extends AbstractAuthenticationToken { private static final long serialVersionUID = 620L; private final String token; /** * Create a {@code BearerTokenAuthenticationToken} using the provided parameter(s) * @param token - the bearer token */ public BearerTokenAuthenticationToken(String token) { super(Collections.emptyList()); Assert.hasText(token, "token cannot be empty"); this.token = token; } /** * Get the * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> * @return the token that proves the caller's authority to perform the * {@link jakarta.servlet.http.HttpServletRequest} */ public String getToken() { return this.token; } @Override public Object getCredentials() { return this.getToken(); } @Override public Object getPrincipal() { return this.getToken(); } }
BearerTokenAuthenticationToken
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/testers/QueuePeekTester.java
{ "start": 1667, "end": 2314 }
class ____<E> extends AbstractQueueTester<E> { @CollectionSize.Require(ZERO) public void testPeek_empty() { assertNull("emptyQueue.peek() should return null", getQueue().peek()); expectUnchanged(); } @CollectionSize.Require(ONE) public void testPeek_size1() { assertEquals("size1Queue.peek() should return first element", e0(), getQueue().peek()); expectUnchanged(); } @CollectionFeature.Require(KNOWN_ORDER) @CollectionSize.Require(SEVERAL) public void testPeek_sizeMany() { assertEquals("sizeManyQueue.peek() should return first element", e0(), getQueue().peek()); expectUnchanged(); } }
QueuePeekTester
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/util/TestSampleQuantiles.java
{ "start": 1187, "end": 5278 }
class ____ { static final Quantile[] quantiles = { new Quantile(0.50, 0.050), new Quantile(0.75, 0.025), new Quantile(0.90, 0.010), new Quantile(0.95, 0.005), new Quantile(0.99, 0.001) }; SampleQuantiles estimator; final static int NUM_REPEATS = 10; @BeforeEach public void init() { estimator = new SampleQuantiles(quantiles); } /** * Check that the counts of the number of items in the window and sample are * incremented correctly as items are added. */ @Test public void testCount() throws IOException { // Counts start off zero assertThat(estimator.getCount()).isZero(); assertThat(estimator.getSampleCount()).isZero(); // Snapshot should be null if there are no entries. assertThat(estimator.snapshot()).isNull(); // Count increment correctly by 1 estimator.insert(1337); assertThat(estimator.getCount()).isOne(); estimator.snapshot(); assertThat(estimator.getSampleCount()).isOne(); assertThat(estimator.toString()).isEqualTo( "50.00 %ile +/- 5.00%: 1337\n" + "75.00 %ile +/- 2.50%: 1337\n" + "90.00 %ile +/- 1.00%: 1337\n" + "95.00 %ile +/- 0.50%: 1337\n" + "99.00 %ile +/- 0.10%: 1337"); } /** * Check that counts and quantile estimates are correctly reset after a call * to {@link SampleQuantiles#clear()}. */ @Test public void testClear() throws IOException { for (int i = 0; i < 1000; i++) { estimator.insert(i); } estimator.clear(); assertThat(estimator.getCount()).isZero(); assertThat(estimator.getSampleCount()).isZero(); assertThat(estimator.snapshot()).isNull(); } /** * Correctness test that checks that absolute error of the estimate is within * specified error bounds for some randomly permuted streams of items. */ @Test public void testQuantileError() throws IOException { final int count = 100000; Random rnd = new Random(0xDEADDEAD); int[] values = new int[count]; for (int i = 0; i < count; i++) { values[i] = i + 1; } // Repeat shuffle/insert/check cycles 10 times for (int i = 0; i < NUM_REPEATS; i++) { // Shuffle Collections.shuffle(Arrays.asList(values), rnd); estimator.clear(); // Insert for (int value : values) { estimator.insert(value); } Map<Quantile, Long> snapshot; snapshot = estimator.snapshot(); // Check for (Quantile q : quantiles) { long actual = (long) (q.quantile * count); long error = (long) (q.error * count); long estimate = snapshot.get(q); assertThat(estimate <= actual + error).isTrue(); assertThat(estimate >= actual - error).isTrue(); } } } /** * Correctness test that checks that absolute error of the estimate for inverse quantiles * is within specified error bounds for some randomly permuted streams of items. */ @Test public void testInverseQuantiles() throws IOException { SampleQuantiles inverseQuantilesEstimator = new SampleQuantiles(MutableInverseQuantiles.INVERSE_QUANTILES); final int count = 100000; Random rnd = new Random(0xDEADDEAD); int[] values = new int[count]; for (int i = 0; i < count; i++) { values[i] = i + 1; } // Repeat shuffle/insert/check cycles 10 times for (int i = 0; i < NUM_REPEATS; i++) { // Shuffle Collections.shuffle(Arrays.asList(values), rnd); inverseQuantilesEstimator.clear(); // Insert for (int value : values) { inverseQuantilesEstimator.insert(value); } Map<Quantile, Long> snapshot; snapshot = inverseQuantilesEstimator.snapshot(); // Check for (Quantile q : MutableInverseQuantiles.INVERSE_QUANTILES) { long actual = (long) (q.quantile * count); long error = (long) (q.error * count); long estimate = snapshot.get(q); assertThat(estimate <= actual + error).isTrue(); assertThat(estimate >= actual - error).isTrue(); } } } }
TestSampleQuantiles
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/AbstractNullAwareCodeGeneratorCastRule.java
{ "start": 1259, "end": 1371 }
class ____ from {@link * AbstractCodeGeneratorCastRule} and takes care of nullability checks. */ abstract
inherits
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java
{ "start": 5846, "end": 5977 }
class ____ { static void main() { mainMethod.set(new MainMethod()); } } public static
PackagePrivateParameterlessMainMethod
java
apache__maven
its/core-it-suite/src/test/resources/mng-3684/maven-mng3684-plugin/src/main/java/plugin/MyReport.java
{ "start": 1896, "end": 6018 }
class ____ extends AbstractMavenReport { /** * @parameter default-value="${project.build}" * @required * @readonly */ private Build build; /** * @parameter default-value="${project}" * @required * @readonly */ private MavenProject project; private void runChecks() throws MavenReportException { Build projectBuild = project.getBuild(); Map failedComparisons = new HashMap(); check("project.build.directory", projectBuild.getDirectory(), build.getDirectory(), failedComparisons); check( "project.build.outputDirectory", projectBuild.getOutputDirectory(), build.getOutputDirectory(), failedComparisons); check( "project.build.sourceDirectory", projectBuild.getSourceDirectory(), build.getSourceDirectory(), failedComparisons); check( "project.build.testSourceDirectory", projectBuild.getTestSourceDirectory(), build.getTestSourceDirectory(), failedComparisons); check( "project.build.scriptSourceDirectory", projectBuild.getScriptSourceDirectory(), build.getScriptSourceDirectory(), failedComparisons); List projectResources = projectBuild.getResources(); List buildResources = build.getResources(); if (projectResources != null) { for (int i = 0; i < projectResources.size(); i++) { Resource projectRes = (Resource) projectResources.get(i); Resource buildRes = (Resource) buildResources.get(i); check( "project.build.resources[" + i + "].directory", projectRes.getDirectory(), buildRes.getDirectory(), failedComparisons); check( "project.build.resources[" + i + "].targetPath", projectRes.getTargetPath(), buildRes.getTargetPath(), failedComparisons); } } if (!failedComparisons.isEmpty()) { StringBuffer buffer = new StringBuffer(); buffer.append("One or more build-section values were not interpolated correctly" + "\nbefore the build instance was injected as a plugin parameter:\n"); for (Iterator it = failedComparisons.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String[] value = (String[]) entry.getValue(); buffer.append("\n- ").append(key); buffer.append("\n\tShould be: \'").append(value[0]); buffer.append("\'\n\t Was: \'").append(value[1]).append("\'\n"); } throw new MavenReportException(buffer.toString()); } } private void check(String description, String projectValue, String buildValue, Map failedComparisons) { if (projectValue == null && buildValue != null) { failedComparisons.put(description, new String[] {projectValue, buildValue}); } else if (projectValue != null && !projectValue.equals(buildValue)) { failedComparisons.put(description, new String[] {projectValue, buildValue}); } } protected void executeReport(Locale locale) throws MavenReportException { runChecks(); } protected String getOutputDirectory() { return project.getReporting().getOutputDirectory(); } protected MavenProject getProject() { return project; } protected Renderer getSiteRenderer() { return null; } public String getDescription(Locale locale) { return "test"; } public String getName(Locale locale) { return "test"; } public String getOutputName() { return "test"; } }
MyReport
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java
{ "start": 4947, "end": 6205 }
class ____ { private int port; @Bean NettyReactiveWebServerFactory netty() { return new NettyReactiveWebServerFactory(0); } @Bean HttpHandler httpHandler(ApplicationContext applicationContext) { return WebHttpHandlerBuilder.applicationContext(applicationContext).build(); } @Bean WebFluxEndpointHandlerMapping webEndpointHandlerMapping(Environment environment, WebEndpointDiscoverer endpointDiscoverer, EndpointMediaTypes endpointMediaTypes) { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedOrigins(Arrays.asList("https://example.com")); corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST")); String endpointPath = environment.getProperty("endpointPath"); return new WebFluxEndpointHandlerMapping(new EndpointMapping(endpointPath), endpointDiscoverer.getEndpoints(), endpointMediaTypes, corsConfiguration, new EndpointLinksResolver(endpointDiscoverer.getEndpoints()), StringUtils.hasText(endpointPath)); } @Bean ApplicationListener<ReactiveWebServerInitializedEvent> serverInitializedListener() { return (event) -> this.port = event.getWebServer().getPort(); } } @Configuration(proxyBeanMethods = false) static
ReactiveConfiguration
java
quarkusio__quarkus
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/paths/PathTreeBuilder.java
{ "start": 141, "end": 2075 }
class ____ { private boolean archive; private Boolean manifestEnabled; private Path root; private List<String> includes; private List<String> excludes; public PathTreeBuilder() { } public PathTreeBuilder setArchive(boolean archive) { this.archive = archive; return this; } public PathTreeBuilder setManifestEnabled(boolean manifestEnabled) { this.manifestEnabled = manifestEnabled; return this; } public PathTreeBuilder setRoot(Path root) { this.root = root; return this; } Path getRoot() { return root; } public PathTreeBuilder include(String expr) { if (includes == null) { includes = new ArrayList<>(1); } includes.add(expr); return this; } List<String> getIncludes() { return includes; } public PathTreeBuilder exclude(String expr) { if (excludes == null) { excludes = new ArrayList<>(1); } excludes.add(expr); return this; } List<String> getExcludes() { return includes; } PathFilter getPathFilter() { return includes == null && excludes == null ? null : new PathFilter(includes, excludes); } public PathTree build() { if (root == null) { throw new RuntimeException("The tree root has not been provided"); } if (!Files.exists(root)) { throw new IllegalArgumentException(root + " does not exist"); } if (archive) { return ArchivePathTree.forPath(root, getPathFilter(), manifestEnabled == null ? true : manifestEnabled); } if (Files.isDirectory(root)) { return new DirectoryPathTree(root, getPathFilter(), manifestEnabled == null ? false : manifestEnabled); } return new FilePathTree(root, getPathFilter()); } }
PathTreeBuilder
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CxfEndpointBuilderFactory.java
{ "start": 50877, "end": 69937 }
interface ____ extends EndpointProducerBuilder { default CxfEndpointProducerBuilder basic() { return (CxfEndpointProducerBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Sets whether synchronous processing should be strictly used. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param synchronous the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder synchronous(boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Sets whether synchronous processing should be strictly used. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param synchronous the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder synchronous(String synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * This option controls whether the CXF component, when running in * PAYLOAD mode, will DOM parse the incoming messages into DOM Elements * or keep the payload as a javax.xml.transform.Source object that would * allow streaming in some cases. * * The option is a: <code>java.lang.Boolean</code> type. * * Default: false * Group: advanced * * @param allowStreaming the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder allowStreaming(Boolean allowStreaming) { doSetProperty("allowStreaming", allowStreaming); return this; } /** * This option controls whether the CXF component, when running in * PAYLOAD mode, will DOM parse the incoming messages into DOM Elements * or keep the payload as a javax.xml.transform.Source object that would * allow streaming in some cases. * * The option will be converted to a <code>java.lang.Boolean</code> * type. * * Default: false * Group: advanced * * @param allowStreaming the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder allowStreaming(String allowStreaming) { doSetProperty("allowStreaming", allowStreaming); return this; } /** * To use a custom configured CXF Bus. * * The option is a: <code>org.apache.cxf.Bus</code> type. * * Group: advanced * * @param bus the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder bus(org.apache.cxf.Bus bus) { doSetProperty("bus", bus); return this; } /** * To use a custom configured CXF Bus. * * The option will be converted to a <code>org.apache.cxf.Bus</code> * type. * * Group: advanced * * @param bus the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder bus(String bus) { doSetProperty("bus", bus); return this; } /** * This option is used to set the CXF continuation timeout which could * be used in CxfConsumer by default when the CXF server is using Jetty * or Servlet transport. * * The option is a: <code>long</code> type. * * Default: 30000 * Group: advanced * * @param continuationTimeout the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder continuationTimeout(long continuationTimeout) { doSetProperty("continuationTimeout", continuationTimeout); return this; } /** * This option is used to set the CXF continuation timeout which could * be used in CxfConsumer by default when the CXF server is using Jetty * or Servlet transport. * * The option will be converted to a <code>long</code> type. * * Default: 30000 * Group: advanced * * @param continuationTimeout the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder continuationTimeout(String continuationTimeout) { doSetProperty("continuationTimeout", continuationTimeout); return this; } /** * To use a custom CxfBinding to control the binding between Camel * Message and CXF Message. * * The option is a: * <code>org.apache.camel.component.cxf.common.CxfBinding</code> type. * * Group: advanced * * @param cxfBinding the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder cxfBinding(org.apache.camel.component.cxf.common.CxfBinding cxfBinding) { doSetProperty("cxfBinding", cxfBinding); return this; } /** * To use a custom CxfBinding to control the binding between Camel * Message and CXF Message. * * The option will be converted to a * <code>org.apache.camel.component.cxf.common.CxfBinding</code> type. * * Group: advanced * * @param cxfBinding the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder cxfBinding(String cxfBinding) { doSetProperty("cxfBinding", cxfBinding); return this; } /** * This option could apply the implementation of * org.apache.camel.component.cxf.CxfEndpointConfigurer which supports * to configure the CXF endpoint in programmatic way. User can configure * the CXF server and client by implementing configure{ServerClient} * method of CxfEndpointConfigurer. * * The option is a: * <code>org.apache.camel.component.cxf.jaxws.CxfConfigurer</code> type. * * Group: advanced * * @param cxfConfigurer the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder cxfConfigurer(org.apache.camel.component.cxf.jaxws.CxfConfigurer cxfConfigurer) { doSetProperty("cxfConfigurer", cxfConfigurer); return this; } /** * This option could apply the implementation of * org.apache.camel.component.cxf.CxfEndpointConfigurer which supports * to configure the CXF endpoint in programmatic way. User can configure * the CXF server and client by implementing configure{ServerClient} * method of CxfEndpointConfigurer. * * The option will be converted to a * <code>org.apache.camel.component.cxf.jaxws.CxfConfigurer</code> type. * * Group: advanced * * @param cxfConfigurer the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder cxfConfigurer(String cxfConfigurer) { doSetProperty("cxfConfigurer", cxfConfigurer); return this; } /** * Will set the default bus when CXF endpoint create a bus by itself. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param defaultBus the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder defaultBus(boolean defaultBus) { doSetProperty("defaultBus", defaultBus); return this; } /** * Will set the default bus when CXF endpoint create a bus by itself. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param defaultBus the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder defaultBus(String defaultBus) { doSetProperty("defaultBus", defaultBus); return this; } /** * To use a custom HeaderFilterStrategy to filter header to and from * Camel message. * * The option is a: * <code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: advanced * * @param headerFilterStrategy the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * To use a custom HeaderFilterStrategy to filter header to and from * Camel message. * * The option will be converted to a * <code>org.apache.camel.spi.HeaderFilterStrategy</code> type. * * Group: advanced * * @param headerFilterStrategy the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder headerFilterStrategy(String headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Whether to merge protocol headers. If enabled then propagating * headers between Camel and CXF becomes more consistent and similar. * For more details see CAMEL-6393. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param mergeProtocolHeaders the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder mergeProtocolHeaders(boolean mergeProtocolHeaders) { doSetProperty("mergeProtocolHeaders", mergeProtocolHeaders); return this; } /** * Whether to merge protocol headers. If enabled then propagating * headers between Camel and CXF becomes more consistent and similar. * For more details see CAMEL-6393. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param mergeProtocolHeaders the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder mergeProtocolHeaders(String mergeProtocolHeaders) { doSetProperty("mergeProtocolHeaders", mergeProtocolHeaders); return this; } /** * To enable MTOM (attachments). This requires to use POJO or PAYLOAD * data format mode. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param mtomEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder mtomEnabled(boolean mtomEnabled) { doSetProperty("mtomEnabled", mtomEnabled); return this; } /** * To enable MTOM (attachments). This requires to use POJO or PAYLOAD * data format mode. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param mtomEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder mtomEnabled(String mtomEnabled) { doSetProperty("mtomEnabled", mtomEnabled); return this; } /** * To set additional CXF options using the key/value pairs from the Map. * For example to turn on stacktraces in SOAP faults, * properties.faultStackTraceEnabled=true. This is a multi-value option * with prefix: properties. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the properties(String, * Object) method to add a value (call the method multiple times to set * more values). * * Group: advanced * * @param key the option key * @param value the option value * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder properties(String key, Object value) { doSetMultiValueProperty("properties", "properties." + key, value); return this; } /** * To set additional CXF options using the key/value pairs from the Map. * For example to turn on stacktraces in SOAP faults, * properties.faultStackTraceEnabled=true. This is a multi-value option * with prefix: properties. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the properties(String, * Object) method to add a value (call the method multiple times to set * more values). * * Group: advanced * * @param values the values * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder properties(Map values) { doSetMultiValueProperties("properties", "properties.", values); return this; } /** * Enable schema validation for request and response. Disabled by * default for performance reason. * * The option is a: <code>java.lang.Boolean</code> type. * * Default: false * Group: advanced * * @param schemaValidationEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder schemaValidationEnabled(Boolean schemaValidationEnabled) { doSetProperty("schemaValidationEnabled", schemaValidationEnabled); return this; } /** * Enable schema validation for request and response. Disabled by * default for performance reason. * * The option will be converted to a <code>java.lang.Boolean</code> * type. * * Default: false * Group: advanced * * @param schemaValidationEnabled the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder schemaValidationEnabled(String schemaValidationEnabled) { doSetProperty("schemaValidationEnabled", schemaValidationEnabled); return this; } /** * Sets whether SOAP message validation should be disabled. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param skipPayloadMessagePartCheck the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder skipPayloadMessagePartCheck(boolean skipPayloadMessagePartCheck) { doSetProperty("skipPayloadMessagePartCheck", skipPayloadMessagePartCheck); return this; } /** * Sets whether SOAP message validation should be disabled. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param skipPayloadMessagePartCheck the value to set * @return the dsl builder */ default AdvancedCxfEndpointProducerBuilder skipPayloadMessagePartCheck(String skipPayloadMessagePartCheck) { doSetProperty("skipPayloadMessagePartCheck", skipPayloadMessagePartCheck); return this; } } /** * Builder for endpoint for the CXF component. */ public
AdvancedCxfEndpointProducerBuilder
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2700/Issue2703.java
{ "start": 196, "end": 607 }
class ____ extends TestCase { public void test_for_issue() { Object a = JSON.toJavaObject(new JSONObject(), JSON.class); assertTrue(a instanceof JSONObject); Object b = new JSONObject().toJavaObject(JSON.class); assertTrue(b instanceof JSONObject); Object c = JSON.toJavaObject(new JSONArray(), JSON.class); assertTrue(c instanceof JSONArray); } }
Issue2703
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/snapshots/IndexShardSnapshotException.java
{ "start": 744, "end": 1210 }
class ____ extends ElasticsearchException { public IndexShardSnapshotException(ShardId shardId, String msg) { this(shardId, msg, null); } @SuppressWarnings("this-escape") public IndexShardSnapshotException(ShardId shardId, String msg, Throwable cause) { super(msg, cause); setShard(shardId); } public IndexShardSnapshotException(StreamInput in) throws IOException { super(in); } }
IndexShardSnapshotException
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/byte_/ByteAssert_isNotCloseToPercentage_byte_Test.java
{ "start": 1002, "end": 1473 }
class ____ extends ByteAssertBaseTest { private final Percentage percentage = withPercentage((byte) 5); private final Byte value = 10; @Override protected ByteAssert invoke_api_method() { return assertions.isNotCloseTo(value, percentage); } @Override protected void verify_internal_effects() { verify(bytes).assertIsNotCloseToPercentage(getInfo(assertions), getActual(assertions), value, percentage); } }
ByteAssert_isNotCloseToPercentage_byte_Test
java
apache__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/vector/reader/BytesColumnReader.java
{ "start": 1298, "end": 3835 }
class ____ extends AbstractColumnReader<WritableBytesVector> { public BytesColumnReader(ColumnDescriptor descriptor, PageReader pageReader) throws IOException { super(descriptor, pageReader); checkTypeName(PrimitiveType.PrimitiveTypeName.BINARY); } @Override protected void readBatch(int rowId, int num, WritableBytesVector column) { int left = num; while (left > 0) { if (runLenDecoder.currentCount == 0) { runLenDecoder.readNextGroup(); } int n = Math.min(left, runLenDecoder.currentCount); switch (runLenDecoder.mode) { case RLE: if (runLenDecoder.currentValue == maxDefLevel) { readBinary(n, column, rowId); } else { column.setNulls(rowId, n); } break; case PACKED: for (int i = 0; i < n; ++i) { if (runLenDecoder.currentBuffer[runLenDecoder.currentBufferIdx++] == maxDefLevel) { readBinary(1, column, rowId + i); } else { column.setNullAt(rowId + i); } } break; } rowId += n; left -= n; runLenDecoder.currentCount -= n; } } @Override protected void readBatchFromDictionaryIds( int rowId, int num, WritableBytesVector column, WritableIntVector dictionaryIds) { for (int i = rowId; i < rowId + num; ++i) { if (!column.isNullAt(i)) { byte[] bytes = dictionary.decodeToBinary(dictionaryIds.getInt(i)).getBytesUnsafe(); column.appendBytes(i, bytes, 0, bytes.length); } } } private void readBinary(int total, WritableBytesVector v, int rowId) { for (int i = 0; i < total; i++) { int len = readDataBuffer(4).getInt(); ByteBuffer buffer = readDataBuffer(len); if (buffer.hasArray()) { v.appendBytes( rowId + i, buffer.array(), buffer.arrayOffset() + buffer.position(), len); } else { byte[] bytes = new byte[len]; buffer.get(bytes); v.appendBytes(rowId + i, bytes, 0, bytes.length); } } } }
BytesColumnReader
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-guava-tests/src/test/java/org/assertj/tests/guava/api/RangeMapAssertBaseTest.java
{ "start": 791, "end": 1272 }
class ____ { protected TreeRangeMap<Integer, String> actual; @BeforeEach public void setUp() { actual = TreeRangeMap.create(); actual.put(Range.closedOpen(380, 450), "violet"); actual.put(Range.closedOpen(450, 495), "blue"); actual.put(Range.closedOpen(495, 570), "green"); actual.put(Range.closedOpen(570, 590), "yellow"); actual.put(Range.closedOpen(590, 620), "orange"); actual.put(Range.closedOpen(620, 750), "red"); } }
RangeMapAssertBaseTest
java
quarkusio__quarkus
test-framework/junit5-component/src/test/java/io/quarkus/test/component/UnsetConfigurationPropertiesTest.java
{ "start": 444, "end": 943 }
class ____ { @RegisterExtension static final QuarkusComponentTestExtension extension = QuarkusComponentTestExtension.builder() .useDefaultConfigProperties() .build(); @Inject Component component; @Test public void testComponent() { assertNull(component.foo); assertFalse(component.bar); assertEquals(0, component.baz); assertNull(component.bazzz); } @Singleton public static
UnsetConfigurationPropertiesTest
java
dropwizard__dropwizard
dropwizard-servlets/src/main/java/io/dropwizard/servlets/assets/ByteRange.java
{ "start": 270, "end": 2344 }
class ____ { private final int start; private final int end; public ByteRange(final int start, final int end) { this.start = start; this.end = end; } public int getStart() { return start; } public int getEnd() { return end; } public static ByteRange parse(final String byteRange, final int resourceLength) { final String asciiString = new String(byteRange.getBytes(StandardCharsets.US_ASCII), StandardCharsets.US_ASCII); // missing separator if (!byteRange.contains("-")) { final int start = Integer.parseInt(asciiString); return new ByteRange(start, resourceLength - 1); } // negative range if (byteRange.indexOf("-") == 0) { final int start = Integer.parseInt(asciiString); return new ByteRange(resourceLength + start, resourceLength - 1); } final List<String> parts = Arrays.stream(asciiString.split("-", -1)) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); final int start = Integer.parseInt(parts.get(0)); if (parts.size() == 2) { int end = Integer.parseInt(parts.get(1)); if (end > resourceLength) { end = resourceLength - 1; } return new ByteRange(start, end); } else { return new ByteRange(start, resourceLength - 1); } } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } final ByteRange other = (ByteRange) obj; return start == other.start && end == other.end; } @Override public int hashCode() { return Objects.hash(start, end); } @Override public String toString() { return String.format("%d-%d", start, end); } }
ByteRange
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/LongVectorBlock.java
{ "start": 665, "end": 2941 }
class ____ extends AbstractVectorBlock implements LongBlock { private final LongVector vector; /** * @param vector considered owned by the current block; must not be used in any other {@code Block} */ LongVectorBlock(LongVector vector) { this.vector = vector; } @Override public LongVector asVector() { return vector; } @Override public long getLong(int valueIndex) { return vector.getLong(valueIndex); } @Override public int getPositionCount() { return vector.getPositionCount(); } @Override public ElementType elementType() { return vector.elementType(); } @Override public LongBlock filter(int... positions) { return vector.filter(positions).asBlock(); } @Override public LongBlock keepMask(BooleanVector mask) { return vector.keepMask(mask); } @Override public LongBlock deepCopy(BlockFactory blockFactory) { return vector.deepCopy(blockFactory).asBlock(); } @Override public ReleasableIterator<? extends LongBlock> lookup(IntBlock positions, ByteSizeValue targetBlockSize) { return vector.lookup(positions, targetBlockSize); } @Override public LongBlock expand() { incRef(); return this; } @Override public long ramBytesUsed() { return vector.ramBytesUsed(); } @Override public boolean equals(Object obj) { if (obj instanceof LongBlock that) { return LongBlock.equals(this, that); } return false; } @Override public int hashCode() { return LongBlock.hash(this); } @Override public String toString() { return getClass().getSimpleName() + "[vector=" + vector + "]"; } @Override public void closeInternal() { assert (vector.isReleased() == false) : "can't release block [" + this + "] containing already released vector"; Releasables.closeExpectNoException(vector); } @Override public void allowPassingToDifferentDriver() { vector.allowPassingToDifferentDriver(); } @Override public BlockFactory blockFactory() { return vector.blockFactory(); } }
LongVectorBlock
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/UModifiers.java
{ "start": 1205, "end": 2439 }
class ____ extends UTree<JCModifiers> implements ModifiersTree { public static UModifiers create(long flagBits, UAnnotation... annotations) { return create(flagBits, ImmutableList.copyOf(annotations)); } public static UModifiers create(long flagBits, Iterable<? extends UAnnotation> annotations) { return new AutoValue_UModifiers(flagBits, ImmutableList.copyOf(annotations)); } abstract long flagBits(); @Override public abstract ImmutableList<UAnnotation> getAnnotations(); @Override public JCModifiers inline(Inliner inliner) throws CouldNotResolveImportException { return inliner .maker() .Modifiers( flagBits(), List.convert(JCAnnotation.class, inliner.inlineList(getAnnotations()))); } @Override public Choice<Unifier> visitModifiers(ModifiersTree modifier, Unifier unifier) { return Choice.condition(getFlags().equals(modifier.getFlags()), unifier); } @Override public <R, D> R accept(TreeVisitor<R, D> visitor, D data) { return visitor.visitModifiers(this, data); } @Override public Kind getKind() { return Kind.MODIFIERS; } @Override public Set<Modifier> getFlags() { return Flags.asModifierSet(flagBits()); } }
UModifiers
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java
{ "start": 62935, "end": 63590 }
class ____ { * String name; * double height; * Person bestFriend; * } * * Person sherlock = new Person("Sherlock", 1.80); * sherlock.bestFriend = new Person("Watson", 1.70); * * Person sherlockClone = new Person("Sherlock", 1.80); * sherlockClone.bestFriend = new Person("Watson", 1.70); * * // assertion succeeds as sherlock and sherlockClone have the same data and types * assertThat(sherlock).usingRecursiveComparison() * .withStrictTypeChecking() * .isEqualTo(sherlockClone); * * // Let's now define a data structure similar to Person * * public
Person
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/QueryWithNullLikeIntegrationTests.java
{ "start": 9268, "end": 10788 }
interface ____ extends JpaRepository<EmployeeWithName, Integer> { @Query("select e from EmployeeWithName e where e.name like %:partialName%") List<EmployeeWithName> customQueryWithNullableParam(@Nullable @Param("partialName") String partialName); @Query("select e.name, concat(e.name, ' with suffix') from EmployeeWithName e") List<EmployeeWithName> customQueryWithMismatchedReturnType(); @Query("select e.name, concat(e.name, ' with suffix') from EmployeeWithName e") List<Object[]> customQueryWithAlignedReturnType(); @Query(value = "select * from EmployeeWithName as e where e.name like %:partialName%", nativeQuery = true) List<EmployeeWithName> customQueryWithNullableParamInNative(@Nullable @Param("partialName") String partialName); @Query("select e from EmployeeWithName e where (:partialName is null or e.name like %:partialName%)") List<EmployeeWithName> customQueryWithOptionalParameter(@Nullable @Param("partialName") String partialName); List<EmployeeWithName> findByNameStartsWith(@Nullable String partialName); List<EmployeeWithName> findByNameEndsWith(@Nullable String partialName); List<EmployeeWithName> findByNameContains(@Nullable String partialName); List<EmployeeWithName> findByNameLike(@Nullable String partialName); } @EnableJpaRepositories(considerNestedRepositories = true, // includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = EmployeeWithNullLikeRepository.class)) @EnableTransactionManagement static
EmployeeWithNullLikeRepository
java
elastic__elasticsearch
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/DecimalDigitFilterFactory.java
{ "start": 961, "end": 1342 }
class ____ extends AbstractTokenFilterFactory implements NormalizingTokenFilterFactory { DecimalDigitFilterFactory(IndexSettings indexSettings, Environment env, String name, Settings settings) { super(name); } @Override public TokenStream create(TokenStream tokenStream) { return new DecimalDigitFilter(tokenStream); } }
DecimalDigitFilterFactory
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/issue50/domain/User.java
{ "start": 898, "end": 1591 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String username; private String password; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public static User withUsernameAndPassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); return user; } }
User
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/metrics/MaxAggregationBuilderTests.java
{ "start": 532, "end": 799 }
class ____ extends AbstractNumericMetricTestCase<MaxAggregationBuilder> { @Override protected MaxAggregationBuilder doCreateTestAggregatorFactory() { return new MaxAggregationBuilder(randomAlphaOfLengthBetween(3, 10)); } }
MaxAggregationBuilderTests
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/serializer/AdderSerializer.java
{ "start": 248, "end": 890 }
class ____ implements ObjectSerializer { public static final AdderSerializer instance = new AdderSerializer(); public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { SerializeWriter out = serializer.out; if (object instanceof LongAdder) { out.writeFieldValue('{', "value", ((LongAdder) object).longValue()); out.write('}'); } else if (object instanceof DoubleAdder) { out.writeFieldValue('{', "value", ((DoubleAdder) object).doubleValue()); out.write('}'); } } }
AdderSerializer
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/clickhouse/parser/CKSelectParser.java
{ "start": 860, "end": 6137 }
class ____ extends SQLSelectParser { public CKSelectParser(Lexer lexer) { super(lexer); } public CKSelectParser(SQLExprParser exprParser, SQLSelectListCache selectListCache) { super(exprParser, selectListCache); } @Override public SQLWithSubqueryClause parseWith() { SQLWithSubqueryClause withQueryClause = new SQLWithSubqueryClause(); if (lexer.hasComment() && lexer.isKeepComments()) { withQueryClause.addBeforeComment(lexer.readAndResetComments()); } accept(Token.WITH); if (lexer.token() == Token.RECURSIVE || lexer.identifierEquals(FnvHash.Constants.RECURSIVE)) { lexer.nextToken(); withQueryClause.setRecursive(true); } for (; ; ) { SQLWithSubqueryClause.Entry entry = new SQLWithSubqueryClause.Entry(); entry.setParent(withQueryClause); SQLExpr sqlExpr = exprParser.expr(); if (sqlExpr instanceof SQLIdentifierExpr) { String alias = ((SQLIdentifierExpr) sqlExpr).getName(); accept(Token.AS); accept(Token.LPAREN); entry.setSubQuery(select()); entry.setPrefixAlias(true); entry.setAlias(alias); accept(Token.RPAREN); } else { entry.setExpr(sqlExpr); accept(Token.AS); String alias = this.lexer.stringVal(); lexer.nextToken(); entry.setPrefixAlias(false); entry.setAlias(alias); } withQueryClause.addEntry(entry); if (lexer.token() == Token.COMMA) { lexer.nextToken(); continue; } break; } return withQueryClause; } @Override protected SQLSelectQueryBlock createSelectQueryBlock() { return new CKSelectQueryBlock(); } @Override public void parseWhere(SQLSelectQueryBlock queryBlock) { if (lexer.nextIf(Token.PREWHERE)) { SQLExpr preWhere = exprParser.expr(); ((CKSelectQueryBlock) queryBlock).setPreWhere(preWhere); } super.parseWhere(queryBlock); } @Override public void parseFrom(SQLSelectQueryBlock queryBlock) { List<String> comments = null; if (lexer.hasComment() && lexer.isKeepComments()) { comments = lexer.readAndResetComments(); } if (lexer.nextIf(Token.FROM)) { SQLTableSource from = parseTableSource(); if (comments != null) { from.addBeforeComment(comments); } queryBlock.setFrom(from); } else { if (comments != null) { queryBlock.addAfterComment(comments); } } if (lexer.nextIf(Token.FINAL)) { if (queryBlock instanceof CKSelectQueryBlock) { ((CKSelectQueryBlock) queryBlock).setFinal(true); } } } @Override protected void afterParseFetchClause(SQLSelectQueryBlock queryBlock) { if (queryBlock instanceof CKSelectQueryBlock) { CKSelectQueryBlock ckSelectQueryBlock = (CKSelectQueryBlock) queryBlock; if (lexer.token() == Token.SETTINGS) { lexer.nextToken(); for (; ; ) { SQLAssignItem item = this.exprParser.parseAssignItem(); ckSelectQueryBlock.getSettings().add(item); if (lexer.token() == Token.COMMA) { lexer.nextToken(); continue; } break; } } if (lexer.token() == Token.FORMAT) { lexer.nextToken(); ckSelectQueryBlock.setFormat(expr()); } } } @Override protected void afterParseLimitClause(SQLSelectQueryBlock queryBlock) { if (queryBlock instanceof CKSelectQueryBlock) { if (lexer.token() == Token.WITH) { lexer.nextToken(); acceptIdentifier("TIES"); ((CKSelectQueryBlock) queryBlock).setWithTies(true); } } } @Override protected void parseOrderByWith(SQLSelectGroupByClause groupBy, SQLSelectQueryBlock queryBlock) { Lexer.SavePoint mark = lexer.mark(); lexer.nextToken(); if (lexer.identifierEquals(FnvHash.Constants.CUBE)) { lexer.nextToken(); groupBy.setWithCube(true); } else if (lexer.identifierEquals(FnvHash.Constants.ROLLUP)) { lexer.nextToken(); groupBy.setWithRollUp(true); } else if (lexer.identifierEquals("TOTALS")) { lexer.nextToken(); ((CKSelectQueryBlock) queryBlock).setWithTotals(true); } else { lexer.reset(mark); } } @Override protected void parseAfterOrderBy(SQLSelectQueryBlock queryBlock) { if (lexer.token() == Token.WITH) { lexer.nextToken(); acceptIdentifier("FILL"); ((CKSelectQueryBlock) queryBlock).setWithFill(true); } } }
CKSelectParser
java
spring-projects__spring-framework
spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/factory/generator/InnerComponentConfiguration.java
{ "start": 1187, "end": 1404 }
class ____ { final Environment environment; EnvironmentAwareComponentWithoutPublicConstructor(Environment environment) { this.environment = environment; } } }
EnvironmentAwareComponentWithoutPublicConstructor
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/JdkMapAdapterStringMapTest.java
{ "start": 2009, "end": 31247 }
class ____ { @Test void testConstructorDisallowsNull() { assertThrows(NullPointerException.class, () -> new JdkMapAdapterStringMap(null, false)); } @Test void testToString() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("a2", "bvalue"); original.putValue("B", "Bvalue"); original.putValue("C", "Cvalue"); original.putValue("3", "3value"); assertEquals("{3=3value, B=Bvalue, C=Cvalue, a=avalue, a2=bvalue}", original.toString()); } @Test void testSerialization() throws Exception { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); final byte[] binary = serialize(original); final JdkMapAdapterStringMap copy = deserialize(binary); assertEquals(original, copy); } private byte[] serialize(final JdkMapAdapterStringMap data) throws IOException { final ByteArrayOutputStream arr = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(arr); out.writeObject(data); return arr.toByteArray(); } private JdkMapAdapterStringMap deserialize(final byte[] binary) throws IOException, ClassNotFoundException { final ByteArrayInputStream inArr = new ByteArrayInputStream(binary); final ObjectInputStream in = new ObjectInputStream(inArr); final JdkMapAdapterStringMap result = (JdkMapAdapterStringMap) in.readObject(); return result; } @Test void testPutAll() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putAll(original); assertEquals(original, other); other.putValue("3", "otherValue"); assertNotEquals(original, other); other.putValue("3", null); assertNotEquals(original, other); other.putValue("3", "3value"); assertEquals(original, other); } @Test void testPutAll_overwritesSameKeys2() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); original.putValue("c", "cORIG"); original.putValue("d", "dORIG"); original.putValue("e", "eORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue("1", "11"); other.putValue("2", "22"); other.putValue("a", "aa"); other.putValue("c", "cc"); original.putAll(other); assertEquals(7, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("cc", original.getValue("c")); assertEquals("dORIG", original.getValue("d")); assertEquals("eORIG", original.getValue("e")); assertEquals("11", original.getValue("1")); assertEquals("22", original.getValue("2")); } @Test void testPutAll_nullKeyInLargeOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); original.putValue("c", "cORIG"); original.putValue("d", "dORIG"); original.putValue("e", "eORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue("1", "11"); other.putValue("a", "aa"); original.putAll(other); assertEquals(7, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("cORIG", original.getValue("c")); assertEquals("dORIG", original.getValue("d")); assertEquals("eORIG", original.getValue("e")); assertEquals("11", original.getValue("1")); assertEquals("nullORIG", original.getValue(null)); } @Test void testPutAll_nullKeyInSmallOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue("1", "11"); other.putValue("2", "22"); other.putValue("3", "33"); other.putValue("a", "aa"); original.putAll(other); assertEquals(6, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("11", original.getValue("1")); assertEquals("22", original.getValue("2")); assertEquals("33", original.getValue("3")); assertEquals("nullORIG", original.getValue(null)); } @Test void testPutAll_nullKeyInSmallAdditional() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); original.putValue("c", "cORIG"); original.putValue("d", "dORIG"); original.putValue("e", "eORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue(null, "nullNEW"); other.putValue("1", "11"); other.putValue("a", "aa"); original.putAll(other); assertEquals(7, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("cORIG", original.getValue("c")); assertEquals("dORIG", original.getValue("d")); assertEquals("eORIG", original.getValue("e")); assertEquals("11", original.getValue("1")); assertEquals("nullNEW", original.getValue(null)); } @Test void testPutAll_nullKeyInLargeAdditional() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue(null, "nullNEW"); other.putValue("1", "11"); other.putValue("2", "22"); other.putValue("3", "33"); other.putValue("a", "aa"); original.putAll(other); assertEquals(6, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("11", original.getValue("1")); assertEquals("22", original.getValue("2")); assertEquals("33", original.getValue("3")); assertEquals("nullNEW", original.getValue(null)); } @Test void testPutAll_nullKeyInBoth_LargeOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); original.putValue("c", "cORIG"); original.putValue("d", "dORIG"); original.putValue("e", "eORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue(null, "nullNEW"); other.putValue("1", "11"); other.putValue("a", "aa"); original.putAll(other); assertEquals(7, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("cORIG", original.getValue("c")); assertEquals("dORIG", original.getValue("d")); assertEquals("eORIG", original.getValue("e")); assertEquals("11", original.getValue("1")); assertEquals("nullNEW", original.getValue(null)); } @Test void testPutAll_nullKeyInBoth_SmallOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue(null, "nullNEW"); other.putValue("1", "11"); other.putValue("2", "22"); other.putValue("3", "33"); other.putValue("a", "aa"); original.putAll(other); assertEquals(6, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("11", original.getValue("1")); assertEquals("22", original.getValue("2")); assertEquals("33", original.getValue("3")); assertEquals("nullNEW", original.getValue(null)); } @Test void testPutAll_overwritesSameKeys1() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); original.putValue("c", "cORIG"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue("1", "11"); other.putValue("2", "22"); other.putValue("a", "aa"); other.putValue("c", "cc"); original.putAll(other); assertEquals(5, original.size(), "size after put other"); assertEquals("aa", original.getValue("a")); assertEquals("bORIG", original.getValue("b")); assertEquals("cc", original.getValue("c")); assertEquals("11", original.getValue("1")); assertEquals("22", original.getValue("2")); } @Test void testEquals() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); assertEquals(original, original); // equal to itself final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue("a", "avalue"); assertNotEquals(original, other); other.putValue("B", "Bvalue"); assertNotEquals(original, other); other.putValue("3", "3value"); assertEquals(original, other); other.putValue("3", "otherValue"); assertNotEquals(original, other); other.putValue("3", null); assertNotEquals(original, other); other.putValue("3", "3value"); assertEquals(original, other); } @Test void testToMap() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); final Map<String, Object> expected = new HashMap<>(); expected.put("a", "avalue"); expected.put("B", "Bvalue"); expected.put("3", "3value"); assertEquals(expected, original.toMap()); try { original.toMap().put("abc", "xyz"); } catch (final UnsupportedOperationException ex) { fail("Expected map to be mutable, but " + ex); } } @Test void testPutAll_KeepsExistingValues() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); original.putValue("c", "ccc"); assertEquals(3, original.size(), "size"); // add empty context data original.putAll(new JdkMapAdapterStringMap()); assertEquals(3, original.size(), "size after put empty"); assertEquals("aaa", original.getValue("a")); assertEquals("bbb", original.getValue("b")); assertEquals("ccc", original.getValue("c")); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue("1", "111"); other.putValue("2", "222"); other.putValue("3", "333"); original.putAll(other); assertEquals(6, original.size(), "size after put other"); assertEquals("aaa", original.getValue("a")); assertEquals("bbb", original.getValue("b")); assertEquals("ccc", original.getValue("c")); assertEquals("111", original.getValue("1")); assertEquals("222", original.getValue("2")); assertEquals("333", original.getValue("3")); } @Test void testPutAll_sizePowerOfTwo() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); original.putValue("c", "ccc"); original.putValue("d", "ddd"); assertEquals(4, original.size(), "size"); // add empty context data original.putAll(new JdkMapAdapterStringMap()); assertEquals(4, original.size(), "size after put empty"); assertEquals("aaa", original.getValue("a")); assertEquals("bbb", original.getValue("b")); assertEquals("ccc", original.getValue("c")); assertEquals("ddd", original.getValue("d")); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); other.putValue("1", "111"); other.putValue("2", "222"); other.putValue("3", "333"); other.putValue("4", "444"); original.putAll(other); assertEquals(8, original.size(), "size after put other"); assertEquals("aaa", original.getValue("a")); assertEquals("bbb", original.getValue("b")); assertEquals("ccc", original.getValue("c")); assertEquals("ddd", original.getValue("d")); assertEquals("111", original.getValue("1")); assertEquals("222", original.getValue("2")); assertEquals("333", original.getValue("3")); assertEquals("444", original.getValue("4")); } @Test void testPutAll_largeAddition() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullVal"); original.putValue("a", "aaa"); original.putValue("b", "bbb"); original.putValue("c", "ccc"); original.putValue("d", "ddd"); assertEquals(5, original.size(), "size"); final JdkMapAdapterStringMap other = new JdkMapAdapterStringMap(); for (int i = 0; i < 500; i++) { other.putValue(String.valueOf(i), String.valueOf(i)); } other.putValue(null, "otherVal"); original.putAll(other); assertEquals(505, original.size(), "size after put other"); assertEquals("otherVal", original.getValue(null)); assertEquals("aaa", original.getValue("a")); assertEquals("bbb", original.getValue("b")); assertEquals("ccc", original.getValue("c")); assertEquals("ddd", original.getValue("d")); for (int i = 0; i < 500; i++) { assertEquals(String.valueOf(i), original.getValue(String.valueOf(i))); } } @Test void testPutAllSelfDoesNotModify() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); original.putValue("c", "ccc"); assertEquals(3, original.size(), "size"); // putAll with self original.putAll(original); assertEquals(3, original.size(), "size after put empty"); assertEquals("aaa", original.getValue("a")); assertEquals("bbb", original.getValue("b")); assertEquals("ccc", original.getValue("c")); } @Test void testNoConcurrentModificationBiConsumerPut() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("c", "aaa"); original.putValue("d", "aaa"); original.putValue("e", "aaa"); original.forEach((s, o) -> original.putValue("c" + s, "other")); } @Test void testNoConcurrentModificationBiConsumerPutValue() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("c", "aaa"); original.putValue("d", "aaa"); original.putValue("e", "aaa"); original.forEach((s, o) -> original.putValue("c" + s, "other")); } @Test void testNoConcurrentModificationBiConsumerRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("c", "aaa"); original.forEach((s, o) -> original.remove("a")); } @Test void testNoConcurrentModificationBiConsumerClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("c", "aaa"); original.putValue("d", "aaa"); original.putValue("e", "aaa"); original.forEach((s, o) -> original.clear()); } @Test void testNoConcurrentModificationTriConsumerPut() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("d", "aaa"); original.putValue("e", "aaa"); original.forEach((s, o, o2) -> original.putValue("c", "other"), null); } @Test void testNoConcurrentModificationTriConsumerPutValue() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("c", "aaa"); original.putValue("d", "aaa"); original.putValue("e", "aaa"); original.forEach((s, o, o2) -> original.putValue("c" + s, "other"), null); } @Test void testNoConcurrentModificationTriConsumerRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("c", "aaa"); original.forEach((s, o, o2) -> original.remove("a"), null); } @Test void testNoConcurrentModificationTriConsumerClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); original.putValue("c", "aaa"); original.putValue("d", "aaa"); original.forEach((s, o, o2) -> original.clear(), null); } @Test void testInitiallyNotFrozen() { assertFalse(new JdkMapAdapterStringMap().isFrozen()); } @Test void testIsFrozenAfterCallingFreeze() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); assertFalse(original.isFrozen(), "before freeze"); original.freeze(); assertTrue(original.isFrozen(), "after freeze"); } @Test void testFreezeProhibitsPutValue() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.freeze(); assertThrows(UnsupportedOperationException.class, () -> original.putValue("a", "aaa")); } @Test void testFreezeProhibitsRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("b", "bbb"); original.freeze(); assertThrows( UnsupportedOperationException.class, () -> original.remove("b")); // existing key: modifies the collection } @Test void testFreezeAllowsRemoveOfNonExistingKey() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("b", "bbb"); original.freeze(); original.remove("a"); // no actual modification } @Test void testFreezeAllowsRemoveIfEmpty() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.freeze(); original.remove("a"); // no exception } @Test void testFreezeProhibitsClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.freeze(); assertThrows(UnsupportedOperationException.class, original::clear); } @Test void testFreezeAllowsClearIfEmpty() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.freeze(); original.clear(); } @Test void testNullKeysAllowed() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); original.putValue("c", "cvalue"); original.putValue("d", "dvalue"); assertEquals(5, original.size()); original.putValue(null, "nullvalue"); assertEquals(6, original.size()); assertEquals("nullvalue", original.getValue(null)); original.putValue(null, "otherNullvalue"); assertEquals("otherNullvalue", original.getValue(null)); assertEquals(6, original.size()); original.putValue(null, "nullvalue"); assertEquals(6, original.size()); assertEquals("nullvalue", original.getValue(null)); original.putValue(null, "abc"); assertEquals(6, original.size()); assertEquals("abc", original.getValue(null)); } @Test void testNullKeysCopiedToAsMap() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); original.putValue("c", "cvalue"); original.putValue("d", "dvalue"); assertEquals(5, original.size()); final HashMap<String, String> expected = new HashMap<>(); expected.put("a", "avalue"); expected.put("B", "Bvalue"); expected.put("3", "3value"); expected.put("c", "cvalue"); expected.put("d", "dvalue"); assertEquals(expected, original.toMap(), "initial"); original.putValue(null, "nullvalue"); expected.put(null, "nullvalue"); assertEquals(6, original.size()); assertEquals(expected, original.toMap(), "with null key"); original.putValue(null, "otherNullvalue"); expected.put(null, "otherNullvalue"); assertEquals(6, original.size()); assertEquals(expected, original.toMap(), "with null key value2"); original.putValue(null, "nullvalue"); expected.put(null, "nullvalue"); assertEquals(6, original.size()); assertEquals(expected, original.toMap(), "with null key value1 again"); original.putValue(null, "abc"); expected.put(null, "abc"); assertEquals(6, original.size()); assertEquals(expected, original.toMap(), "with null key value3"); } @Test void testRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); assertEquals(1, original.size()); assertEquals("avalue", original.getValue("a")); original.remove("a"); assertEquals(0, original.size()); assertNull(original.getValue("a"), "no a val"); original.remove("B"); assertEquals(0, original.size()); assertNull(original.getValue("B"), "no B val"); } @Test void testRemoveWhenFull() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("b", "bvalue"); original.putValue("c", "cvalue"); original.putValue("d", "dvalue"); // default capacity = 4 original.remove("d"); } @Test void testNullValuesArePreserved() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); assertEquals(1, original.size()); assertEquals("avalue", original.getValue("a")); original.putValue("a", null); assertEquals(1, original.size()); assertNull(original.getValue("a"), "no a val"); original.putValue("B", null); assertEquals(2, original.size()); assertNull(original.getValue("B"), "no B val"); } @Test void testGet() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); assertEquals("avalue", original.getValue("a")); assertEquals("Bvalue", original.getValue("B")); assertEquals("3value", original.getValue("3")); original.putValue("0", "0value"); assertEquals("0value", original.getValue("0")); assertEquals("3value", original.getValue("3")); assertEquals("Bvalue", original.getValue("B")); assertEquals("avalue", original.getValue("a")); } @Test void testClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); assertEquals(3, original.size()); original.clear(); assertEquals(0, original.size()); } @Test void testContainsKey() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); assertFalse(original.containsKey("a"), "a"); assertFalse(original.containsKey("B"), "B"); assertFalse(original.containsKey("3"), "3"); assertFalse(original.containsKey("A"), "A"); original.putValue("a", "avalue"); assertTrue(original.containsKey("a"), "a"); assertFalse(original.containsKey("B"), "B"); assertFalse(original.containsKey("3"), "3"); assertFalse(original.containsKey("A"), "A"); original.putValue("B", "Bvalue"); assertTrue(original.containsKey("a"), "a"); assertTrue(original.containsKey("B"), "B"); assertFalse(original.containsKey("3"), "3"); assertFalse(original.containsKey("A"), "A"); original.putValue("3", "3value"); assertTrue(original.containsKey("a"), "a"); assertTrue(original.containsKey("B"), "B"); assertTrue(original.containsKey("3"), "3"); assertFalse(original.containsKey("A"), "A"); original.putValue("A", "AAA"); assertTrue(original.containsKey("a"), "a"); assertTrue(original.containsKey("B"), "B"); assertTrue(original.containsKey("3"), "3"); assertTrue(original.containsKey("A"), "A"); } @Test void testSizeAndIsEmpty() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); assertEquals(0, original.size()); assertTrue(original.isEmpty(), "initial"); original.putValue("a", "avalue"); assertEquals(1, original.size()); assertFalse(original.isEmpty(), "size=" + original.size()); original.putValue("B", "Bvalue"); assertEquals(2, original.size()); assertFalse(original.isEmpty(), "size=" + original.size()); original.putValue("3", "3value"); assertEquals(3, original.size()); assertFalse(original.isEmpty(), "size=" + original.size()); original.remove("B"); assertEquals(2, original.size()); assertFalse(original.isEmpty(), "size=" + original.size()); original.remove("3"); assertEquals(1, original.size()); assertFalse(original.isEmpty(), "size=" + original.size()); original.remove("a"); assertEquals(0, original.size()); assertTrue(original.isEmpty(), "size=" + original.size()); } @Test void testForEachBiConsumer() throws Exception { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); original.putValue("3", "3value"); original.forEach(new BiConsumer<String, String>() { int count = 0; @Override public void accept(final String key, final String value) { // assertEquals("key", key, original.getKeyAt(count)); // assertEquals("val", value, original.getValueAt(count)); count++; assertTrue(count <= original.size(), "count should not exceed size but was " + count); } }); } static
JdkMapAdapterStringMapTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreEventType.java
{ "start": 880, "end": 1283 }
enum ____ { STORE_APP_ATTEMPT, STORE_APP, UPDATE_APP, UPDATE_APP_ATTEMPT, REMOVE_APP, REMOVE_APP_ATTEMPT, FENCED, // Below events should be called synchronously STORE_MASTERKEY, REMOVE_MASTERKEY, STORE_DELEGATION_TOKEN, REMOVE_DELEGATION_TOKEN, UPDATE_DELEGATION_TOKEN, UPDATE_AMRM_TOKEN, STORE_RESERVATION, REMOVE_RESERVATION, STORE_PROXY_CA_CERT, }
RMStateStoreEventType
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/security/TestYARNTokenIdentifier.java
{ "start": 2515, "end": 21251 }
class ____ { @Test void testNMTokenIdentifier() throws IOException { testNMTokenIdentifier(false); } @Test void testNMTokenIdentifierOldFormat() throws IOException { testNMTokenIdentifier(true); } public void testNMTokenIdentifier(boolean oldFormat) throws IOException { ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(ApplicationId.newInstance(1, 1), 1); NodeId nodeId = NodeId.newInstance("host0", 0); String applicationSubmitter = "usr0"; int masterKeyId = 1; NMTokenIdentifier token = new NMTokenIdentifier(appAttemptId, nodeId, applicationSubmitter, masterKeyId); NMTokenIdentifier anotherToken = new NMTokenIdentifier(); byte[] tokenContent; if (oldFormat) { tokenContent = writeInOldFormat(token); } else { tokenContent = token.getBytes(); } DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); // verify the whole record equals with original record assertEquals(token, anotherToken, "Token is not the same after serialization " + "and deserialization."); // verify all properties are the same as original assertEquals(anotherToken.getApplicationAttemptId(), appAttemptId, "appAttemptId from proto is not the same with original token"); assertEquals(anotherToken.getNodeId(), nodeId, "NodeId from proto is not the same with original token"); assertEquals(anotherToken.getApplicationSubmitter(), applicationSubmitter, "applicationSubmitter from proto is not the same with original token"); assertEquals(anotherToken.getKeyId(), masterKeyId, "masterKeyId from proto is not the same with original token"); } @Test void testAMRMTokenIdentifier() throws IOException { testAMRMTokenIdentifier(false); } @Test void testAMRMTokenIdentifierOldFormat() throws IOException { testAMRMTokenIdentifier(true); } public void testAMRMTokenIdentifier(boolean oldFormat) throws IOException { ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(1, 1), 1); int masterKeyId = 1; AMRMTokenIdentifier token = new AMRMTokenIdentifier(appAttemptId, masterKeyId); AMRMTokenIdentifier anotherToken = new AMRMTokenIdentifier(); byte[] tokenContent; if (oldFormat) { tokenContent = writeInOldFormat(token); } else { tokenContent = token.getBytes(); } DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); // verify the whole record equals with original record assertEquals(token, anotherToken, "Token is not the same after serialization " + "and deserialization."); assertEquals(anotherToken.getApplicationAttemptId(), appAttemptId, "ApplicationAttemptId from proto is not the same with original token"); assertEquals(anotherToken.getKeyId(), masterKeyId, "masterKeyId from proto is not the same with original token"); } @Test void testClientToAMTokenIdentifier() throws IOException { ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(1, 1), 1); String clientName = "user"; ClientToAMTokenIdentifier token = new ClientToAMTokenIdentifier( appAttemptId, clientName); ClientToAMTokenIdentifier anotherToken = new ClientToAMTokenIdentifier(); byte[] tokenContent = token.getBytes(); DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); // verify the whole record equals with original record assertEquals(token, anotherToken, "Token is not the same after serialization " + "and deserialization."); assertEquals(anotherToken.getApplicationAttemptID(), appAttemptId, "ApplicationAttemptId from proto is not the same with original token"); assertEquals(anotherToken.getClientName(), clientName, "clientName from proto is not the same with original token"); } @Test void testContainerTokenIdentifierProtoMissingFields() throws IOException { ContainerTokenIdentifierProto.Builder builder = ContainerTokenIdentifierProto.newBuilder(); ContainerTokenIdentifierProto proto = builder.build(); assertFalse(proto.hasContainerType()); assertFalse(proto.hasExecutionType()); assertFalse(proto.hasNodeLabelExpression()); byte[] tokenData = proto.toByteArray(); DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenData, tokenData.length); ContainerTokenIdentifier tid = new ContainerTokenIdentifier(); tid.readFields(dib); assertEquals(ContainerType.TASK, tid.getContainerType(), "container type"); assertEquals(ExecutionType.GUARANTEED, tid.getExecutionType(), "execution type"); assertEquals(CommonNodeLabelsManager.NO_LABEL, tid.getNodeLabelExpression(), "node label expression"); } @Test void testContainerTokenIdentifier() throws IOException { testContainerTokenIdentifier(false, false); } @Test void testContainerTokenIdentifierOldFormat() throws IOException { testContainerTokenIdentifier(true, true); testContainerTokenIdentifier(true, false); } public void testContainerTokenIdentifier(boolean oldFormat, boolean withLogAggregation) throws IOException { ContainerId containerID = ContainerId.newContainerId( ApplicationAttemptId.newInstance(ApplicationId.newInstance( 1, 1), 1), 1); String hostName = "host0"; String appSubmitter = "usr0"; Resource r = Resource.newInstance(1024, 1); long expiryTimeStamp = 1000; int masterKeyId = 1; long rmIdentifier = 1; Priority priority = Priority.newInstance(1); long creationTime = 1000; ContainerTokenIdentifier token = new ContainerTokenIdentifier( containerID, hostName, appSubmitter, r, expiryTimeStamp, masterKeyId, rmIdentifier, priority, creationTime); ContainerTokenIdentifier anotherToken = new ContainerTokenIdentifier(); byte[] tokenContent; if (oldFormat) { tokenContent = writeInOldFormat(token, withLogAggregation); } else { tokenContent = token.getBytes(); } DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); // verify the whole record equals with original record assertEquals(token, anotherToken, "Token is not the same after serialization " + "and deserialization."); assertEquals(anotherToken.getContainerID(), containerID, "ContainerID from proto is not the same with original token"); assertEquals(anotherToken.getNmHostAddress(), hostName, "Hostname from proto is not the same with original token"); assertEquals(anotherToken.getApplicationSubmitter(), appSubmitter, "ApplicationSubmitter from proto is not the same with original token"); assertEquals(anotherToken.getResource(), r, "Resource from proto is not the same with original token"); assertEquals(anotherToken.getExpiryTimeStamp(), expiryTimeStamp, "expiryTimeStamp from proto is not the same with original token"); assertEquals(anotherToken.getMasterKeyId(), masterKeyId, "KeyId from proto is not the same with original token"); assertEquals(anotherToken.getRMIdentifier(), rmIdentifier, "RMIdentifier from proto is not the same with original token"); assertEquals(anotherToken.getPriority(), priority, "Priority from proto is not the same with original token"); assertEquals(anotherToken.getCreationTime(), creationTime, "CreationTime from proto is not the same with original token"); assertNull(anotherToken.getLogAggregationContext()); assertEquals(CommonNodeLabelsManager.NO_LABEL, anotherToken.getNodeLabelExpression()); assertEquals(ContainerType.TASK, anotherToken.getContainerType()); assertEquals(ExecutionType.GUARANTEED, anotherToken.getExecutionType()); } @Test void testRMDelegationTokenIdentifier() throws IOException { testRMDelegationTokenIdentifier(false); } @Test void testRMDelegationTokenIdentifierOldFormat() throws IOException { testRMDelegationTokenIdentifier(true); } public void testRMDelegationTokenIdentifier(boolean oldFormat) throws IOException { Text owner = new Text("user1"); Text renewer = new Text("user2"); Text realUser = new Text("user3"); long issueDate = 1; long maxDate = 2; int sequenceNumber = 3; int masterKeyId = 4; RMDelegationTokenIdentifier originalToken = new RMDelegationTokenIdentifier(owner, renewer, realUser); originalToken.setIssueDate(issueDate); originalToken.setMaxDate(maxDate); originalToken.setSequenceNumber(sequenceNumber); originalToken.setMasterKeyId(masterKeyId); RMDelegationTokenIdentifier anotherToken = new RMDelegationTokenIdentifier(); if (oldFormat) { DataInputBuffer inBuf = new DataInputBuffer(); DataOutputBuffer outBuf = new DataOutputBuffer(); originalToken.writeInOldFormat(outBuf); inBuf.reset(outBuf.getData(), 0, outBuf.getLength()); anotherToken.readFieldsInOldFormat(inBuf); inBuf.close(); } else { byte[] tokenContent = originalToken.getBytes(); DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); dib.close(); } // verify the whole record equals with original record assertEquals(originalToken, anotherToken, "Token is not the same after serialization and deserialization."); assertEquals(owner, anotherToken.getOwner(), "owner from proto is not the same with original token"); assertEquals(renewer, anotherToken.getRenewer(), "renewer from proto is not the same with original token"); assertEquals(realUser, anotherToken.getRealUser(), "realUser from proto is not the same with original token"); assertEquals(issueDate, anotherToken.getIssueDate(), "issueDate from proto is not the same with original token"); assertEquals(maxDate, anotherToken.getMaxDate(), "maxDate from proto is not the same with original token"); assertEquals(sequenceNumber, anotherToken.getSequenceNumber(), "sequenceNumber from proto is not the same with original token"); assertEquals(masterKeyId, anotherToken.getMasterKeyId(), "masterKeyId from proto is not the same with original token"); // Test getProto YARNDelegationTokenIdentifierProto tokenProto = originalToken.getProto(); // Write token proto to stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); tokenProto.writeTo(out); // Read token byte[] tokenData = baos.toByteArray(); RMDelegationTokenIdentifier readToken = new RMDelegationTokenIdentifier(); DataInputBuffer db = new DataInputBuffer(); db.reset(tokenData, tokenData.length); readToken.readFields(db); // Verify if read token equals with original token assertEquals(originalToken, readToken, "Token from getProto is not the same after " + "serialization and deserialization."); db.close(); out.close(); } @Test void testTimelineDelegationTokenIdentifier() throws IOException { Text owner = new Text("user1"); Text renewer = new Text("user2"); Text realUser = new Text("user3"); long issueDate = 1; long maxDate = 2; int sequenceNumber = 3; int masterKeyId = 4; TimelineDelegationTokenIdentifier token = new TimelineDelegationTokenIdentifier(owner, renewer, realUser); token.setIssueDate(issueDate); token.setMaxDate(maxDate); token.setSequenceNumber(sequenceNumber); token.setMasterKeyId(masterKeyId); TimelineDelegationTokenIdentifier anotherToken = new TimelineDelegationTokenIdentifier(); byte[] tokenContent = token.getBytes(); DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); // verify the whole record equals with original record assertEquals(token, anotherToken, "Token is not the same after serialization " + "and deserialization."); assertEquals(anotherToken.getOwner(), owner, "owner from proto is not the same with original token"); assertEquals(anotherToken.getRenewer(), renewer, "renewer from proto is not the same with original token"); assertEquals(anotherToken.getRealUser(), realUser, "realUser from proto is not the same with original token"); assertEquals(anotherToken.getIssueDate(), issueDate, "issueDate from proto is not the same with original token"); assertEquals(anotherToken.getMaxDate(), maxDate, "maxDate from proto is not the same with original token"); assertEquals(anotherToken.getSequenceNumber(), sequenceNumber, "sequenceNumber from proto is not the same with original token"); assertEquals(anotherToken.getMasterKeyId(), masterKeyId, "masterKeyId from proto is not the same with original token"); } @Test void testParseTimelineDelegationTokenIdentifierRenewer() throws IOException { // Server side when generation a timeline DT Configuration conf = new YarnConfiguration(); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTH_TO_LOCAL, "RULE:[2:$1@$0]([nr]m@.*EXAMPLE.COM)s/.*/yarn/"); HadoopKerberosName.setConfiguration(conf); Text owner = new Text("owner"); Text renewer = new Text("rm/localhost@EXAMPLE.COM"); Text realUser = new Text("realUser"); TimelineDelegationTokenIdentifier token = new TimelineDelegationTokenIdentifier(owner, renewer, realUser); assertEquals(new Text("yarn"), token.getRenewer()); } @Test void testAMContainerTokenIdentifier() throws IOException { ContainerId containerID = ContainerId.newContainerId( ApplicationAttemptId.newInstance(ApplicationId.newInstance( 1, 1), 1), 1); String hostName = "host0"; String appSubmitter = "usr0"; Resource r = Resource.newInstance(1024, 1); long expiryTimeStamp = 1000; int masterKeyId = 1; long rmIdentifier = 1; Priority priority = Priority.newInstance(1); long creationTime = 1000; ContainerTokenIdentifier token = new ContainerTokenIdentifier(containerID, hostName, appSubmitter, r, expiryTimeStamp, masterKeyId, rmIdentifier, priority, creationTime, null, CommonNodeLabelsManager.NO_LABEL, ContainerType.APPLICATION_MASTER); ContainerTokenIdentifier anotherToken = new ContainerTokenIdentifier(); byte[] tokenContent = token.getBytes(); DataInputBuffer dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); assertEquals(ContainerType.APPLICATION_MASTER, anotherToken.getContainerType()); assertEquals(ExecutionType.GUARANTEED, anotherToken.getExecutionType()); token = new ContainerTokenIdentifier(containerID, 0, hostName, appSubmitter, r, expiryTimeStamp, masterKeyId, rmIdentifier, priority, creationTime, null, CommonNodeLabelsManager.NO_LABEL, ContainerType.TASK, ExecutionType.OPPORTUNISTIC); anotherToken = new ContainerTokenIdentifier(); tokenContent = token.getBytes(); dib = new DataInputBuffer(); dib.reset(tokenContent, tokenContent.length); anotherToken.readFields(dib); assertEquals(ContainerType.TASK, anotherToken.getContainerType()); assertEquals(ExecutionType.OPPORTUNISTIC, anotherToken.getExecutionType()); } @SuppressWarnings("deprecation") private byte[] writeInOldFormat(ContainerTokenIdentifier token, boolean withLogAggregation) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); ApplicationAttemptId applicationAttemptId = token.getContainerID() .getApplicationAttemptId(); ApplicationId applicationId = applicationAttemptId.getApplicationId(); out.writeLong(applicationId.getClusterTimestamp()); out.writeInt(applicationId.getId()); out.writeInt(applicationAttemptId.getAttemptId()); out.writeLong(token.getContainerID().getContainerId()); out.writeUTF(token.getNmHostAddress()); out.writeUTF(token.getApplicationSubmitter()); out.writeInt(token.getResource().getMemory()); out.writeInt(token.getResource().getVirtualCores()); out.writeLong(token.getExpiryTimeStamp()); out.writeInt(token.getMasterKeyId()); out.writeLong(token.getRMIdentifier()); out.writeInt(token.getPriority().getPriority()); out.writeLong(token.getCreationTime()); if (withLogAggregation) { if (token.getLogAggregationContext() == null) { out.writeInt(-1); } else { byte[] logAggregationContext = ((LogAggregationContextPBImpl) token.getLogAggregationContext()).getProto().toByteArray(); out.writeInt(logAggregationContext.length); out.write(logAggregationContext); } } out.close(); return baos.toByteArray(); } private byte[] writeInOldFormat(NMTokenIdentifier token) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); ApplicationId applicationId = token.getApplicationAttemptId() .getApplicationId(); out.writeLong(applicationId.getClusterTimestamp()); out.writeInt(applicationId.getId()); out.writeInt(token.getApplicationAttemptId().getAttemptId()); out.writeUTF(token.getNodeId().toString()); out.writeUTF(token.getApplicationSubmitter()); out.writeInt(token.getKeyId()); out.close(); return baos.toByteArray(); } private byte[] writeInOldFormat(AMRMTokenIdentifier token) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); ApplicationId applicationId = token.getApplicationAttemptId() .getApplicationId(); out.writeLong(applicationId.getClusterTimestamp()); out.writeInt(applicationId.getId()); out.writeInt(token.getApplicationAttemptId().getAttemptId()); out.writeInt(token.getKeyId()); out.close(); return baos.toByteArray(); } }
TestYARNTokenIdentifier
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/api/dataview/DataView.java
{ "start": 1343, "end": 1446 }
interface ____ { /** Clears the {@link DataView} and removes all data. */ void clear(); }
DataView
java
netty__netty
resolver-dns/src/main/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProvider.java
{ "start": 11588, "end": 20497 }
interface ____ does not exists // on the host. if (!addr.isUnresolved()) { addresses.add(addr); } } else if (line.startsWith(DOMAIN_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, DOMAIN_ROW_LABEL.length()); if (i < 0) { throw new IllegalArgumentException("error parsing label " + DOMAIN_ROW_LABEL + " in file " + etcResolverFile + " value: " + line); } domainName = line.substring(i); if (!addresses.isEmpty()) { putIfAbsent(domainToNameServerStreamMap, domainName, addresses, rotate); } addresses = new ArrayList<InetSocketAddress>(2); } else if (line.startsWith(PORT_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, PORT_ROW_LABEL.length()); if (i < 0) { throw new IllegalArgumentException("error parsing label " + PORT_ROW_LABEL + " in file " + etcResolverFile + " value: " + line); } port = Integer.parseInt(line.substring(i)); } else if (line.startsWith(SORTLIST_ROW_LABEL)) { logger.info("row type {} not supported. Ignoring line: {}", SORTLIST_ROW_LABEL, line); } } catch (IllegalArgumentException e) { logger.warn("Could not parse entry. Ignoring line: {}", line, e); } } if (!addresses.isEmpty()) { putIfAbsent(domainToNameServerStreamMap, domainName, addresses, rotate); } } finally { if (br == null) { fr.close(); } else { br.close(); } } } return domainToNameServerStreamMap; } private static void putIfAbsent(Map<String, DnsServerAddresses> domainToNameServerStreamMap, String domainName, List<InetSocketAddress> addresses, boolean rotate) { // TODO(scott): sortlist is being ignored. DnsServerAddresses addrs = rotate ? DnsServerAddresses.rotational(addresses) : DnsServerAddresses.sequential(addresses); putIfAbsent(domainToNameServerStreamMap, domainName, addrs); } private static void putIfAbsent(Map<String, DnsServerAddresses> domainToNameServerStreamMap, String domainName, DnsServerAddresses addresses) { DnsServerAddresses existingAddresses = domainToNameServerStreamMap.put(domainName, addresses); if (existingAddresses != null) { domainToNameServerStreamMap.put(domainName, existingAddresses); if (logger.isDebugEnabled()) { logger.debug("Domain name {} already maps to addresses {} so new addresses {} will be discarded", domainName, existingAddresses, addresses); } } } /** * Parse <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a> and return options of interest, namely: * timeout, attempts and ndots. * @return The options values provided by /etc/resolve.conf. * @throws IOException If a failure occurs parsing the file. */ static UnixResolverOptions parseEtcResolverOptions() throws IOException { return parseEtcResolverOptions(new File(ETC_RESOLV_CONF_FILE)); } /** * Parse a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a> and return options * of interest, namely: timeout, attempts and ndots. * @param etcResolvConf a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a>. * @return The options values provided by /etc/resolve.conf. * @throws IOException If a failure occurs parsing the file. */ static UnixResolverOptions parseEtcResolverOptions(File etcResolvConf) throws IOException { UnixResolverOptions.Builder optionsBuilder = UnixResolverOptions.newBuilder(); FileReader fr = new FileReader(etcResolvConf); BufferedReader br = null; try { br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { if (line.startsWith(OPTIONS_ROW_LABEL)) { parseResOptions(line.substring(OPTIONS_ROW_LABEL.length()), optionsBuilder); break; } } } finally { if (br == null) { fr.close(); } else { br.close(); } } // amend options if (RES_OPTIONS != null) { parseResOptions(RES_OPTIONS, optionsBuilder); } return optionsBuilder.build(); } private static void parseResOptions(String line, UnixResolverOptions.Builder builder) { String[] opts = WHITESPACE_PATTERN.split(line); for (String opt : opts) { try { if (opt.startsWith("ndots:")) { builder.setNdots(parseResIntOption(opt, "ndots:")); } else if (opt.startsWith("attempts:")) { builder.setAttempts(parseResIntOption(opt, "attempts:")); } else if (opt.startsWith("timeout:")) { builder.setTimeout(parseResIntOption(opt, "timeout:")); } } catch (NumberFormatException ignore) { // skip bad int values from resolv.conf to keep value already set in UnixResolverOptions } } } private static int parseResIntOption(String opt, String fullLabel) { String optValue = opt.substring(fullLabel.length()); return Integer.parseInt(optValue); } /** * Parse a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a> and return the * list of search domains found in it or an empty list if not found. * @return List of search domains. * @throws IOException If a failure occurs parsing the file. */ static List<String> parseEtcResolverSearchDomains() throws IOException { return parseEtcResolverSearchDomains(new File(ETC_RESOLV_CONF_FILE)); } /** * Parse a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a> and return the * list of search domains found in it or an empty list if not found. * @param etcResolvConf a file of the format <a href="https://linux.die.net/man/5/resolver">/etc/resolv.conf</a>. * @return List of search domains. * @throws IOException If a failure occurs parsing the file. */ static List<String> parseEtcResolverSearchDomains(File etcResolvConf) throws IOException { String localDomain = null; List<String> searchDomains = new ArrayList<String>(); FileReader fr = new FileReader(etcResolvConf); BufferedReader br = null; try { br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { if (localDomain == null && line.startsWith(DOMAIN_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, DOMAIN_ROW_LABEL.length()); if (i >= 0) { localDomain = line.substring(i); } } else if (line.startsWith(SEARCH_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, SEARCH_ROW_LABEL.length()); if (i >= 0) { // May contain more then one entry, either separated by whitespace or tab. // See https://linux.die.net/man/5/resolver String[] domains = WHITESPACE_PATTERN.split(line.substring(i)); Collections.addAll(searchDomains, domains); } } } } finally { if (br == null) { fr.close(); } else { br.close(); } } // return what was on the 'domain' line only if there were no 'search' lines return localDomain != null && searchDomains.isEmpty() ? Collections.singletonList(localDomain) : searchDomains; } }
that
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallAlterTest_0.java
{ "start": 784, "end": 1139 }
class ____ extends TestCase { private String sql = "alter index idx_t1 rebuild"; private WallConfig config = new WallConfig(); protected void setUp() throws Exception { config.setUpdateAllow(true); } public void testORACLE() throws Exception { assertTrue(WallUtils.isValidateOracle(sql, config)); } }
WallAlterTest_0
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/EnumJdbcType.java
{ "start": 1014, "end": 3055 }
class ____ implements JdbcType { public static final EnumJdbcType INSTANCE = new EnumJdbcType(); @Override public int getJdbcTypeCode() { return VARCHAR; } @Override public int getDefaultSqlTypeCode() { return ENUM; } @Override public <T> JdbcLiteralFormatter<T> getJdbcLiteralFormatter(JavaType<T> javaType) { return new JdbcLiteralFormatterCharacterData<>( javaType ); } @Override public String getFriendlyName() { return "ENUM"; } @Override public Class<?> getPreferredJavaTypeClass(WrapperOptions options) { return String.class; } @Override public <X> ValueBinder<X> getBinder(JavaType<X> javaType) { return new BasicBinder<>( javaType, this ) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { st.setString( index, getJavaType().unwrap( value, String.class, options ) ); } @Override protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException { st.setString( name, getJavaType().unwrap( value, String.class, options ) ); } @Override public Object getBindValue(X value, WrapperOptions options) throws SQLException { return getJavaType().unwrap( value, String.class, options ); } }; } @Override public <X> ValueExtractor<X> getExtractor(JavaType<X> javaType) { return new BasicExtractor<>( javaType, this ) { @Override protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException { return getJavaType().wrap( rs.getString( paramIndex ), options ); } @Override protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { return getJavaType().wrap( statement.getString( index ), options ); } @Override protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { return getJavaType().wrap( statement.getString( name ), options ); } }; } }
EnumJdbcType
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/FileSystemTableSink.java
{ "start": 25252, "end": 26131 }
class ____ implements BucketAssigner<RowData, String> { private final PartitionComputer<RowData> computer; public TableBucketAssigner(PartitionComputer<RowData> computer) { this.computer = computer; } @Override public String getBucketId(RowData element, Context context) { try { return PartitionPathUtils.generatePartitionPath( computer.generatePartValues(element)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public SimpleVersionedSerializer<String> getSerializer() { return SimpleVersionedStringSerializer.INSTANCE; } } /** Table {@link RollingPolicy}, it extends {@link CheckpointRollingPolicy} for bulk writers. */ public static
TableBucketAssigner
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-tos/src/test/java/org/apache/hadoop/fs/tosfs/ops/TestDefaultFsOps.java
{ "start": 1789, "end": 4191 }
class ____ extends TestBaseFsOps { private static ExecutorService threadPool; static Stream<Arguments> provideArguments() { // Case1: direct rename. List<Arguments> values = new ArrayList<>(); Configuration directRenameConf = new Configuration(); directRenameConf.setBoolean(ConfKeys.FS_OBJECT_RENAME_ENABLED.key("tos"), true); directRenameConf.setBoolean(ConfKeys.FS_ASYNC_CREATE_MISSED_PARENT.key("tos"), false); ObjectStorage storage0 = ObjectStorageFactory.createWithPrefix(String.format("tos-%s/", UUIDUtils.random()), TOS_SCHEME, TestUtility.bucket(), directRenameConf); values.add(Arguments.of( storage0, new DefaultFsOps(storage0, directRenameConf, threadPool, obj -> { long modifiedTime = RawFileSystem.dateToLong(obj.mtime()); String path = String.format("%s://%s/%s", storage0.scheme(), storage0.bucket().name(), obj.key()); return new RawFileStatus(obj.size(), obj.isDir(), 0, modifiedTime, new Path(path), "fake", obj.checksum()); }))); // Case2: copied rename. Configuration copiedRenameConf = new Configuration(); copiedRenameConf.setLong(ConfKeys.FS_MULTIPART_COPY_THRESHOLD.key("tos"), 1L << 20); copiedRenameConf.setBoolean(ConfKeys.FS_ASYNC_CREATE_MISSED_PARENT.key("tos"), false); ObjectStorage storage1 = ObjectStorageFactory.createWithPrefix(String.format("tos-%s/", UUIDUtils.random()), TOS_SCHEME, TestUtility.bucket(), copiedRenameConf); values.add(Arguments.of( storage1, new DefaultFsOps(storage1, copiedRenameConf, threadPool, obj -> { long modifiedTime = RawFileSystem.dateToLong(obj.mtime()); String path = String.format("%s://%s/%s", storage1.scheme(), storage1.bucket().name(), obj.key()); return new RawFileStatus(obj.size(), obj.isDir(), 0, modifiedTime, new Path(path), "fake", obj.checksum()); }))); return values.stream(); } @BeforeAll public static void beforeClass() { assumeTrue(TestEnv.checkTestEnabled()); threadPool = ThreadPools.newWorkerPool("TestDefaultFsHelper-pool"); } @AfterAll public static void afterClass() { if (!TestEnv.checkTestEnabled()) { return; } if (!threadPool.isShutdown()) { threadPool.shutdown(); } } }
TestDefaultFsOps
java
spring-projects__spring-framework
spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java
{ "start": 10148, "end": 10331 }
class ____ { @JmsListener(containerFactory = "defaultFactory", destination = "myQueue") public void defaultHandle(@Validated String msg) { } } @Component static
ValidationBean
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/twosteperror/ErroneousMapperCM.java
{ "start": 316, "end": 665 }
interface ____ { ErroneousMapperCM INSTANCE = Mappers.getMapper( ErroneousMapperCM.class ); Target map(Source s); default TargetType methodY1(String s) { return new TargetType( s ); } default TargetType methodY2(Double d) { return new TargetType( d.toString() ); } // CHECKSTYLE:OFF
ErroneousMapperCM
java
redisson__redisson
redisson/src/main/java/org/redisson/api/redisnode/RedisCluster.java
{ "start": 762, "end": 1639 }
interface ____ extends BaseRedisNodes { /** * Returns collection of Redis Master nodes belongs to this Redis Cluster. * * @return Redis Master nodes */ Collection<RedisClusterMaster> getMasters(); /** * Returns Redis Master node by defined address. * <p> * Address example: <code>redis://127.0.0.1:9233</code> * * @return Redis Master node */ RedisClusterMaster getMaster(String address); /** * Returns collection of Redis Slave nodes belongs to this Redis Cluster. * * @return Redis Slave nodes */ Collection<RedisClusterSlave> getSlaves(); /** * Returns Redis Slave node by defined address. * <p> * Address example: <code>redis://127.0.0.1:9233</code> * * @return Redis Slave node */ RedisClusterSlave getSlave(String address); }
RedisCluster
java
apache__camel
core/camel-util/src/main/java/org/apache/camel/util/ReflectionHelper.java
{ "start": 1678, "end": 2035 }
interface ____ { /** * Perform an operation using the given method. * * @param method the method to operate on */ void doWith(Method method) throws IllegalArgumentException, IllegalAccessException; } /** * Action to take on each class. */ @FunctionalInterface public
MethodCallback