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
apache__camel
components/camel-huawei/camel-huaweicloud-imagerecognition/src/test/java/org/apache/camel/component/huaweicloud/image/TagRecognitionWithImageUrlTest.java
{ "start": 1345, "end": 3514 }
class ____ extends CamelTestSupport { TestConfiguration testConfiguration = new TestConfiguration(); protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:trigger_route") .setProperty(ImageRecognitionProperties.IMAGE_URL, constant(testConfiguration.getProperty("imageUrl"))) .setProperty(ImageRecognitionProperties.THRESHOLD, constant(testConfiguration.getProperty("tagThreshold"))) .to("hwcloud-imagerecognition:tagRecognition?accessKey=" + testConfiguration.getProperty("accessKey") + "&secretKey=" + testConfiguration.getProperty("secretKey") + "&projectId=" + testConfiguration.getProperty("projectId") + "&region=" + testConfiguration.getProperty("region") + "&ignoreSslVerification=true") .log("perform tag recognition successful") .to("mock:perform_tag_recognition_result"); } }; } /** * Following test cases should be manually enabled to perform test against the actual Huawei Cloud Image Recognition * service with real user credentials. To perform this test, manually comment out the @Disabled annotation and enter * relevant service parameters in the placeholders above (static variables of this test class) * * @throws Exception Exception */ @Test @Disabled("Manually comment out this line once you configure service parameters in placeholders above") public void testTagRecognition() throws Exception { MockEndpoint mock = getMockEndpoint("mock:perform_tag_recognition_result"); mock.expectedMinimumMessageCount(1); template.sendBody("direct:trigger_route", ""); Exchange responseExchange = mock.getExchanges().get(0); mock.assertIsSatisfied(); assertTrue(responseExchange.getIn().getBody() instanceof RunImageTaggingResponse); } }
TagRecognitionWithImageUrlTest
java
square__retrofit
retrofit/src/main/java/retrofit2/Retrofit.java
{ "start": 1444, "end": 1622 }
interface ____ HTTP calls by using annotations on the declared methods to * define how requests are made. Create instances using {@linkplain Builder the builder} and pass * your
to
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/tck/MulticastProcessorTckTest.java
{ "start": 900, "end": 1902 }
class ____ extends IdentityProcessorVerification<Integer> { public MulticastProcessorTckTest() { super(new TestEnvironment(50)); } @Override public Processor<Integer, Integer> createIdentityProcessor(int bufferSize) { MulticastProcessor<Integer> mp = MulticastProcessor.create(); return new RefCountProcessor<>(mp); } @Override public Publisher<Integer> createFailedPublisher() { MulticastProcessor<Integer> mp = MulticastProcessor.create(); mp.start(); mp.onError(new TestException()); return mp; } @Override public ExecutorService publisherExecutorService() { return Executors.newCachedThreadPool(); } @Override public Integer createElement(int element) { return element; } @Override public long maxSupportedSubscribers() { return 1; } @Override public long maxElementsFromPublisher() { return 1024; } }
MulticastProcessorTckTest
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanInfo.java
{ "start": 50555, "end": 50846 }
class ____ implements Comparator<Object> { private static final ToStringComparator INSTANCE = new ToStringComparator(); @Override public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } } }
ToStringComparator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/android/IsLoggableTagLengthTest.java
{ "start": 4615, "end": 5106 }
class ____ { public void log() { // BUG: Diagnostic contains: IsLoggableTagLength Log.isLoggable(ThisClassNameIsWayTooLong.class.getSimpleName(), Log.INFO); } } """) .doTest(); } @Test public void negativeCaseFinalFieldClassName() { compilationHelper .addSourceLines( "Test.java", """ import android.util.Log;
ThisClassNameIsWayTooLong
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/arbiters/ClassArbiter.java
{ "start": 1426, "end": 1857 }
class ____ implements Arbiter { private final String className; private ClassArbiter(final String className) { this.className = className; } @Override public boolean isCondition() { return LoaderUtil.isClassAvailable(className); } @PluginBuilderFactory public static ClassArbiter.Builder newBuilder() { return new ClassArbiter.Builder(); } public static
ClassArbiter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass3/UnionSubclassTest.java
{ "start": 4794, "end": 4901 }
class ____ extends Parent { @Column String fathersDay; } @Entity(name = "Mother") public static
Father
java
mockito__mockito
mockito-core/src/main/java/org/mockito/Mockito.java
{ "start": 171894, "end": 175687 }
class ____ all tests) because adding a special action to <code>&#064;After</code> has zero cost. * <p> * See examples in javadoc for {@link Mockito} class */ public static void validateMockitoUsage() { MOCKITO_CORE.validateMockitoUsage(); } /** * Allows mock creation with additional mock settings. * <p> * Don't use it too often. * Consider writing simple tests that use simple mocks. * Repeat after me: simple tests push simple, KISSy, readable and maintainable code. * If you cannot write a test in a simple way - refactor the code under test. * <p> * Examples of mock settings: * <pre class="code"><code class="java"> * //Creates mock with different default answer and name * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie")); * * //Creates mock with different default answer, descriptive name and extra interfaces * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie") * .extraInterfaces(Bar.class)); * </code></pre> * {@link MockSettings} has been introduced for two reasons. * Firstly, to make it easy to add another mock settings when the demand comes. * Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods. * <p> * See javadoc for {@link MockSettings} to learn about possible mock settings. * <p> * * @return mock settings instance with defaults. */ public static MockSettings withSettings() { return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS); } /** * Adds a description to be printed if verification fails. * <pre class="code"><code class="java"> * verify(mock, description("This will print on failure")).someMethod("some arg"); * </code></pre> * @param description The description to print on failure. * @return verification mode * @since 2.1.0 */ public static VerificationMode description(String description) { return times(1).description(description); } /** * For advanced users or framework integrators. See {@link MockitoFramework} class. * * @since 2.1.0 */ public static MockitoFramework framework() { return new DefaultMockitoFramework(); } /** * {@code MockitoSession} is an optional, highly recommended feature * that drives writing cleaner tests by eliminating boilerplate code and adding extra validation. * <p> * For more information, including use cases and sample code, see the javadoc for {@link MockitoSession}. * * @since 2.7.0 */ public static MockitoSessionBuilder mockitoSession() { return new DefaultMockitoSessionBuilder(); } /** * Lenient stubs bypass "strict stubbing" validation (see {@link Strictness#STRICT_STUBS}). * When stubbing is declared as lenient, it will not be checked for potential stubbing problems such as * 'unnecessary stubbing' ({@link UnnecessaryStubbingException}) or for 'stubbing argument mismatch' {@link PotentialStubbingProblem}. * * <pre class="code"><code class="java"> * lenient().when(mock.foo()).thenReturn("ok"); * </code></pre> * * Most mocks in most tests don't need leniency and should happily prosper with {@link Strictness#STRICT_STUBS}. * <ul> * <li>If a specific stubbing needs to be lenient - use this method</li> * <li>If a specific mock need to have lenient stubbings - use {@link MockSettings#strictness(Strictness)}</li> * <li>If a specific test method / test
for
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/rpc/service/GenericExceptionTest.java
{ "start": 996, "end": 2857 }
class ____ { @Test void jsonSupport() throws IOException { { GenericException src = new GenericException(); String s = JsonUtils.toJson(src); GenericException dst = JsonUtils.toJavaObject(s, GenericException.class); Assertions.assertEquals(src.getExceptionClass(), dst.getExceptionClass()); Assertions.assertEquals(src.getExceptionMessage(), dst.getExceptionMessage()); Assertions.assertEquals(src.getMessage(), dst.getMessage()); Assertions.assertEquals(src.getExceptionMessage(), dst.getExceptionMessage()); } { GenericException src = new GenericException(this.getClass().getSimpleName(), "test"); String s = JsonUtils.toJson(src); GenericException dst = JsonUtils.toJavaObject(s, GenericException.class); Assertions.assertEquals(src.getExceptionClass(), dst.getExceptionClass()); Assertions.assertEquals(src.getExceptionMessage(), dst.getExceptionMessage()); Assertions.assertEquals(src.getMessage(), dst.getMessage()); Assertions.assertEquals(src.getExceptionMessage(), dst.getExceptionMessage()); } { Throwable throwable = new Throwable("throwable"); GenericException src = new GenericException(throwable); String s = JsonUtils.toJson(src); GenericException dst = JsonUtils.toJavaObject(s, GenericException.class); Assertions.assertEquals(src.getExceptionClass(), dst.getExceptionClass()); Assertions.assertEquals(src.getExceptionMessage(), dst.getExceptionMessage()); Assertions.assertEquals(src.getMessage(), dst.getMessage()); Assertions.assertEquals(src.getExceptionMessage(), dst.getExceptionMessage()); } } }
GenericExceptionTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-guava-tests/src/test/java/org/assertj/tests/guava/api/OptionalAssert_isAbsent_Test.java
{ "start": 1038, "end": 2036 }
class ____ { @Test public void should_fail_if_actual_is_null() { // GIVEN Optional<String> actual = null; // WHEN Throwable throwable = catchThrowable(() -> assertThat(actual).isAbsent()); // THEN assertThat(throwable).isInstanceOf(AssertionError.class) .hasMessage(actualIsNull()); } @Test public void should_fail_when_expected_present_optional_is_absent() { // GIVEN final Optional<String> actual = Optional.of("X"); // WHEN Throwable throwable = catchThrowable(() -> assertThat(actual).isAbsent()); // THEN assertThat(throwable).isInstanceOf(AssertionError.class) .hasMessage("Expecting Optional to contain nothing (absent Optional) but contained \"X\""); } @Test public void should_pass_when_optional_is_absent() { // GIVEN final Optional<String> testedOptional = Optional.absent(); // THEN assertThat(testedOptional).isAbsent(); } }
OptionalAssert_isAbsent_Test
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/annotation/Order.java
{ "start": 2947, "end": 3129 }
interface ____ { /** * The order value. * <p>Default is {@link Ordered#LOWEST_PRECEDENCE}. * @see Ordered#getOrder() */ int value() default Ordered.LOWEST_PRECEDENCE; }
Order
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/impl/converter/SpringTypeConvertersOverrideTest.java
{ "start": 1266, "end": 2038 }
class ____ extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/spring/impl/converter/SpringTypeConvertersOverrideTest.xml"); } @Test public void testConvertersShouldBeAddedAutomaticBySpring() throws Exception { Country country = context.getTypeConverter().convertTo(Country.class, "en"); assertNotNull(country); assertEquals("en", country.getIso()); assertEquals("Country:en", country.getName()); String iso = context.getTypeConverter().convertTo(String.class, country); assertNotNull(iso); assertEquals("en", iso); } }
SpringTypeConvertersOverrideTest
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealm.java
{ "start": 1546, "end": 15862 }
class ____ extends UsernamePasswordRealm implements CachingRealm { private final Cache<String, ListenableFuture<CachedResult>> cache; private final ThreadPool threadPool; private final boolean authenticationEnabled; final Hasher cacheHasher; protected CachingUsernamePasswordRealm(RealmConfig config, ThreadPool threadPool) { super(config); cacheHasher = Hasher.resolve(this.config.getSetting(CachingUsernamePasswordRealmSettings.CACHE_HASH_ALGO_SETTING)); this.threadPool = threadPool; final TimeValue ttl = this.config.getSetting(CachingUsernamePasswordRealmSettings.CACHE_TTL_SETTING); if (ttl.getNanos() > 0) { cache = CacheBuilder.<String, ListenableFuture<CachedResult>>builder() .setExpireAfterWrite(ttl) .setMaximumWeight(this.config.getSetting(CachingUsernamePasswordRealmSettings.CACHE_MAX_USERS_SETTING)) .build(); } else { cache = null; } this.authenticationEnabled = config.getSetting(CachingUsernamePasswordRealmSettings.AUTHC_ENABLED_SETTING); } @Override public final void expire(String username) { if (cache != null) { logger.trace("invalidating cache for user [{}] in realm [{}]", username, name()); cache.invalidate(username); } } @Override public final void expireAll() { if (cache != null) { logger.trace("invalidating cache for all users in realm [{}]", name()); cache.invalidateAll(); } } @Override public UsernamePasswordToken token(ThreadContext threadContext) { if (authenticationEnabled == false) { return null; } return super.token(threadContext); } @Override public boolean supports(AuthenticationToken token) { return authenticationEnabled && super.supports(token); } /** * If the user exists in the cache (keyed by the principle name), then the password is validated * against a hash also stored in the cache. Otherwise the subclass authenticates the user via * doAuthenticate. * This method will respond with {@link AuthenticationResult#notHandled()} if * {@link CachingUsernamePasswordRealmSettings#AUTHC_ENABLED_SETTING authentication is not enabled}. * @param authToken The authentication token * @param listener to be called at completion */ @Override public final void authenticate(AuthenticationToken authToken, ActionListener<AuthenticationResult<User>> listener) { if (authenticationEnabled == false) { listener.onResponse(AuthenticationResult.notHandled()); return; } final UsernamePasswordToken token = (UsernamePasswordToken) authToken; try { if (cache == null) { doAuthenticate(token, listener); } else { authenticateWithCache(token, listener); } } catch (final Exception e) { // each realm should handle exceptions, if we get one here it should be considered fatal listener.onFailure(e); } } /** * This validates the {@code token} while making sure there is only one inflight * request to the authentication source. Only successful responses are cached * and any subsequent requests, bearing the <b>same</b> password, will succeed * without reaching to the authentication source. A different password in a * subsequent request, however, will clear the cache and <b>try</b> to reach to * the authentication source. * * @param token The authentication token * @param listener to be called at completion */ private void authenticateWithCache(UsernamePasswordToken token, ActionListener<AuthenticationResult<User>> listener) { assert cache != null; try { final AtomicBoolean authenticationInCache = new AtomicBoolean(true); final ListenableFuture<CachedResult> listenableCacheEntry = cache.computeIfAbsent(token.principal(), k -> { authenticationInCache.set(false); return new ListenableFuture<>(); }); if (authenticationInCache.get()) { // there is a cached or an inflight authenticate request listenableCacheEntry.addListener(ActionListener.wrap(cachedResult -> { final boolean credsMatch = cachedResult.verify(token.credentials()); if (cachedResult.authenticationResult.isAuthenticated()) { if (credsMatch) { // cached credential hash matches the credential hash for this forestalled request handleCachedAuthentication(cachedResult.user, ActionListener.wrap(authResult -> { if (authResult.isAuthenticated()) { logger.debug( "realm [{}] authenticated user [{}], with roles [{}] (cached)", name(), token.principal(), authResult.getValue().roles() ); } else { logger.debug( "realm [{}] authenticated user [{}] from cache, but then failed [{}]", name(), token.principal(), authResult.getMessage() ); } listener.onResponse(authResult); }, listener::onFailure)); } else { logger.trace( "realm [{}], provided credentials for user [{}] do not match (known good) cached credentials," + " invalidating cache and retrying", name(), token.principal() ); // its credential hash does not match the // hash of the credential for this forestalled request. // clear cache and try to reach the authentication source again because password // might have changed there and the local cached hash got stale cache.invalidate(token.principal(), listenableCacheEntry); authenticateWithCache(token, listener); } } else if (credsMatch) { // not authenticated but instead of hammering reuse the result. a new // request will trigger a retried auth logger.trace( "realm [{}], provided credentials for user [{}] are invalid (cached result) status:[{}] message:[{}]", name(), token.principal(), cachedResult.authenticationResult.getStatus(), cachedResult.authenticationResult.getMessage() ); listener.onResponse(cachedResult.authenticationResult); } else { logger.trace( "realm [{}], provided credentials for user [{}] do not match (possibly invalid) cached credentials," + " invalidating cache and retrying", name(), token.principal() ); cache.invalidate(token.principal(), listenableCacheEntry); authenticateWithCache(token, listener); } }, listener::onFailure), threadPool.executor(ThreadPool.Names.GENERIC), threadPool.getThreadContext()); } else { logger.trace( "realm [{}] does not have a cached result for user [{}]; attempting fresh authentication", name(), token.principal() ); // attempt authentication against the authentication source doAuthenticate(token, ActionListener.wrap(authResult -> { if (authResult.isAuthenticated() == false) { logger.trace("realm [{}] did not authenticate user [{}] ([{}])", name(), token.principal(), authResult); // a new request should trigger a new authentication cache.invalidate(token.principal(), listenableCacheEntry); } else if (authResult.getValue().enabled() == false) { logger.debug( "realm [{}] cannot authenticate [{}], user is not enabled ([{}])", name(), token.principal(), authResult.getValue() ); // a new request should trigger a new authentication cache.invalidate(token.principal(), listenableCacheEntry); } else { logger.debug("realm [{}], successful authentication [{}] for [{}]", name(), authResult, token.principal()); } // notify any forestalled request listeners; they will not reach to the // authentication request and instead will use this result if they contain // the same credentials listenableCacheEntry.onResponse(new CachedResult(authResult, cacheHasher, authResult.getValue(), token.credentials())); listener.onResponse(authResult); }, e -> { cache.invalidate(token.principal(), listenableCacheEntry); // notify any staved off listeners; they will propagate this error listenableCacheEntry.onFailure(e); // notify the listener of the inflight authentication request listener.onFailure(e); })); } } catch (final ExecutionException e) { listener.onFailure(e); } } /** * {@code handleCachedAuthentication} is called when a {@link User} is retrieved from the cache. * The first {@code user} parameter is the user object that was found in the cache. * The default implementation returns a {@link AuthenticationResult#success(Object) success result} with the * provided user, but sub-classes can return a different {@code User} object, or an unsuccessful result. */ protected void handleCachedAuthentication(User user, ActionListener<AuthenticationResult<User>> listener) { listener.onResponse(AuthenticationResult.success(user)); } @Override public void usageStats(ActionListener<Map<String, Object>> listener) { super.usageStats(ActionListener.wrap(stats -> { stats.put("cache", Collections.singletonMap("size", getCacheSize())); listener.onResponse(stats); }, listener::onFailure)); } protected int getCacheSize() { return cache == null ? -1 : cache.count(); } protected abstract void doAuthenticate(UsernamePasswordToken token, ActionListener<AuthenticationResult<User>> listener); @Override public final void lookupUser(String username, ActionListener<User> listener) { try { if (cache == null) { doLookupUser(username, listener); } else { lookupWithCache(username, listener); } } catch (final Exception e) { // each realm should handle exceptions, if we get one here it should be // considered fatal listener.onFailure(e); } } private void lookupWithCache(String username, ActionListener<User> listener) { assert cache != null; try { final AtomicBoolean lookupInCache = new AtomicBoolean(true); final ListenableFuture<CachedResult> listenableCacheEntry = cache.computeIfAbsent(username, key -> { lookupInCache.set(false); return new ListenableFuture<>(); }); if (false == lookupInCache.get()) { // attempt lookup against the user directory doLookupUser(username, ActionListener.wrap(user -> { final CachedResult result = new CachedResult(AuthenticationResult.notHandled(), cacheHasher, user, null); if (user == null) { // user not found, invalidate cache so that subsequent requests are forwarded to // the user directory cache.invalidate(username, listenableCacheEntry); } // notify forestalled request listeners listenableCacheEntry.onResponse(result); }, e -> { // the next request should be forwarded, not halted by a failed lookup attempt cache.invalidate(username, listenableCacheEntry); // notify forestalled listeners listenableCacheEntry.onFailure(e); })); } listenableCacheEntry.addListener(ActionListener.wrap(cachedResult -> { if (cachedResult.user != null) { listener.onResponse(cachedResult.user); } else { listener.onResponse(null); } }, listener::onFailure), threadPool.executor(ThreadPool.Names.GENERIC), threadPool.getThreadContext()); } catch (final ExecutionException e) { listener.onFailure(e); } } protected abstract void doLookupUser(String username, ActionListener<User> listener); private static
CachingUsernamePasswordRealm
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/server/StreamManager.java
{ "start": 1513, "end": 3925 }
class ____ { /** * Called in response to a fetchChunk() request. The returned buffer will be passed as-is to the * client. A single stream will be associated with a single TCP connection, so this method * will not be called in parallel for a particular stream. * * Chunks may be requested in any order, and requests may be repeated, but it is not required * that implementations support this behavior. * * The returned ManagedBuffer will be release()'d after being written to the network. * * @param streamId id of a stream that has been previously registered with the StreamManager. * @param chunkIndex 0-indexed chunk of the stream that's requested */ public abstract ManagedBuffer getChunk(long streamId, int chunkIndex); /** * Called in response to a stream() request. The returned data is streamed to the client * through a single TCP connection. * * Note the <code>streamId</code> argument is not related to the similarly named argument in the * {@link #getChunk(long, int)} method. * * @param streamId id of a stream that has been previously registered with the StreamManager. * @return A managed buffer for the stream, or null if the stream was not found. */ public ManagedBuffer openStream(String streamId) { throw new UnsupportedOperationException(); } /** * Indicates that the given channel has been terminated. After this occurs, we are guaranteed not * to read from the associated streams again, so any state can be cleaned up. */ public void connectionTerminated(Channel channel) { } /** * Verify that the client is authorized to read from the given stream. * * @throws SecurityException If client is not authorized. */ public void checkAuthorization(TransportClient client, long streamId) { } /** * Return the number of chunks being transferred and not finished yet in this StreamManager. */ public long chunksBeingTransferred() { return 0; } /** * Called when start sending a chunk. */ public void chunkBeingSent(long streamId) { } /** * Called when start sending a stream. */ public void streamBeingSent(String streamId) { } /** * Called when a chunk is successfully sent. */ public void chunkSent(long streamId) { } /** * Called when a stream is successfully sent. */ public void streamSent(String streamId) { } }
StreamManager
java
quarkusio__quarkus
test-framework/common/src/main/java/io/quarkus/test/common/TestInstantiator.java
{ "start": 232, "end": 1341 }
class ____ { private static final Logger log = Logger.getLogger(TestInstantiator.class); public static Object instantiateTest(Class<?> testClass, ClassLoader classLoader) { try { Class<?> actualTestClass = Class.forName(testClass.getName(), true, Thread.currentThread().getContextClassLoader()); Class<?> delegate = Thread.currentThread().getContextClassLoader() .loadClass("io.quarkus.test.common.TestInstantiator$Delegate"); Method instantiate = delegate.getMethod("instantiate", Class.class); return instantiate.invoke(null, actualTestClass); } catch (Exception e) { log.warn("Failed to initialize test as a CDI bean, falling back to direct initialization", e); try { Constructor<?> ctor = testClass.getDeclaredConstructor(); ctor.setAccessible(true); return ctor.newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } } } // this
TestInstantiator
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/ElasticsearchException.java
{ "start": 4390, "end": 16560 }
class ____ extends RuntimeException implements ToXContentFragment, Writeable { /** * Passed in the {@link Params} of {@link #generateThrowableXContent(XContentBuilder, Params, Throwable)} * to control if the {@code caused_by} element should render. Unlike most parameters to {@code toXContent} methods this parameter is * internal only and not available as a URL parameter. */ public static final String REST_EXCEPTION_SKIP_CAUSE = "rest.exception.cause.skip"; /** * Passed in the {@link Params} of {@link #generateThrowableXContent(XContentBuilder, Params, Throwable)} * to control if the {@code stack_trace} element should render. Unlike most parameters to {@code toXContent} methods this parameter is * internal only and not available as a URL parameter. Use the {@code error_trace} parameter instead. */ public static final String REST_EXCEPTION_SKIP_STACK_TRACE = "rest.exception.stacktrace.skip"; public static final boolean REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT = true; private static final boolean REST_EXCEPTION_SKIP_CAUSE_DEFAULT = false; private static final String INDEX_METADATA_KEY = "es.index"; private static final String INDEX_METADATA_KEY_UUID = "es.index_uuid"; private static final String SHARD_METADATA_KEY = "es.shard"; private static final String RESOURCE_METADATA_TYPE_KEY = "es.resource.type"; private static final String RESOURCE_METADATA_ID_KEY = "es.resource.id"; private static final String TYPE = "type"; private static final String REASON = "reason"; private static final String TIMED_OUT = "timed_out"; private static final String CAUSED_BY = "caused_by"; private static final ParseField SUPPRESSED = new ParseField("suppressed"); public static final String STACK_TRACE = "stack_trace"; private static final String HEADER = "header"; private static final String ERROR = "error"; private static final String ROOT_CAUSE = "root_cause"; static final String TIMED_OUT_HEADER = "X-Timed-Out"; static final String EXCEPTION_TYPE_HEADER = "X-Elastic-App-Exception"; private static final Map<Integer, CheckedFunction<StreamInput, ? extends ElasticsearchException, IOException>> ID_TO_SUPPLIER; private static final Map<Class<? extends ElasticsearchException>, ElasticsearchExceptionHandle> CLASS_TO_ELASTICSEARCH_EXCEPTION_HANDLE; private final Map<String, List<String>> metadata = new HashMap<>(); private final Map<String, List<String>> bodyHeaders = new HashMap<>(); private final Map<String, List<String>> httpHeaders = new HashMap<>(); /** * Construct a <code>ElasticsearchException</code> with the specified cause exception. */ @SuppressWarnings("this-escape") public ElasticsearchException(Throwable cause) { super(cause); } /** * Construct a <code>ElasticsearchException</code> with the specified detail message. * * The message can be parameterized using <code>{}</code> as placeholders for the given * arguments * * @param msg the detail message * @param args the arguments for the message */ @SuppressWarnings("this-escape") public ElasticsearchException(String msg, Object... args) { super(LoggerMessageFormat.format(msg, args)); } /** * Construct a <code>ElasticsearchException</code> with the specified detail message * and nested exception. * * The message can be parameterized using <code>{}</code> as placeholders for the given * arguments * * @param msg the detail message * @param cause the nested exception * @param args the arguments for the message */ @SuppressWarnings("this-escape") public ElasticsearchException(String msg, Throwable cause, Object... args) { super(LoggerMessageFormat.format(msg, args), cause); } @SuppressWarnings("this-escape") public ElasticsearchException(StreamInput in) throws IOException { super(in.readOptionalString(), in.readException()); readStackTrace(this, in); bodyHeaders.putAll(in.readMapOfLists(StreamInput::readString)); metadata.putAll(in.readMapOfLists(StreamInput::readString)); } private void maybeAddErrorHeaders() { if (isTimeout()) { // see https://www.rfc-editor.org/rfc/rfc8941.html#section-4.1.9 for booleans in structured headers bodyHeaders.put(TIMED_OUT_HEADER, List.of("?1")); } if (httpHeaders.containsKey(EXCEPTION_TYPE_HEADER) == false) { // TODO: cache unwrapping the cause? we do this in several places... Throwable cause = unwrapCause(); RestStatus status = ExceptionsHelper.status(cause); if (status.getStatus() >= 500) { httpHeaders.put(EXCEPTION_TYPE_HEADER, List.of(cause.getClass().getSimpleName())); } } } /** * Adds a new piece of metadata with the given key. * If the provided key is already present, the corresponding metadata will be replaced */ public void addMetadata(String key, String... values) { addMetadata(key, Arrays.asList(values)); } /** * Adds a new piece of metadata with the given key. * If the provided key is already present, the corresponding metadata will be replaced */ public void addMetadata(String key, List<String> values) { // we need to enforce this otherwise bw comp doesn't work properly, as "es." was the previous criteria to split headers in two sets if (key.startsWith("es.") == false) { throw new IllegalArgumentException("exception metadata must start with [es.], found [" + key + "] instead"); } this.metadata.put(key, values); } /** * Returns a set of all metadata keys on this exception */ public Set<String> getMetadataKeys() { return metadata.keySet(); } /** * Returns the list of metadata values for the given key or {@code null} if no metadata for the * given key exists. */ public List<String> getMetadata(String key) { return metadata.get(key); } protected Map<String, List<String>> getMetadata() { return metadata; } /** * Adds a new header with the given key that is part of the response body and http headers. * This method will replace existing header if a header with the same key already exists */ public void addBodyHeader(String key, List<String> value) { // we need to enforce this otherwise bw comp doesn't work properly, as "es." was the previous criteria to split headers in two sets if (key.startsWith("es.")) { throw new IllegalArgumentException("exception headers must not start with [es.], found [" + key + "] instead"); } this.bodyHeaders.put(key, value); } /** * Adds a new header with the given key that is part of the response body and http headers. * This method will replace existing header if a header with the same key already exists */ public void addBodyHeader(String key, String... value) { addBodyHeader(key, Arrays.asList(value)); } /** * Returns a set of all body header keys on this exception */ public Set<String> getBodyHeaderKeys() { maybeAddErrorHeaders(); return bodyHeaders.keySet(); } /** * Returns the list of body header values for the given key or {@code null} if no header for the * given key exists. */ public List<String> getBodyHeader(String key) { maybeAddErrorHeaders(); return bodyHeaders.get(key); } protected Map<String, List<String>> getBodyHeaders() { maybeAddErrorHeaders(); return bodyHeaders; } /** * Adds a new http header with the given key. * This method will replace existing http header if a header with the same key already exists */ public void addHttpHeader(String key, List<String> value) { this.httpHeaders.put(key, value); } /** * Adds a new http header with the given key. * This method will replace existing http header if a header with the same key already exists */ public void addHttpHeader(String key, String... value) { this.httpHeaders.put(key, List.of(value)); } /** * Returns a set of all body header keys on this exception */ public Set<String> getHttpHeaderKeys() { maybeAddErrorHeaders(); return httpHeaders.keySet(); } /** * Returns the list of http header values for the given key or {@code null} if no header for the * given key exists. */ public List<String> getHttpHeader(String key) { maybeAddErrorHeaders(); return httpHeaders.get(key); } protected Map<String, List<String>> getHttpHeaders() { maybeAddErrorHeaders(); return httpHeaders; } /** * Returns the rest status code associated with this exception. */ public RestStatus status() { Throwable cause = unwrapCause(); if (cause == this) { return RestStatus.INTERNAL_SERVER_ERROR; } else { return ExceptionsHelper.status(cause); } } /** * Returns whether this exception represents a timeout. */ public boolean isTimeout() { return false; } /** * Unwraps the actual cause from the exception for cases when the exception is a * {@link ElasticsearchWrapperException}. * * @see ExceptionsHelper#unwrapCause(Throwable) */ public Throwable unwrapCause() { return ExceptionsHelper.unwrapCause(this); } /** * Return the detail message, including the message from the nested exception * if there is one. */ public String getDetailedMessage() { if (getCause() != null) { StringBuilder sb = new StringBuilder(); sb.append(this).append("; "); if (getCause() instanceof ElasticsearchException) { sb.append(((ElasticsearchException) getCause()).getDetailedMessage()); } else { sb.append(getCause()); } return sb.toString(); } else { return super.toString(); } } /** * Retrieve the innermost cause of this exception, if none, returns the current exception. */ public Throwable getRootCause() { Throwable rootCause = this; Throwable cause = getCause(); while (cause != null && cause != rootCause) { rootCause = cause; cause = cause.getCause(); } return rootCause; } @Override public final void writeTo(StreamOutput out) throws IOException { writeTo(out, createNestingFunction(0, () -> {})); } private static Writer<Throwable> createNestingFunction(int thisLevel, Runnable nestedExceptionLimitCallback) { int nextLevel = thisLevel + 1; return (o, t) -> { writeException(t.getCause(), o, nextLevel, nestedExceptionLimitCallback); writeStackTraces(t, o, (no, nt) -> writeException(nt, no, nextLevel, nestedExceptionLimitCallback)); }; } protected void writeTo(StreamOutput out, Writer<Throwable> nestedExceptionsWriter) throws IOException { out.writeOptionalString(this.getMessage()); nestedExceptionsWriter.write(out, this); out.writeMap(bodyHeaders, StreamOutput::writeStringCollection); out.writeMap(metadata, StreamOutput::writeStringCollection); } public static ElasticsearchException readException(StreamInput input, int id) throws IOException { CheckedFunction<StreamInput, ? extends ElasticsearchException, IOException> elasticsearchException = ID_TO_SUPPLIER.get(id); if (elasticsearchException == null) { throw new IllegalStateException("unknown exception for id: " + id); } return elasticsearchException.apply(input); } /** * Returns <code>true</code> iff the given
ElasticsearchException
java
apache__camel
components/camel-atmosphere-websocket/src/generated/java/org/apache/camel/component/atmosphere/websocket/WebsocketEndpointConfigurer.java
{ "start": 747, "end": 3031 }
class ____ extends ServletEndpointConfigurer implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { WebsocketEndpoint target = (WebsocketEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeendpoint": case "bridgeEndpoint": target.setBridgeEndpoint(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "sendtoall": case "sendToAll": target.setSendToAll(property(camelContext, boolean.class, value)); return true; case "usestreaming": case "useStreaming": target.setUseStreaming(property(camelContext, boolean.class, value)); return true; default: return super.configure(camelContext, obj, name, value, ignoreCase); } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeendpoint": case "bridgeEndpoint": return boolean.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "sendtoall": case "sendToAll": return boolean.class; case "usestreaming": case "useStreaming": return boolean.class; default: return super.getOptionType(name, ignoreCase); } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { WebsocketEndpoint target = (WebsocketEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeendpoint": case "bridgeEndpoint": return target.isBridgeEndpoint(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "sendtoall": case "sendToAll": return target.isSendToAll(); case "usestreaming": case "useStreaming": return target.isUseStreaming(); default: return super.getOptionValue(obj, name, ignoreCase); } } }
WebsocketEndpointConfigurer
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullable.java
{ "start": 7460, "end": 20414 }
enum ____ and throws an exception for non-MyEnum values. Also, we * assume that no one minds annotating methods like ImmutableMap.put() with * @Nullable even though they always throw an exception instead of returning. */ streamElements(state, "java.util.Map") .filter( m -> hasName(m, "get") || hasName(m, "put") || hasName(m, "putIfAbsent") || (hasName(m, "remove") && hasParams(m, 1)) || (hasName(m, "replace") && hasParams(m, 2))), streamElements(state, "com.google.common.collect.BiMap") .filter(m -> hasName(m, "forcePut")), streamElements(state, "com.google.common.collect.Table") .filter( m -> hasName(m, "get") || hasName(m, "put") || hasName(m, "remove")), streamElements(state, "com.google.common.cache.Cache") .filter(m -> hasName(m, "getIfPresent")), /* * We assume that no one is implementing a never-empty Queue, etc. -- or at * least that no one minds annotating its return types with @Nullable anyway. */ streamElements(state, "java.util.Queue") .filter(m -> hasName(m, "poll") || hasName(m, "peek")), streamElements(state, "java.util.Deque") .filter( m -> hasName(m, "pollFirst") || hasName(m, "peekFirst") || hasName(m, "pollLast") || hasName(m, "peekLast")), streamElements(state, "java.util.NavigableSet") .filter( m -> hasName(m, "lower") || hasName(m, "floor") || hasName(m, "ceiling") || hasName(m, "higher") || hasName(m, "pollFirst") || hasName(m, "pollLast")), streamElements(state, "java.util.NavigableMap") .filter( m -> hasName(m, "lowerEntry") || hasName(m, "floorEntry") || hasName(m, "ceilingEntry") || hasName(m, "higherEntry") || hasName(m, "lowerKey") || hasName(m, "floorKey") || hasName(m, "ceilingKey") || hasName(m, "higherKey") || hasName(m, "firstEntry") || hasName(m, "lastEntry") || hasName(m, "pollFirstEntry") || hasName(m, "pollLastEntry")), // We assume no one is implementing an infinite Spliterator. streamElements(state, "java.util.Spliterator") .filter(m -> hasName(m, "trySplit"))) /* * TODO(cpovirk): Consider AbstractIterator.computeNext(). * */ .map(MethodSymbol.class::cast) .collect(toImmutableSet())); private final boolean beingConservative; @Inject ReturnMissingNullable(ErrorProneFlags flags) { this.beingConservative = nullnessChecksShouldBeConservative(flags); } @Override public Description matchCompilationUnit( CompilationUnitTree tree, VisitorState stateForCompilationUnit) { if (beingConservative && stateForCompilationUnit.errorProneOptions().isTestOnlyTarget()) { // Annotating test code for nullness can be useful, but it's not our primary focus. return NO_MATCH; } /* * In each scanner below, we define helper methods so that we can return early without the * verbosity of `return super.visitFoo(...)`. */ ImmutableSet.Builder<VarSymbol> definitelyNullVarsBuilder = ImmutableSet.builder(); new TreePathScanner<Void, Void>() { @Override public Void visitVariable(VariableTree tree, Void unused) { doVisitVariable(tree); return super.visitVariable(tree, null); } void doVisitVariable(VariableTree tree) { VarSymbol symbol = getSymbol(tree); if (!isConsideredFinal(symbol)) { return; } ExpressionTree initializer = tree.getInitializer(); if (initializer == null) { return; } if (initializer.getKind() != NULL_LITERAL) { return; } definitelyNullVarsBuilder.add(symbol); } }.scan(tree, null); ImmutableSet<VarSymbol> definitelyNullVars = definitelyNullVarsBuilder.build(); new SuppressibleTreePathScanner<Void, Void>(stateForCompilationUnit) { @Override public Void visitBlock(BlockTree block, Void unused) { for (StatementTree statement : block.getStatements()) { if (METHODS_THAT_NEVER_RETURN.matches(statement, stateForCompilationUnit)) { break; } if (FAILS_IF_PASSED_FALSE.matches(statement, stateForCompilationUnit) && constValue( ((MethodInvocationTree) ((ExpressionStatementTree) statement).getExpression()) .getArguments() .getFirst()) == FALSE) { break; } scan(statement, null); } return null; } @Override public Void visitMethod(MethodTree tree, Void unused) { doVisitMethod(tree); return super.visitMethod(tree, null); } void doVisitMethod(MethodTree tree) { if (beingConservative) { /* * In practice, we don't see any of the cases in which a compliant implementation of a * method like Map.get would never return null. But we do see cases in which people have * implemented Map.get to handle non-existent keys by returning "new Foo()" or by throwing * IllegalArgumentException. Presumably, users of such methods would not be thrilled if we * added @Nullable to their return types, given the effort that the types have gone to not * to ever return null. So we avoid making such changes in conservative mode. */ return; } MethodSymbol possibleOverride = getSymbol(tree); /* * TODO(cpovirk): Provide an option to shortcut if !hasAnnotation(possibleOverride, * Override.class). NullAway makes this assumption for performance reasons, so we could * follow suit, at least for compile-time checking. (Maybe this will confuse someone * someday, but hopefully Error Prone users are saved by the MissingOverride check.) We * should still retain the *option* to check for overriding even in the absence of an * annotation (in order to serve the case of running this in refactoring/patch mode over a * codebase). */ if (isAlreadyAnnotatedNullable(possibleOverride)) { return; } if (tree.getBody() != null && tree.getBody().getStatements().size() == 1 && getOnlyElement(tree.getBody().getStatements()) instanceof ThrowTree) { return; } if (hasAnnotation( tree, "com.google.errorprone.annotations.DoNotCall", stateForCompilationUnit)) { return; } for (MethodSymbol methodKnownToReturnNull : METHODS_KNOWN_TO_RETURN_NULL.get(stateForCompilationUnit)) { if (stateForCompilationUnit .getElements() .overrides(possibleOverride, methodKnownToReturnNull, possibleOverride.enclClass())) { SuggestedFix fix = fixByAddingNullableAnnotationToReturnType( stateForCompilationUnit.withPath(getCurrentPath()), tree); if (!fix.isEmpty()) { stateForCompilationUnit.reportMatch( buildDescription(tree) .setMessage( "Nearly all implementations of this method must return null, but it is" + " not annotated @Nullable") .addFix(fix) .build()); } } } } @Override public Void visitReturn(ReturnTree tree, Void unused) { doVisitReturn(tree); return super.visitReturn(tree, null); } void doVisitReturn(ReturnTree returnTree) { /* * We need the VisitorState to have the correct TreePath for (a) the call to * findEnclosingMethod and (b) the call to NullnessFixes (which looks up identifiers). */ VisitorState state = stateForCompilationUnit.withPath(getCurrentPath()); ExpressionTree returnExpression = returnTree.getExpression(); if (returnExpression == null) { return; } MethodTree methodTree = findEnclosingMethod(state); if (methodTree == null) { return; } MethodSymbol method = getSymbol(methodTree); List<? extends StatementTree> statements = methodTree.getBody().getStatements(); if (beingConservative && statements.size() == 1 && getOnlyElement(statements) == returnTree && returnExpression.getKind() == NULL_LITERAL && methodCanBeOverridden(method)) { /* * When the entire body of an overrideable method is `return null`, we are sometimes * looking at a "stub" implementation that all "real" implementations are meant to * override. Ideally such stubs would use implementation like `throw new * UnsupportedOperationException()`, but we see `return null` often enough in practice * that it warrants a special case when running in conservative mode. */ return; } Type returnType = method.getReturnType(); if (beingConservative && isVoid(returnType, state)) { // `@Nullable Void` is accurate but noisy, so some users won't want it. return; } if (returnType.isPrimitive()) { // Buggy code, but adding @Nullable just makes it worse. return; } if (beingConservative && returnType.getKind() == TYPEVAR) { /* * Consider AbstractFuture.getDoneValue: It returns a literal `null`, but it shouldn't be * annotated @Nullable because it returns null *only* if the AbstractFuture's type * argument permits that. */ return; } if (isAlreadyAnnotatedNullable(method)) { return; } ImmutableSet<Name> varsProvenNullByParentIf = varsProvenNullByParentIf(getCurrentPath()); /* * TODO(cpovirk): Consider reporting only one finding per method? Our patching * infrastructure is smart enough not to mind duplicate suggested fixes, but users might be * annoyed by multiple robocomments with the same fix. */ if (hasDefinitelyNullBranch( returnExpression, definitelyNullVars, varsProvenNullByParentIf, stateForCompilationUnit)) { SuggestedFix fix = fixByAddingNullableAnnotationToReturnType( state.withPath(getCurrentPath()), methodTree); if (!fix.isEmpty()) { state.reportMatch(describeMatch(returnTree, fix)); } } } }.scan(tree, null); return NO_MATCH; // Any reports were made through state.reportMatch. } private static boolean hasName(Symbol symbol, String name) { return symbol.name.contentEquals(name); } private static boolean hasParams(Symbol method, int paramCount) { return ((MethodSymbol) method).getParameters().size() == paramCount; } private static Stream<Symbol> streamElements(VisitorState state, String clazz) { Symbol symbol = state.getSymbolFromString(clazz); return symbol == null ? Stream.empty() : getEnclosedElements(symbol).stream(); } }
constant
java
reactor__reactor-core
reactor-core/src/withMicrometerTest/java/reactor/core/publisher/FluxTapTest.java
{ "start": 24314, "end": 25344 }
class ____ { //TODO test tryOnNext @Test void implementationSmokeTest() { Flux<Integer> fuseableSource = Flux.just(1); //the TestSubscriber "requireFusion" configuration below is intentionally inverted //so that an exception describing the actual Subscription is thrown when calling block() TestSubscriber<Integer> conditionalTestSubscriberForFuseable = TestSubscriber.builder().requireNotFuseable().buildConditional(i -> true); Flux<Integer> fuseable = fuseableSource.tap(TestSignalListener::new); assertThat(fuseableSource).as("smoke test fuseableSource").isInstanceOf(Fuseable.class); assertThat(fuseable).as("fuseable").isInstanceOf(FluxTapFuseable.class); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> fuseable.subscribeWith(conditionalTestSubscriberForFuseable).block()) .as("TapConditionalFuseableSubscriber") .withMessageContaining("got reactor.core.publisher.FluxTapFuseable$TapConditionalFuseableSubscriber"); } } @Nested
FluxTapConditionalFuseableTest
java
quarkusio__quarkus
extensions/azure-functions/deployment/src/main/java/io/quarkus/azure/functions/deployment/AzureFunctionsConfig.java
{ "start": 1583, "end": 3707 }
interface ____ { /** * App name for azure function project. This is required setting. * * Defaults to the base artifact name */ Optional<String> appName(); /** * Azure Resource Group for your Azure Functions */ @WithDefault("quarkus") String resourceGroup(); /** * Specifies the region where your Azure Functions will be hosted; default value is westus. * <a href= * "https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-regions">Valid * values</a> */ @WithDefault("westus") String region(); /** * Specifies whether to disable application insights for your function app */ @WithDefault("false") boolean disableAppInsights(); /** * Specifies the instrumentation key of application insights which will bind to your function app */ Optional<String> appInsightsKey(); RuntimeConfig runtime(); AuthConfig auth(); /** * Specifies the name of the existing App Service Plan when you do not want to create a new one. */ @WithDefault("java-functions-app-service-plan") String appServicePlanName(); /** * The app service plan resource group. */ Optional<String> appServicePlanResourceGroup(); /** * Azure subscription id. Required only if there are more than one subscription in your account */ Optional<String> subscriptionId(); /** * The pricing tier. */ Optional<String> pricingTier(); /** * Port to run azure function in local runtime. * Will default to quarkus.http.test-port or 8081 */ Optional<Integer> funcPort(); /** * Config String for local debug */ @WithDefault("transport=dt_socket,server=y,suspend=n,address=5005") String localDebugConfig(); /** * Specifies the application settings for your Azure Functions, which are defined in name-value pairs */ @ConfigDocMapKey("setting-name") Map<String, String> appSettings = Collections.emptyMap(); @ConfigGroup
AzureFunctionsConfig
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/SimpleFunctionAuditExpression.java
{ "start": 696, "end": 1449 }
class ____ implements AuditCriterion { private AuditFunction function; private Object value; private String op; public SimpleFunctionAuditExpression(AuditFunction function, Object value, String op) { this.function = function; this.value = value; this.op = op; } @Override public void addToQuery( EnversService enversService, AuditReaderImplementor versionsReader, Map<String, String> aliasToEntityNameMap, Map<String, String> aliasToComponentPropertyNameMap, String baseAlias, QueryBuilder qb, Parameters parameters) { parameters.addWhereWithFunction( enversService.getConfig(), aliasToEntityNameMap, aliasToComponentPropertyNameMap, function, op, value ); } }
SimpleFunctionAuditExpression
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RExpirableAsync.java
{ "start": 884, "end": 6851 }
interface ____ extends RObjectAsync { /** * Use {@link #expireAsync(Duration)} instead * * @param timeToLive - timeout before object will be deleted * @param timeUnit - timeout time unit * @return <code>true</code> if the timeout was set and <code>false</code> if not */ @Deprecated RFuture<Boolean> expireAsync(long timeToLive, TimeUnit timeUnit); /** * Use {@link #expireAsync(Instant)} instead * * @param timestamp - expire date * @return <code>true</code> if the timeout was set and <code>false</code> if not */ @Deprecated RFuture<Boolean> expireAtAsync(Date timestamp); /** * Use {@link #expireAsync(Instant)} instead * * @param timestamp - expire date in milliseconds (Unix timestamp) * @return <code>true</code> if the timeout was set and <code>false</code> if not */ @Deprecated RFuture<Boolean> expireAtAsync(long timestamp); /** * Set an expire date for object. When expire date comes * the key will automatically be deleted. * * @param time - expire date * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireAsync(Instant time); /** * Sets an expiration date for this object only if it has been already set. * When expire date comes the object will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param time expire date * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfSetAsync(Instant time); /** * Sets an expiration date for this object only if it hasn't been set before. * When expire date comes the object will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param time expire date * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfNotSetAsync(Instant time); /** * Sets an expiration date for this object only if it's greater than expiration date set before. * When expire date comes the object will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param time expire date * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfGreaterAsync(Instant time); /** * Sets an expiration date for this object only if it's less than expiration date set before. * When expire date comes the object will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param time expire date * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfLessAsync(Instant time); /** * Set a timeout for object. After the timeout has expired, * the key will automatically be deleted. * * @param duration timeout before object will be deleted * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireAsync(Duration duration); /** * Sets a timeout for this object only if it has been already set. * After the timeout has expired, the key will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param duration timeout before object will be deleted * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfSetAsync(Duration duration); /** * Sets a timeout for this object only if it hasn't been set before. * After the timeout has expired, the key will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param duration timeout before object will be deleted * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfNotSetAsync(Duration duration); /** * Sets a timeout for this object only if it's greater than timeout set before. * After the timeout has expired, the key will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param duration timeout before object will be deleted * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfGreaterAsync(Duration duration); /** * Sets a timeout for this object only if it's less than timeout set before. * After the timeout has expired, the key will automatically be deleted. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @param duration timeout before object will be deleted * @return <code>true</code> if the timeout was set and <code>false</code> if not */ RFuture<Boolean> expireIfLessAsync(Duration duration); /** * Clear an expire timeout or expire date for object in async mode. * Object will not be deleted. * * @return <code>true</code> if the timeout was cleared and <code>false</code> if not */ RFuture<Boolean> clearExpireAsync(); /** * Returns remaining time of the object in milliseconds. * * @return time in milliseconds * -2 if the key does not exist. * -1 if the key exists but has no associated expire. */ RFuture<Long> remainTimeToLiveAsync(); /** * Returns expiration time of the object as the absolute Unix expiration timestamp in milliseconds. * <p> * Requires <b>Redis 7.0.0 and higher.</b> * * @return Unix time in milliseconds * -2 if the key does not exist. * -1 if the key exists but has no associated expiration time. */ RFuture<Long> getExpireTimeAsync(); }
RExpirableAsync
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/function/xml/XmlForestTest.java
{ "start": 863, "end": 1136 }
class ____ { @Test public void testSimple(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-xmlforest-example[] em.createQuery( "select xmlforest(123 as e1, 'text' as e2)" ).getResultList(); //end::hql-xmlforest-example[] } ); } }
XmlForestTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/IdTest.java
{ "start": 2901, "end": 10107 }
class ____ { @Test public void testGenericGenerator(SessionFactoryScope scope) { SoundSystem system = new SoundSystem(); Furniture fur = new Furniture(); scope.inTransaction( session -> { system.setBrand( "Genelec" ); system.setModel( "T234" ); session.persist( system ); session.persist( fur ); } ); scope.inTransaction( session -> { SoundSystem systemfromDb = session.get( SoundSystem.class, system.getId() ); Furniture furFromDb = session.get( Furniture.class, fur.getId() ); assertNotNull( systemfromDb ); assertNotNull( furFromDb ); session.remove( systemfromDb ); session.remove( furFromDb ); } ); } @Test public void testGenericGenerators(SessionFactoryScope scope) { // Ensures that GenericGenerator annotations wrapped inside a GenericGenerators holder are bound correctly scope.inTransaction( session -> { Monkey monkey = new Monkey(); session.persist( monkey ); session.flush(); assertNotNull( monkey.getId() ); } ); scope.inTransaction( session -> session.createQuery( "delete from Monkey" ).executeUpdate() ); } @Test public void testTableGenerator(SessionFactoryScope scope) { Ball b = new Ball(); Dog d = new Dog(); Computer c = new Computer(); scope.inTransaction( session -> { session.persist( b ); session.persist( d ); session.persist( c ); } ); assertEquals( new Integer( 1 ), b.getId(), "table id not generated" ); assertEquals( new Integer( 1 ), d.getId(), "generator should not be shared" ); assertEquals( new Long( 1 ), c.getId(), "default value should work" ); scope.inTransaction( session -> { session.remove( session.get( Ball.class, 1 ) ); session.remove( session.get( Dog.class, 1 ) ); session.remove( session.get( Computer.class, 1L ) ); } ); } @Test public void testSequenceGenerator(SessionFactoryScope scope) { Shoe b = new Shoe(); scope.inTransaction( session -> session.persist( b ) ); assertNotNull( b.getId() ); scope.inTransaction( session -> session.remove( session.get( Shoe.class, b.getId() ) ) ); } @Test public void testClassLevelGenerator(SessionFactoryScope scope) { Store b = new Store(); scope.inTransaction( session -> session.persist( b ) ); assertNotNull( b.getId() ); scope.inTransaction( session -> session.remove( session.get( Store.class, b.getId() ) ) ); } @Test public void testMethodLevelGenerator(SessionFactoryScope scope) { Department b = new Department(); scope.inTransaction( session -> session.persist( b ) ); assertNotNull( b.getId() ); scope.inTransaction( session -> session.remove( session.get( Department.class, b.getId() ) ) ); } @Test public void testDefaultSequence(SessionFactoryScope scope) { Home h = new Home(); scope.inTransaction( session -> session.persist( h ) ); assertNotNull( h.getId() ); scope.inTransaction( session -> { Home reloadedHome = session.get( Home.class, h.getId() ); assertEquals( h.getId(), reloadedHome.getId() ); session.remove( reloadedHome ); } ); } @Test public void testParameterizedAuto(SessionFactoryScope scope) { Home h = new Home(); scope.inTransaction( session -> session.persist( h ) ); assertNotNull( h.getId() ); scope.inTransaction( session -> { Home reloadedHome = session.get( Home.class, h.getId() ); assertEquals( h.getId(), reloadedHome.getId() ); session.remove( reloadedHome ); } ); } @Test public void testIdInEmbeddableSuperclass(SessionFactoryScope scope) { scope.inTransaction( session -> { FirTree christmasTree = new FirTree(); session.persist( christmasTree ); session.getTransaction().commit(); session.clear(); session.beginTransaction(); christmasTree = session.get( FirTree.class, christmasTree.getId() ); assertNotNull( christmasTree ); session.remove( christmasTree ); } ); } @Test public void testIdClass(SessionFactoryScope scope) { scope.inTransaction( session -> { Footballer fb = new Footballer( "David", "Beckam", "Arsenal" ); GoalKeeper keeper = new GoalKeeper( "Fabien", "Bartez", "OM" ); session.persist( fb ); session.persist( keeper ); session.getTransaction().commit(); session.clear(); // lookup by id session.beginTransaction(); FootballerPk fpk = new FootballerPk( "David", "Beckam" ); fb = session.get( Footballer.class, fpk ); FootballerPk fpk2 = new FootballerPk( "Fabien", "Bartez" ); keeper = session.get( GoalKeeper.class, fpk2 ); assertNotNull( fb ); assertNotNull( keeper ); assertEquals( "Beckam", fb.getLastname() ); assertEquals( "Arsenal", fb.getClub() ); assertEquals( 1, session.createQuery( "from Footballer f where f.firstname = 'David'" ) .list().size() ); session.getTransaction().commit(); // reattach by merge session.beginTransaction(); fb.setClub( "Bimbo FC" ); session.merge( fb ); session.getTransaction().commit(); // reattach by saveOrUpdate session.beginTransaction(); fb.setClub( "Bimbo FC SA" ); session.merge( fb ); session.getTransaction().commit(); // clean up session.clear(); session.beginTransaction(); fpk = new FootballerPk( "David", "Beckam" ); fb = session.get( Footballer.class, fpk ); assertEquals( "Bimbo FC SA", fb.getClub() ); session.remove( fb ); session.remove( keeper ); } ); } @Test @JiraKey(value = "HHH-6790") public void testSequencePerEntity(SessionFactoryScope scope) { DedicatedSequenceEntity1 entity1 = new DedicatedSequenceEntity1(); DedicatedSequenceEntity2 entity2 = new DedicatedSequenceEntity2(); scope.inTransaction( session -> { session.persist( entity1 ); session.persist( entity2 ); } ); assertEquals( 1, entity1.getId().intValue() ); assertEquals( 1, entity2.getId().intValue() ); scope.inTransaction( session -> { session.createQuery( "delete from DedicatedSequenceEntity1" ).executeUpdate(); session.createQuery( "delete from " + DedicatedSequenceEntity2.ENTITY_NAME ).executeUpdate(); } ); } @Test public void testColumnDefinition(SessionFactoryScope scope) { Column idCol = (Column) scope.getMetadataImplementor().getEntityBinding( Ball.class.getName() ) .getIdentifierProperty().getValue().getSelectables().get( 0 ); assertEquals( "ball_id", idCol.getName() ); } @Test public void testLowAllocationSize(SessionFactoryScope scope) { scope.inTransaction( session -> { int size = 4; BreakDance[] bds = new BreakDance[size]; for ( int i = 0; i < size; i++ ) { bds[i] = new BreakDance(); session.persist( bds[i] ); } session.flush(); for ( int i = 0; i < size; i++ ) { assertEquals( i + 1, bds[i].id.intValue() ); } } ); scope.inTransaction( session -> session.createQuery( "delete from BreakDance" ).executeUpdate() ); } }
IdTest
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerSplitLogStatement.java
{ "start": 2130, "end": 3192 }
class ____ extends BugChecker implements MethodTreeMatcher, VariableTreeMatcher { private static final Matcher<Tree> IS_LOGGER_API = isSubtypeOf("com.google.common.flogger.LoggingApi"); private static final Matcher<Tree> CLASS_MATCHES = not( anyOf( enclosingClass(isSubtypeOf("com.google.common.flogger.AbstractLogger")), enclosingClass(isSubtypeOf("com.google.common.flogger.LoggingApi")))); private static final Matcher<MethodTree> METHOD_MATCHES = allOf(methodReturns(IS_LOGGER_API), CLASS_MATCHES); private static final Matcher<VariableTree> VARIABLE_MATCHES = allOf(variableType(IS_LOGGER_API), CLASS_MATCHES); @Override public Description matchMethod(MethodTree tree, VisitorState state) { return METHOD_MATCHES.matches(tree, state) ? describeMatch(tree) : NO_MATCH; } @Override public Description matchVariable(VariableTree tree, VisitorState state) { return VARIABLE_MATCHES.matches(tree, state) ? describeMatch(tree) : NO_MATCH; } }
FloggerSplitLogStatement
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java
{ "start": 22847, "end": 25775 }
class ____ extends ParserRuleContext { public FromCommandContext fromCommand() { return getRuleContext(FromCommandContext.class,0); } public RowCommandContext rowCommand() { return getRuleContext(RowCommandContext.class,0); } public ShowCommandContext showCommand() { return getRuleContext(ShowCommandContext.class,0); } public TimeSeriesCommandContext timeSeriesCommand() { return getRuleContext(TimeSeriesCommandContext.class,0); } public ExplainCommandContext explainCommand() { return getRuleContext(ExplainCommandContext.class,0); } @SuppressWarnings("this-escape") public SourceCommandContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_sourceCommand; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterSourceCommand(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitSourceCommand(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitSourceCommand(this); else return visitor.visitChildren(this); } } public final SourceCommandContext sourceCommand() throws RecognitionException { SourceCommandContext _localctx = new SourceCommandContext(_ctx, getState()); enterRule(_localctx, 6, RULE_sourceCommand); try { setState(225); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,2,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(219); fromCommand(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(220); rowCommand(); } break; case 3: enterOuterAlt(_localctx, 3); { setState(221); showCommand(); } break; case 4: enterOuterAlt(_localctx, 4); { setState(222); timeSeriesCommand(); } break; case 5: enterOuterAlt(_localctx, 5); { setState(223); if (!(this.isDevVersion())) throw new FailedPredicateException(this, "this.isDevVersion()"); setState(224); explainCommand(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
SourceCommandContext
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/detached/initialization/DetachedNestedInitializationBatchFetchTest.java
{ "start": 1053, "end": 5915 }
class ____ { @Test public void test1(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.find( EntityB.class, 1L ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.find( EntityB.class, 1L ); fetchQuery( entityB, session ); } ); } @Test public void test2(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.find( EntityB.class, 1L ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.getReference( EntityB.class, 1L ); Hibernate.initialize( ignored ); fetchQuery( entityB, session ); } ); } @Test public void test3(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.find( EntityB.class, 1L ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.getReference( EntityB.class, 1L ); fetchQuery( entityB, session ); } ); } @Test public void test4(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.getReference( EntityB.class, 1L ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.find( EntityB.class, 1L ); fetchQuery( entityB, session ); } ); } @Test public void test5(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.getReference( EntityB.class, 1L ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.getReference( EntityB.class, 1L ); Hibernate.initialize( ignored ); fetchQuery( entityB, session ); } ); } @Test public void test6(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.getReference( EntityB.class, 1L ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.getReference( EntityB.class, 1L ); fetchQuery( entityB, session ); } ); } @Test public void testDetachedEntityJoinFetch(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.getReference( EntityB.class, 1L ); Hibernate.initialize( entityB ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.find( EntityB.class, 1L ); fetchQuery( entityB, session ); } ); } @Test public void testDetachedInitializedProxyJoinFetch(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.getReference( EntityB.class, 1L ); Hibernate.initialize( entityB ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.getReference( EntityB.class, 1L ); Hibernate.initialize( ignored ); fetchQuery( entityB, session ); } ); } @Test public void testDetachedUninitializedProxyJoinFetch(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = session.getReference( EntityB.class, 1L ); Hibernate.initialize( entityB ); session.clear(); // put a different instance of EntityB in the persistence context final var ignored = session.getReference( EntityB.class, 1L ); fetchQuery( entityB, session ); } ); } @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final var entityB = new EntityB(); entityB.id = 1L; entityB.name = "b_1"; session.persist( entityB ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "delete from EntityA" ).executeUpdate(); } ); } private void fetchQuery(EntityB entityB, SessionImplementor session) { final var entityA = new EntityA(); entityA.id = 1L; entityA.b = entityB; session.persist( entityA ); final var entityA2 = new EntityA(); entityA2.id = 2L; session.persist( entityA2 ); final var wasInitialized = Hibernate.isInitialized( entityB ); final var result = session.createQuery( "from EntityA a order by a.id", EntityA.class ).getResultList().get( 0 ); assertThat( Hibernate.isInitialized( entityB ) ).isEqualTo( wasInitialized ); assertThat( result.b ).isSameAs( entityB ); final var id = session.getSessionFactory().getPersistenceUnitUtil().getIdentifier( entityB ); final var reference = session.getReference( EntityB.class, id ); assertThat( Hibernate.isInitialized( reference ) ).isTrue(); assertThat( reference ).isNotSameAs( entityB ); } @Entity(name = "EntityA") static
DetachedNestedInitializationBatchFetchTest
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/TotalProgressListener.java
{ "start": 1228, "end": 2972 }
class ____<E extends ImageProgressUpdateEvent> implements UpdateListener<E> { private final Map<String, Layer> layers = new ConcurrentHashMap<>(); private final Consumer<TotalProgressEvent> consumer; private final String[] trackedStatusKeys; private boolean progressStarted; /** * Create a new {@link TotalProgressListener} that sends {@link TotalProgressEvent * events} to the given consumer. * @param consumer the consumer that receives {@link TotalProgressEvent progress * events} * @param trackedStatusKeys a list of status event keys to track the progress of */ protected TotalProgressListener(Consumer<TotalProgressEvent> consumer, String[] trackedStatusKeys) { this.consumer = consumer; this.trackedStatusKeys = trackedStatusKeys; } @Override public void onStart() { } @Override public void onUpdate(E event) { if (event.getId() != null) { this.layers.computeIfAbsent(event.getId(), (value) -> new Layer(this.trackedStatusKeys)).update(event); } this.progressStarted = this.progressStarted || event.getProgress() != null; if (this.progressStarted) { publish(0); } } @Override public void onFinish() { this.layers.values().forEach(Layer::finish); publish(100); } private void publish(int fallback) { int count = 0; int total = 0; for (Layer layer : this.layers.values()) { count++; total += layer.getProgress(); } TotalProgressEvent event = new TotalProgressEvent( (count != 0) ? withinPercentageBounds(total / count) : fallback); this.consumer.accept(event); } private static int withinPercentageBounds(int value) { return (value < 0) ? 0 : Math.min(value, 100); } /** * Progress for an individual layer. */ private static
TotalProgressListener
java
apache__dubbo
dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java
{ "start": 1074, "end": 1380 }
class ____ implements ScopeModelInitializer { @Override public void initializeApplicationModel(ApplicationModel applicationModel) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); beanFactory.registerBean(MetricsDispatcher.class); } }
MetricsScopeModelInitializer
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
{ "start": 20898, "end": 21053 }
interface ____ other policies like round-robin are less effective * given that we cache connections to datanodes. * * @return one of the local
because
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableMapNavigationTester.java
{ "start": 2055, "end": 9266 }
class ____<K, V> extends AbstractMapTester<K, V> { private NavigableMap<K, V> navigableMap; private List<Entry<K, V>> entries; private Entry<K, V> a; private Entry<K, V> b; private Entry<K, V> c; @Override public void setUp() throws Exception { super.setUp(); navigableMap = (NavigableMap<K, V>) getMap(); entries = copyToList( getSubjectGenerator() .getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements())); sort(entries, Helpers.entryComparator(navigableMap.comparator())); // some tests assume SEVERAL == 3 if (entries.size() >= 1) { a = entries.get(0); if (entries.size() >= 3) { b = entries.get(1); c = entries.get(2); } } } /** Resets the contents of navigableMap to have entries a, c, for the navigation tests. */ @SuppressWarnings("unchecked") // Needed to stop Eclipse whining private void resetWithHole() { Entry<K, V>[] entries = (Entry<K, V>[]) new Entry<?, ?>[] {a, c}; super.resetMap(entries); navigableMap = (NavigableMap<K, V>) getMap(); } @CollectionSize.Require(ZERO) public void testEmptyMapFirst() { assertNull(navigableMap.firstEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptyMapPollFirst() { assertNull(navigableMap.pollFirstEntry()); } @CollectionSize.Require(ZERO) public void testEmptyMapNearby() { assertNull(navigableMap.lowerEntry(k0())); assertNull(navigableMap.lowerKey(k0())); assertNull(navigableMap.floorEntry(k0())); assertNull(navigableMap.floorKey(k0())); assertNull(navigableMap.ceilingEntry(k0())); assertNull(navigableMap.ceilingKey(k0())); assertNull(navigableMap.higherEntry(k0())); assertNull(navigableMap.higherKey(k0())); } @CollectionSize.Require(ZERO) public void testEmptyMapLast() { assertNull(navigableMap.lastEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testEmptyMapPollLast() { assertNull(navigableMap.pollLastEntry()); } @CollectionSize.Require(ONE) public void testSingletonMapFirst() { assertEquals(a, navigableMap.firstEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonMapPollFirst() { assertEquals(a, navigableMap.pollFirstEntry()); assertTrue(navigableMap.isEmpty()); } @CollectionSize.Require(ONE) public void testSingletonMapNearby() { assertNull(navigableMap.lowerEntry(k0())); assertNull(navigableMap.lowerKey(k0())); assertEquals(a, navigableMap.floorEntry(k0())); assertEquals(a.getKey(), navigableMap.floorKey(k0())); assertEquals(a, navigableMap.ceilingEntry(k0())); assertEquals(a.getKey(), navigableMap.ceilingKey(k0())); assertNull(navigableMap.higherEntry(k0())); assertNull(navigableMap.higherKey(k0())); } @CollectionSize.Require(ONE) public void testSingletonMapLast() { assertEquals(a, navigableMap.lastEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testSingletonMapPollLast() { assertEquals(a, navigableMap.pollLastEntry()); assertTrue(navigableMap.isEmpty()); } @CollectionSize.Require(SEVERAL) public void testFirst() { assertEquals(a, navigableMap.firstEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollFirst() { assertEquals(a, navigableMap.pollFirstEntry()); assertEquals(entries.subList(1, entries.size()), copyToList(navigableMap.entrySet())); } @MapFeature.Require(absent = SUPPORTS_REMOVE) public void testPollFirstUnsupported() { assertThrows(UnsupportedOperationException.class, () -> navigableMap.pollFirstEntry()); } @CollectionSize.Require(SEVERAL) public void testLower() { resetWithHole(); assertEquals(null, navigableMap.lowerEntry(a.getKey())); assertEquals(null, navigableMap.lowerKey(a.getKey())); assertEquals(a, navigableMap.lowerEntry(b.getKey())); assertEquals(a.getKey(), navigableMap.lowerKey(b.getKey())); assertEquals(a, navigableMap.lowerEntry(c.getKey())); assertEquals(a.getKey(), navigableMap.lowerKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testFloor() { resetWithHole(); assertEquals(a, navigableMap.floorEntry(a.getKey())); assertEquals(a.getKey(), navigableMap.floorKey(a.getKey())); assertEquals(a, navigableMap.floorEntry(b.getKey())); assertEquals(a.getKey(), navigableMap.floorKey(b.getKey())); assertEquals(c, navigableMap.floorEntry(c.getKey())); assertEquals(c.getKey(), navigableMap.floorKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testCeiling() { resetWithHole(); assertEquals(a, navigableMap.ceilingEntry(a.getKey())); assertEquals(a.getKey(), navigableMap.ceilingKey(a.getKey())); assertEquals(c, navigableMap.ceilingEntry(b.getKey())); assertEquals(c.getKey(), navigableMap.ceilingKey(b.getKey())); assertEquals(c, navigableMap.ceilingEntry(c.getKey())); assertEquals(c.getKey(), navigableMap.ceilingKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testHigher() { resetWithHole(); assertEquals(c, navigableMap.higherEntry(a.getKey())); assertEquals(c.getKey(), navigableMap.higherKey(a.getKey())); assertEquals(c, navigableMap.higherEntry(b.getKey())); assertEquals(c.getKey(), navigableMap.higherKey(b.getKey())); assertEquals(null, navigableMap.higherEntry(c.getKey())); assertEquals(null, navigableMap.higherKey(c.getKey())); } @CollectionSize.Require(SEVERAL) public void testLast() { assertEquals(c, navigableMap.lastEntry()); } @MapFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLast() { assertEquals(c, navigableMap.pollLastEntry()); assertEquals(entries.subList(0, entries.size() - 1), copyToList(navigableMap.entrySet())); } @MapFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLastUnsupported() { assertThrows(UnsupportedOperationException.class, () -> navigableMap.pollLastEntry()); } @CollectionSize.Require(SEVERAL) public void testDescendingNavigation() { List<Entry<K, V>> descending = new ArrayList<>(navigableMap.descendingMap().entrySet()); Collections.reverse(descending); assertEquals(entries, descending); } @CollectionSize.Require(absent = ZERO) public void testHeadMapExclusive() { assertFalse(navigableMap.headMap(a.getKey(), false).containsKey(a.getKey())); } @CollectionSize.Require(absent = ZERO) public void testHeadMapInclusive() { assertTrue(navigableMap.headMap(a.getKey(), true).containsKey(a.getKey())); } @CollectionSize.Require(absent = ZERO) public void testTailMapExclusive() { assertFalse(navigableMap.tailMap(a.getKey(), false).containsKey(a.getKey())); } @CollectionSize.Require(absent = ZERO) public void testTailMapInclusive() { assertTrue(navigableMap.tailMap(a.getKey(), true).containsKey(a.getKey())); } }
NavigableMapNavigationTester
java
apache__camel
components/camel-netty/src/generated/java/org/apache/camel/component/netty/NettyConverterLoader.java
{ "start": 881, "end": 6504 }
class ____ implements TypeConverterLoader, CamelContextAware { private CamelContext camelContext; public NettyConverterLoader() { } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { registerConverters(registry); } private void registerConverters(TypeConverterRegistry registry) { addTypeConverter(registry, byte[].class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toByteArray((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, io.netty.buffer.ByteBuf.class, byte[].class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toByteBuffer((byte[]) value); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, io.netty.buffer.ByteBuf.class, java.lang.String.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toByteBuffer((java.lang.String) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, java.io.InputStream.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toInputStream((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, java.io.ObjectInput.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toObjectInput((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, java.lang.String.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toString((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, javax.xml.transform.dom.DOMSource.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toDOMSource((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, javax.xml.transform.sax.SAXSource.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toSAXSource((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, javax.xml.transform.stax.StAXSource.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toStAXSource((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, javax.xml.transform.stream.StreamSource.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toStreamSource((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.w3c.dom.Document.class, io.netty.buffer.ByteBuf.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.netty.NettyConverter.toDocument((io.netty.buffer.ByteBuf) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); } private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) { registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method)); } }
NettyConverterLoader
java
spring-projects__spring-security
docs/src/test/java/org/springframework/security/docs/features/authentication/password4jpbkdf2/Pbkdf2UsageTests.java
{ "start": 1071, "end": 1722 }
class ____ { @Test void defaultParams() { // tag::default-params[] PasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder(); String result = encoder.encode("myPassword"); assertThat(encoder.matches("myPassword", result)).isTrue(); // end::default-params[] } @Test void customParameters() { // tag::custom-params[] PBKDF2Function pbkdf2Fn = PBKDF2Function.getInstance(Hmac.SHA256, 100000, 256); PasswordEncoder encoder = new Pbkdf2Password4jPasswordEncoder(pbkdf2Fn); String result = encoder.encode("myPassword"); assertThat(encoder.matches("myPassword", result)).isTrue(); // end::custom-params[] } }
Pbkdf2UsageTests
java
apache__dubbo
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/ObservabilityUtils.java
{ "start": 1108, "end": 2102 }
class ____ { public static final String DUBBO_TRACING_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing"; public static final String DUBBO_TRACING_PROPAGATION = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "propagation"; public static final String DUBBO_TRACING_BAGGAGE = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "baggage"; public static final String DUBBO_TRACING_BAGGAGE_CORRELATION = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "correlation"; public static final String DUBBO_TRACING_BAGGAGE_ENABLED = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "enabled"; public static final String DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.zipkin-config"; public static final String DUBBO_TRACING_OTLP_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.otlp-config"; }
ObservabilityUtils
java
elastic__elasticsearch
modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/AugmentedAnnotation.java
{ "start": 742, "end": 1261 }
class ____ { * int MAX_VALUE @augmented[augmented_canonical_class_name="java.lang.Integer"] * int MIN_VALUE @augmented[augmented_canonical_class_name="java.lang.Integer"] * } * ... * * // Script * ... * long value = <some_value>; * int augmented = 0; * if (value < Augmented.MAX_VALUE && value > Augmented.MIN_VALUE) { * augmented = (int)value; * } * ... * } */ public record AugmentedAnnotation(String augmentedCanonicalClassName) { public static final String NAME = "augmented"; }
Augmented
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/AbstractAsyncStateStreamOperatorV2Test.java
{ "start": 33330, "end": 34110 }
class ____ extends AbstractStreamOperatorFactory<String> { private final ElementOrder elementOrder; TestWithAsyncProcessTimerOperatorFactory(ElementOrder elementOrder) { this.elementOrder = elementOrder; } @Override public <T extends StreamOperator<String>> T createStreamOperator( StreamOperatorParameters<String> parameters) { return (T) new SingleInputTestOperatorWithAsyncProcessTimer(parameters, elementOrder); } @Override public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return SingleInputTestOperatorWithAsyncProcessTimer.class; } } private static
TestWithAsyncProcessTimerOperatorFactory
java
quarkusio__quarkus
extensions/scheduler/common/src/main/java/io/quarkus/scheduler/common/runtime/SchedulerContext.java
{ "start": 207, "end": 1221 }
interface ____ { CronType getCronType(); List<ScheduledMethod> getScheduledMethods(); boolean forceSchedulerStart(); List<ScheduledMethod> getScheduledMethods(String implementation); boolean matchesImplementation(Scheduled scheduled, String implementation); String autoImplementation(); @SuppressWarnings("unchecked") default ScheduledInvoker createInvoker(String invokerClassName) { try { Class<? extends ScheduledInvoker> invokerClazz = (Class<? extends ScheduledInvoker>) Thread.currentThread() .getContextClassLoader() .loadClass(invokerClassName); return invokerClazz.getDeclaredConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) { throw new IllegalStateException("Unable to create invoker: " + invokerClassName, e); } } }
SchedulerContext
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/testkit/FloatArrays.java
{ "start": 694, "end": 924 }
class ____ { private static final float[] EMPTY = {}; public static float[] arrayOf(float... values) { return values; } public static float[] emptyArray() { return EMPTY; } private FloatArrays() {} }
FloatArrays
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/server/ObservationWebFilterChainDecoratorTests.java
{ "start": 11453, "end": 11663 }
class ____ implements WebFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return Mono.error(() -> new RuntimeException("ack")); } } static
ErroringFilter
java
apache__hadoop
hadoop-tools/hadoop-azure-datalake/src/test/java/org/apache/hadoop/fs/adl/TestRelativePathFormation.java
{ "start": 1347, "end": 2445 }
class ____ { @Test public void testToRelativePath() throws URISyntaxException, IOException { AdlFileSystem fs = new AdlFileSystem(); Configuration configuration = new Configuration(); configuration.setEnum(AZURE_AD_TOKEN_PROVIDER_TYPE_KEY, TokenProviderType.Custom); configuration.set(AZURE_AD_TOKEN_PROVIDER_CLASS_KEY, "org.apache.hadoop.fs.adl.common.CustomMockTokenProvider"); fs.initialize(new URI("adl://temp.account.net"), configuration); assertEquals("/usr", fs.toRelativeFilePath(new Path("/usr"))); assertEquals("/usr", fs.toRelativeFilePath(new Path("adl://temp.account.net/usr"))); // When working directory is set. fs.setWorkingDirectory(new Path("/a/b/")); assertEquals("/usr", fs.toRelativeFilePath(new Path("/usr"))); assertEquals("/a/b/usr", fs.toRelativeFilePath(new Path("usr"))); assertEquals("/usr", fs.toRelativeFilePath(new Path("adl://temp.account.net/usr"))); assertEquals("/usr", fs.toRelativeFilePath(new Path("wasb://temp.account.net/usr"))); } }
TestRelativePathFormation
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/analysis/AnalysisRegistryTests.java
{ "start": 3260, "end": 12755 }
class ____ extends Plugin implements AnalysisPlugin { @Override public List<PreConfiguredTokenFilter> getPreConfiguredTokenFilters() { return singletonList(PreConfiguredTokenFilter.singleton("reverse", true, ReverseStringFilter::new)); } } private static IndexSettings indexSettingsOfCurrentVersion(Settings.Builder settings) { return IndexSettingsModule.newIndexSettings( "index", settings.put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()).build() ); } @Override public void setUp() throws Exception { super.setUp(); Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build(); emptyRegistry = emptyAnalysisRegistry(settings); // Module loaded to register in-built normalizers for testing AnalysisModule module = new AnalysisModule( TestEnvironment.newEnvironment(settings), singletonList(new MockAnalysisPlugin()), new StablePluginsRegistry() ); nonEmptyRegistry = module.getAnalysisRegistry(); } public void testDefaultAnalyzers() throws IOException { IndexVersion version = IndexVersionUtils.randomVersion(); Settings settings = Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, version) .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()) .build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings); IndexAnalyzers indexAnalyzers = emptyRegistry.build(IndexCreationContext.CREATE_INDEX, idxSettings); assertThat(indexAnalyzers.getDefaultIndexAnalyzer().analyzer(), instanceOf(StandardAnalyzer.class)); assertThat(indexAnalyzers.getDefaultSearchAnalyzer().analyzer(), instanceOf(StandardAnalyzer.class)); assertThat(indexAnalyzers.getDefaultSearchQuoteAnalyzer().analyzer(), instanceOf(StandardAnalyzer.class)); assertThat(indexAnalyzers.get(AnalysisRegistry.DEFAULT_ANALYZER_NAME).name(), equalTo("default")); } public void testOverrideDefaultAnalyzer() throws IOException { IndexVersion version = IndexVersionUtils.randomVersion(); Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, version).build(); IndexAnalyzers indexAnalyzers = AnalysisRegistry.build( IndexCreationContext.CREATE_INDEX, IndexSettingsModule.newIndexSettings("index", settings), singletonMap("default", analyzerProvider("default")), emptyMap(), emptyMap(), emptyMap(), emptyMap() ); assertThat(indexAnalyzers.getDefaultIndexAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class)); assertThat(indexAnalyzers.getDefaultSearchAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class)); assertThat(indexAnalyzers.getDefaultSearchQuoteAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class)); } public void testOverrideDefaultAnalyzerWithoutAnalysisModeAll() throws IOException { IndexVersion version = IndexVersionUtils.randomVersion(); Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, version).build(); IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("index", settings); TokenFilterFactory tokenFilter = new AbstractTokenFilterFactory("my_filter") { @Override public AnalysisMode getAnalysisMode() { return randomFrom(AnalysisMode.SEARCH_TIME, AnalysisMode.INDEX_TIME); } @Override public TokenStream create(TokenStream tokenStream) { return tokenStream; } }; TokenizerFactory tokenizer = new AbstractTokenizerFactory("my_tokenizer") { @Override public Tokenizer create() { return new StandardTokenizer(); } }; Analyzer analyzer = new CustomAnalyzer(tokenizer, new CharFilterFactory[0], new TokenFilterFactory[] { tokenFilter }); MapperException ex = expectThrows( MapperException.class, () -> AnalysisRegistry.build( IndexCreationContext.CREATE_INDEX, IndexSettingsModule.newIndexSettings("index", settings), singletonMap("default", new PreBuiltAnalyzerProvider("default", AnalyzerScope.INDEX, analyzer)), emptyMap(), emptyMap(), emptyMap(), emptyMap() ) ); assertEquals("analyzer [default] contains filters [my_filter] that are not allowed to run in all mode.", ex.getMessage()); } public void testNameClashNormalizer() throws IOException { // Test out-of-the-box normalizer works OK. IndexAnalyzers indexAnalyzers = nonEmptyRegistry.build( IndexCreationContext.CREATE_INDEX, IndexSettingsModule.newIndexSettings("index", Settings.EMPTY) ); assertNotNull(indexAnalyzers.getNormalizer("lowercase")); assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field", "AbC").utf8ToString(), equalTo("abc")); // Test that a name clash with a custom normalizer will favour the index's normalizer rather than the out-of-the-box // one of the same name. (However this "feature" will be removed with https://github.com/elastic/elasticsearch/issues/22263 ) Settings settings = Settings.builder() // Deliberately bad choice of normalizer name for the job it does. .put("index.analysis.normalizer.lowercase.type", "custom") .putList("index.analysis.normalizer.lowercase.filter", "reverse") .build(); indexAnalyzers = nonEmptyRegistry.build(IndexCreationContext.CREATE_INDEX, IndexSettingsModule.newIndexSettings("index", settings)); assertNotNull(indexAnalyzers.getNormalizer("lowercase")); assertThat(indexAnalyzers.getNormalizer("lowercase").normalize("field", "AbC").utf8ToString(), equalTo("CbA")); } public void testOverrideDefaultIndexAnalyzerIsUnsupported() { IndexVersion version = IndexVersionUtils.randomCompatibleVersion(random()); Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, version).build(); AnalyzerProvider<?> defaultIndex = new PreBuiltAnalyzerProvider("default_index", AnalyzerScope.INDEX, new EnglishAnalyzer()); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> AnalysisRegistry.build( IndexCreationContext.CREATE_INDEX, IndexSettingsModule.newIndexSettings("index", settings), singletonMap("default_index", defaultIndex), emptyMap(), emptyMap(), emptyMap(), emptyMap() ) ); assertTrue(e.getMessage().contains("[index.analysis.analyzer.default_index] is not supported")); } public void testOverrideDefaultSearchAnalyzer() { IndexVersion version = IndexVersionUtils.randomVersion(); Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, version).build(); IndexAnalyzers indexAnalyzers = AnalysisRegistry.build( IndexCreationContext.CREATE_INDEX, IndexSettingsModule.newIndexSettings("index", settings), singletonMap("default_search", analyzerProvider("default_search")), emptyMap(), emptyMap(), emptyMap(), emptyMap() ); assertThat(indexAnalyzers.getDefaultIndexAnalyzer().analyzer(), instanceOf(StandardAnalyzer.class)); assertThat(indexAnalyzers.getDefaultSearchAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class)); assertThat(indexAnalyzers.getDefaultSearchQuoteAnalyzer().analyzer(), instanceOf(EnglishAnalyzer.class)); } /** * Tests that {@code camelCase} filter names and {@code snake_case} filter names don't collide. */ public void testConfigureCamelCaseTokenFilter() throws IOException { Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build(); Settings indexSettings = Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put("index.analysis.filter.testFilter.type", "mock") .put("index.analysis.filter.test_filter.type", "mock") .put("index.analysis.analyzer.custom_analyzer_with_camel_case.tokenizer", "standard") .putList("index.analysis.analyzer.custom_analyzer_with_camel_case.filter", "lowercase", "testFilter") .put("index.analysis.analyzer.custom_analyzer_with_snake_case.tokenizer", "standard") .putList("index.analysis.analyzer.custom_analyzer_with_snake_case.filter", "lowercase", "test_filter") .build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", indexSettings); /* The snake_case version of the name should not filter out any stopwords while the * camelCase version will filter out English stopwords. */ AnalysisPlugin plugin = new AnalysisPlugin() {
MockAnalysisPlugin
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/plugin/MessageStoreFactory.java
{ "start": 973, "end": 2188 }
class ____ { public static MessageStore build(MessageStorePluginContext context, MessageStore messageStore) throws IOException { String plugin = context.getBrokerConfig().getMessageStorePlugIn(); if (plugin != null && plugin.trim().length() != 0) { String[] pluginClasses = plugin.split(","); for (int i = pluginClasses.length - 1; i >= 0; --i) { String pluginClass = pluginClasses[i]; try { @SuppressWarnings("unchecked") Class<AbstractPluginMessageStore> clazz = (Class<AbstractPluginMessageStore>) Class.forName(pluginClass); Constructor<AbstractPluginMessageStore> construct = clazz.getConstructor(MessageStorePluginContext.class, MessageStore.class); AbstractPluginMessageStore pluginMessageStore = construct.newInstance(context, messageStore); messageStore = pluginMessageStore; } catch (Throwable e) { throw new RuntimeException("Initialize plugin's class: " + pluginClass + " not found!", e); } } } return messageStore; } }
MessageStoreFactory
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvQuotingOnlyWhenNeededTest.java
{ "start": 8886, "end": 10107 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; @DataField(pos = 1) private String firstField; @DataField(pos = 2) private String secondField; @DataField(pos = 3, pattern = "#.##") private Double aNumber; @DataField(pos = 4) private Boolean aBoolean; public String getFirstField() { return firstField; } public void setFirstField(String firstField) { this.firstField = firstField; } public String getSecondField() { return secondField; } public void setSecondField(String secondField) { this.secondField = secondField; } public Double getaNumber() { return aNumber; } public void setaNumber(Double aNumber) { this.aNumber = aNumber; } public Boolean getaBoolean() { return aBoolean; } public void setaBoolean(Boolean aBoolean) { this.aBoolean = aBoolean; } } @CsvRecord(separator = ";", quoting = true, quotingOnlyWhenNeeded = true) public static
BindyCsvRowFormat191432
java
apache__camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/BaseNettyTest.java
{ "start": 1393, "end": 3134 }
class ____ extends CamelTestSupport { protected static final Logger LOG = LoggerFactory.getLogger(BaseNettyTest.class); @RegisterExtension AvailablePortFinder.Port port = AvailablePortFinder.find(); @BeforeAll public static void startLeakDetection() { System.setProperty("io.netty.leakDetection.maxRecords", "100"); System.setProperty("io.netty.leakDetection.acquireAndReleaseOnly", "true"); System.setProperty("io.netty.leakDetection.targetRecords", "100"); LogCaptureAppender.reset(); } @AfterAll public static void verifyNoLeaks() { //Force GC to bring up leaks System.gc(); //Kick leak detection logging ByteBufAllocator.DEFAULT.buffer(1).release(); Collection<LogEvent> events = LogCaptureAppender.getEvents(); if (!events.isEmpty()) { String message = "Leaks detected while running tests: " + events; // Just write the message into log to help debug for (LogEvent event : events) { LOG.info(event.getMessage().getFormattedMessage()); } LogCaptureAppender.reset(); throw new AssertionError(message); } } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.getPropertiesComponent().setLocation("ref:prop"); return context; } @BindToRegistry("prop") public Properties loadProp() { Properties prop = new Properties(); prop.setProperty("port", Integer.toString(getPort())); return prop; } protected int getPort() { return port.getPort(); } }
BaseNettyTest
java
google__guava
android/guava/src/com/google/common/collect/Multimaps.java
{ "start": 13412, "end": 14918 }
class ____ * does {@code factory.get()}. * * <p>The multimap is serializable if {@code map}, {@code factory}, the lists generated by {@code * factory}, and the multimap contents are all serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link * #synchronizedListMultimap}. * * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()} and {@link * LinkedListMultimap#create()} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and the lists returned by * {@code factory}. Those objects should not be manually updated, they should be empty when * provided, and they should not use soft, weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding values * @param factory supplier of new, empty lists that will each hold all values for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K extends @Nullable Object, V extends @Nullable Object> ListMultimap<K, V> newListMultimap( Map<K, Collection<V>> map, Supplier<? extends List<V>> factory) { return new CustomListMultimap<>(map, factory); } private static final
than
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/ReflectionUtil.java
{ "start": 8328, "end": 9008 }
class ____"); final Constructor<T> constructor = getDefaultConstructor(clazz); try { return constructor.newInstance(); } catch (final LinkageError | InstantiationException e) { // LOG4J2-1051 // On platforms like Google App Engine and Android, some JRE classes are not supported: JMX, JNDI, etc. throw new IllegalArgumentException(e); } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } catch (final InvocationTargetException e) { Throwables.rethrow(e.getCause()); throw new InternalError("Unreachable"); } } }
provided
java
apache__kafka
share-coordinator/src/main/java/org/apache/kafka/coordinator/share/ShareCoordinatorOffsetsManager.java
{ "start": 1116, "end": 1378 }
class ____ track the offsets written into the internal topic * per share partition key. * It calculates the minimum offset globally up to which the records * in the internal partition are redundant i.e. they have been overridden * by newer records. */ public
to
java
apache__camel
components/camel-wasm/src/test/java/org/apache/camel/language/wasm/WasmLanguageTest.java
{ "start": 1415, "end": 3694 }
class ____ { @ParameterizedTest @ValueSource(strings = { "transform@functions.wasm", "transform@file:{{wasm.resources.path}}/functions.wasm" }) public void testLanguage(String expression) throws Exception { try (CamelContext cc = new DefaultCamelContext()) { FluentProducerTemplate pt = cc.createFluentProducerTemplate(); cc.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:in") .transform() .wasm( StringHelper.before(expression, "@"), StringHelper.after(expression, "@")); } }); cc.start(); Exchange out = pt.to("direct:in") .withHeader("foo", "bar") .withBody("hello") .request(Exchange.class); assertThat(out.getMessage().getHeaders()) .containsEntry("foo", "bar"); assertThat(out.getMessage().getBody(String.class)) .isEqualTo("HELLO"); } } @Test public void testLanguageFailure() throws Exception { try (CamelContext cc = new DefaultCamelContext()) { FluentProducerTemplate pt = cc.createFluentProducerTemplate(); cc.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:in") .transform() .wasm("transform_err", "functions.wasm"); } }); cc.start(); Exchange out = pt.to("direct:in") .withHeader("foo", "bar") .withBody("hello") .request(Exchange.class); assertThat(out.getException()) .isNotNull() .hasCauseInstanceOf(RuntimeException.class) .extracting(Throwable::getCause, as(InstanceOfAssertFactories.THROWABLE)) .hasMessage("this is an error"); } } }
WasmLanguageTest
java
quarkusio__quarkus
extensions/kubernetes/spi/src/main/java/io/quarkus/kubernetes/spi/KubernetesInitContainerBuildItem.java
{ "start": 458, "end": 2056 }
class ____ extends MultiBuildItem implements Targetable { private static final String DEFAULT_IMAGE_PULL_POLICY = "Always"; private final String name; private final String target; private final String image; private final String imagePullPolicy; private final List<String> command; private final List<String> arguments; private final Map<String, String> envVars; private final boolean sharedEnvironment; private final boolean sharedFilesystem; public static KubernetesInitContainerBuildItem create(String name, String image) { return create(name, image, DEFAULT_IMAGE_PULL_POLICY); } public static KubernetesInitContainerBuildItem create(String name, String image, String imagePullPolicy) { return new KubernetesInitContainerBuildItem(name, null, image, DEFAULT_IMAGE_PULL_POLICY, Collections.emptyList(), Collections.emptyList(), Collections.emptyMap(), false, false); } @Deprecated(forRemoval = true, since = "3.18") public KubernetesInitContainerBuildItem(String name, String target, String image, List<String> command, List<String> arguments, Map<String, String> envVars, boolean sharedEnvironment, boolean sharedFilesystem) { this(name, target, image, DEFAULT_IMAGE_PULL_POLICY, command, arguments, envVars, sharedEnvironment, sharedFilesystem); } private KubernetesInitContainerBuildItem(String name, String target, String image, String imagePullPolicy, // using a string here as we don't have the
KubernetesInitContainerBuildItem
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/frame/AbstractSockJsMessageCodec.java
{ "start": 923, "end": 2481 }
class ____ implements SockJsMessageCodec { @Override public String encode(String... messages) { Assert.notNull(messages, "messages must not be null"); StringBuilder sb = new StringBuilder(); sb.append("a["); for (int i = 0; i < messages.length; i++) { sb.append('"'); char[] quotedChars = applyJsonQuoting(messages[i]); sb.append(escapeSockJsSpecialChars(quotedChars)); sb.append('"'); if (i < messages.length - 1) { sb.append(','); } } sb.append(']'); return sb.toString(); } /** * Apply standard JSON string quoting (see <a href="https://www.json.org/">json.org</a>). */ protected abstract char[] applyJsonQuoting(String content); /** * See "JSON Unicode Encoding" section of SockJS protocol. */ private String escapeSockJsSpecialChars(char[] characters) { StringBuilder result = new StringBuilder(); for (char c : characters) { if (isSockJsSpecialChar(c)) { result.append('\\').append('u'); String hex = Integer.toHexString(c).toLowerCase(Locale.ROOT); result.append("0".repeat(Math.max(0, (4 - hex.length())))); result.append(hex); } else { result.append(c); } } return result.toString(); } /** * See `escapable_by_server` variable in the SockJS protocol test suite. */ private boolean isSockJsSpecialChar(char ch) { return (ch <= '\u001F') || (ch >= '\u200C' && ch <= '\u200F') || (ch >= '\u2028' && ch <= '\u202F') || (ch >= '\u2060' && ch <= '\u206F') || (ch >= '\uFFF0') || (ch >= '\uD800' && ch <= '\uDFFF'); } }
AbstractSockJsMessageCodec
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/SecondaryTableSource.java
{ "start": 289, "end": 1496 }
interface ____ extends ForeignKeyContributingSource { /** * Obtain the table being joined to. * * @return The joined table. */ TableSpecificationSource getTableSource(); /** * Retrieves the columns defines as making up this secondary tables primary key. Each entry should have * a corresponding entry in the foreign-key columns described by the {@link ForeignKeyContributingSource} * aspect of this contract. * * @return The columns defining the primary key for this secondary table */ List<ColumnSource> getPrimaryKeyColumnSources(); String getLogicalTableNameForContainedColumns(); String getComment(); FetchStyle getFetchStyle(); boolean isInverse(); boolean isOptional(); boolean isCascadeDeleteEnabled(); /** * Obtain the custom SQL to be used for inserts for this entity * * @return The custom insert SQL */ CustomSql getCustomSqlInsert(); /** * Obtain the custom SQL to be used for updates for this entity * * @return The custom update SQL */ CustomSql getCustomSqlUpdate(); /** * Obtain the custom SQL to be used for deletes for this entity * * @return The custom delete SQL */ CustomSql getCustomSqlDelete(); }
SecondaryTableSource
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/rules/action/PutQueryRulesetActionRequestBWCSerializingTests.java
{ "start": 1041, "end": 3558 }
class ____ extends AbstractBWCSerializationTestCase<PutQueryRulesetAction.Request> { private QueryRuleset queryRulesSet; @Override protected Writeable.Reader<PutQueryRulesetAction.Request> instanceReader() { return PutQueryRulesetAction.Request::new; } @Override protected PutQueryRulesetAction.Request createTestInstance() { this.queryRulesSet = EnterpriseSearchModuleTestUtils.randomQueryRuleset(); return new PutQueryRulesetAction.Request(this.queryRulesSet); } @Override protected PutQueryRulesetAction.Request mutateInstance(PutQueryRulesetAction.Request instance) { return new PutQueryRulesetAction.Request( randomValueOtherThan(instance.queryRuleset(), () -> EnterpriseSearchModuleTestUtils.randomQueryRuleset()) ); } @Override protected PutQueryRulesetAction.Request doParseInstance(XContentParser parser) throws IOException { return PutQueryRulesetAction.Request.fromXContent(this.queryRulesSet.id(), parser); } @Override protected PutQueryRulesetAction.Request mutateInstanceForVersion(PutQueryRulesetAction.Request instance, TransportVersion version) { if (version.before(CRITERIA_METADATA_VALUES_TRANSPORT_VERSION)) { List<QueryRule> rules = new ArrayList<>(); for (QueryRule rule : instance.queryRuleset().rules()) { List<QueryRuleCriteria> newCriteria = new ArrayList<>(); for (QueryRuleCriteria criteria : rule.criteria()) { newCriteria.add( new QueryRuleCriteria(criteria.criteriaType(), criteria.criteriaMetadata(), criteria.criteriaValues().subList(0, 1)) ); } rules.add(new QueryRule(rule.id(), rule.type(), newCriteria, rule.actions(), null)); } return new PutQueryRulesetAction.Request(new QueryRuleset(instance.queryRuleset().id(), rules)); } else if (version.before(TransportVersions.V_8_15_0)) { List<QueryRule> rules = new ArrayList<>(); for (QueryRule rule : instance.queryRuleset().rules()) { rules.add(new QueryRule(rule.id(), rule.type(), rule.criteria(), rule.actions(), null)); } return new PutQueryRulesetAction.Request(new QueryRuleset(instance.queryRuleset().id(), rules)); } // Default to current instance return instance; } }
PutQueryRulesetActionRequestBWCSerializingTests
java
apache__camel
components/camel-bean/src/main/java/org/apache/camel/language/bean/BeanExpression.java
{ "start": 2468, "end": 5303 }
class ____ implements Expression, Predicate { private ParameterMappingStrategy parameterMappingStrategy; private BeanComponent beanComponent; private Language simple; private Class<?> resultType; private final Object bean; private String beanName; private Class<?> type; private final String method; private BeanHolder beanHolder; private boolean ognlMethod; private BeanScope scope = BeanScope.Singleton; private boolean validate = true; public BeanExpression(Object bean, String method) { this.bean = bean; this.method = method; this.beanName = null; this.type = null; } public BeanExpression(String beanName, String method) { this.beanName = beanName; this.method = method; this.bean = null; this.type = null; } public BeanExpression(Class<?> type, String method) { this.type = type; this.method = method; this.bean = null; this.beanName = null; } public Object getBean() { return bean; } public String getBeanName() { return beanName; } public Class<?> getType() { return type; } public String getMethod() { return method; } public BeanScope getScope() { return scope; } public void setScope(BeanScope scope) { this.scope = scope; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public ParameterMappingStrategy getParameterMappingStrategy() { return parameterMappingStrategy; } public void setParameterMappingStrategy(ParameterMappingStrategy parameterMappingStrategy) { this.parameterMappingStrategy = parameterMappingStrategy; } public BeanComponent getBeanComponent() { return beanComponent; } public void setBeanComponent(BeanComponent beanComponent) { this.beanComponent = beanComponent; } public Language getSimple() { return simple; } public void setSimple(Language simple) { this.simple = simple; } public Class<?> getResultType() { return resultType; } public void setResultType(Class<?> resultType) { this.resultType = resultType; } @Override public void init(CamelContext context) { if (parameterMappingStrategy == null) { parameterMappingStrategy = ParameterMappingStrategyHelper.createParameterMappingStrategy(context); } if (beanComponent == null) { beanComponent = context.getComponent("bean", BeanComponent.class); } if (beanName != null && beanName.startsWith("type:")) { // its a reference to a fqn
BeanExpression
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ClassCanBeStaticTest.java
{ "start": 12745, "end": 13022 }
class ____ {} public void run() {} }; } """) .doTest(); } @Test public void nestedInLocal() { compilationHelper .addSourceLines( "A.java", """ public
Inner
java
quarkusio__quarkus
extensions/elytron-security-ldap/deployment/src/test/java/io/quarkus/elytron/security/ldap/CacheTest.java
{ "start": 445, "end": 1075 }
class ____ { protected static Class[] testClasses = { SingleRoleSecuredServlet.class }; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(testClasses) .addAsResource("cache/application.properties", "application.properties")); @Test() public void testNoCacheFailure() { RestAssured.given().auth().preemptive().basic("standardUser", "standardUserPassword") .when().get("/servlet-secured").then() .statusCode(200); } }
CacheTest
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/utils/LogicalTypeChecks.java
{ "start": 19158, "end": 19408 }
class ____ extends Extractor<Integer> { @Override public Integer visit(YearMonthIntervalType yearMonthIntervalType) { return yearMonthIntervalType.getYearPrecision(); } } private static
YearPrecisionExtractor
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/util/ConfigurationUtils.java
{ "start": 1108, "end": 3113 }
class ____ { /** * Copy configuration key/value pairs from one configuration to another if a property exists in the target, it gets * replaced. * * @param source source configuration. * @param target target configuration. */ public static void copy(Configuration source, Configuration target) { Check.notNull(source, "source"); Check.notNull(target, "target"); for (Map.Entry<String, String> entry : source) { target.set(entry.getKey(), entry.getValue()); } } /** * Injects configuration key/value pairs from one configuration to another if the key does not exist in the target * configuration. * * @param source source configuration. * @param target target configuration. */ public static void injectDefaults(Configuration source, Configuration target) { Check.notNull(source, "source"); Check.notNull(target, "target"); for (Map.Entry<String, String> entry : source) { if (target.get(entry.getKey()) == null) { target.set(entry.getKey(), entry.getValue()); } } } /** * Returns a new ConfigurationUtils instance with all inline values resolved. * * @return a new ConfigurationUtils instance with all inline values resolved. */ public static Configuration resolve(Configuration conf) { Configuration resolved = new Configuration(false); for (Map.Entry<String, String> entry : conf) { resolved.set(entry.getKey(), conf.get(entry.getKey())); } return resolved; } // Canibalized from FileSystemAccess <code>Configuration.loadResource()</code>. /** * Create a configuration from an InputStream. * <p> * ERROR canibalized from <code>Configuration.loadResource()</code>. * * @param is inputstream to read the configuration from. * * @throws IOException thrown if the configuration could not be read. */ public static void load(Configuration conf, InputStream is) throws IOException { conf.addResource(is); } }
ConfigurationUtils
java
elastic__elasticsearch
benchmarks/src/main/java/org/elasticsearch/benchmark/search/fetch/subphase/SourceFilteringBenchmark.java
{ "start": 1605, "end": 3583 }
class ____ { private BytesReference sourceBytes; private SourceFilter filter; @Param({ "tiny", "short", "one_4k_field", "one_4m_field" }) private String source; @Param({ "message" }) private String includes; @Param({ "" }) private String excludes; @Setup public void setup() throws IOException { sourceBytes = switch (source) { case "tiny" -> new BytesArray("{\"message\": \"short\"}"); case "short" -> read300BytesExample(); case "one_4k_field" -> buildBigExample("huge".repeat(1024)); case "one_4m_field" -> buildBigExample("huge".repeat(1024 * 1024)); default -> throw new IllegalArgumentException("Unknown source [" + source + "]"); }; FetchSourceContext fetchContext = FetchSourceContext.of( true, Strings.splitStringByCommaToArray(includes), Strings.splitStringByCommaToArray(excludes) ); filter = fetchContext.filter(); } private BytesReference read300BytesExample() throws IOException { return Streams.readFully(FetchSourcePhaseBenchmark.class.getResourceAsStream("300b_example.json")); } private BytesReference buildBigExample(String extraText) throws IOException { String bigger = read300BytesExample().utf8ToString(); bigger = "{\"huge\": \"" + extraText + "\"," + bigger.substring(1); return new BytesArray(bigger); } // We want to compare map filtering with bytes filtering when the map has already // been parsed. @Benchmark public Source filterMap() { Source source = Source.fromBytes(sourceBytes); source.source(); // build map return filter.filterMap(source); } @Benchmark public Source filterBytes() { Source source = Source.fromBytes(sourceBytes); source.source(); // build map return filter.filterBytes(source); } }
SourceFilteringBenchmark
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/huggingface/request/HuggingFaceEmbeddingsRequestTests.java
{ "start": 1174, "end": 3795 }
class ____ extends ESTestCase { @SuppressWarnings("unchecked") public void testCreateRequest() throws URISyntaxException, IOException { var huggingFaceRequest = createRequest("www.google.com", "secret", "abc"); var httpRequest = huggingFaceRequest.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getURI().toString(), is("www.google.com")); assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaTypeWithoutParameters())); assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is("Bearer secret")); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat(requestMap.size(), is(1)); assertThat(requestMap.get("inputs"), instanceOf(List.class)); var inputList = (List<String>) requestMap.get("inputs"); assertThat(inputList, contains("abc")); } public void testTruncate_ReducesInputTextSizeByHalf() throws URISyntaxException, IOException { var huggingFaceRequest = createRequest("www.google.com", "secret", "abcd"); var truncatedRequest = huggingFaceRequest.truncate(); assertThat(truncatedRequest.getURI().toString(), is(new URI("www.google.com").toString())); var httpRequest = truncatedRequest.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat(requestMap.get("inputs"), instanceOf(List.class)); assertThat(requestMap.get("inputs"), is(List.of("ab"))); } public void testIsTruncated_ReturnsTrue() throws URISyntaxException, IOException { var huggingFaceRequest = createRequest("www.google.com", "secret", "abcd"); assertFalse(huggingFaceRequest.getTruncationInfo()[0]); var truncatedRequest = huggingFaceRequest.truncate(); assertTrue(truncatedRequest.getTruncationInfo()[0]); } public static HuggingFaceEmbeddingsRequest createRequest(String url, String apiKey, String input) throws URISyntaxException { return new HuggingFaceEmbeddingsRequest( TruncatorTests.createTruncator(), new Truncator.TruncationResult(List.of(input), new boolean[] { false }), HuggingFaceEmbeddingsModelTests.createModel(url, apiKey) ); } }
HuggingFaceEmbeddingsRequestTests
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkGeneratorSupplier.java
{ "start": 1776, "end": 1972 }
interface ____ { /** * Returns the metric group for the context in which the created {@link WatermarkGenerator} * is used. * * <p>Instances of this
Context
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/connections/ConnectionCloseAfterStatementTest.java
{ "start": 2905, "end": 3329 }
class ____ { @Id private Long id; private String name; public TestEntity() { } public TestEntity(Long id, String name) { this.id = id; this.name = name; } } private JtaAwareConnectionProvider getConnectionProvider(SessionFactoryScope scope) { return (JtaAwareConnectionProvider) scope.getSessionFactory().getServiceRegistry() .getService( ConnectionProvider.class ); } public static
TestEntity
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/PartitionedTable.java
{ "start": 1411, "end": 4798 }
interface ____ { /** * Converts this table object into a named argument. * * <p>This method is intended for calls to process table functions (PTFs) that take table * arguments. * * <p>Example: * * <pre>{@code * env.fromCall( * "MyPTF", * table.partitionBy($("key")).asArgument("input_table") * ) * }</pre> * * @see ProcessTableFunction * @return an expression that can be passed into {@link TableEnvironment#fromCall}. */ ApiExpression asArgument(String name); /** * Transforms the given table by passing it into a process table function (PTF) with set * semantics. * * <p>A PTF maps zero, one, or multiple tables to a new table. PTFs are the most powerful * function kind for Flink SQL and Table API. They enable implementing user-defined operators * that can be as feature-rich as built-in operations. PTFs have access to Flink's managed * state, event-time and timer services, and underlying table changelogs. * * <p>This method assumes a call to a previously registered function that takes exactly one * table argument with set semantics as the first argument. Additional scalar arguments can be * passed if necessary. Thus, this method is a shortcut for: * * <pre>{@code * env.fromCall( * "MyPTF", * THIS_TABLE, * SOME_SCALAR_ARGUMENTS... * ); * }</pre> * * <p>Example: * * <pre>{@code * env.createFunction("MyPTF", MyPTF.class); * * Table table = table * .partitionBy($("key")) * .process( * "MyPTF" * lit("Bob").asArgument("default_name"), * lit(42).asArgument("default_threshold") * ); * }</pre> * * @param path The path of a function * @param arguments Table and scalar argument {@link Expressions}. * @return The {@link Table} object describing the pipeline for further transformations. * @see Expressions#call(String, Object...) * @see ProcessTableFunction */ Table process(String path, Object... arguments); /** * Transforms the given table by passing it into a process table function (PTF) with set * semantics. * * <p>A PTF maps zero, one, or multiple tables to a new table. PTFs are the most powerful * function kind for Flink SQL and Table API. They enable implementing user-defined operators * that can be as feature-rich as built-in operations. PTFs have access to Flink's managed * state, event-time and timer services, and underlying table changelogs. * * <p>This method assumes a call to an unregistered, inline function that takes exactly one * table argument with set semantics as the first argument. Additional scalar arguments can be * passed if necessary. Thus, this method is a shortcut for: * * <pre>{@code * env.fromCall( * MyPTF.class, * THIS_TABLE, * SOME_SCALAR_ARGUMENTS... * ); * }</pre> * * <p>Example: * * <pre>{@code * Table table = table * .partitionBy($("key")) * .process( * MyPTF.class, * lit("Bob").asArgument("default_name"), * lit(42).asArgument("default_threshold") * ); * }</pre> * * @param function The
PartitionedTable
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java
{ "start": 1520, "end": 2765 }
class ____ extends AbstractSingleBeanDefinitionParser { /** * parse * <prev> * &lt;dubbo:annotation package="" /&gt; * </prev> * * @param element * @param parserContext * @param builder */ @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { String packageToScan = element.getAttribute("package"); String[] packagesToScan = trimArrayElements(commaDelimitedListToStringArray(packageToScan)); builder.addConstructorArgValue(packagesToScan); builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); /** * @since 2.7.6 Register the common beans * @since 2.7.8 comment this code line, and migrated to * @see DubboNamespaceHandler#parse(Element, ParserContext) * @see https://github.com/apache/dubbo/issues/6174 */ // registerCommonBeans(parserContext.getRegistry()); } @Override protected boolean shouldGenerateIdAsFallback() { return true; } @Override protected Class<?> getBeanClass(Element element) { return SpringCompatUtils.serviceAnnotationPostProcessor(); } }
AnnotationBeanDefinitionParser
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/UuidGeneratedValueTest.java
{ "start": 1529, "end": 2191 }
class ____ { @Id @GeneratedValue private UUID id; private String title; private String author; //Getters and setters are omitted for brevity //end::identifiers-generators-uuid-mapping-example[] public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } //tag::identifiers-generators-uuid-mapping-example[] } //end::identifiers-generators-uuid-mapping-example[] }
Book
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDelay.java
{ "start": 1706, "end": 3775 }
class ____<T> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable, Runnable { private static final long serialVersionUID = 5566860102500855068L; final MaybeObserver<? super T> downstream; final long delay; final TimeUnit unit; final Scheduler scheduler; final boolean delayError; T value; Throwable error; DelayMaybeObserver(MaybeObserver<? super T> actual, long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) { this.downstream = actual; this.delay = delay; this.unit = unit; this.scheduler = scheduler; this.delayError = delayError; } @Override public void run() { Throwable ex = error; if (ex != null) { downstream.onError(ex); } else { T v = value; if (v != null) { downstream.onSuccess(v); } else { downstream.onComplete(); } } } @Override public void dispose() { DisposableHelper.dispose(this); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(this, d)) { downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { this.value = value; schedule(delay); } @Override public void onError(Throwable e) { this.error = e; schedule(delayError ? delay : 0); } @Override public void onComplete() { schedule(delay); } void schedule(long delay) { DisposableHelper.replace(this, scheduler.scheduleDirect(this, delay, unit)); } } }
DelayMaybeObserver
java
playframework__playframework
core/play/src/main/java/play/libs/reflect/MemberUtils.java
{ "start": 1965, "end": 6239 }
class ____ a default access superclass with {@code public} members, * these members are accessible. Calling them from compiled code works fine. Unfortunately, on * some JVMs, using reflection to invoke these members seems to (wrongly) prevent access even when * the modifier is {@code public}. Calling {@code setAccessible(true)} solves the problem but will * only work from sufficiently privileged code. Better workarounds would be gratefully accepted. * * @param o the AccessibleObject to set as accessible * @return a boolean indicating whether the accessibility of the object was set to true. */ static boolean setAccessibleWorkaround(final AccessibleObject o) { if (o == null || o.isAccessible()) { return false; } final Member m = (Member) o; if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); return true; } catch (final SecurityException e) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } return false; } /** * Compares the relative fitness of two Constructors in terms of how well they match a set of * runtime parameter types, such that a list ordered by the results of the comparison would return * the best match first (least). * * @param left the "left" Constructor * @param right the "right" Constructor * @param actual the runtime parameter types to match against {@code left}/{@code right} * @return int consistent with {@code compare} semantics * @since 3.5 */ static int compareConstructorFit( final Constructor<?> left, final Constructor<?> right, final Class<?>[] actual) { return compareParameterTypes(Executable.of(left), Executable.of(right), actual); } /** * Compares the relative fitness of two Methods in terms of how well they match a set of runtime * parameter types, such that a list ordered by the results of the comparison would return the * best match first (least). * * @param left the "left" Method * @param right the "right" Method * @param actual the runtime parameter types to match against {@code left}/{@code right} * @return int consistent with {@code compare} semantics * @since 3.5 */ static int compareMethodFit(final Method left, final Method right, final Class<?>[] actual) { return compareParameterTypes(Executable.of(left), Executable.of(right), actual); } /** * Compares the relative fitness of two Executables in terms of how well they match a set of * runtime parameter types, such that a list ordered by the results of the comparison would return * the best match first (least). * * @param left the "left" Executable * @param right the "right" Executable * @param actual the runtime parameter types to match against {@code left}/{@code right} * @return int consistent with {@code compare} semantics */ private static int compareParameterTypes( final Executable left, final Executable right, final Class<?>[] actual) { final float leftCost = getTotalTransformationCost(actual, left); final float rightCost = getTotalTransformationCost(actual, right); return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0; } /** * Gets the number of steps required to promote a primitive number to another type. * * @param srcClass the (primitive) source class * @param destClass the (primitive) destination class * @return The cost of promoting the primitive */ private static float getPrimitivePromotionCost( final Class<?> srcClass, final Class<?> destClass) { float cost = 0.0f; Class<?> cls = srcClass; if (!cls.isPrimitive()) { // slight unwrapping penalty cost += 0.1f; cls = ClassUtils.wrapperToPrimitive(cls); } for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) { if (cls == ORDERED_PRIMITIVE_TYPES[i]) { cost += 0.1f; if (i < ORDERED_PRIMITIVE_TYPES.length - 1) { cls = ORDERED_PRIMITIVE_TYPES[i + 1]; } } } return cost; } /** * Returns the sum of the object transformation cost for each
has
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java
{ "start": 41099, "end": 41702 }
class ____ extends AnalyzerRule<Project> { @Override protected LogicalPlan rule(Project p) { if (containsAggregate(p.projections())) { return new Aggregate(p.source(), p.child(), emptyList(), p.projections()); } return p; } } // // Detect implicit grouping with filtering and convert them into aggregates. // SELECT 1 FROM x HAVING COUNT(*) > 0 // is a filter followed by projection and fails as the engine does not // understand it is an implicit grouping. // private static
ProjectedAggregations
java
elastic__elasticsearch
libs/native/src/main/java/org/elasticsearch/nativeaccess/CloseableByteBuffer.java
{ "start": 791, "end": 968 }
interface ____ extends AutoCloseable { /** * Returns the wrapped {@link ByteBuffer}. */ ByteBuffer buffer(); @Override void close(); }
CloseableByteBuffer
java
elastic__elasticsearch
x-pack/plugin/text-structure/src/test/java/org/elasticsearch/xpack/textstructure/structurefinder/FieldStatsCalculatorTests.java
{ "start": 572, "end": 11981 }
class ____ extends TextStructureTestCase { private static final Map<String, String> LONG = Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "long"); private static final Map<String, String> DOUBLE = Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "double"); private static final Map<String, String> KEYWORD = Collections.singletonMap(TextStructureUtils.MAPPING_TYPE_SETTING, "keyword"); public void testMean() { FieldStatsCalculator calculator = new FieldStatsCalculator(DOUBLE); calculator.accept(Arrays.asList("1", "3.5", "2.5", "9")); assertEquals(4.0, calculator.calculateMean(), 1e-10); } public void testMedianGivenOddCount() { FieldStatsCalculator calculator = new FieldStatsCalculator(LONG); calculator.accept(Arrays.asList("3", "23", "-1", "5", "1000")); assertEquals(5.0, calculator.calculateMedian(), 1e-10); } public void testMedianGivenOddCountMinimal() { FieldStatsCalculator calculator = new FieldStatsCalculator(LONG); calculator.accept(Collections.singletonList("3")); assertEquals(3.0, calculator.calculateMedian(), 1e-10); } public void testMedianGivenEvenCountMiddleValuesDifferent() { FieldStatsCalculator calculator = new FieldStatsCalculator(LONG); calculator.accept(Arrays.asList("3", "23", "-1", "5", "1000", "6")); assertEquals(5.5, calculator.calculateMedian(), 1e-10); } public void testMedianGivenEvenCountMiddleValuesSame() { FieldStatsCalculator calculator = new FieldStatsCalculator(LONG); calculator.accept(Arrays.asList("3", "23", "-1", "5", "1000", "5")); assertEquals(5.0, calculator.calculateMedian(), 1e-10); } public void testMedianGivenEvenCountMinimal() { FieldStatsCalculator calculator = new FieldStatsCalculator(LONG); calculator.accept(Arrays.asList("4", "4")); assertEquals(4.0, calculator.calculateMedian(), 1e-10); } public void testTopHitsNumeric() { FieldStatsCalculator calculator = new FieldStatsCalculator(DOUBLE); calculator.accept(Arrays.asList("4", "4", "7", "4", "6", "5.2", "6", "5.2", "16", "4", "5.2")); List<Map<String, Object>> topHits = calculator.findNumericTopHits(3); assertEquals(3, topHits.size()); assertEquals(4, topHits.get(0).get("value")); assertEquals(4, topHits.get(0).get("count")); assertEquals(5.2, topHits.get(1).get("value")); assertEquals(3, topHits.get(1).get("count")); assertEquals(6, topHits.get(2).get("value")); assertEquals(2, topHits.get(2).get("count")); } public void testTopHitsString() { FieldStatsCalculator calculator = new FieldStatsCalculator(KEYWORD); calculator.accept(Arrays.asList("s", "s", "d", "s", "f", "x", "f", "x", "n", "s", "x")); List<Map<String, Object>> topHits = calculator.findStringTopHits(3); assertEquals(3, topHits.size()); assertEquals("s", topHits.get(0).get("value")); assertEquals(4, topHits.get(0).get("count")); assertEquals("x", topHits.get(1).get("value")); assertEquals(3, topHits.get(1).get("count")); assertEquals("f", topHits.get(2).get("value")); assertEquals(2, topHits.get(2).get("count")); } public void testCalculateGivenEmpty() { FieldStatsCalculator calculator = new FieldStatsCalculator( randomFrom(Arrays.asList(LONG, DOUBLE, KEYWORD, TextStructureUtils.DATE_MAPPING_WITHOUT_FORMAT)) ); calculator.accept(Collections.emptyList()); FieldStats stats = calculator.calculate(3); assertEquals(0L, stats.getCount()); assertEquals(0, stats.getCardinality()); assertNull(stats.getMinValue()); assertNull(stats.getMaxValue()); assertNull(stats.getMeanValue()); assertNull(stats.getMedianValue()); assertNull(stats.getEarliestTimestamp()); assertNull(stats.getLatestTimestamp()); assertEquals(0, stats.getTopHits().size()); } public void testCalculateGivenNumericField() { FieldStatsCalculator calculator = new FieldStatsCalculator(DOUBLE); calculator.accept(Arrays.asList("4.5", "4.5", "7", "4.5", "6", "5", "6", "5", "25", "4.5", "5")); FieldStats stats = calculator.calculate(3); assertEquals(11L, stats.getCount()); assertEquals(5, stats.getCardinality()); assertEquals(4.5, stats.getMinValue(), 1e-10); assertEquals(25.0, stats.getMaxValue(), 1e-10); assertEquals(7.0, stats.getMeanValue(), 1e-10); assertEquals(5.0, stats.getMedianValue(), 1e-10); assertNull(stats.getEarliestTimestamp()); assertNull(stats.getLatestTimestamp()); List<Map<String, Object>> topHits = stats.getTopHits(); assertEquals(3, topHits.size()); assertEquals(4.5, topHits.get(0).get("value")); assertEquals(4, topHits.get(0).get("count")); assertEquals(5, topHits.get(1).get("value")); assertEquals(3, topHits.get(1).get("count")); assertEquals(6, topHits.get(2).get("value")); assertEquals(2, topHits.get(2).get("count")); } public void testCalculateGivenStringField() { FieldStatsCalculator calculator = new FieldStatsCalculator(KEYWORD); calculator.accept(Arrays.asList("s", "s", "d", "s", "f", "x", "f", "x", "n", "s", "x")); FieldStats stats = calculator.calculate(3); assertEquals(11L, stats.getCount()); assertEquals(5, stats.getCardinality()); assertNull(stats.getMinValue()); assertNull(stats.getMaxValue()); assertNull(stats.getMeanValue()); assertNull(stats.getMedianValue()); assertNull(stats.getEarliestTimestamp()); assertNull(stats.getLatestTimestamp()); List<Map<String, Object>> topHits = stats.getTopHits(); assertEquals(3, topHits.size()); assertEquals("s", topHits.get(0).get("value")); assertEquals(4, topHits.get(0).get("count")); assertEquals("x", topHits.get(1).get("value")); assertEquals(3, topHits.get(1).get("count")); assertEquals("f", topHits.get(2).get("value")); assertEquals(2, topHits.get(2).get("count")); } public void testCalculateGivenMixedField() { FieldStatsCalculator calculator = new FieldStatsCalculator(KEYWORD); calculator.accept(Arrays.asList("4", "4", "d", "4", "f", "x", "f", "x", "16", "4", "x")); FieldStats stats = calculator.calculate(3); assertEquals(11L, stats.getCount()); assertEquals(5, stats.getCardinality()); assertNull(stats.getMinValue()); assertNull(stats.getMaxValue()); assertNull(stats.getMeanValue()); assertNull(stats.getMedianValue()); assertNull(stats.getEarliestTimestamp()); assertNull(stats.getLatestTimestamp()); List<Map<String, Object>> topHits = stats.getTopHits(); assertEquals(3, topHits.size()); assertEquals("4", topHits.get(0).get("value")); assertEquals(4, topHits.get(0).get("count")); assertEquals("x", topHits.get(1).get("value")); assertEquals(3, topHits.get(1).get("count")); assertEquals("f", topHits.get(2).get("value")); assertEquals(2, topHits.get(2).get("count")); } public void testGivenDateFieldWithoutFormat() { FieldStatsCalculator calculator = new FieldStatsCalculator(TextStructureUtils.DATE_MAPPING_WITHOUT_FORMAT); calculator.accept( Arrays.asList( "2018-10-08T10:49:16.642", "2018-10-08T10:49:16.642", "2018-10-08T10:49:16.642", "2018-09-08T11:12:13.789", "2019-01-28T01:02:03.456", "2018-09-08T11:12:13.789" ) ); FieldStats stats = calculator.calculate(3); assertEquals(6L, stats.getCount()); assertEquals(3, stats.getCardinality()); assertNull(stats.getMinValue()); assertNull(stats.getMaxValue()); assertNull(stats.getMeanValue()); assertNull(stats.getMedianValue()); assertEquals("2018-09-08T11:12:13.789", stats.getEarliestTimestamp()); assertEquals("2019-01-28T01:02:03.456", stats.getLatestTimestamp()); List<Map<String, Object>> topHits = stats.getTopHits(); assertEquals(3, topHits.size()); assertEquals("2018-10-08T10:49:16.642", topHits.get(0).get("value")); assertEquals(3, topHits.get(0).get("count")); assertEquals("2018-09-08T11:12:13.789", topHits.get(1).get("value")); assertEquals(2, topHits.get(1).get("count")); assertEquals("2019-01-28T01:02:03.456", topHits.get(2).get("value")); assertEquals(1, topHits.get(2).get("count")); } public void testGivenDateFieldWithFormat() { Map<String, String> dateMapping = new HashMap<>(); dateMapping.put(TextStructureUtils.MAPPING_TYPE_SETTING, "date"); dateMapping.put(TextStructureUtils.MAPPING_FORMAT_SETTING, "M/dd/yyyy h:mma"); FieldStatsCalculator calculator = new FieldStatsCalculator(dateMapping); calculator.accept( Arrays.asList( "10/08/2018 10:49AM", "10/08/2018 10:49AM", "10/08/2018 10:49AM", "9/08/2018 11:12AM", "1/28/2019 1:02AM", "9/08/2018 11:12AM" ) ); FieldStats stats = calculator.calculate(3); assertEquals(6L, stats.getCount()); assertEquals(3, stats.getCardinality()); assertNull(stats.getMinValue()); assertNull(stats.getMaxValue()); assertNull(stats.getMeanValue()); assertNull(stats.getMedianValue()); assertEquals("9/08/2018 11:12AM", stats.getEarliestTimestamp()); assertEquals("1/28/2019 1:02AM", stats.getLatestTimestamp()); List<Map<String, Object>> topHits = stats.getTopHits(); assertEquals(3, topHits.size()); assertEquals("10/08/2018 10:49AM", topHits.get(0).get("value")); assertEquals(3, topHits.get(0).get("count")); assertEquals("9/08/2018 11:12AM", topHits.get(1).get("value")); assertEquals(2, topHits.get(1).get("count")); assertEquals("1/28/2019 1:02AM", topHits.get(2).get("value")); assertEquals(1, topHits.get(2).get("count")); } public void testJavaStatsEquivalence() { DoubleSummaryStatistics summaryStatistics = new DoubleSummaryStatistics(); FieldStatsCalculator calculator = new FieldStatsCalculator(DOUBLE); for (int numValues = randomIntBetween(1000, 10000); numValues > 0; --numValues) { double value = randomDouble(); summaryStatistics.accept(value); calculator.accept(Collections.singletonList(Double.toString(value))); } FieldStats stats = calculator.calculate(1); assertEquals(summaryStatistics.getCount(), stats.getCount()); assertEquals(summaryStatistics.getMin(), stats.getMinValue(), 1e-10); assertEquals(summaryStatistics.getMax(), stats.getMaxValue(), 1e-10); assertEquals(summaryStatistics.getAverage(), stats.getMeanValue(), 1e-10); } }
FieldStatsCalculatorTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/filter/JsonIncludeArrayTest.java
{ "start": 1755, "end": 4455 }
class ____ { @JsonInclude(JsonInclude.Include.NON_EMPTY) public float[] value; public NonEmptyFloatArray(float... v) { value = v; } } /* /********************************************************** /* Test methods /********************************************************** */ final private ObjectMapper MAPPER = new ObjectMapper(); @Test public void testByteArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyByteArray())); } @Test public void testShortArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyShortArray())); assertEquals("{\"value\":[1]}", MAPPER.writeValueAsString(new NonEmptyShortArray((short) 1))); } @Test public void testCharArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyCharArray())); // by default considered to be serialized as String assertEquals("{\"value\":\"ab\"}", MAPPER.writeValueAsString(new NonEmptyCharArray('a', 'b'))); // but can force as sparse (real) array too assertEquals("{\"value\":[\"a\",\"b\"]}", MAPPER .writer().with(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS) .writeValueAsString(new NonEmptyCharArray('a', 'b'))); } @Test public void testIntArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyIntArray())); assertEquals("{\"value\":[2]}", MAPPER.writeValueAsString(new NonEmptyIntArray(2))); } @Test public void testLongArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyLongArray())); assertEquals("{\"value\":[3,4]}", MAPPER.writeValueAsString(new NonEmptyLongArray(3, 4))); } @Test public void testBooleanArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyBooleanArray())); assertEquals("{\"value\":[true,false]}", MAPPER.writeValueAsString(new NonEmptyBooleanArray(true,false))); } @Test public void testDoubleArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyDoubleArray())); assertEquals("{\"value\":[0.25,-1.0]}", MAPPER.writeValueAsString(new NonEmptyDoubleArray(0.25,-1.0))); } @Test public void testFloatArray() throws IOException { assertEquals("{}", MAPPER.writeValueAsString(new NonEmptyFloatArray())); assertEquals("{\"value\":[0.5]}", MAPPER.writeValueAsString(new NonEmptyFloatArray(0.5f))); } }
NonEmptyFloatArray
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java
{ "start": 23649, "end": 36395 }
class ____ extends DelegatingIntroductionInterceptor implements TimeStamped { /** * @see org.springframework.core.testfixture.TimeStamped#getTimeStamp() */ @Override public long getTimeStamp() { throw new UnsupportedOperationException(); } } pc.addAdvisor(new DefaultIntroductionAdvisor(new MyDi())); TimeStamped ts = (TimeStamped) createProxy(pc); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(ts::getTimeStamp); } /** * Should only be able to introduce interfaces, not classes. */ @Test void cannotAddIntroductionAdviceToIntroduceClass() { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); assertThatIllegalArgumentException().as("Shouldn't be able to add introduction advice that introduces a class, rather than an interface").isThrownBy(() -> pc.addAdvisor(0, new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor(), TestBean.class))) .withMessageContaining("interface"); // Check it still works: proxy factory state shouldn't have been corrupted ITestBean proxied = (ITestBean) createProxy(pc); assertThat(proxied.getAge()).isEqualTo(target.getAge()); } @Test void cannotAddInterceptorWhenFrozen() { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); assertThat(pc.isFrozen()).isFalse(); pc.addAdvice(new NopInterceptor()); ITestBean proxied = (ITestBean) createProxy(pc); pc.setFrozen(true); assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add interceptor when frozen") .isThrownBy(() -> pc.addAdvice(0, new NopInterceptor())) .withMessageContaining("frozen"); // Check it still works: proxy factory state shouldn't have been corrupted assertThat(proxied.getAge()).isEqualTo(target.getAge()); assertThat(((Advised) proxied).getAdvisors()).hasSize(1); } /** * Check that casting to Advised can't get around advice freeze. */ @Test void cannotAddAdvisorWhenFrozenUsingCast() { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); assertThat(pc.isFrozen()).isFalse(); pc.addAdvice(new NopInterceptor()); ITestBean proxied = (ITestBean) createProxy(pc); pc.setFrozen(true); Advised advised = (Advised) proxied; assertThat(pc.isFrozen()).isTrue(); assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add Advisor when frozen") .isThrownBy(() -> advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()))) .withMessageContaining("frozen"); // Check it still works: proxy factory state shouldn't have been corrupted assertThat(proxied.getAge()).isEqualTo(target.getAge()); assertThat(advised.getAdvisors()).hasSize(1); } @Test void cannotRemoveAdvisorWhenFrozen() { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); assertThat(pc.isFrozen()).isFalse(); pc.addAdvice(new NopInterceptor()); ITestBean proxied = (ITestBean) createProxy(pc); pc.setFrozen(true); Advised advised = (Advised) proxied; assertThat(pc.isFrozen()).isTrue(); assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to remove Advisor when frozen") .isThrownBy(() -> advised.removeAdvisor(0)) .withMessageContaining("frozen"); // Didn't get removed assertThat(advised.getAdvisors()).hasSize(1); pc.setFrozen(false); // Can now remove it advised.removeAdvisor(0); // Check it still works: proxy factory state shouldn't have been corrupted assertThat(proxied.getAge()).isEqualTo(target.getAge()); assertThat(advised.getAdvisors()).isEmpty(); } @Test void useAsHashKey() { TestBean target1 = new TestBean(); ProxyFactory pf1 = new ProxyFactory(target1); pf1.addAdvice(new NopInterceptor()); ITestBean proxy1 = (ITestBean) createProxy(pf1); TestBean target2 = new TestBean(); ProxyFactory pf2 = new ProxyFactory(target2); pf2.addAdvisor(new DefaultIntroductionAdvisor(new TimestampIntroductionInterceptor())); ITestBean proxy2 = (ITestBean) createProxy(pf2); HashMap<ITestBean, Object> h = new HashMap<>(); Object value1 = "foo"; Object value2 = "bar"; assertThat(h).doesNotContainKey(proxy1); h.put(proxy1, value1); h.put(proxy2, value2); assertThat(value1).isEqualTo(h.get(proxy1)); assertThat(value2).isEqualTo(h.get(proxy2)); } /** * Check that the string is informative. */ @Test void proxyConfigString() { TestBean target = new TestBean(); ProxyFactory pc = new ProxyFactory(target); pc.setInterfaces(ITestBean.class); pc.addAdvice(new NopInterceptor()); MethodBeforeAdvice mba = new CountingBeforeAdvice(); Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut(), mba); pc.addAdvisor(advisor); ITestBean proxied = (ITestBean) createProxy(pc); String proxyConfigString = ((Advised) proxied).toProxyConfigString(); assertThat(proxyConfigString).contains(advisor.toString()); assertThat(proxyConfigString).contains("1 interface"); } @Test void canPreventCastToAdvisedUsingOpaque() { TestBean target = new TestBean(); ProxyFactory pc = new ProxyFactory(target); pc.setInterfaces(ITestBean.class); pc.addAdvice(new NopInterceptor()); CountingBeforeAdvice mba = new CountingBeforeAdvice(); Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut().addMethodName("setAge"), mba); pc.addAdvisor(advisor); assertThat(pc.isOpaque()).as("Opaque defaults to false").isFalse(); pc.setOpaque(true); assertThat(pc.isOpaque()).as("Opaque now true for this config").isTrue(); ITestBean proxied = (ITestBean) createProxy(pc); proxied.setAge(10); assertThat(proxied.getAge()).isEqualTo(10); assertThat(mba.getCalls()).isEqualTo(1); boolean condition = proxied instanceof Advised; assertThat(condition).as("Cannot be cast to Advised").isFalse(); } @Test void adviceSupportListeners() { TestBean target = new TestBean(); target.setAge(21); ProxyFactory pc = new ProxyFactory(target); CountingAdvisorListener l = new CountingAdvisorListener(pc); pc.addListener(l); RefreshCountingAdvisorChainFactory acf = new RefreshCountingAdvisorChainFactory(); // Should be automatically added as a listener pc.addListener(acf); assertThat(pc.isActive()).isFalse(); assertThat(l.activates).isEqualTo(0); assertThat(acf.refreshes).isEqualTo(0); ITestBean proxied = (ITestBean) createProxy(pc); assertThat(acf.refreshes).isEqualTo(1); assertThat(l.activates).isEqualTo(1); assertThat(pc.isActive()).isTrue(); assertThat(proxied.getAge()).isEqualTo(target.getAge()); assertThat(l.adviceChanges).isEqualTo(0); NopInterceptor di = new NopInterceptor(); pc.addAdvice(0, di); assertThat(l.adviceChanges).isEqualTo(1); assertThat(acf.refreshes).isEqualTo(2); assertThat(proxied.getAge()).isEqualTo(target.getAge()); pc.removeAdvice(di); assertThat(l.adviceChanges).isEqualTo(2); assertThat(acf.refreshes).isEqualTo(3); assertThat(proxied.getAge()).isEqualTo(target.getAge()); pc.getProxy(); assertThat(l.activates).isEqualTo(1); pc.removeListener(l); assertThat(l.adviceChanges).isEqualTo(2); pc.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor())); // No longer counting assertThat(l.adviceChanges).isEqualTo(2); } @Test void existingProxyChangesTarget() { TestBean tb1 = new TestBean(); tb1.setAge(33); TestBean tb2 = new TestBean(); tb2.setAge(26); tb2.setName("Juergen"); TestBean tb3 = new TestBean(); tb3.setAge(37); ProxyFactory pc = new ProxyFactory(tb1); NopInterceptor nop = new NopInterceptor(); pc.addAdvice(nop); ITestBean proxy = (ITestBean) createProxy(pc); assertThat(nop.getCount()).isZero(); assertThat(proxy.getAge()).isEqualTo(tb1.getAge()); assertThat(nop.getCount()).isOne(); // Change to a new static target pc.setTarget(tb2); assertThat(proxy.getAge()).isEqualTo(tb2.getAge()); assertThat(nop.getCount()).isEqualTo(2); // Change to a new dynamic target HotSwappableTargetSource hts = new HotSwappableTargetSource(tb3); pc.setTargetSource(hts); assertThat(proxy.getAge()).isEqualTo(tb3.getAge()); assertThat(nop.getCount()).isEqualTo(3); hts.swap(tb1); assertThat(proxy.getAge()).isEqualTo(tb1.getAge()); tb1.setName("Colin"); assertThat(proxy.getName()).isEqualTo(tb1.getName()); assertThat(nop.getCount()).isEqualTo(5); // Change back, relying on casting to Advised Advised advised = (Advised) proxy; assertThat(advised.getTargetSource()).isSameAs(hts); SingletonTargetSource sts = new SingletonTargetSource(tb2); advised.setTargetSource(sts); assertThat(proxy.getName()).isEqualTo(tb2.getName()); assertThat(advised.getTargetSource()).isSameAs(sts); assertThat(proxy.getAge()).isEqualTo(tb2.getAge()); } @Test void dynamicMethodPointcutThatAlwaysAppliesStatically() { TestBean tb = new TestBean(); ProxyFactory pc = new ProxyFactory(); pc.addInterface(ITestBean.class); TestDynamicPointcutAdvice dp = new TestDynamicPointcutAdvice(new NopInterceptor(), "getAge"); pc.addAdvisor(dp); pc.setTarget(tb); ITestBean it = (ITestBean) createProxy(pc); assertThat(dp.count).isEqualTo(0); it.getAge(); assertThat(dp.count).isEqualTo(1); it.setAge(11); assertThat(it.getAge()).isEqualTo(11); assertThat(dp.count).isEqualTo(2); } @Test void dynamicMethodPointcutThatAppliesStaticallyOnlyToSetters() { TestBean tb = new TestBean(); ProxyFactory pc = new ProxyFactory(); pc.addInterface(ITestBean.class); // Could apply dynamically to getAge/setAge but not to getName TestDynamicPointcutForSettersOnly dp = new TestDynamicPointcutForSettersOnly(new NopInterceptor(), "Age"); pc.addAdvisor(dp); this.mockTargetSource.setTarget(tb); pc.setTargetSource(mockTargetSource); ITestBean it = (ITestBean) createProxy(pc); assertThat(dp.count).isEqualTo(0); it.getAge(); // Statically vetoed assertThat(dp.count).isEqualTo(0); it.setAge(11); assertThat(it.getAge()).isEqualTo(11); assertThat(dp.count).isEqualTo(1); // Applies statically but not dynamically it.setName("joe"); assertThat(dp.count).isEqualTo(1); } @Test void staticMethodPointcut() { TestBean tb = new TestBean(); ProxyFactory pc = new ProxyFactory(); pc.addInterface(ITestBean.class); NopInterceptor di = new NopInterceptor(); TestStaticPointcutAdvice sp = new TestStaticPointcutAdvice(di, "getAge"); pc.addAdvisor(sp); pc.setTarget(tb); ITestBean it = (ITestBean) createProxy(pc); assertThat(di.getCount()).isEqualTo(0); it.getAge(); assertThat(di.getCount()).isEqualTo(1); it.setAge(11); assertThat(it.getAge()).isEqualTo(11); assertThat(di.getCount()).isEqualTo(2); } /** * There are times when we want to call proceed() twice. * We can do this if we clone the invocation. */ @Test void cloneInvocationToProceedThreeTimes() { TestBean tb = new TestBean(); ProxyFactory pc = new ProxyFactory(tb); pc.addInterface(ITestBean.class); MethodInterceptor twoBirthdayInterceptor = mi -> { // Clone the invocation to proceed three times // "The Moor's Last Sigh": this technology can cause premature aging MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone(); MethodInvocation clone2 = ((ReflectiveMethodInvocation) mi).invocableClone(); clone1.proceed(); clone2.proceed(); return mi.proceed(); }; @SuppressWarnings("serial") StaticMethodMatcherPointcutAdvisor advisor = new StaticMethodMatcherPointcutAdvisor(twoBirthdayInterceptor) { @Override public boolean matches(Method m, @Nullable Class<?> targetClass) { return "haveBirthday".equals(m.getName()); } }; pc.addAdvisor(advisor); ITestBean it = (ITestBean) createProxy(pc); final int age = 20; it.setAge(age); assertThat(it.getAge()).isEqualTo(age); // Should return the age before the third, AOP-induced birthday assertThat(it.haveBirthday()).isEqualTo((age + 2)); // Return the final age produced by 3 birthdays assertThat(it.getAge()).isEqualTo((age + 3)); } /** * We want to change the arguments on a clone: it shouldn't affect the original. */ @Test void canChangeArgumentsIndependentlyOnClonedInvocation() { TestBean tb = new TestBean(); ProxyFactory pc = new ProxyFactory(tb); pc.addInterface(ITestBean.class); MethodInterceptor nameReverter = mi -> { MethodInvocation clone = ((ReflectiveMethodInvocation) mi).invocableClone(); String oldName = ((ITestBean) mi.getThis()).getName(); clone.getArguments()[0] = oldName; // Original method invocation should be unaffected by changes to argument list of clone mi.proceed(); return clone.proceed(); };
MyDi
java
elastic__elasticsearch
modules/repository-azure/src/internalClusterTest/java/org/elasticsearch/repositories/azure/AzureBlobStoreRepositoryTests.java
{ "start": 8562, "end": 9868 }
class ____ extends AzureRepositoryPlugin { public TestAzureRepositoryPlugin(Settings settings) { super(settings); } @Override AzureStorageService createAzureStorageService( Settings settingsToUse, AzureClientProvider azureClientProvider, ClusterService clusterService, ProjectResolver projectResolver ) { return new AzureStorageService(settingsToUse, azureClientProvider, clusterService, projectResolver) { @Override RequestRetryOptions getRetryOptions(LocationMode locationMode, AzureStorageSettings azureStorageSettings) { return new RequestRetryOptions( RetryPolicyType.EXPONENTIAL, azureStorageSettings.getMaxRetries() + 1, 60, 5L, 10L, null ); } @Override long getUploadBlockSize() { return ByteSizeUnit.MB.toBytes(1); } }; } } @SuppressForbidden(reason = "this test uses a HttpHandler to emulate an Azure endpoint") private static
TestAzureRepositoryPlugin
java
quarkusio__quarkus
extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/sql_load_script/FileNotFoundSqlLoadScriptTestCase.java
{ "start": 1336, "end": 1670 }
class ____ { @Id public long id; public String name; public MyEntity() { } public MyEntity(String name) { this.name = name; } @Override public String toString() { return getClass().getSimpleName() + ":" + name; } } }
MyEntity
java
spring-projects__spring-framework
spring-tx/src/testFixtures/java/org/springframework/transaction/testfixture/ReactiveCallCountingTransactionManager.java
{ "start": 1150, "end": 2323 }
class ____ extends AbstractReactiveTransactionManager { public TransactionDefinition lastDefinition; public int begun; public int commits; public int rollbacks; public int inflight; @Override protected Object doGetTransaction(TransactionSynchronizationManager synchronizationManager) throws TransactionException { return new Object(); } @Override protected Mono<Void> doBegin(TransactionSynchronizationManager synchronizationManager, Object transaction, TransactionDefinition definition) throws TransactionException { this.lastDefinition = definition; ++begun; ++inflight; return Mono.empty(); } @Override protected Mono<Void> doCommit(TransactionSynchronizationManager synchronizationManager, GenericReactiveTransaction status) throws TransactionException { ++commits; --inflight; return Mono.empty(); } @Override protected Mono<Void> doRollback(TransactionSynchronizationManager synchronizationManager, GenericReactiveTransaction status) throws TransactionException { ++rollbacks; --inflight; return Mono.empty(); } public void clear() { begun = commits = rollbacks = inflight = 0; } }
ReactiveCallCountingTransactionManager
java
bumptech__glide
samples/imgur/src/main/java/com/bumptech/glide/samples/imgur/MainActivityModule.java
{ "start": 133, "end": 250 }
class ____ { @ContributesAndroidInjector abstract MainActivity contributeMainActivityInjector(); }
MainActivityModule
java
greenrobot__EventBus
EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusMultithreadedTest.java
{ "start": 903, "end": 6423 }
class ____ extends AbstractEventBusTest { static final int COUNT = LONG_TESTS ? 100000 : 1000; final AtomicInteger countStringEvent = new AtomicInteger(); final AtomicInteger countIntegerEvent = new AtomicInteger(); final AtomicInteger countObjectEvent = new AtomicInteger(); final AtomicInteger countIntTestEvent = new AtomicInteger(); String lastStringEvent; Integer lastIntegerEvent; IntTestEvent lastIntTestEvent; @Test public void testPost01Thread() throws InterruptedException { runThreadsSingleEventType(1); } @Test public void testPost04Threads() throws InterruptedException { runThreadsSingleEventType(4); } @Test public void testPost40Threads() throws InterruptedException { runThreadsSingleEventType(40); } @Test public void testPostMixedEventType01Thread() throws InterruptedException { runThreadsMixedEventType(1); } @Test public void testPostMixedEventType04Threads() throws InterruptedException { runThreadsMixedEventType(4); } @Test public void testPostMixedEventType40Threads() throws InterruptedException { runThreadsMixedEventType(40); } private void runThreadsSingleEventType(int threadCount) throws InterruptedException { int iterations = COUNT / threadCount; eventBus.register(this); CountDownLatch latch = new CountDownLatch(threadCount + 1); List<PosterThread> threads = startThreads(latch, threadCount, iterations, "Hello"); long time = triggerAndWaitForThreads(threads, latch); log(threadCount + " threads posted " + iterations + " events each in " + time + "ms"); waitForEventCount(COUNT * 2, 5000); assertEquals("Hello", lastStringEvent); int expectedCount = threadCount * iterations; assertEquals(expectedCount, countStringEvent.intValue()); assertEquals(expectedCount, countObjectEvent.intValue()); } private void runThreadsMixedEventType(int threadCount) throws InterruptedException { runThreadsMixedEventType(COUNT, threadCount); } void runThreadsMixedEventType(int count, int threadCount) throws InterruptedException { eventBus.register(this); int eventTypeCount = 3; int iterations = count / threadCount / eventTypeCount; CountDownLatch latch = new CountDownLatch(eventTypeCount * threadCount + 1); List<PosterThread> threadsString = startThreads(latch, threadCount, iterations, "Hello"); List<PosterThread> threadsInteger = startThreads(latch, threadCount, iterations, 42); List<PosterThread> threadsIntTestEvent = startThreads(latch, threadCount, iterations, new IntTestEvent(7)); List<PosterThread> threads = new ArrayList<PosterThread>(); threads.addAll(threadsString); threads.addAll(threadsInteger); threads.addAll(threadsIntTestEvent); long time = triggerAndWaitForThreads(threads, latch); log(threadCount * eventTypeCount + " mixed threads posted " + iterations + " events each in " + time + "ms"); int expectedCountEach = threadCount * iterations; int expectedCountTotal = expectedCountEach * eventTypeCount * 2; waitForEventCount(expectedCountTotal, 5000); assertEquals("Hello", lastStringEvent); assertEquals(42, lastIntegerEvent.intValue()); assertEquals(7, lastIntTestEvent.value); assertEquals(expectedCountEach, countStringEvent.intValue()); assertEquals(expectedCountEach, countIntegerEvent.intValue()); assertEquals(expectedCountEach, countIntTestEvent.intValue()); assertEquals(expectedCountEach * eventTypeCount, countObjectEvent.intValue()); } private long triggerAndWaitForThreads(List<PosterThread> threads, CountDownLatch latch) throws InterruptedException { while (latch.getCount() != 1) { // Let all other threads prepare and ensure this one is the last Thread.sleep(1); } long start = System.currentTimeMillis(); latch.countDown(); for (PosterThread thread : threads) { thread.join(); } return System.currentTimeMillis() - start; } private List<PosterThread> startThreads(CountDownLatch latch, int threadCount, int iterations, Object eventToPost) { List<PosterThread> threads = new ArrayList<PosterThread>(threadCount); for (int i = 0; i < threadCount; i++) { PosterThread thread = new PosterThread(latch, iterations, eventToPost); thread.start(); threads.add(thread); } return threads; } @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onEventBackgroundThread(String event) { lastStringEvent = event; countStringEvent.incrementAndGet(); trackEvent(event); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(Integer event) { lastIntegerEvent = event; countIntegerEvent.incrementAndGet(); trackEvent(event); } @Subscribe(threadMode = ThreadMode.ASYNC) public void onEventAsync(IntTestEvent event) { countIntTestEvent.incrementAndGet(); lastIntTestEvent = event; trackEvent(event); } @Subscribe public void onEvent(Object event) { countObjectEvent.incrementAndGet(); trackEvent(event); }
EventBusMultithreadedTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/recovery/PeerRecoverySourceService.java
{ "start": 9042, "end": 13949 }
class ____ { private final Map<IndexShard, ShardRecoveryContext> ongoingRecoveries = new HashMap<>(); private final Map<DiscoveryNode, Collection<RemoteRecoveryTargetHandler>> nodeToHandlers = new HashMap<>(); @Nullable private List<ActionListener<Void>> emptyListeners; synchronized RecoverySourceHandler addNewRecovery(StartRecoveryRequest request, Task task, IndexShard shard) { assert lifecycle.started(); final ShardRecoveryContext shardContext = ongoingRecoveries.computeIfAbsent(shard, s -> new ShardRecoveryContext()); final Tuple<RecoverySourceHandler, RemoteRecoveryTargetHandler> handlers = shardContext.addNewRecovery(request, task, shard); final RemoteRecoveryTargetHandler recoveryTargetHandler = handlers.v2(); nodeToHandlers.computeIfAbsent(recoveryTargetHandler.targetNode(), k -> new HashSet<>()).add(recoveryTargetHandler); shard.recoveryStats().incCurrentAsSource(); return handlers.v1(); } synchronized void cancelOnNodeLeft(DiscoveryNode node) { final Collection<RemoteRecoveryTargetHandler> handlers = nodeToHandlers.get(node); if (handlers != null) { for (RemoteRecoveryTargetHandler handler : handlers) { handler.cancel(); } } } synchronized void reestablishRecovery( ReestablishRecoveryRequest request, IndexShard shard, ActionListener<RecoveryResponse> listener ) { assert lifecycle.started(); final ShardRecoveryContext shardContext = ongoingRecoveries.get(shard); if (shardContext == null) { throw new PeerRecoveryNotFound(request.recoveryId(), request.shardId(), request.targetAllocationId()); } shardContext.reestablishRecovery(request, listener); } synchronized void remove(IndexShard shard, RecoverySourceHandler handler) { final ShardRecoveryContext shardRecoveryContext = ongoingRecoveries.get(shard); assert shardRecoveryContext != null : "Shard was not registered [" + shard + "]"; final RemoteRecoveryTargetHandler removed = shardRecoveryContext.recoveryHandlers.remove(handler); assert removed != null : "Handler was not registered [" + handler + "]"; if (removed != null) { shard.recoveryStats().decCurrentAsSource(); removed.cancel(); assert nodeToHandlers.getOrDefault(removed.targetNode(), Collections.emptySet()).contains(removed) : "Remote recovery was not properly tracked [" + removed + "]"; nodeToHandlers.computeIfPresent(removed.targetNode(), (k, handlersForNode) -> { handlersForNode.remove(removed); if (handlersForNode.isEmpty()) { return null; } return handlersForNode; }); } if (shardRecoveryContext.recoveryHandlers.isEmpty()) { ongoingRecoveries.remove(shard); } if (ongoingRecoveries.isEmpty()) { if (emptyListeners != null) { final List<ActionListener<Void>> onEmptyListeners = emptyListeners; emptyListeners = null; ActionListener.onResponse(onEmptyListeners, null); } } } synchronized void cancel(IndexShard shard) { final ShardRecoveryContext shardRecoveryContext = ongoingRecoveries.get(shard); if (shardRecoveryContext != null) { final List<Exception> failures = new ArrayList<>(); for (RecoverySourceHandler handlers : shardRecoveryContext.recoveryHandlers.keySet()) { try { handlers.cancel("shard is closed"); } catch (Exception ex) { failures.add(ex); } finally { shard.recoveryStats().decCurrentAsSource(); } } ExceptionsHelper.maybeThrowRuntimeAndSuppress(failures); } } void awaitEmpty() { assert lifecycle.stoppedOrClosed(); final PlainActionFuture<Void> future; synchronized (this) { if (ongoingRecoveries.isEmpty()) { return; } future = new PlainActionFuture<>(); if (emptyListeners == null) { emptyListeners = new ArrayList<>(); } emptyListeners.add(future); } FutureUtils.get(future); } private final
OngoingRecoveries
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/runtime/src/main/java/io/quarkus/restclient/runtime/RestClientRecorder.java
{ "start": 3045, "end": 3124 }
class ____ provider " + providerToRegister, e); } } } }
for
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/wrongannotations/WrongPostConstructPreDestroyTest.java
{ "start": 458, "end": 1167 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot(root -> root .addClasses(MySingleton.class)) .assertException(t -> { Throwable rootCause = ExceptionUtil.getRootCause(t); assertTrue(rootCause.getMessage().contains("javax.annotation.PostConstruct"), t.toString()); assertTrue(rootCause.getMessage().contains("javax.annotation.PreDestroy"), t.toString()); }); @Test public void testValidationFailed() { // This method should not be invoked fail(); } @Singleton static
WrongPostConstructPreDestroyTest
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/query/handler/ConfigChainEntryHandler.java
{ "start": 1378, "end": 3460 }
class ____ extends AbstractConfigQueryHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigChainEntryHandler.class); private static final String CHAIN_ENTRY_HANDLER = "chainEntryHandler"; private static final ThreadLocal<CacheItem> CACHE_ITEM_THREAD_LOCAL = new ThreadLocal<>(); @Override public String getName() { return CHAIN_ENTRY_HANDLER; } @Override public ConfigQueryChainResponse handle(ConfigQueryChainRequest request) throws IOException { request.setTenant(NamespaceUtil.processNamespaceParameter(request.getTenant())); String groupKey = GroupKey2.getKey(request.getDataId(), request.getGroup(), request.getTenant()); int lockResult = ConfigCacheService.tryConfigReadLock(groupKey); CacheItem cacheItem = ConfigCacheService.getContentCache(groupKey); if (lockResult > 0 && cacheItem != null) { try { CACHE_ITEM_THREAD_LOCAL.set(cacheItem); if (nextHandler != null) { return nextHandler.handle(request); } else { LOGGER.warn("chainEntryHandler's next handler is null"); return new ConfigQueryChainResponse(); } } finally { CACHE_ITEM_THREAD_LOCAL.remove(); ConfigCacheService.releaseReadLock(groupKey); } } else if (lockResult == 0 || cacheItem == null) { ConfigQueryChainResponse response = new ConfigQueryChainResponse(); response.setStatus(ConfigQueryChainResponse.ConfigQueryStatus.CONFIG_NOT_FOUND); return response; } else { ConfigQueryChainResponse response = new ConfigQueryChainResponse(); response.setStatus(ConfigQueryChainResponse.ConfigQueryStatus.CONFIG_QUERY_CONFLICT); return response; } } public static CacheItem getThreadLocalCacheItem() { return CACHE_ITEM_THREAD_LOCAL.get(); } }
ConfigChainEntryHandler
java
quarkusio__quarkus
devtools/cli/src/main/java/io/quarkus/cli/Test.java
{ "start": 761, "end": 1520 }
class ____ extends BaseBuildCommand implements Callable<Integer> { @CommandLine.ArgGroup(order = 1, exclusive = false, heading = "%nContinuous Test Mode options:%n") DevOptions testOptions = new DevOptions(); @CommandLine.ArgGroup(order = 3, exclusive = false, validate = true, heading = "%nDebug options:%n") DebugOptions debugOptions = new DebugOptions(); @CommandLine.Option(names = "--once", description = "Run the test suite with continuous mode disabled.") boolean runOnce = false; @CommandLine.Option(names = "--filter", description = { "Run a subset of the test suite that matches the given filter.", "If continuous testing is enabled then the value is a regular expression that is matched against the test
Test
java
netty__netty
transport-native-unix-common/src/main/java/io/netty/channel/unix/UnixChannel.java
{ "start": 811, "end": 974 }
interface ____ extends Channel { /** * Returns the {@link FileDescriptor} that is used by this {@link Channel}. */ FileDescriptor fd(); }
UnixChannel
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/JoinQueryOperation.java
{ "start": 1441, "end": 1952 }
class ____ implements QueryOperation { private static final String INPUT_1_ALIAS = "$$T1_JOIN"; private static final String INPUT_2_ALIAS = "$$T2_JOIN"; private final QueryOperation left; private final QueryOperation right; private final JoinType joinType; private final ResolvedExpression condition; private final boolean correlated; private final ResolvedSchema resolvedSchema; /** Specifies how the two Tables should be joined. */ @Internal public
JoinQueryOperation
java
google__guice
core/src/com/google/inject/internal/Annotations.java
{ "start": 7870, "end": 9639 }
class ____ { final boolean quote; final boolean includeMemberName; final boolean dollarSeparator; AnnotationToStringConfig(boolean quote, boolean includeMemberName, boolean dollarSeparator) { this.quote = quote; this.includeMemberName = includeMemberName; this.dollarSeparator = dollarSeparator; } } private static final AnnotationToStringConfig ANNOTATION_TO_STRING_CONFIG = determineAnnotationToStringConfig(); /** * Returns {@code value}, quoted if annotation implementations quote their member values. In Java * 9, annotations quote their string members. */ public static String memberValueString(String value) { return ANNOTATION_TO_STRING_CONFIG.quote ? "\"" + value + "\"" : value; } /** * Returns string representation of the annotation memeber. * * <p>The value of the member is prefixed with `memberName=` unless the runtime omits the member * name. The value of the member is quoted if annotation implementations quote their member values * and the value type is String. * * <p>In Java 9, annotations quote their string members and in Java 15, the member name is * omitted. */ public static String memberValueString(String memberName, Object value) { StringBuilder sb = new StringBuilder(); boolean quote = ANNOTATION_TO_STRING_CONFIG.quote; boolean includeMemberName = ANNOTATION_TO_STRING_CONFIG.includeMemberName; if (includeMemberName) { sb.append(memberName).append('='); } if (quote && (value instanceof String)) { sb.append('"').append(value).append('"'); } else { sb.append(value); } return sb.toString(); } /** * Returns the string representation of the annotation
AnnotationToStringConfig
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConsumerIncludeNameIT.java
{ "start": 1076, "end": 2331 }
class ____ extends FtpServerTestSupport { private String getFtpUrl() { return "ftp://admin@localhost:{{ftp.server.port}}/includename?password=admin" + "&include=report.*&exclude=.*xml"; } @Override public void doPostSetup() throws Exception { prepareFtpServer(); } @Test public void testIncludeAndExludePreAndPostfixes() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedBodiesReceived("Report 1"); mock.assertIsSatisfied(); } private void prepareFtpServer() { // prepares the FTP Server by creating files on the server that we want // to unit // test that we can pool and store as a local file sendFile(getFtpUrl(), "Hello World", "hello.xml"); sendFile(getFtpUrl(), "Report 1", "report1.txt"); sendFile(getFtpUrl(), "Bye World", "secret.txt"); sendFile(getFtpUrl(), "Report 2", "report2.xml"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(getFtpUrl()).to("mock:result"); } }; } }
FtpConsumerIncludeNameIT
java
apache__kafka
storage/src/test/java/org/apache/kafka/tiered/storage/integration/DeleteTopicTest.java
{ "start": 1326, "end": 3545 }
class ____ extends TieredStorageTestHarness { @Override public int brokerCount() { return 2; } @Override protected void writeTestSpecifications(TieredStorageTestBuilder builder) { final int broker0 = 0; final int broker1 = 1; final String topicA = "topicA"; final int p0 = 0; final int p1 = 1; final int partitionCount = 2; final int replicationFactor = 2; final int maxBatchCountPerSegment = 1; final boolean enableRemoteLogStorage = true; final Map<Integer, List<Integer>> assignment = mkMap( mkEntry(p0, List.of(broker0, broker1)), mkEntry(p1, List.of(broker1, broker0)) ); builder .createTopic(topicA, partitionCount, replicationFactor, maxBatchCountPerSegment, assignment, enableRemoteLogStorage) // send records to partition 0 .expectSegmentToBeOffloaded(broker0, topicA, p0, 0, new KeyValueSpec("k0", "v0")) .expectSegmentToBeOffloaded(broker0, topicA, p0, 1, new KeyValueSpec("k1", "v1")) .expectEarliestLocalOffsetInLogDirectory(topicA, p0, 2L) .produce(topicA, p0, new KeyValueSpec("k0", "v0"), new KeyValueSpec("k1", "v1"), new KeyValueSpec("k2", "v2")) // send records to partition 1 .expectSegmentToBeOffloaded(broker1, topicA, p1, 0, new KeyValueSpec("k0", "v0")) .expectSegmentToBeOffloaded(broker1, topicA, p1, 1, new KeyValueSpec("k1", "v1")) .expectEarliestLocalOffsetInLogDirectory(topicA, p1, 2L) .produce(topicA, p1, new KeyValueSpec("k0", "v0"), new KeyValueSpec("k1", "v1"), new KeyValueSpec("k2", "v2")) // delete the topic .expectDeletionInRemoteStorage(broker0, topicA, p0, DELETE_SEGMENT, 2) .expectDeletionInRemoteStorage(broker1, topicA, p1, DELETE_SEGMENT, 2) .deleteTopic(List.of(topicA)) .expectEmptyRemoteStorage(topicA, p0) .expectEmptyRemoteStorage(topicA, p1); } }
DeleteTopicTest
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/SimpleDiffableSerializationTestCase.java
{ "start": 829, "end": 1005 }
class ____ tests of Metadata.MetadataCustom classes and other classes that support, * Writable serialization, XContent-based serialization and is diffable. */ public abstract
for
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/SampleLongAggregatorFunctionTests.java
{ "start": 1264, "end": 3821 }
class ____ extends AggregatorFunctionTestCase { private static final int LIMIT = 50; @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { return new SequenceLongBlockSourceOperator(blockFactory, LongStream.range(0, size).map(l -> randomLong())); } @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new SampleLongAggregatorFunctionSupplier(LIMIT); } @Override protected String expectedDescriptionOfAggregator() { return "sample of longs"; } @Override public void assertSimpleOutput(List<Page> input, Block result) { Set<Long> inputValues = input.stream().flatMapToLong(p -> allLongs(p.getBlock(0))).boxed().collect(Collectors.toSet()); Long[] resultValues = AggregatorFunctionTestCase.allLongs(result).boxed().toArray(Long[]::new); assertThat(resultValues, arrayWithSize(Math.min(inputValues.size(), LIMIT))); assertThat(inputValues, hasItems(resultValues)); } public void testDistribution() { // Sample from the numbers 0...99. int N = 100; Aggregator.Factory aggregatorFactory = aggregatorFunction().aggregatorFactory(AggregatorMode.SINGLE, List.of(0)); AggregationOperator.AggregationOperatorFactory operatorFactory = new AggregationOperator.AggregationOperatorFactory( List.of(aggregatorFactory), AggregatorMode.SINGLE ); // Repeat 1000x, count how often each number is sampled. int[] sampledCounts = new int[N]; for (int iteration = 0; iteration < 1000; iteration++) { List<Page> input = CannedSourceOperator.collectPages( new SequenceLongBlockSourceOperator(driverContext().blockFactory(), LongStream.range(0, N)) ); List<Page> results = drive(operatorFactory.get(driverContext()), input.iterator(), driverContext()); for (Page page : results) { LongBlock block = page.getBlock(0); for (int i = 0; i < block.getTotalValueCount(); i++) { sampledCounts[(int) block.getLong(i)]++; } } MixWithIncrement.next(); } // On average, each number should be sampled 500x. // The interval [300,700] is approx. 10 sigma, so this should never fail. for (int i = 0; i < N; i++) { assertThat(sampledCounts[i], both(greaterThan(300)).and(lessThan(700))); } } }
SampleLongAggregatorFunctionTests
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/impl/ITestUploadPurgeOnDirectoryOperations.java
{ "start": 2372, "end": 5517 }
class ____ extends AbstractS3ACostTest { @Override public Configuration createConfiguration() { final Configuration conf = super.createConfiguration(); removeBaseAndBucketOverrides(conf, DIRECTORY_OPERATIONS_PURGE_UPLOADS, MAGIC_COMMITTER_ENABLED); conf.setBoolean(DIRECTORY_OPERATIONS_PURGE_UPLOADS, true); conf.setBoolean(MAGIC_COMMITTER_ENABLED, true); return conf; } @BeforeEach @Override public void setup() throws Exception { super.setup(); final S3AFileSystem fs = getFileSystem(); assumeMultipartUploads(fs.getConf()); assertHasPathCapabilities(fs, new Path("/"), DIRECTORY_OPERATIONS_PURGE_UPLOADS); clearAnyUploads(fs, methodPath()); } @Test public void testDeleteWithPendingUpload() throws Throwable { final S3AFileSystem fs = getFileSystem(); final Path dir = methodPath(); // create a magic file. createMagicFile(fs, dir); // and there's a pending upload assertUploadCount(dir, 1); // delete the dir, with a cost of 1 abort, 1 list. verifyMetrics(() -> fs.delete(dir, true), with(OBJECT_MULTIPART_UPLOAD_ABORTED, 1), // abort with(OBJECT_MULTIPART_UPLOAD_LIST, 1), // HTTP request inside iterator with(MULTIPART_UPLOAD_LIST, 0)); // api list call // and the pending upload is gone assertUploadCount(dir, 0); } @Test public void testRenameWithPendingUpload() throws Throwable { final S3AFileSystem fs = getFileSystem(); final Path base = methodPath(); final Path dir = new Path(base, "src"); final Path dest = new Path(base, "dest"); // create a magic file. createMagicFile(fs, dir); // and there's a pending upload assertUploadCount(dir, 1); // rename the dir, with a cost of 1 abort, 1 list. verifyMetrics(() -> fs.rename(dir, dest), with(OBJECT_MULTIPART_UPLOAD_ABORTED, 1), // abort with(OBJECT_MULTIPART_UPLOAD_LIST, 1), // HTTP request inside iterator with(MULTIPART_UPLOAD_LIST, 0)); // api list call // and there isn't assertUploadCount(dir, 0); } /** * Assert the upload count under a dir is the expected value. * Failure message will include the list of entries. * @param dir dir * @param expected expected count * @throws IOException listing problem */ private void assertUploadCount(final Path dir, final int expected) throws IOException { Assertions.assertThat(toList(listUploads(dir))) .describedAs("uploads under %s", dir) .hasSize(expected); } /** * List uploads; use the same APIs that the directory operations use, * so implicitly validating them. * @param dir directory to list * @return full list of entries * @throws IOException listing problem */ private RemoteIterator<MultipartUpload> listUploads(Path dir) throws IOException { final S3AFileSystem fs = getFileSystem(); try (AuditSpan ignored = span()) { final StoreContext sc = fs.createStoreContext(); return fs.listUploadsUnderPrefix(sc, sc.pathToKey(dir)); } } }
ITestUploadPurgeOnDirectoryOperations
java
resilience4j__resilience4j
resilience4j-micrometer/src/main/java/io/github/resilience4j/micrometer/tagged/RateLimiterMetricNames.java
{ "start": 107, "end": 1849 }
class ____ { private static final String DEFAULT_PREFIX = "resilience4j.ratelimiter"; public static final String DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME = DEFAULT_PREFIX + ".available.permissions"; public static final String DEFAULT_WAITING_THREADS_METRIC_NAME = DEFAULT_PREFIX + ".waiting_threads"; private String availablePermissionsMetricName = DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME; private String waitingThreadsMetricName = DEFAULT_WAITING_THREADS_METRIC_NAME; /** * Returns a builder for creating custom metric names. Note that names have default values, * so only desired metrics can be renamed. * * @return The builder. */ public static Builder custom() { return new Builder(); } /** * Returns default metric names. * * @return The default {@link RateLimiterMetricNames} instance. */ public static RateLimiterMetricNames ofDefaults() { return new RateLimiterMetricNames(); } /** * Returns the metric name for available permissions, defaults to {@value * DEFAULT_AVAILABLE_PERMISSIONS_METRIC_NAME}. * * @return The available permissions metric name. */ public String getAvailablePermissionsMetricName() { return availablePermissionsMetricName; } /** * Returns the metric name for waiting threads, defaults to {@value * DEFAULT_WAITING_THREADS_METRIC_NAME}. * * @return The waiting threads metric name. */ public String getWaitingThreadsMetricName() { return waitingThreadsMetricName; } /** * Helps building custom instance of {@link RateLimiterMetricNames}. */ public static
RateLimiterMetricNames
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/script/StoredScriptsIT.java
{ "start": 1666, "end": 4230 }
class ____ extends ESIntegTestCase { private static final int SCRIPT_MAX_SIZE_IN_BYTES = 64; private static final String LANG = MockScriptEngine.NAME; @Override protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal, otherSettings)) .put(ScriptService.SCRIPT_MAX_SIZE_IN_BYTES.getKey(), SCRIPT_MAX_SIZE_IN_BYTES) .build(); } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(CustomScriptPlugin.class); } public void testBasics() { putJsonStoredScript("foobar", Strings.format(""" {"script": {"lang": "%s", "source": "1"} } """, LANG)); String script = safeExecute(GetStoredScriptAction.INSTANCE, new GetStoredScriptRequest(TEST_REQUEST_TIMEOUT, "foobar")).getSource() .getSource(); assertNotNull(script); assertEquals("1", script); assertAcked( safeExecute( TransportDeleteStoredScriptAction.TYPE, new DeleteStoredScriptRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "foobar") ) ); StoredScriptSource source = safeExecute(GetStoredScriptAction.INSTANCE, new GetStoredScriptRequest(TEST_REQUEST_TIMEOUT, "foobar")) .getSource(); assertNull(source); assertEquals( "Validation Failed: 1: id cannot contain '#' for stored script;", safeAwaitAndUnwrapFailure( IllegalArgumentException.class, AcknowledgedResponse.class, l -> client().execute(TransportPutStoredScriptAction.TYPE, newPutStoredScriptTestRequest("id#", Strings.format(""" {"script": {"lang": "%s", "source": "1"} } """, LANG)), l) ).getMessage() ); } public void testMaxScriptSize() { assertEquals( "exceeded max allowed stored script size in bytes [64] with size [65] for script [foobar]", safeAwaitAndUnwrapFailure( IllegalArgumentException.class, AcknowledgedResponse.class, l -> client().execute(TransportPutStoredScriptAction.TYPE, newPutStoredScriptTestRequest("foobar", Strings.format(""" {"script": { "lang": "%s", "source":"0123456789abcdef"} }\ """, LANG)), l) ).getMessage() ); } public static
StoredScriptsIT
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/processor/PopMessageResultFilter.java
{ "start": 1077, "end": 1292 }
enum ____ { TO_DLQ, NO_MATCH, MATCH } FilterResult filterMessage(ProxyContext ctx, String consumerGroup, SubscriptionData subscriptionData, MessageExt messageExt); }
FilterResult
java
elastic__elasticsearch
qa/packaging/src/test/java/org/elasticsearch/packaging/util/Distribution.java
{ "start": 3328, "end": 3508 }
enum ____ { LINUX, WINDOWS, DARWIN; public String toString() { return name().toLowerCase(Locale.ROOT); } } public
Platform
java
google__guava
guava-tests/test/com/google/common/collect/ImmutableMapFloodingTest.java
{ "start": 1328, "end": 3656 }
enum ____ implements Construction<Map<Object, Object>> { COPY_OF_MAP { @Override public Map<Object, Object> create(List<?> keys) { Map<Object, Object> sourceMap = new LinkedHashMap<>(); for (Object k : keys) { if (sourceMap.put(k, "dummy value") != null) { throw new UnsupportedOperationException("duplicate key"); } } return ImmutableMap.copyOf(sourceMap); } }, COPY_OF_ENTRIES { @Override public Map<Object, Object> create(List<?> keys) { return ImmutableMap.copyOf(transform(keys, k -> immutableEntry(k, "dummy value"))); } }, BUILDER_PUT_ONE_BY_ONE { @Override public Map<Object, Object> create(List<?> keys) { ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); for (Object k : keys) { builder.put(k, "dummy value"); } return builder.buildOrThrow(); } }, BUILDER_PUT_ENTRIES_ONE_BY_ONE { @Override public Map<Object, Object> create(List<?> keys) { ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); for (Object k : keys) { builder.put(immutableEntry(k, "dummy value")); } return builder.buildOrThrow(); } }, BUILDER_PUT_ALL_MAP { @Override public Map<Object, Object> create(List<?> keys) { Map<Object, Object> sourceMap = new LinkedHashMap<>(); for (Object k : keys) { if (sourceMap.put(k, "dummy value") != null) { throw new UnsupportedOperationException("duplicate key"); } } return ImmutableMap.builder().putAll(sourceMap).buildOrThrow(); } }, BUILDER_PUT_ALL_ENTRIES { @Override public Map<Object, Object> create(List<?> keys) { return ImmutableMap.builder() .putAll(transform(keys, k -> immutableEntry(k, "dummy value"))) .buildOrThrow(); } }, FORCE_JDK { @Override public Map<Object, Object> create(List<?> keys) { ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder(); for (Object k : keys) { builder.put(k, "dummy value"); } return builder.buildJdkBacked(); } }; } }
ConstructionPathway
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/UncollectToTableFunctionScanRule.java
{ "start": 5306, "end": 5965 }
interface ____ extends RelRule.Config { UncollectToTableFunctionScanRule.UncollectToTableFunctionScanRuleConfig DEFAULT = ImmutableUncollectToTableFunctionScanRule.UncollectToTableFunctionScanRuleConfig .builder() .build() .withOperandSupplier(b0 -> b0.operand(Uncollect.class).anyInputs()) .withDescription("UncollectToTableFunctionScanRule"); @Override default UncollectToTableFunctionScanRule toRule() { return new UncollectToTableFunctionScanRule(this); } } }
UncollectToTableFunctionScanRuleConfig
java
greenrobot__greendao
DaoCore/src/main/java/org/greenrobot/greendao/query/WhereCondition.java
{ "start": 886, "end": 1031 }
interface ____ model WHERE conditions used in queries. Use the {@link Property} objects in the DAO classes to * create new conditions. */ public
to
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractClassAssert.java
{ "start": 30918, "end": 32048 }
class ____ { * public String fieldOne; * private String fieldTwo; * } * * // this assertion succeeds: * assertThat(MyClass.class).hasDeclaredFields("fieldOne", "fieldTwo"); * * // this assertion fails: * assertThat(MyClass.class).hasDeclaredFields("fieldThree");</code></pre> * <p> * The assertion succeeds if no given fields are passed and the actual {@code Class} has no declared fields. * * @see Class#getDeclaredField(String) * @param fields the fields who must be declared in the class. * @return {@code this} assertions object * @throws AssertionError if {@code actual} is {@code null}. * @throws AssertionError if the actual {@code Class} doesn't contains all the specified fields. */ public SELF hasDeclaredFields(String... fields) { classes.assertHasDeclaredFields(info, actual, fields); return myself; } /** * Verifies that the actual {@code Class} <b>only</b> has the given declared {@code fields} and nothing more <b>in any order</b> * (as in {@link Class#getDeclaredFields()}). * <p> * Example: * <pre><code class='java'>
MyClass
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/resulttype/Apple.java
{ "start": 244, "end": 430 }
class ____ extends Fruit implements IsFruit { public Apple() { super( "constructed-by-constructor" ); } public Apple(String type) { super( type ); } }
Apple
java
quarkusio__quarkus
extensions/resteasy-classic/rest-client-config/runtime/src/test/java/io/quarkus/restclient/config/RestClientConfigTest.java
{ "start": 994, "end": 19471 }
class ____ { @Test void restClientConfigClass() { RegisteredRestClient registeredRestClient = new RegisteredRestClient(FullNameRestClient.class, null); // application.properties in test/resources SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(registeredRestClient); } }.configBuilder(builder); } }) .build(); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(1, restClientsConfig.clients().size()); assertTrue(restClientsConfig.clients().containsKey(FullNameRestClient.class.getName())); verifyConfig(restClientsConfig.getClient(FullNameRestClient.class)); } @Test void restClientConfigKey() { RegisteredRestClient registeredRestClient = new RegisteredRestClient(ConfigKeyRestClient.class, "key"); // application.properties in test/resources SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(registeredRestClient); } }.configBuilder(builder); } }) .build(); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(1, restClientsConfig.clients().size()); assertTrue(restClientsConfig.clients().containsKey(ConfigKeyRestClient.class.getName())); verifyConfig(restClientsConfig.getClient(ConfigKeyRestClient.class)); assertTrue(restClientsConfig.getClient(ConfigKeyRestClient.class).disableDefaultMapper()); } @Test void restClientConfigKeyMatchName() { SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(new RegisteredRestClient(ConfigKeyRestClient.class, ConfigKeyRestClient.class.getName())); } }.configBuilder(builder); } }) .build(); assertNotNull(config); config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(new RegisteredRestClient(ConfigKeyRestClient.class, ConfigKeyRestClient.class.getSimpleName())); } }.configBuilder(builder); } }) .build(); assertNotNull(config); } @Test void restClientMicroProfile() { RegisteredRestClient registeredRestClient = new RegisteredRestClient(MPRestClient.class, null); // application.properties in test/resources SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(registeredRestClient); } }.configBuilder(builder); } }) .withSources(new PropertiesConfigSource(Map.of("microprofile.rest.client.disable.default.mapper", "true"), "")) .build(); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(1, restClientsConfig.clients().size()); assertTrue(restClientsConfig.clients().containsKey(MPRestClient.class.getName())); RestClientConfig clientConfig = restClientsConfig.getClient(MPRestClient.class); assertTrue(clientConfig.url().isPresent()); assertThat(clientConfig.url().get()).isEqualTo("http://localhost:8080"); assertTrue(clientConfig.uri().isPresent()); assertThat(clientConfig.uri().get()).isEqualTo("http://localhost:8081"); assertTrue(clientConfig.providers().isPresent()); assertThat(clientConfig.providers().get()).isEqualTo("io.quarkus.restclient.configuration.MyResponseFilter"); assertTrue(clientConfig.connectTimeout().isPresent()); assertThat(clientConfig.connectTimeout().get()).isEqualTo(5000); assertTrue(clientConfig.readTimeout().isPresent()); assertThat(clientConfig.readTimeout().get()).isEqualTo(6000); assertTrue(clientConfig.followRedirects().isPresent()); assertThat(clientConfig.followRedirects().get()).isEqualTo(true); assertTrue(clientConfig.proxyAddress().isPresent()); assertTrue(clientConfig.queryParamStyle().isPresent()); assertThat(clientConfig.queryParamStyle().get()).isEqualTo(QueryParamStyle.COMMA_SEPARATED); assertThat(clientConfig.disableDefaultMapper()).isTrue(); } @Test void restClientMicroProfileConfigKey() { RegisteredRestClient registeredRestClient = new RegisteredRestClient(MPConfigKeyRestClient.class, "mp.key"); // application.properties in test/resources SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(registeredRestClient); } }.configBuilder(builder); } }) .build(); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(1, restClientsConfig.clients().size()); assertTrue(restClientsConfig.clients().containsKey(MPConfigKeyRestClient.class.getName())); RestClientConfig clientConfig = restClientsConfig.getClient(MPConfigKeyRestClient.class); assertTrue(clientConfig.url().isPresent()); assertThat(clientConfig.url().get()).isEqualTo("http://localhost:8080"); assertTrue(clientConfig.uri().isPresent()); assertThat(clientConfig.uri().get()).isEqualTo("http://localhost:8081"); assertTrue(clientConfig.providers().isPresent()); assertThat(clientConfig.providers().get()).isEqualTo("io.quarkus.restclient.configuration.MyResponseFilter"); assertTrue(clientConfig.connectTimeout().isPresent()); assertThat(clientConfig.connectTimeout().get()).isEqualTo(5000); assertTrue(clientConfig.readTimeout().isPresent()); assertThat(clientConfig.readTimeout().get()).isEqualTo(6000); assertTrue(clientConfig.followRedirects().isPresent()); assertThat(clientConfig.followRedirects().get()).isEqualTo(true); assertTrue(clientConfig.proxyAddress().isPresent()); assertTrue(clientConfig.queryParamStyle().isPresent()); assertThat(clientConfig.queryParamStyle().get()).isEqualTo(QueryParamStyle.COMMA_SEPARATED); } @Test void restClientMicroProfileConfigKeyMatchName() { SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(new RegisteredRestClient(MPConfigKeyRestClient.class, MPConfigKeyRestClient.class.getName())); } }.configBuilder(builder); } }) .build(); assertNotNull(config); config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(new RegisteredRestClient(MPConfigKeyRestClient.class, MPConfigKeyRestClient.class.getSimpleName())); } }.configBuilder(builder); } }) .build(); assertNotNull(config); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(1, restClientsConfig.clients().size()); assertTrue(restClientsConfig.clients().containsKey(MPConfigKeyRestClient.class.getName())); RestClientConfig restClientConfig = restClientsConfig.getClient(MPConfigKeyRestClient.class); assertTrue(restClientConfig.uri().isPresent()); assertThat(restClientConfig.uri().get()).isEqualTo("http://localhost:8082"); } @Test void restClientDuplicateSimpleName() { SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of( new RegisteredRestClient( io.quarkus.restclient.config.simple.one.SimpleNameRestClient.class, "one"), new RegisteredRestClient( io.quarkus.restclient.config.simple.two.SimpleNameRestClient.class, "two")); } }.configBuilder(builder); } }) .build(); assertNotNull(config); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(2, restClientsConfig.clients().size()); assertThat(restClientsConfig.getClient(io.quarkus.restclient.config.simple.one.SimpleNameRestClient.class).uri().get()) .isEqualTo("http://localhost:8081"); assertThat(restClientsConfig.getClient(io.quarkus.restclient.config.simple.two.SimpleNameRestClient.class).uri().get()) .isEqualTo("http://localhost:8082"); } @Test void restClientSharedConfigKey() { SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of( new RegisteredRestClient(SharedOneConfigKeyRestClient.class, "shared"), new RegisteredRestClient(SharedTwoConfigKeyRestClient.class, "shared"), new RegisteredRestClient(SharedThreeConfigKeyRestClient.class, "shared")); } }.configBuilder(builder); } }) .build(); assertNotNull(config); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(3, restClientsConfig.clients().size()); RestClientConfig restClientConfigOne = restClientsConfig.getClient(SharedOneConfigKeyRestClient.class); assertThat(restClientConfigOne.uri().get()).isEqualTo("http://localhost:8081"); assertEquals(2, restClientConfigOne.headers().size()); assertEquals("one", restClientConfigOne.headers().get("two")); assertEquals("two", restClientConfigOne.headers().get("one")); RestClientConfig restClientConfigTwo = restClientsConfig .getClient(SharedTwoConfigKeyRestClient.class); assertThat(restClientConfigTwo.uri().get()).isEqualTo("http://localhost:8082"); assertEquals(2, restClientConfigTwo.headers().size()); assertEquals("one", restClientConfigTwo.headers().get("two")); assertEquals("two", restClientConfigTwo.headers().get("one")); RestClientConfig restClientConfigThree = restClientsConfig .getClient(SharedThreeConfigKeyRestClient.class); assertThat(restClientConfigThree.uri().get()).isEqualTo("http://localhost:8083"); assertEquals(2, restClientConfigThree.headers().size()); assertEquals("one", restClientConfigThree.headers().get("two")); assertEquals("two", restClientConfigThree.headers().get("one")); } @Test void defaultPackage() { RegisteredRestClient registeredRestClient = new RegisteredRestClient("FullNameRestClient", "FullNameRestClient", null); // application.properties in test/resources SmallRyeConfig config = ConfigUtils.emptyConfigBuilder() .withMapping(RestClientsConfig.class) .withCustomizers(new SmallRyeConfigBuilderCustomizer() { @Override public void configBuilder(final SmallRyeConfigBuilder builder) { new AbstractRestClientConfigBuilder() { @Override public List<RegisteredRestClient> getRestClients() { return List.of(registeredRestClient); } }.configBuilder(builder); } }) .build(); RestClientsConfig restClientsConfig = config.getConfigMapping(RestClientsConfig.class); assertEquals(1, restClientsConfig.clients().size()); } private void verifyConfig(RestClientConfig config) { assertTrue(config.url().isPresent()); assertThat(config.url().get()).isEqualTo("http://localhost:8080"); assertTrue(config.uri().isPresent()); assertThat(config.uri().get()).isEqualTo("http://localhost:8081"); assertTrue(config.providers().isPresent()); assertThat(config.providers().get()).isEqualTo("io.quarkus.restclient.configuration.MyResponseFilter"); assertTrue(config.connectTimeout().isPresent()); assertThat(config.connectTimeout().get()).isEqualTo(5000); assertTrue(config.readTimeout().isPresent()); assertThat(config.readTimeout().get()).isEqualTo(6000); assertTrue(config.followRedirects().isPresent()); assertThat(config.followRedirects().get()).isEqualTo(true); assertTrue(config.proxyAddress().isPresent()); assertTrue(config.queryParamStyle().isPresent()); assertThat(config.queryParamStyle().get()).isEqualTo(QueryParamStyle.COMMA_SEPARATED); assertTrue(config.hostnameVerifier().isPresent()); assertThat(config.hostnameVerifier().get()).isEqualTo("io.quarkus.restclient.configuration.MyHostnameVerifier"); assertTrue(config.connectionTTL().isPresent()); assertThat(config.connectionTTL().getAsInt()).isEqualTo(30000); assertTrue(config.connectionPoolSize().isPresent()); assertThat(config.connectionPoolSize().getAsInt()).isEqualTo(10); assertTrue(config.maxChunkSize().isPresent()); assertThat(config.maxChunkSize().get().asBigInteger()).isEqualTo(BigInteger.valueOf(1024)); } }
RestClientConfigTest
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/config/RegistryConfigImpl.java
{ "start": 2183, "end": 6660 }
class ____ implements RegistryConfig { private static RegistryConfig defaultRegistry; private final String id; private final boolean enabled; private final String updatePolicy; private final RegistryDescriptorConfig descriptor; private final RegistryPlatformsConfig platforms; private final RegistryNonPlatformExtensionsConfig nonPlatformExtensions; private final RegistryMavenConfig mavenConfig; private final RegistryQuarkusVersionsConfig versionsConfig; private final Map<String, Object> extra; private RegistryConfigImpl(Builder builder) { this.id = builder.id; this.enabled = builder.enabled; this.updatePolicy = JsonBuilder.buildIfBuilder(builder.updatePolicy); this.descriptor = builder.descriptor == null || builder.descriptor.getArtifact() == null ? new RegistryDescriptorConfigImpl(repoIdToArtifact(id), true) : JsonBuilder.buildIfBuilder(builder.descriptor); this.platforms = JsonBuilder.buildIfBuilder(builder.platforms); this.nonPlatformExtensions = JsonBuilder.buildIfBuilder(builder.nonPlatformExtensions); this.mavenConfig = JsonBuilder.buildIfBuilder(builder.mavenConfig); this.versionsConfig = JsonBuilder.buildIfBuilder(builder.versionsConfig); this.extra = JsonBuilder.toUnmodifiableMap(builder.extra); } @Override @JsonIgnore public String getId() { return id; } @Override @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = JsonBooleanTrueFilter.class) public boolean isEnabled() { return enabled; } @Override public String getUpdatePolicy() { return updatePolicy; } @Override public RegistryDescriptorConfig getDescriptor() { return descriptor; } @Override public RegistryPlatformsConfig getPlatforms() { return platforms; } @Override public RegistryNonPlatformExtensionsConfig getNonPlatformExtensions() { return nonPlatformExtensions; } @Override public RegistryMavenConfig getMaven() { return mavenConfig; } @Override public RegistryQuarkusVersionsConfig getQuarkusVersions() { return versionsConfig; } @Override @JsonAnyGetter public Map<String, Object> getExtra() { return extra; } private ArtifactCoords repoIdToArtifact(String id) { final String[] parts = id.split("\\."); final StringBuilder buf = new StringBuilder(id.length()); int i = parts.length; buf.append(parts[--i]); while (--i >= 0) { buf.append('.').append(parts[i]); } return ArtifactCoords.of(buf.toString(), Constants.DEFAULT_REGISTRY_DESCRIPTOR_ARTIFACT_ID, null, Constants.JSON, Constants.DEFAULT_REGISTRY_ARTIFACT_VERSION); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RegistryConfigImpl that = (RegistryConfigImpl) o; return enabled == that.enabled && Objects.equals(id, that.id) && Objects.equals(updatePolicy, that.updatePolicy) && Objects.equals(descriptor, that.descriptor) && Objects.equals(platforms, that.platforms) && Objects.equals(nonPlatformExtensions, that.nonPlatformExtensions) && Objects.equals(mavenConfig, that.mavenConfig) && Objects.equals(versionsConfig, that.versionsConfig) && Objects.equals(extra, that.extra); } @Override public int hashCode() { return Objects.hash(id, enabled, updatePolicy, descriptor, platforms, nonPlatformExtensions, mavenConfig, versionsConfig, extra); } @Override public String toString() { return this.getClass().getSimpleName() + "{id='" + id + '\'' + ", enabled=" + enabled + ", updatePolicy='" + updatePolicy + '\'' + ", descriptor=" + descriptor + ", platforms=" + platforms + ", nonPlatformExtensions=" + nonPlatformExtensions + ", mavenConfig=" + mavenConfig + ", versionsConfig=" + versionsConfig + ", extra=" + extra + '}'; } public static
RegistryConfigImpl