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__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/table/lookup/CachingLookupFunction.java
{ "start": 2226, "end": 7571 }
class ____ extends LookupFunction { private static final long serialVersionUID = 1L; // Constants public static final String LOOKUP_CACHE_METRIC_GROUP_NAME = "cache"; // The actual user-provided lookup function @Nullable private final LookupFunction delegate; private LookupCache cache; private transient String cacheIdentifier; // Cache metrics private transient CacheMetricGroup cacheMetricGroup; private transient Counter loadCounter; private transient Counter numLoadFailuresCounter; private volatile long latestLoadTime = UNINITIALIZED; /** * Create a {@link CachingLookupFunction}. * * <p>Please note that the cache may not be the final instance serving in this function. The * actual cache instance will be retrieved from the {@link LookupCacheManager} during {@link * #open}. */ public CachingLookupFunction(LookupCache cache, @Nullable LookupFunction delegate) { this.cache = cache; this.delegate = delegate; } /** * Open the {@link CachingLookupFunction}. * * <p>In order to reduce the memory usage of the cache, {@link LookupCacheManager} is used to * provide a shared cache instance across subtasks of this function. Here we use {@link * #functionIdentifier()} as the id of the cache, which is generated by MD5 of serialized bytes * of this function. As different subtasks of the function will generate the same MD5, this * could promise that they will be served with the same cache instance. * * @see #functionIdentifier() */ @Override public void open(FunctionContext context) throws Exception { // Get the shared cache from manager cacheIdentifier = functionIdentifier(); cache = LookupCacheManager.getInstance().registerCacheIfAbsent(cacheIdentifier, cache); // Register metrics cacheMetricGroup = new InternalCacheMetricGroup( context.getMetricGroup(), LOOKUP_CACHE_METRIC_GROUP_NAME); if (!(cache instanceof LookupFullCache)) { loadCounter = new SimpleCounter(); cacheMetricGroup.loadCounter(loadCounter); numLoadFailuresCounter = new SimpleCounter(); cacheMetricGroup.numLoadFailuresCounter(numLoadFailuresCounter); } else { initializeFullCache(((LookupFullCache) cache), context); } // Initialize cache and the delegating function cache.open(cacheMetricGroup); if (delegate != null) { delegate.open(context); } } @Override public Collection<RowData> lookup(RowData keyRow) throws IOException { Collection<RowData> cachedValues = cache.getIfPresent(keyRow); if (cachedValues != null) { // Cache hit return cachedValues; } else { // Cache miss Collection<RowData> lookupValues = lookupByDelegate(keyRow); // Here we use keyRow as the cache key directly, as keyRow always contains the copy of // key fields from left table, no matter if object reuse is enabled. if (lookupValues == null || lookupValues.isEmpty()) { cache.put(keyRow, Collections.emptyList()); } else { cache.put(keyRow, lookupValues); } return lookupValues; } } @Override public void close() throws Exception { if (delegate != null) { delegate.close(); } if (cacheIdentifier != null) { LookupCacheManager.getInstance().unregisterCache(cacheIdentifier); } } @VisibleForTesting public LookupCache getCache() { return cache; } // -------------------------------- Helper functions ------------------------------ private Collection<RowData> lookupByDelegate(RowData keyRow) throws IOException { try { Preconditions.checkState( delegate != null, "User's lookup function can't be null, if there are possible cache misses."); long loadStart = System.currentTimeMillis(); Collection<RowData> lookupValues = delegate.lookup(keyRow); updateLatestLoadTime(System.currentTimeMillis() - loadStart); loadCounter.inc(); return lookupValues; } catch (Exception e) { // TODO: Should implement retry on failure logic as proposed in FLIP-234 numLoadFailuresCounter.inc(); throw new IOException(String.format("Failed to lookup with key '%s'", keyRow), e); } } private void updateLatestLoadTime(long loadTime) { checkNotNull( cacheMetricGroup, "Could not register metric '%s' as cache metric group is not initialized", MetricNames.LATEST_LOAD_TIME); // Lazily register the metric if (latestLoadTime == UNINITIALIZED) { cacheMetricGroup.latestLoadTimeGauge(() -> latestLoadTime); } latestLoadTime = loadTime; } private void initializeFullCache(LookupFullCache lookupFullCache, FunctionContext context) { lookupFullCache.setUserCodeClassLoader(context.getUserCodeClassLoader()); } }
CachingLookupFunction
java
spring-projects__spring-boot
module/spring-boot-http-converter/src/test/java/org/springframework/boot/http/converter/autoconfigure/HttpMessageConvertersAutoConfigurationTests.java
{ "start": 20295, "end": 20612 }
class ____ { @Bean JacksonJsonHttpMessageConverter customJacksonMessageConverter(JsonMapper jsonMapperMapper) { JacksonJsonHttpMessageConverter converter = new JacksonJsonHttpMessageConverter(jsonMapperMapper); return converter; } } @Configuration(proxyBeanMethods = false) static
JacksonConverterConfig
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/WireTapShutdownBeanTest.java
{ "start": 2741, "end": 3203 }
class ____ { private String tapped; public void tapSomething(String body) { try { EXCHANGER.exchange(null); Thread.sleep(100); } catch (Exception e) { fail("Should not be interrupted"); } LOG.info("Wire tapping: {}", body); tapped = body; } public String getTapped() { return tapped; } } }
MyTapBean
java
spring-projects__spring-boot
module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/DefaultRestartInitializer.java
{ "start": 1113, "end": 2925 }
class ____ implements RestartInitializer { @Override public URL @Nullable [] getInitialUrls(Thread thread) { if (!isMain(thread)) { return null; } if (!DevToolsEnablementDeducer.shouldEnable(thread)) { return null; } return getUrls(thread); } /** * Returns if the thread is for a main invocation. By default {@link #isMain(Thread) * checks the name of the thread} and {@link #isDevelopmentClassLoader(ClassLoader) * the context classloader}. * @param thread the thread to check * @return {@code true} if the thread is a main invocation * @see #isMainThread * @see #isDevelopmentClassLoader(ClassLoader) */ protected boolean isMain(Thread thread) { return isMainThread(thread) && isDevelopmentClassLoader(thread.getContextClassLoader()); } /** * Returns whether the given {@code thread} is considered to be the main thread. * @param thread the thread to check * @return {@code true} if it's the main thread, otherwise {@code false} * @since 2.4.0 */ protected boolean isMainThread(Thread thread) { return thread.getName().equals("main"); } /** * Returns whether the given {@code classLoader} is one that is typically used during * development. * @param classLoader the ClassLoader to check * @return {@code true} if it's a ClassLoader typically used during development, * otherwise {@code false} * @since 2.4.0 */ protected boolean isDevelopmentClassLoader(ClassLoader classLoader) { return classLoader.getClass().getName().contains("AppClassLoader"); } /** * Return the URLs that should be used with initialization. * @param thread the source thread * @return the URLs */ protected URL[] getUrls(Thread thread) { return ChangeableUrls.fromClassLoader(thread.getContextClassLoader()).toArray(); } }
DefaultRestartInitializer
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/oscar/ast/expr/OscarExpr.java
{ "start": 781, "end": 834 }
interface ____ extends SQLExpr, OscarObject { }
OscarExpr
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/DeleteForecastAction.java
{ "start": 822, "end": 1145 }
class ____ extends ActionType<AcknowledgedResponse> { public static final DeleteForecastAction INSTANCE = new DeleteForecastAction(); public static final String NAME = "cluster:admin/xpack/ml/job/forecast/delete"; private DeleteForecastAction() { super(NAME); } public static
DeleteForecastAction
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/LongStringHolder.java
{ "start": 656, "end": 1433 }
class ____ { private Long id; private char[] name; private Character[] whatEver; private String longString; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @JdbcTypeCode( Types.LONGVARCHAR ) public String getLongString() { return longString; } public void setLongString(String longString) { this.longString = longString; } @JdbcTypeCode( Types.LONGVARCHAR ) public char[] getName() { return name; } public void setName(char[] name) { this.name = name; } @JdbcTypeCode( Types.LONGVARCHAR ) @JavaType( CharacterArrayJavaType.class ) public Character[] getWhatEver() { return whatEver; } public void setWhatEver(Character[] whatEver) { this.whatEver = whatEver; } }
LongStringHolder
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/source/expressions/java/TargetBooleanWorkAround.java
{ "start": 211, "end": 395 }
class ____ { private boolean val; public boolean isVal() { return val; } public void setVal(boolean val) { this.val = val; } }
TargetBooleanWorkAround
java
apache__camel
components/camel-schematron/src/test/java/org/apache/camel/component/schematron/SchematronComponentTest.java
{ "start": 1341, "end": 3430 }
class ____ extends CamelTestSupport { /** * @throws Exception */ @Test public void testSendBodyAsString() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); String payload = IOUtils.toString(ClassLoader.getSystemResourceAsStream("xml/article-1.xml"), Charset.defaultCharset()); template.sendBody("direct:start", payload); MockEndpoint.assertIsSatisfied(context); String result = mock.getExchanges().get(0).getIn().getHeader(Constants.VALIDATION_REPORT, String.class); assertEquals(0, Integer.valueOf(Utils.evaluate("count(//svrl:failed-assert)", result)).intValue()); assertEquals(0, Integer.valueOf(Utils.evaluate("count(//svrl:successful-report)", result)).intValue()); } /** * @throws Exception */ @Test public void testSendBodyAsInputStreamInvalidXML() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); String payload = IOUtils.toString(ClassLoader.getSystemResourceAsStream("xml/article-2.xml"), Charset.defaultCharset()); template.sendBody("direct:start", payload); MockEndpoint.assertIsSatisfied(context); String result = mock.getExchanges().get(0).getIn().getHeader(Constants.VALIDATION_REPORT, String.class); // should throw two assertions because of the missing chapters in the XML. assertEquals("A chapter should have a title", Utils.evaluate("//svrl:failed-assert[1]/svrl:text", result)); assertEquals("A chapter should have a title", Utils.evaluate("//svrl:failed-assert[2]/svrl:text", result)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start") .to("schematron://sch/schematron-1.sch") .to("mock:result"); } }; } }
SchematronComponentTest
java
apache__dubbo
dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/Context.java
{ "start": 1104, "end": 1527 }
interface ____ { OpenAPIRequest getRequest(); HttpRequest getHttpRequest(); HttpResponse getHttpResponse(); String getGroup(); OpenAPI getOpenAPI(); boolean isOpenAPI31(); SchemaResolver getSchemaResolver(); ExtensionFactory getExtensionFactory(); <T> T getAttribute(String name); <T> T removeAttribute(String name); void setAttribute(String name, Object value); }
Context
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/security/SecurityFactoryServiceLoader.java
{ "start": 1377, "end": 3523 }
class ____ { /** Find a suitable {@link SecurityModuleFactory} based on canonical name. */ public static SecurityModuleFactory findModuleFactory(String securityModuleFactoryClass) throws NoMatchSecurityFactoryException { return findFactoryInternal( securityModuleFactoryClass, SecurityModuleFactory.class, SecurityModuleFactory.class.getClassLoader()); } /** Find a suitable {@link SecurityContextFactory} based on canonical name. */ public static SecurityContextFactory findContextFactory(String securityContextFactoryClass) throws NoMatchSecurityFactoryException { return findFactoryInternal( securityContextFactoryClass, SecurityContextFactory.class, SecurityContextFactory.class.getClassLoader()); } private static <T> T findFactoryInternal( String factoryClassCanonicalName, Class<T> factoryClass, ClassLoader classLoader) throws NoMatchSecurityFactoryException { Preconditions.checkNotNull(factoryClassCanonicalName); ServiceLoader<T> serviceLoader; if (classLoader != null) { serviceLoader = ServiceLoader.load(factoryClass, classLoader); } else { serviceLoader = ServiceLoader.load(factoryClass); } List<T> matchingFactories = new ArrayList<>(); Iterator<T> classFactoryIterator = serviceLoader.iterator(); classFactoryIterator.forEachRemaining( classFactory -> { if (factoryClassCanonicalName.matches( classFactory.getClass().getCanonicalName())) { matchingFactories.add(classFactory); } }); if (matchingFactories.size() != 1) { throw new NoMatchSecurityFactoryException( "zero or more than one security factory found", factoryClassCanonicalName, matchingFactories); } return matchingFactories.get(0); } }
SecurityFactoryServiceLoader
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/support/RootBeanDefinitionTests.java
{ "start": 4893, "end": 5045 }
class ____ implements ExecutorService, AutoCloseable { @Override public void close() { } } static
BeanImplementingExecutorServiceAndAutoCloseable
java
apache__camel
components/camel-univocity-parsers/src/main/java/org/apache/camel/dataformat/univocity/Unmarshaller.java
{ "start": 4266, "end": 4396 }
class ____ an iterator that transforms each row into a List. * * @param <P> Parser class */ private static final
is
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/ibatis/SqlMapSessionWrapper.java
{ "start": 895, "end": 2145 }
class ____ extends SqlMapExecutorWrapper implements SqlMapSession { private SqlMapSession session; public SqlMapSessionWrapper(ExtendedSqlMapClient client, SqlMapSession session) { super(client, session); this.session = session; } public void startTransaction() throws SQLException { session.startTransaction(); } public void startTransaction(int transactionIsolation) throws SQLException { session.startTransaction(transactionIsolation); } public void commitTransaction() throws SQLException { session.commitTransaction(); } public void endTransaction() throws SQLException { session.endTransaction(); } public void setUserConnection(Connection connection) throws SQLException { session.setUserConnection(connection); } @Deprecated public Connection getUserConnection() throws SQLException { return session.getUserConnection(); } public Connection getCurrentConnection() throws SQLException { return session.getCurrentConnection(); } public DataSource getDataSource() { return session.getDataSource(); } public void close() { session.close(); } }
SqlMapSessionWrapper
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/webdriver/MockMvcHtmlUnitDriverBuilder.java
{ "start": 1981, "end": 6146 }
class ____ extends MockMvcWebConnectionBuilderSupport<MockMvcHtmlUnitDriverBuilder> { private @Nullable HtmlUnitDriver driver; private boolean javascriptEnabled = true; protected MockMvcHtmlUnitDriverBuilder(MockMvc mockMvc) { super(mockMvc); } protected MockMvcHtmlUnitDriverBuilder(WebApplicationContext context) { super(context); } protected MockMvcHtmlUnitDriverBuilder(WebApplicationContext context, MockMvcConfigurer configurer) { super(context, configurer); } /** * Create a new {@code MockMvcHtmlUnitDriverBuilder} based on the supplied * {@link MockMvc} instance. * @param mockMvc the {@code MockMvc} instance to use (never {@code null}) * @return the MockMvcHtmlUnitDriverBuilder to customize */ public static MockMvcHtmlUnitDriverBuilder mockMvcSetup(MockMvc mockMvc) { Assert.notNull(mockMvc, "MockMvc must not be null"); return new MockMvcHtmlUnitDriverBuilder(mockMvc); } /** * Create a new {@code MockMvcHtmlUnitDriverBuilder} based on the supplied * {@link WebApplicationContext}. * @param context the {@code WebApplicationContext} to create a {@link MockMvc} * instance from (never {@code null}) * @return the MockMvcHtmlUnitDriverBuilder to customize */ public static MockMvcHtmlUnitDriverBuilder webAppContextSetup(WebApplicationContext context) { Assert.notNull(context, "WebApplicationContext must not be null"); return new MockMvcHtmlUnitDriverBuilder(context); } /** * Create a new {@code MockMvcHtmlUnitDriverBuilder} based on the supplied * {@link WebApplicationContext} and {@link MockMvcConfigurer}. * @param context the {@code WebApplicationContext} to create a {@link MockMvc} * instance from (never {@code null}) * @param configurer the {@code MockMvcConfigurer} to apply (never {@code null}) * @return the MockMvcHtmlUnitDriverBuilder to customize */ public static MockMvcHtmlUnitDriverBuilder webAppContextSetup(WebApplicationContext context, MockMvcConfigurer configurer) { Assert.notNull(context, "WebApplicationContext must not be null"); Assert.notNull(configurer, "MockMvcConfigurer must not be null"); return new MockMvcHtmlUnitDriverBuilder(context, configurer); } /** * Specify whether JavaScript should be enabled. * <p>Default is {@code true}. * @param javascriptEnabled {@code true} if JavaScript should be enabled * @return this builder for further customizations * @see #build() */ public MockMvcHtmlUnitDriverBuilder javascriptEnabled(boolean javascriptEnabled) { this.javascriptEnabled = javascriptEnabled; return this; } /** * Supply the {@code WebConnectionHtmlUnitDriver} that the driver * {@linkplain #build built} by this builder should delegate to when * processing non-{@linkplain WebRequestMatcher matching} requests. * @param driver the {@code WebConnectionHtmlUnitDriver} to delegate to * for requests that do not match (never {@code null}) * @return this builder for further customizations * @see #build() */ public MockMvcHtmlUnitDriverBuilder withDelegate(WebConnectionHtmlUnitDriver driver) { Assert.notNull(driver, "HtmlUnitDriver must not be null"); driver.setJavascriptEnabled(this.javascriptEnabled); driver.setWebConnection(createConnection(driver.getWebClient())); this.driver = driver; return this; } /** * Build the {@link HtmlUnitDriver} configured via this builder. * <p>The returned driver will use the configured {@link MockMvc} instance * for processing any {@linkplain WebRequestMatcher matching} requests * and a delegate {@code HtmlUnitDriver} for all other requests. * <p>If a {@linkplain #withDelegate delegate} has been explicitly configured, * it will be used; otherwise, a default {@code WebConnectionHtmlUnitDriver} * with the {@link BrowserVersion} set to {@link BrowserVersion#CHROME CHROME} * will be configured as the delegate. * @return the {@code HtmlUnitDriver} to use * @see #withDelegate(WebConnectionHtmlUnitDriver) */ public HtmlUnitDriver build() { return (this.driver != null ? this.driver : withDelegate(new WebConnectionHtmlUnitDriver(BrowserVersion.CHROME)).build()); } }
MockMvcHtmlUnitDriverBuilder
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/workflow/ResumeRefreshWorkflow.java
{ "start": 1206, "end": 1758 }
class ____<T extends RefreshHandler> implements ModifyRefreshWorkflow<T> { private final T refreshHandler; private final Map<String, String> dynamicOptions; public ResumeRefreshWorkflow(T refreshHandler, Map<String, String> dynamicOptions) { this.refreshHandler = refreshHandler; this.dynamicOptions = dynamicOptions; } public Map<String, String> getDynamicOptions() { return dynamicOptions; } @Override public T getRefreshHandler() { return refreshHandler; } }
ResumeRefreshWorkflow
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableOption.java
{ "start": 979, "end": 1815 }
class ____ extends MySqlObjectImpl implements SQLAlterTableItem { private String name; private SQLObject value; public MySqlAlterTableOption(String name, String value) { this(name, new SQLIdentifierExpr(value)); } public MySqlAlterTableOption(String name, SQLObject value) { this.name = name; this.setValue(value); } public MySqlAlterTableOption() { } @Override public void accept0(MySqlASTVisitor visitor) { visitor.visit(this); visitor.endVisit(this); } public String getName() { return name; } public void setName(String name) { this.name = name; } public SQLObject getValue() { return value; } public void setValue(SQLObject value) { this.value = value; } }
MySqlAlterTableOption
java
grpc__grpc-java
binder/src/androidTest/java/io/grpc/binder/BinderChannelSmokeTest.java
{ "start": 14000, "end": 14655 }
class ____ implements ServerInterceptor { @Override public <ReqT, RespT> Listener<ReqT> interceptCall( ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { return next.startCall( new SimpleForwardingServerCall<ReqT, RespT>(call) { @Override public void sendHeaders(Metadata headers) { if (parcelableForResponseHeaders != null) { headers.put(POISON_KEY, parcelableForResponseHeaders); } super.sendHeaders(headers); } }, headers); } } static
AddParcelableServerInterceptor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/CaseStatementWithTypeTest.java
{ "start": 6709, "end": 6919 }
class ____ { @Id private Long id; public UnionParent() { } public UnionParent(Long id) { this.id = id; } } @SuppressWarnings("unused") @Entity( name = "UnionChildA" ) public static
UnionParent
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/TypeFactory1604Test.java
{ "start": 839, "end": 941 }
class ____<V,K> extends TwoParam1604<K,List<V>> { } // [databind#2577] static
SneakyTwoParam1604
java
apache__camel
components/camel-huawei/camel-huaweicloud-frs/src/test/java/org/apache/camel/component/huaweicloud/frs/constants/FaceRecognitionPropertiesTest.java
{ "start": 972, "end": 2188 }
class ____ { @Test public void testPropertyNames() { assertEquals("CamelHwCloudFrsImageBase64", FaceRecognitionProperties.FACE_IMAGE_BASE64); assertEquals("CamelHwCloudFrsImageUrl", FaceRecognitionProperties.FACE_IMAGE_URL); assertEquals("CamelHwCloudFrsImageFilePath", FaceRecognitionProperties.FACE_IMAGE_FILE_PATH); assertEquals("CamelHwCloudFrsAnotherImageBase64", FaceRecognitionProperties.ANOTHER_FACE_IMAGE_BASE64); assertEquals("CamelHwCloudFrsAnotherImageUrl", FaceRecognitionProperties.ANOTHER_FACE_IMAGE_URL); assertEquals("CamelHwCloudFrsAnotherImageFilePath", FaceRecognitionProperties.ANOTHER_FACE_IMAGE_FILE_PATH); assertEquals("CamelHwCloudFrsVideoBase64", FaceRecognitionProperties.FACE_VIDEO_BASE64); assertEquals("CamelHwCloudFrsVideoUrl", FaceRecognitionProperties.FACE_VIDEO_URL); assertEquals("CamelHwCloudFrsVideoFilePath", FaceRecognitionProperties.FACE_VIDEO_FILE_PATH); assertEquals("CamelHwCloudFrsVideoActions", FaceRecognitionProperties.FACE_VIDEO_ACTIONS); assertEquals("CamelHwCloudFrsVideoActionTimes", FaceRecognitionProperties.FACE_VIDEO_ACTION_TIMES); } }
FaceRecognitionPropertiesTest
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/nestedtests/InheritedNestedTestConfigurationTests.java
{ "start": 2045, "end": 2531 }
class ____ { @Test void mockWasInvokedOnce() { InheritedNestedTestConfigurationTests.this.performer.run(); then(InheritedNestedTestConfigurationTests.this.action).should().perform(); } @Test void mockWasInvokedTwice() { InheritedNestedTestConfigurationTests.this.performer.run(); InheritedNestedTestConfigurationTests.this.performer.run(); then(InheritedNestedTestConfigurationTests.this.action).should(times(2)).perform(); } } @Component static
InnerTests
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/security/HttpUpgradePermissionCheckerTest.java
{ "start": 6868, "end": 8677 }
class ____ { @PermissionChecker("endpoint:connect") boolean canConnectToEndpoint(SecurityIdentity securityIdentity) { if (HttpSecurityUtils.getRoutingContextAttribute(securityIdentity) == null) { Log.error("Routing context not found, denying access"); return false; } return securityIdentity.getPrincipal().getName().equals("user"); } @PermissionChecker("endpoint:read") boolean canDoReadOnEndpoint(SecurityIdentity securityIdentity) { if (HttpSecurityUtils.getRoutingContextAttribute(securityIdentity) == null) { Log.error("Routing context not found, denying access"); return false; } return securityIdentity.getPrincipal().getName().equals("admin"); } @PermissionChecker("perm1") boolean hasPerm1(SecurityIdentity securityIdentity) { if (HttpSecurityUtils.getRoutingContextAttribute(securityIdentity) == null) { Log.error("Routing context not found, denying access"); return false; } String principalName = securityIdentity.getPrincipal().getName(); return principalName.equals("admin") || principalName.equals("almighty"); } @PermissionChecker("perm2") boolean hasPerm2(SecurityIdentity securityIdentity) { if (HttpSecurityUtils.getRoutingContextAttribute(securityIdentity) == null) { Log.error("Routing context not found, denying access"); return false; } String principalName = securityIdentity.getPrincipal().getName(); return principalName.equals("user") || principalName.equals("almighty"); } } }
Checker
java
apache__dubbo
dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java
{ "start": 1570, "end": 2341 }
class ____ { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Test public void test() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestConfiguration.class); TestService testService = applicationContext.getBean(TestService.class); testService.test(); // check initialization customizer MockSpringInitCustomizer.checkCustomizer(applicationContext); } @EnableDubbo(scanBasePackages = "org.apache.dubbo.test.common.impl") @Configuration @PropertySource("/demo-app.properties") static
SpringAnnotationBeanTest
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/RequestDeserializeHandler.java
{ "start": 1084, "end": 6496 }
class ____ implements ServerRestHandler { private static final Logger log = Logger.getLogger(RequestDeserializeHandler.class); private final Class<?> type; private final Type genericType; private final List<MediaType> acceptableMediaTypes; private final ServerSerialisers serialisers; private final int parameterIndex; public RequestDeserializeHandler(Class<?> type, Type genericType, List<MediaType> acceptableMediaTypes, ServerSerialisers serialisers, int parameterIndex) { this.type = type; this.genericType = genericType; this.acceptableMediaTypes = acceptableMediaTypes; this.serialisers = serialisers; this.parameterIndex = parameterIndex; } @Override public void handle(ResteasyReactiveRequestContext requestContext) throws Exception { requestContext.requireCDIRequestScope(); MediaType effectiveRequestType = null; Object requestType = requestContext.getHeader(HttpHeaders.CONTENT_TYPE, true); if (requestType != null) { try { effectiveRequestType = MediaTypeHelper.valueOf((String) requestType); } catch (Exception e) { log.debugv("Incorrect media type", e); throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build()); } // We need to verify media type for sub-resources, this mimics what is done in {@code ClassRoutingHandler} if (MediaTypeHelper.getFirstMatch( acceptableMediaTypes, Collections.singletonList(effectiveRequestType)) == null) { throw new NotSupportedException("The content-type header value did not match the value in @Consumes"); } } else if (!acceptableMediaTypes.isEmpty()) { effectiveRequestType = acceptableMediaTypes.get(0); } else { effectiveRequestType = MediaType.APPLICATION_OCTET_STREAM_TYPE; } List<MessageBodyReader<?>> readers = serialisers.findReaders(null, type, effectiveRequestType, RuntimeType.SERVER); if (readers.isEmpty()) { log.debugv("No matching MessageBodyReader found for type {0} and media type {1}", type, effectiveRequestType); throw new NotSupportedException(); } for (MessageBodyReader<?> reader : readers) { if (isReadable(reader, requestContext, effectiveRequestType)) { Object result; ReaderInterceptor[] interceptors = requestContext.getReaderInterceptors(); try { try { if (interceptors == null) { result = readFrom(reader, requestContext, effectiveRequestType); } else { result = new ReaderInterceptorContextImpl(requestContext, getAnnotations(requestContext), type, genericType, effectiveRequestType, reader, requestContext.getInputStream(), interceptors, serialisers) .proceed(); } } catch (NoContentException e) { throw new BadRequestException(e); } } catch (Exception e) { log.debug("Error occurred during deserialization of input", e); requestContext.handleException(e, true); requestContext.resume(); return; } requestContext.setRequestEntity(result); requestContext.resume(); return; } } log.debugv("No matching MessageBodyReader found for type {0} and media type {1}", type, effectiveRequestType); throw new NotSupportedException("No supported MessageBodyReader found"); } private boolean isReadable(MessageBodyReader<?> reader, ResteasyReactiveRequestContext requestContext, MediaType requestType) { if (reader instanceof ServerMessageBodyReader) { return ((ServerMessageBodyReader<?>) reader).isReadable(type, genericType, requestContext.getTarget().getLazyMethod(), requestType); } return reader.isReadable(type, genericType, getAnnotations(requestContext), requestType); } @SuppressWarnings("unchecked") public Object readFrom(MessageBodyReader<?> reader, ResteasyReactiveRequestContext requestContext, MediaType requestType) throws IOException { requestContext.requireCDIRequestScope(); if (reader instanceof ServerMessageBodyReader) { return ((ServerMessageBodyReader<?>) reader).readFrom((Class) type, genericType, requestType, requestContext); } return reader.readFrom((Class) type, genericType, getAnnotations(requestContext), requestType, requestContext.getHttpHeaders().getRequestHeaders(), requestContext.getInputStream()); } private Annotation[] getAnnotations(ResteasyReactiveRequestContext requestContext) { return requestContext.getTarget().getLazyMethod().getParameterAnnotations(parameterIndex); } }
RequestDeserializeHandler
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/query/SpanTermQueryBuilderTests.java
{ "start": 1143, "end": 6134 }
class ____ extends AbstractTermQueryTestCase<SpanTermQueryBuilder> { @Override protected SpanTermQueryBuilder doCreateTestQueryBuilder() { String fieldName = randomFrom(TEXT_FIELD_NAME, TEXT_ALIAS_FIELD_NAME, randomAlphaOfLengthBetween(1, 10)); Object value; if (frequently()) { value = randomAlphaOfLengthBetween(1, 10); } else { // generate unicode string in 10% of cases JsonStringEncoder encoder = JsonStringEncoder.getInstance(); value = new String(encoder.quoteAsString(randomUnicodeOfLength(10))); } return createQueryBuilder(fieldName, value); } @Override protected SpanTermQueryBuilder createQueryBuilder(String fieldName, Object value) { return new SpanTermQueryBuilder(fieldName, value); } @Override protected void doAssertLuceneQuery(SpanTermQueryBuilder queryBuilder, Query query, SearchExecutionContext context) throws IOException { MappedFieldType mapper = context.getFieldType(queryBuilder.fieldName()); if (mapper != null) { String expectedFieldName = expectedFieldName(queryBuilder.fieldName); assertThat(query, instanceOf(SpanTermQuery.class)); SpanTermQuery spanTermQuery = (SpanTermQuery) query; assertThat(spanTermQuery.getTerm().field(), equalTo(expectedFieldName)); Term term = ((TermQuery) mapper.termQuery(queryBuilder.value(), null)).getTerm(); assertThat(spanTermQuery.getTerm(), equalTo(term)); } else { assertThat(query, instanceOf(SpanMatchNoDocsQuery.class)); } } /** * @param amount a number of clauses that will be returned * @return the array of random {@link SpanTermQueryBuilder} with same field name */ public SpanTermQueryBuilder[] createSpanTermQueryBuilders(int amount) { SpanTermQueryBuilder[] clauses = new SpanTermQueryBuilder[amount]; SpanTermQueryBuilder first = createTestQueryBuilder(false, true); clauses[0] = first; for (int i = 1; i < amount; i++) { // we need same field name in all clauses, so we only randomize value SpanTermQueryBuilder spanTermQuery = new SpanTermQueryBuilder(first.fieldName(), getRandomValueForFieldName(first.fieldName())); if (randomBoolean()) { spanTermQuery.queryName(randomAlphaOfLengthBetween(1, 10)); } clauses[i] = spanTermQuery; } return clauses; } public void testFromJson() throws IOException { String json = "{ \"span_term\" : { \"user\" : { \"value\" : \"kimchy\", \"boost\" : 2.0 } }}"; SpanTermQueryBuilder parsed = (SpanTermQueryBuilder) parseQuery(json); checkGeneratedJson(json, parsed); assertEquals(json, "kimchy", parsed.value()); assertEquals(json, 2.0, parsed.boost(), 0.0001); } public void testParseFailsWithMultipleFields() throws IOException { String json = """ { "span_term" : { "message1" : { "term" : "this" }, "message2" : { "term" : "this" } } }"""; ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json)); assertEquals("[span_term] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage()); String shortJson = """ { "span_term" : { "message1" : "this", "message2" : "this" } }"""; e = expectThrows(ParsingException.class, () -> parseQuery(shortJson)); assertEquals("[span_term] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage()); } public void testWithBoost() throws IOException { SearchExecutionContext context = createSearchExecutionContext(); for (String field : new String[] { TEXT_FIELD_NAME, TEXT_ALIAS_FIELD_NAME }) { SpanTermQueryBuilder spanTermQueryBuilder = new SpanTermQueryBuilder(field, "toto"); spanTermQueryBuilder.boost(10); Query query = spanTermQueryBuilder.toQuery(context); Query expected = new BoostQuery(new SpanTermQuery(new Term(TEXT_FIELD_NAME, "toto")), 10); assertEquals(expected, query); } } public void testFieldWithoutPositions() { SearchExecutionContext context = createSearchExecutionContext(); SpanTermQueryBuilder spanTermQueryBuilder = new SpanTermQueryBuilder(IdFieldMapper.NAME, "1234"); IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> spanTermQueryBuilder.toQuery(context)); assertEquals("Span term query requires position data, but field _id was indexed without position data", iae.getMessage()); } }
SpanTermQueryBuilderTests
java
quarkusio__quarkus
extensions/web-dependency-locator/deployment/src/test/java/io/quarkus/webdependency/locator/test/ImportMapTest.java
{ "start": 400, "end": 1297 }
class ____ extends WebDependencyLocatorTestSupport { private static final String META_INF_RESOURCES = "META-INF/resources/"; @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource(new StringAsset("<html>Hello!<html>"), META_INF_RESOURCES + "/index.html") .addAsResource(new StringAsset("Test"), META_INF_RESOURCES + "/some/path/test.txt")) .setForcedDependencies(List.of( Dependency.of("org.mvnpm", "bootstrap", BOOTSTRAP_VERSION))); @Test public void test() { // Test normal files RestAssured.get("/_importmap/generated_importmap.js").then() .statusCode(200) .body(containsString("\"bootstrap/\" : \"/_static/bootstrap/" + BOOTSTRAP_VERSION + "/dist/\"")); } }
ImportMapTest
java
mapstruct__mapstruct
integrationtest/src/test/resources/defaultPackage/main/java/DefaultPackageObject.java
{ "start": 1861, "end": 2062 }
interface ____ { CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); @Mapping(source = "numberOfSeats", target = "seatCount") CarDto carToCarDto(Car car); } }
CarMapper
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java
{ "start": 14452, "end": 14842 }
class ____ extends TableFunction<String> { * public void eval(String str) { * str.split("#").forEach(this::collect); * } * } * * table.joinLateral(call(MySplitUDTF.class, $("c")).as("s"), $("a").isEqual($("s"))) * .select($("a"), $("b"), $("c"), $("s")); * }</pre> * * <p>Scala Example: * * <pre>{@code *
MySplitUDTF
java
elastic__elasticsearch
x-pack/plugin/voting-only-node/src/internalClusterTest/java/org/elasticsearch/cluster/coordination/votingonly/VotingOnlyNodePluginTests.java
{ "start": 12724, "end": 13839 }
class ____ extends FsRepository { private final ClusterService clusterService; private AccessVerifyingRepo( ProjectId projectId, RepositoryMetadata metadata, Environment environment, NamedXContentRegistry namedXContentRegistry, ClusterService clusterService, BigArrays bigArrays, RecoverySettings recoverySettings ) { super(projectId, metadata, environment, namedXContentRegistry, clusterService, bigArrays, recoverySettings); this.clusterService = clusterService; } @Override protected BlobStore createBlobStore() throws Exception { final DiscoveryNode localNode = clusterService.state().nodes().getLocalNode(); if (localNode.getRoles().contains(DiscoveryNodeRole.VOTING_ONLY_NODE_ROLE)) { assertTrue(localNode.canContainData()); } return super.createBlobStore(); } } } }
AccessVerifyingRepo
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java
{ "start": 1569, "end": 8110 }
class ____ { @Mock @SuppressWarnings("NullAway.Init") private ConfigurableApplicationContext mockContext; private RuntimeException startupFailure; private Supplier<ApplicationContext> mockContextSupplier; private Supplier<ApplicationContext> startupFailureSupplier; @BeforeEach void setup() { this.startupFailure = new RuntimeException(); this.mockContextSupplier = () -> this.mockContext; this.startupFailureSupplier = () -> { throw this.startupFailure; }; } @Test @SuppressWarnings("NullAway") // Test null check void getWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("'type' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void getWhenTypeIsClassShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("'type' must not be null"); } @Test void getWhenContextTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, ApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("'type' must be an interface"); } @Test @SuppressWarnings("NullAway") // Test null check void getWhenContextTypeIsClassShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, null, this.mockContextSupplier)) .withMessageContaining("'contextType' must not be null"); } @Test void getWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, StaticApplicationContext.class, this.mockContextSupplier)) .withMessageContaining("'contextType' must be an interface"); } @Test void getWhenContextStartsShouldReturnProxyThatCallsRealMethods() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier); assertThat((Object) context).isNotNull(); context.getBean("foo"); then(this.mockContext).should().getBean("foo"); } @Test void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier); assertThat((Object) context).isNotNull(); assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")) .withCause(this.startupFailure) .withMessageContaining("failed to start"); } @Test void getSourceContextWhenContextStartsShouldReturnSourceContext() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier); assertThat(context.getSourceApplicationContext()).isSameAs(this.mockContext); } @Test void getSourceContextWhenContextFailsShouldThrowException() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier); assertThatIllegalStateException().isThrownBy(context::getSourceApplicationContext) .withCause(this.startupFailure) .withMessageContaining("failed to start"); } @Test void getSourceContextOfTypeWhenContextStartsShouldReturnSourceContext() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier); assertThat(context.getSourceApplicationContext(ApplicationContext.class)).isSameAs(this.mockContext); } @Test void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier); assertThatIllegalStateException() .isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class)) .withCause(this.startupFailure) .withMessageContaining("failed to start"); } @Test void getStartupFailureWhenContextStartsShouldReturnNull() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier); assertThat(context.getStartupFailure()).isNull(); } @Test void getStartupFailureWhenContextFailsToStartShouldReturnException() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier); assertThat(context.getStartupFailure()).isEqualTo(this.startupFailure); } @Test void assertThatWhenContextStartsShouldReturnAssertions() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier); ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context); assertThat(contextAssert.getApplicationContext()).isSameAs(context); assertThat(contextAssert.getStartupFailure()).isNull(); } @Test void assertThatWhenContextFailsShouldReturnAssertions() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier); ApplicationContextAssert<ApplicationContext> contextAssert = assertThat(context); assertThat(contextAssert.getApplicationContext()).isSameAs(context); assertThat(contextAssert.getStartupFailure()).isSameAs(this.startupFailure); } @Test void toStringWhenContextStartsShouldReturnSimpleString() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier); assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock") .endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]"); } @Test void toStringWhenContextFailsToStartShouldReturnSimpleString() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.startupFailureSupplier); assertThat(context).hasToString("Unstarted application context " + "org.springframework.context.ApplicationContext[startupFailure=java.lang.RuntimeException]"); } @Test void closeShouldCloseContext() { ApplicationContextAssertProvider<ApplicationContext> context = get(this.mockContextSupplier); context.close(); then(this.mockContext).should().close(); } private ApplicationContextAssertProvider<ApplicationContext> get(Supplier<ApplicationContext> contextSupplier) { return ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, ApplicationContext.class, contextSupplier); }
ApplicationContextAssertProviderTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/ChannelReaderInputViewIterator.java
{ "start": 1572, "end": 4571 }
class ____<E> implements MutableObjectIterator<E> { private final AbstractChannelReaderInputView inView; private final TypeSerializer<E> accessors; private final List<MemorySegment> freeMemTarget; public ChannelReaderInputViewIterator( IOManager ioAccess, FileIOChannel.ID channel, List<MemorySegment> segments, List<MemorySegment> freeMemTarget, TypeSerializer<E> accessors, int numBlocks) throws IOException { this( ioAccess, channel, new LinkedBlockingQueue<MemorySegment>(), segments, freeMemTarget, accessors, numBlocks); } public ChannelReaderInputViewIterator( IOManager ioAccess, FileIOChannel.ID channel, LinkedBlockingQueue<MemorySegment> returnQueue, List<MemorySegment> segments, List<MemorySegment> freeMemTarget, TypeSerializer<E> accessors, int numBlocks) throws IOException { this( ioAccess.createBlockChannelReader(channel, returnQueue), returnQueue, segments, freeMemTarget, accessors, numBlocks); } public ChannelReaderInputViewIterator( BlockChannelReader<MemorySegment> reader, LinkedBlockingQueue<MemorySegment> returnQueue, List<MemorySegment> segments, List<MemorySegment> freeMemTarget, TypeSerializer<E> accessors, int numBlocks) throws IOException { this.accessors = accessors; this.freeMemTarget = freeMemTarget; this.inView = new ChannelReaderInputView(reader, segments, numBlocks, false); } public ChannelReaderInputViewIterator( AbstractChannelReaderInputView inView, List<MemorySegment> freeMemTarget, TypeSerializer<E> accessors) { this.inView = inView; this.freeMemTarget = freeMemTarget; this.accessors = accessors; } @Override public E next(E reuse) throws IOException { try { return this.accessors.deserialize(reuse, this.inView); } catch (EOFException eofex) { final List<MemorySegment> freeMem = this.inView.close(); if (this.freeMemTarget != null) { this.freeMemTarget.addAll(freeMem); } return null; } } @Override public E next() throws IOException { try { return this.accessors.deserialize(this.inView); } catch (EOFException eofex) { final List<MemorySegment> freeMem = this.inView.close(); if (this.freeMemTarget != null) { this.freeMemTarget.addAll(freeMem); } return null; } } }
ChannelReaderInputViewIterator
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/fs/contract/router/web/TestRouterWebHDFSContractAppend.java
{ "start": 999, "end": 1449 }
class ____ extends AbstractContractAppendTest { @BeforeAll public static void createCluster() throws IOException { RouterWebHDFSContract.createCluster(); } @AfterAll public static void teardownCluster() throws IOException { RouterWebHDFSContract.destroyCluster(); } @Override protected AbstractFSContract createContract(Configuration conf) { return new RouterWebHDFSContract(conf); } }
TestRouterWebHDFSContractAppend
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/ResponseEntity.java
{ "start": 2994, "end": 6224 }
class ____<T> extends HttpEntity<T> { private final HttpStatusCode status; /** * Create a {@code ResponseEntity} with a status code only. * @param status the status code */ public ResponseEntity(HttpStatusCode status) { this(null, (HttpHeaders) null, status); } /** * Create a {@code ResponseEntity} with a body and status code. * @param body the entity body * @param status the status code */ public ResponseEntity(@Nullable T body, HttpStatusCode status) { this(body, (HttpHeaders) null, status); } /** * Create a {@code ResponseEntity} with headers and a status code. * @param headers the entity headers * @param status the status code * @since 7.0 */ public ResponseEntity(HttpHeaders headers, HttpStatusCode status) { this(null, headers, status); } /** * Create a {@code ResponseEntity} with a body, headers, and a raw status code. * @param body the entity body * @param headers the entity headers * @param rawStatus the status code value * @since 7.0 */ public ResponseEntity(@Nullable T body, @Nullable HttpHeaders headers, int rawStatus) { this(body, headers, HttpStatusCode.valueOf(rawStatus)); } /** * Create a {@code ResponseEntity} with a body, headers, and a status code. * @param body the entity body * @param headers the entity headers * @param statusCode the status code * @since 7.0 */ public ResponseEntity(@Nullable T body, @Nullable HttpHeaders headers, HttpStatusCode statusCode) { super(body, headers); Assert.notNull(statusCode, "HttpStatusCode must not be null"); this.status = statusCode; } /** * Create a {@code ResponseEntity} with headers and a status code. * @param headers the entity headers * @param status the status code * @deprecated in favor of {@link #ResponseEntity(HttpHeaders, HttpStatusCode)} */ @Deprecated(since = "7.0", forRemoval = true) public ResponseEntity(MultiValueMap<String, String> headers, HttpStatusCode status) { this(null, headers, status); } /** * Create a {@code ResponseEntity} with a body, headers, and a raw status code. * @param body the entity body * @param headers the entity headers * @param rawStatus the status code value * @since 5.3.2 * @deprecated in favor of {@link #ResponseEntity(Object, HttpHeaders, int)} */ @Deprecated(since = "7.0", forRemoval = true) public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, int rawStatus) { this(body, headers, HttpStatusCode.valueOf(rawStatus)); } /** * Create a {@code ResponseEntity} with a body, headers, and a status code. * @param body the entity body * @param headers the entity headers * @param statusCode the status code * @deprecated in favor of {@link #ResponseEntity(Object, HttpHeaders, HttpStatusCode)} */ @SuppressWarnings("removal") @Deprecated(since = "7.0", forRemoval = true) public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatusCode statusCode) { super(body, headers); Assert.notNull(statusCode, "HttpStatusCode must not be null"); this.status = statusCode; } /** * Return the HTTP status code of the response. * @return the HTTP status as an HttpStatus
ResponseEntity
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/script/ScriptCacheStatsTests.java
{ "start": 812, "end": 3513 }
class ____ extends ESTestCase { public void testXContentChunkedWithGeneralMode() throws IOException { var builder = XContentFactory.jsonBuilder().prettyPrint(); var contextStats = List.of( new ScriptContextStats("context-1", 302, new TimeSeries(1000, 1001, 1002, 100), new TimeSeries(2000, 2001, 2002, 201)), new ScriptContextStats("context-2", 3020, new TimeSeries(1000), new TimeSeries(2010)) ); var stats = ScriptStats.read(contextStats); var scriptCacheStats = new ScriptCacheStats(stats); builder.startObject(); scriptCacheStats.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); String expected = """ { "script_cache" : { "sum" : { "compilations" : 1100, "cache_evictions" : 2211, "compilation_limit_triggered" : 3322 } } }"""; assertThat(Strings.toString(builder), equalTo(expected)); } public void testXContentChunkedWithContextMode() throws IOException { var builder = XContentFactory.jsonBuilder().prettyPrint(); var scriptCacheStats = new ScriptCacheStats( Map.of( "context-1", ScriptStats.read( new ScriptContextStats("context-1", 302, new TimeSeries(1000, 1001, 1002, 100), new TimeSeries(2000, 2001, 2002, 201)) ), "context-2", ScriptStats.read(new ScriptContextStats("context-2", 3020, new TimeSeries(1000), new TimeSeries(2010))) ) ); builder.startObject(); scriptCacheStats.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); String expected = """ { "script_cache" : { "sum" : { "compilations" : 1100, "cache_evictions" : 2211, "compilation_limit_triggered" : 3322 }, "contexts" : [ { "context" : "context-1", "compilations" : 100, "cache_evictions" : 201, "compilation_limit_triggered" : 302 }, { "context" : "context-2", "compilations" : 1000, "cache_evictions" : 2010, "compilation_limit_triggered" : 3020 } ] } }"""; assertThat(Strings.toString(builder), equalTo(expected)); } }
ScriptCacheStatsTests
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/CustomSdkSigner.java
{ "start": 1918, "end": 5668 }
class ____ extends AbstractAwsS3V4Signer implements Signer { private static final Logger LOG = LoggerFactory .getLogger(CustomSdkSigner.class); private static final AtomicInteger INSTANTIATION_COUNT = new AtomicInteger(0); private static final AtomicInteger INVOCATION_COUNT = new AtomicInteger(0); /** * Signer for all S3 requests. */ private final AwsS3V4Signer s3Signer = AwsS3V4Signer.create(); /** * Signer for other services. */ private final Aws4Signer aws4Signer = Aws4Signer.create(); public CustomSdkSigner() { int c = INSTANTIATION_COUNT.incrementAndGet(); LOG.info("Creating Signer #{}", c); } /** * Method to sign the incoming request with credentials. * <p> * NOTE: In case of Client-side encryption, we do a "Generate Key" POST * request to AWSKMS service rather than S3, this was causing the test to * break. When this request happens, we have the endpoint in form of * "kms.[REGION].amazonaws.com", and bucket-name becomes "kms". We can't * use AWSS3V4Signer for AWSKMS service as it contains a header * "x-amz-content-sha256:UNSIGNED-PAYLOAD", which returns a 400 bad * request because the signature calculated by the service doesn't match * what we sent. * @param request the request to sign. * @param executionAttributes request executionAttributes which contain the credentials. */ @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { int c = INVOCATION_COUNT.incrementAndGet(); String host = request.host(); LOG.debug("Signing request #{} against {}: class {}", c, host, request.getClass()); String bucketName = parseBucketFromHost(host); if (bucketName.equals("kms")) { return aws4Signer.sign(request, executionAttributes); } else { return s3Signer.sign(request, executionAttributes); } } /** * Parse the bucket name from the host. * This does not work for path-style access; the hostname of the endpoint is returned. * @param host hostname * @return the parsed bucket name; if "kms" is KMS signing. */ static String parseBucketFromHost(String host) { String[] hostBits = host.split("\\."); String bucketName = hostBits[0]; String service = hostBits[1]; if (bucketName.equals("kms")) { return bucketName; } if (service.contains("s3-accesspoint") || service.contains("s3-outposts") || service.contains("s3-object-lambda")) { // If AccessPoint then bucketName is of format `accessPoint-accountId`; String[] accessPointBits = bucketName.split("-"); String accountId = accessPointBits[accessPointBits.length - 1]; // Extract the access point name from bucket name. eg: if bucket name is // test-custom-signer-<accountId>, get the access point name test-custom-signer by removing // -<accountId> from the bucket name. String accessPointName = bucketName.substring(0, bucketName.length() - (accountId.length() + 1)); Arn arn = Arn.builder() .accountId(accountId) .partition("aws") .region(hostBits[2]) .resource("accesspoint" + "/" + accessPointName) .service("s3").build(); bucketName = arn.toString(); } return bucketName; } public static int getInstantiationCount() { return INSTANTIATION_COUNT.get(); } public static int getInvocationCount() { return INVOCATION_COUNT.get(); } public static String description() { return "CustomSigner{" + "invocations=" + INVOCATION_COUNT.get() + ", instantiations=" + INSTANTIATION_COUNT.get() + "}"; } public static
CustomSdkSigner
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-common/spi-deployment/src/main/java/io/quarkus/resteasy/reactive/spi/MessageBodyReaderBuildItem.java
{ "start": 2026, "end": 3209 }
class ____ { private final String className; private final String handledClassName; private List<String> mediaTypeStrings = Collections.emptyList(); private RuntimeType runtimeType = null; private boolean builtin = false; private Integer priority = Priorities.USER; public Builder(String className, String handledClassName) { this.className = className; this.handledClassName = handledClassName; } public Builder setMediaTypeStrings(List<String> mediaTypeStrings) { this.mediaTypeStrings = mediaTypeStrings; return this; } public Builder setRuntimeType(RuntimeType runtimeType) { this.runtimeType = runtimeType; return this; } public Builder setBuiltin(boolean builtin) { this.builtin = builtin; return this; } public Builder setPriority(Integer priority) { this.priority = priority; return this; } public MessageBodyReaderBuildItem build() { return new MessageBodyReaderBuildItem(this); } } }
Builder
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java
{ "start": 1130, "end": 3943 }
class ____ { @Test void testLookupSucceeds() throws Exception { Object o = new Object(); String name = "foo"; final Context context = mock(); given(context.lookup(name)).willReturn(o); JndiTemplate jt = new JndiTemplate() { @Override protected Context createInitialContext() { return context; } }; Object o2 = jt.lookup(name); assertThat(o2).isEqualTo(o); verify(context).close(); } @Test void testLookupFails() throws Exception { NameNotFoundException ne = new NameNotFoundException(); String name = "foo"; final Context context = mock(); given(context.lookup(name)).willThrow(ne); JndiTemplate jt = new JndiTemplate() { @Override protected Context createInitialContext() { return context; } }; assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> jt.lookup(name)); verify(context).close(); } @Test void testLookupReturnsNull() throws Exception { String name = "foo"; final Context context = mock(); given(context.lookup(name)).willReturn(null); JndiTemplate jt = new JndiTemplate() { @Override protected Context createInitialContext() { return context; } }; assertThatExceptionOfType(NameNotFoundException.class).isThrownBy(() -> jt.lookup(name)); verify(context).close(); } @Test void testLookupFailsWithTypeMismatch() throws Exception { Object o = new Object(); String name = "foo"; final Context context = mock(); given(context.lookup(name)).willReturn(o); JndiTemplate jt = new JndiTemplate() { @Override protected Context createInitialContext() { return context; } }; assertThatExceptionOfType(TypeMismatchNamingException.class).isThrownBy(() -> jt.lookup(name, String.class)); verify(context).close(); } @Test void testBind() throws Exception { Object o = new Object(); String name = "foo"; final Context context = mock(); JndiTemplate jt = new JndiTemplate() { @Override protected Context createInitialContext() { return context; } }; jt.bind(name, o); verify(context).bind(name, o); verify(context).close(); } @Test void testRebind() throws Exception { Object o = new Object(); String name = "foo"; final Context context = mock(); JndiTemplate jt = new JndiTemplate() { @Override protected Context createInitialContext() { return context; } }; jt.rebind(name, o); verify(context).rebind(name, o); verify(context).close(); } @Test void testUnbind() throws Exception { String name = "something"; final Context context = mock(); JndiTemplate jt = new JndiTemplate() { @Override protected Context createInitialContext() { return context; } }; jt.unbind(name); verify(context).unbind(name); verify(context).close(); } }
JndiTemplateTests
java
elastic__elasticsearch
x-pack/plugin/downsample/src/main/java/org/elasticsearch/xpack/downsample/TransportDownsampleAction.java
{ "start": 52732, "end": 56312 }
class ____ implements ActionListener<BroadcastResponse> { private final ProjectId projectId; private final ActionListener<AcknowledgedResponse> actionListener; private final TaskId parentTask; private final String downsampleIndexName; private final TimeValue timeout; private final long startTime; RefreshDownsampleIndexActionListener( ProjectId projectId, final ActionListener<AcknowledgedResponse> actionListener, TaskId parentTask, final String downsampleIndexName, final TimeValue timeout, final long startTime ) { this.projectId = projectId; this.actionListener = actionListener; this.parentTask = parentTask; this.downsampleIndexName = downsampleIndexName; this.timeout = timeout; this.startTime = startTime; } @Override public void onResponse(final BroadcastResponse response) { if (response.getFailedShards() != 0) { logger.info("Post refresh failed [{}],{}", downsampleIndexName, Strings.toString(response)); } ActionListener<AcknowledgedResponse> nextStepListener = new FlushActionListener( parentTask, downsampleIndexName, startTime, actionListener ); // Mark downsample index as "completed successfully" ("index.downsample.status": "success") taskQueue.submitTask( "update-downsample-metadata [" + downsampleIndexName + "]", new DownsampleClusterStateUpdateTask(nextStepListener) { @Override public ClusterState execute(ClusterState currentState) { logger.debug("Updating downsample index status for [{}]", downsampleIndexName); final ProjectMetadata project = currentState.metadata().getProject(projectId); final IndexMetadata downsampleIndex = project.index(downsampleIndexName); if (downsampleIndex == null) { throw new IllegalStateException( "Failed to update downsample status because [" + downsampleIndexName + "] does not exist" ); } if (IndexMetadata.INDEX_DOWNSAMPLE_STATUS.get(downsampleIndex.getSettings()) == DownsampleTaskStatus.SUCCESS) { return currentState; } final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(project); projectBuilder.updateSettings( Settings.builder() .put(downsampleIndex.getSettings()) .put(IndexMetadata.INDEX_DOWNSAMPLE_STATUS.getKey(), DownsampleTaskStatus.SUCCESS) .build(), downsampleIndexName ); return ClusterState.builder(currentState).putProjectMetadata(projectBuilder).build(); } }, timeout ); } @Override public void onFailure(Exception e) { actionListener.onFailure(e); } } /** * Triggers a flush operation on the downsample target index */
RefreshDownsampleIndexActionListener
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialWithin.java
{ "start": 2759, "end": 14099 }
class ____ extends SpatialRelatesFunction implements SurrogateExpression { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( Expression.class, "SpatialWithin", SpatialWithin::new ); // public for test access with reflection public static final SpatialRelations GEO = new SpatialRelations( ShapeField.QueryRelation.WITHIN, SpatialCoordinateTypes.GEO, CoordinateEncoder.GEO, new GeoShapeIndexer(Orientation.CCW, "ST_Within") ); // public for test access with reflection public static final SpatialRelations CARTESIAN = new SpatialRelations( ShapeField.QueryRelation.WITHIN, SpatialCoordinateTypes.CARTESIAN, CoordinateEncoder.CARTESIAN, new CartesianShapeIndexer("ST_Within") ); @FunctionInfo( returnType = { "boolean" }, description = """ Returns whether the first geometry is within the second geometry. This is the inverse of the <<esql-st_contains,ST_CONTAINS>> function.""", examples = @Example(file = "spatial_shapes", tag = "st_within-airport_city_boundaries") ) public SpatialWithin( Source source, @Param(name = "geomA", type = { "geo_point", "cartesian_point", "geo_shape", "cartesian_shape" }, description = """ Expression of type `geo_point`, `cartesian_point`, `geo_shape` or `cartesian_shape`. If `null`, the function returns `null`.""") Expression left, @Param(name = "geomB", type = { "geo_point", "cartesian_point", "geo_shape", "cartesian_shape" }, description = """ Expression of type `geo_point`, `cartesian_point`, `geo_shape` or `cartesian_shape`. If `null`, the function returns `null`. The second parameter must also have the same coordinate system as the first. This means it is not possible to combine `geo_*` and `cartesian_*` parameters.""") Expression right ) { this(source, left, right, false, false); } SpatialWithin(Source source, Expression left, Expression right, boolean leftDocValues, boolean rightDocValues) { super(source, left, right, leftDocValues, rightDocValues); } private SpatialWithin(StreamInput in) throws IOException { super(in, false, false); } @Override public String getWriteableName() { return ENTRY.name; } @Override public ShapeRelation queryRelation() { return ShapeRelation.WITHIN; } @Override public SpatialWithin withDocValues(boolean foundLeft, boolean foundRight) { // Only update the docValues flags if the field is found in the attributes boolean leftDV = leftDocValues || foundLeft; boolean rightDV = rightDocValues || foundRight; return new SpatialWithin(source(), left(), right(), leftDV, rightDV); } @Override protected SpatialWithin replaceChildren(Expression newLeft, Expression newRight) { return new SpatialWithin(source(), newLeft, newRight, leftDocValues, rightDocValues); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, SpatialWithin::new, left(), right()); } @Override public Object fold(FoldContext ctx) { try { GeometryDocValueReader docValueReader = asGeometryDocValueReader(ctx, crsType(), left()); Component2D component2D = asLuceneComponent2D(ctx, crsType(), right()); return (crsType() == SpatialCrsType.GEO) ? GEO.geometryRelatesGeometry(docValueReader, component2D) : CARTESIAN.geometryRelatesGeometry(docValueReader, component2D); } catch (IOException e) { throw new IllegalArgumentException("Failed to fold constant fields: " + e.getMessage(), e); } } @Override Map<SpatialEvaluatorFactory.SpatialEvaluatorKey, SpatialEvaluatorFactory<?, ?>> evaluatorRules() { return evaluatorMap; } /** * To keep the number of evaluators to a minimum, we swap the arguments to get the CONTAINS relation. * This also makes other optimizations, like lucene-pushdown, simpler to develop. */ @Override public SpatialRelatesFunction surrogate() { if (left().foldable() && right().foldable() == false) { return new SpatialContains(source(), right(), left(), rightDocValues, leftDocValues); } return this; } private static final Map<SpatialEvaluatorFactory.SpatialEvaluatorKey, SpatialEvaluatorFactory<?, ?>> evaluatorMap = new HashMap<>(); static { // Support geo_point and geo_shape from source and constant combinations for (DataType spatialType : new DataType[] { GEO_POINT, GEO_SHAPE }) { for (DataType otherType : new DataType[] { GEO_POINT, GEO_SHAPE }) { evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSources(spatialType, otherType), new SpatialEvaluatorFactory.SpatialEvaluatorFactoryWithFields(SpatialWithinGeoSourceAndSourceEvaluator.Factory::new) ); evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSourceAndConstant(spatialType, otherType), new SpatialEvaluatorFactory.SpatialEvaluatorWithConstantFactory(SpatialWithinGeoSourceAndConstantEvaluator.Factory::new) ); if (DataType.isSpatialPoint(spatialType)) { evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSources(spatialType, otherType).withLeftDocValues(), new SpatialEvaluatorFactory.SpatialEvaluatorFactoryWithFields( SpatialWithinGeoPointDocValuesAndSourceEvaluator.Factory::new ) ); evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSourceAndConstant(spatialType, otherType).withLeftDocValues(), new SpatialEvaluatorFactory.SpatialEvaluatorWithConstantFactory( SpatialWithinGeoPointDocValuesAndConstantEvaluator.Factory::new ) ); } } } // Support cartesian_point and cartesian_shape from source and constant combinations for (DataType spatialType : new DataType[] { CARTESIAN_POINT, CARTESIAN_SHAPE }) { for (DataType otherType : new DataType[] { CARTESIAN_POINT, CARTESIAN_SHAPE }) { evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSources(spatialType, otherType), new SpatialEvaluatorFactory.SpatialEvaluatorFactoryWithFields( SpatialWithinCartesianSourceAndSourceEvaluator.Factory::new ) ); evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSourceAndConstant(spatialType, otherType), new SpatialEvaluatorFactory.SpatialEvaluatorWithConstantFactory( SpatialWithinCartesianSourceAndConstantEvaluator.Factory::new ) ); if (DataType.isSpatialPoint(spatialType)) { evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSources(spatialType, otherType).withLeftDocValues(), new SpatialEvaluatorFactory.SpatialEvaluatorFactoryWithFields( SpatialWithinCartesianPointDocValuesAndSourceEvaluator.Factory::new ) ); evaluatorMap.put( SpatialEvaluatorFactory.SpatialEvaluatorKey.fromSourceAndConstant(spatialType, otherType).withLeftDocValues(), new SpatialEvaluatorFactory.SpatialEvaluatorWithConstantFactory( SpatialWithinCartesianPointDocValuesAndConstantEvaluator.Factory::new ) ); } } } } @Evaluator(extraName = "GeoSourceAndConstant", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processGeoSourceAndConstant(BooleanBlock.Builder results, @Position int p, BytesRefBlock left, @Fixed Component2D right) throws IOException { GEO.processSourceAndConstant(results, p, left, right); } @Evaluator(extraName = "GeoSourceAndSource", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processGeoSourceAndSource(BooleanBlock.Builder builder, @Position int p, BytesRefBlock left, BytesRefBlock right) throws IOException { GEO.processSourceAndSource(builder, p, left, right); } @Evaluator(extraName = "GeoPointDocValuesAndConstant", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processGeoPointDocValuesAndConstant(BooleanBlock.Builder builder, @Position int p, LongBlock left, @Fixed Component2D right) throws IOException { GEO.processPointDocValuesAndConstant(builder, p, left, right); } @Evaluator(extraName = "GeoPointDocValuesAndSource", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processGeoPointDocValuesAndSource(BooleanBlock.Builder builder, @Position int p, LongBlock left, BytesRefBlock right) throws IOException { GEO.processPointDocValuesAndSource(builder, p, left, right); } @Evaluator(extraName = "CartesianSourceAndConstant", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processCartesianSourceAndConstant( BooleanBlock.Builder builder, @Position int p, BytesRefBlock left, @Fixed Component2D right ) throws IOException { CARTESIAN.processSourceAndConstant(builder, p, left, right); } @Evaluator(extraName = "CartesianSourceAndSource", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processCartesianSourceAndSource(BooleanBlock.Builder builder, @Position int p, BytesRefBlock left, BytesRefBlock right) throws IOException { CARTESIAN.processSourceAndSource(builder, p, left, right); } @Evaluator(extraName = "CartesianPointDocValuesAndConstant", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processCartesianPointDocValuesAndConstant( BooleanBlock.Builder builder, @Position int p, LongBlock left, @Fixed Component2D right ) throws IOException { CARTESIAN.processPointDocValuesAndConstant(builder, p, left, right); } @Evaluator(extraName = "CartesianPointDocValuesAndSource", warnExceptions = { IllegalArgumentException.class, IOException.class }) static void processCartesianPointDocValuesAndSource(BooleanBlock.Builder builder, @Position int p, LongBlock left, BytesRefBlock right) throws IOException { CARTESIAN.processPointDocValuesAndSource(builder, p, left, right); } }
SpatialWithin
java
spring-projects__spring-security
ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java
{ "start": 1916, "end": 2079 }
class ____ adds extra functionality required * by Spring Security. * * @author Ben Alex * @author Luke Taylor * @author Filip Hanik * @since 2.0 */ public
which
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/transport/RemoteClusterServerInfo.java
{ "start": 934, "end": 2190 }
class ____ implements ReportingService.Info { private final BoundTransportAddress address; public RemoteClusterServerInfo(StreamInput in) throws IOException { this(new BoundTransportAddress(in)); } public RemoteClusterServerInfo(BoundTransportAddress address) { this.address = address; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject("remote_cluster_server"); builder.array("bound_address", (Object[]) address.boundAddresses()); TransportAddress publishAddress = address.publishAddress(); String publishAddressString = publishAddress.toString(); String hostString = publishAddress.address().getHostString(); if (InetAddresses.isInetAddress(hostString) == false) { publishAddressString = hostString + '/' + publishAddress; } builder.field("publish_address", publishAddressString); builder.endObject(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { address.writeTo(out); } public BoundTransportAddress getAddress() { return address; } }
RemoteClusterServerInfo
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEventHandler.java
{ "start": 1419, "end": 2916 }
class ____ { private final BlockingQueue<BackgroundEvent> backgroundEventQueue; private final Time time; private final AsyncConsumerMetrics asyncConsumerMetrics; public BackgroundEventHandler(final BlockingQueue<BackgroundEvent> backgroundEventQueue, final Time time, final AsyncConsumerMetrics asyncConsumerMetrics) { this.backgroundEventQueue = backgroundEventQueue; this.time = time; this.asyncConsumerMetrics = asyncConsumerMetrics; } /** * Add a {@link BackgroundEvent} to the handler. * * @param event A {@link BackgroundEvent} created by the {@link ConsumerNetworkThread network thread} */ public void add(BackgroundEvent event) { Objects.requireNonNull(event, "BackgroundEvent provided to add must be non-null"); event.setEnqueuedMs(time.milliseconds()); asyncConsumerMetrics.recordBackgroundEventQueueSize(backgroundEventQueue.size() + 1); backgroundEventQueue.add(event); } /** * Drain all the {@link BackgroundEvent events} from the handler. * * @return A list of {@link BackgroundEvent events} that were drained */ public List<BackgroundEvent> drainEvents() { List<BackgroundEvent> events = new ArrayList<>(); backgroundEventQueue.drainTo(events); asyncConsumerMetrics.recordBackgroundEventQueueSize(0); return events; } }
BackgroundEventHandler
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestMaintenanceState.java
{ "start": 2524, "end": 2565 }
class ____ node maintenance. */ public
tests
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/FailableLongToDoubleFunction.java
{ "start": 918, "end": 1100 }
interface ____ {@link LongToDoubleFunction} that declares a {@link Throwable}. * * @param <E> The kind of thrown exception or error. * @since 3.11 */ @FunctionalInterface public
like
java
elastic__elasticsearch
libs/x-content/src/main/java/org/elasticsearch/xcontent/spi/XContentProvider.java
{ "start": 975, "end": 1083 }
interface ____ { /** * A provider of a specific content format, e.g. JSON */
XContentProvider
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/unmappedsource/beanmapping/BeanMappingSourcePolicyErroneousMapper.java
{ "start": 369, "end": 518 }
interface ____ { @BeanMapping(unmappedSourcePolicy = ReportingPolicy.ERROR) Target map(Source source); }
BeanMappingSourcePolicyErroneousMapper
java
redisson__redisson
redisson/src/main/java/org/redisson/api/listener/ScoredSortedSetRemoveListener.java
{ "start": 906, "end": 1134 }
interface ____ extends ObjectListener { /** * Invoked when entry removed from RScoredSortedSet object * * @param name - name of object */ void onRemove(String name); }
ScoredSortedSetRemoveListener
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/allocation/allocator/PendingListenersQueue.java
{ "start": 1356, "end": 3493 }
class ____ { private static final Logger logger = LogManager.getLogger(PendingListenersQueue.class); private record PendingListener(long index, ActionListener<Void> listener) {} private final Queue<PendingListener> pendingListeners = new LinkedList<>(); private volatile long completedIndex = -1; public void add(long index, ActionListener<Void> listener) { synchronized (pendingListeners) { pendingListeners.add(new PendingListener(index, listener)); } } public void complete(long convergedIndex) { assert MasterService.assertMasterUpdateOrTestThread(); synchronized (pendingListeners) { if (convergedIndex > completedIndex) { completedIndex = convergedIndex; } } executeListeners(completedIndex, true); } public void completeAllAsNotMaster() { assert ThreadPool.assertCurrentThreadPool(MASTER_UPDATE_THREAD_NAME, CLUSTER_UPDATE_THREAD_NAME); completedIndex = -1; executeListeners(Long.MAX_VALUE, false); } public long getCompletedIndex() { return completedIndex; } private void executeListeners(long convergedIndex, boolean isMaster) { var listeners = pollListeners(convergedIndex); if (listeners.isEmpty() == false) { if (isMaster) { ActionListener.onResponse(listeners, null); } else { ActionListener.onFailure(listeners, new NotMasterException("no longer master")); } } } private Collection<ActionListener<Void>> pollListeners(long maxIndex) { var listeners = new ArrayList<ActionListener<Void>>(); PendingListener listener; synchronized (pendingListeners) { while ((listener = pendingListeners.peek()) != null && listener.index <= maxIndex) { listeners.add(pendingListeners.poll().listener); } logger.trace("Polled listeners up to [{}]. Poll {}, remaining {}", maxIndex, listeners, pendingListeners); } return listeners; } }
PendingListenersQueue
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdTest.java
{ "start": 7613, "end": 7654 }
enum ____ { BIG_DECIMAL } static
Type965
java
apache__kafka
connect/api/src/main/java/org/apache/kafka/connect/health/ConnectorHealth.java
{ "start": 1022, "end": 3431 }
class ____ { private final String name; private final ConnectorState connectorState; private final Map<Integer, TaskState> tasks; private final ConnectorType type; public ConnectorHealth(String name, ConnectorState connectorState, Map<Integer, TaskState> tasks, ConnectorType type) { if (Utils.isBlank(name)) { throw new IllegalArgumentException("Connector name is required"); } Objects.requireNonNull(connectorState, "connectorState can't be null"); Objects.requireNonNull(tasks, "tasks can't be null"); Objects.requireNonNull(type, "type can't be null"); this.name = name; this.connectorState = connectorState; this.tasks = tasks; this.type = type; } /** * Provides the name of the connector. * * @return name, never {@code null} or empty */ public String name() { return name; } /** * Provides the current state of the connector. * * @return the connector state, never {@code null} */ public ConnectorState connectorState() { return connectorState; } /** * Provides the current state of the connector tasks. * * @return the state for each task ID; never {@code null} */ public Map<Integer, TaskState> tasksState() { return tasks; } /** * Provides the type of the connector. * * @return type, never {@code null} */ public ConnectorType type() { return type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConnectorHealth that = (ConnectorHealth) o; return name.equals(that.name) && connectorState.equals(that.connectorState) && tasks.equals(that.tasks) && type == that.type; } @Override public int hashCode() { return Objects.hash(name, connectorState, tasks, type); } @Override public String toString() { return "ConnectorHealth{" + "name='" + name + '\'' + ", connectorState=" + connectorState + ", tasks=" + tasks + ", type=" + type + '}'; } }
ConnectorHealth
java
spring-projects__spring-boot
module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java
{ "start": 9127, "end": 9439 }
class ____ implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources() .registerPatternIfPresent(classLoader, "schema.ldif", (hint) -> hint.includes("schema.ldif")); } } }
EmbeddedLdapAutoConfigurationRuntimeHints
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/VelocityEndpointBuilderFactory.java
{ "start": 1437, "end": 1564 }
interface ____ { /** * Builder for endpoint for the Velocity component. */ public
VelocityEndpointBuilderFactory
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ShareUnsubscribeEvent.java
{ "start": 1326, "end": 1515 }
class ____ extends CompletableApplicationEvent<Void> { public ShareUnsubscribeEvent(final long deadlineMs) { super(Type.SHARE_UNSUBSCRIBE, deadlineMs); } }
ShareUnsubscribeEvent
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/NullablePrimitiveTest.java
{ "start": 4876, "end": 5019 }
class ____ { // BUG: Diagnostic contains: @NonNull int xs; } """) .doTest(); } }
Test
java
elastic__elasticsearch
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/UAX29URLEmailTokenizerFactory.java
{ "start": 896, "end": 1470 }
class ____ extends AbstractTokenizerFactory { private final int maxTokenLength; UAX29URLEmailTokenizerFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) { super(name); maxTokenLength = settings.getAsInt("max_token_length", StandardAnalyzer.DEFAULT_MAX_TOKEN_LENGTH); } @Override public Tokenizer create() { UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(); tokenizer.setMaxTokenLength(maxTokenLength); return tokenizer; } }
UAX29URLEmailTokenizerFactory
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/mixins/TestMixinMerging.java
{ "start": 857, "end": 905 }
interface ____ extends Contact {} static
Person
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectData.java
{ "start": 4331, "end": 11237 }
class ____ be treated as though it had an {@link Stringable} * * annotation. */ public ReflectData addStringable(Class c) { stringableClasses.add(c); return this; } /** * If this flag is set to true, default values for fields will be assigned * dynamically using Java reflections. When enabled, defaults are the field * values of an instance created with a no-arg constructor. * * <p> * Let's call this feature `default reflection`. Initially this feature is * disabled. */ private boolean defaultGenerated = false; /** * Enable or disable `default reflection` * * @param enabled set to `true` to enable the feature. This feature is disabled * by default * @return The current instance */ public ReflectData setDefaultsGenerated(boolean enabled) { this.defaultGenerated = enabled; return this; } private final Map<Type, Object> defaultValues = new WeakHashMap<>(); /** * Set the default value for a type. When encountering such type, we'll use this * provided value instead of trying to create a new one. * * <p> * NOTE: This method automatically enable feature `default reflection`. * * @param type The type * @param value Its default value * @return The current instance */ public ReflectData setDefaultGeneratedValue(Type type, Object value) { this.defaultValues.put(type, value); this.setDefaultsGenerated(true); return this; } /** * Get or create new value instance for a field * * @param type The current type * @param field A child field * @return The default field value */ protected Object getOrCreateDefaultValue(Type type, Field field) { Object defaultValue = null; field.setAccessible(true); try { Object typeValue = getOrCreateDefaultValue(type); if (typeValue != null) { defaultValue = field.get(typeValue); } } catch (Exception e) { } return defaultValue; } /** * Get or create new value instance for a type. * * New instances will be instantiated using no-arg constructors. The newly * created one will be cached for later use. * * @param type The type * @return The value */ protected Object getOrCreateDefaultValue(Type type) { return this.defaultValues.computeIfAbsent(type, ignored -> { try { Constructor constructor = ((Class) type).getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (ClassCastException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { // do nothing } return null; }); } @Override public DatumReader createDatumReader(Schema schema) { return new ReflectDatumReader(schema, schema, this); } @Override public DatumReader createDatumReader(Schema writer, Schema reader) { return new ReflectDatumReader(writer, reader, this); } @Override public DatumWriter createDatumWriter(Schema schema) { return new ReflectDatumWriter(schema, this); } @Override public void setField(Object record, String name, int position, Object value) { setField(record, name, position, value, null); } @Override protected void setField(Object record, String name, int position, Object value, Object state) { if (record instanceof IndexedRecord) { super.setField(record, name, position, value); return; } try { getAccessorForField(record, name, position, state).set(record, value); } catch (IllegalAccessException | IOException e) { throw new AvroRuntimeException(e); } } @Override public Object getField(Object record, String name, int position) { return getField(record, name, position, null); } @Override protected Object getField(Object record, String name, int pos, Object state) { if (record instanceof IndexedRecord) { return super.getField(record, name, pos); } try { return getAccessorForField(record, name, pos, state).get(record); } catch (IllegalAccessException e) { throw new AvroRuntimeException(e); } } private FieldAccessor getAccessorForField(Object record, String name, int pos, Object optionalState) { if (optionalState != null) { return ((FieldAccessor[]) optionalState)[pos]; } return getFieldAccessor(record.getClass(), name); } @Override protected boolean isRecord(Object datum) { if (datum == null) return false; if (super.isRecord(datum)) return true; if (datum instanceof Collection) return false; if (datum instanceof Map) return false; if (datum instanceof GenericFixed) return false; return getSchema(datum.getClass()).getType() == Schema.Type.RECORD; } /** * Returns true for arrays and false otherwise, with the following exceptions: * * <ul> * <li> * <p> * Returns true for non-string-keyed maps, which are written as an array of * key/value pair records. * <li> * <p> * Returns false for arrays of bytes, since those should be treated as byte data * type instead. * </ul> */ @Override protected boolean isArray(Object datum) { if (datum == null) return false; Class c = datum.getClass(); return (datum instanceof Collection) || (c.isArray() && c.getComponentType() != Byte.TYPE) || isNonStringMap(datum); } @Override protected Collection getArrayAsCollection(Object datum) { return (datum instanceof Map) ? ((Map) datum).entrySet() : (Collection) datum; } @Override protected boolean isBytes(Object datum) { if (datum == null) return false; if (super.isBytes(datum)) return true; Class c = datum.getClass(); return c.isArray() && c.getComponentType() == Byte.TYPE; } @Override protected Schema getRecordSchema(Object record) { if (record instanceof GenericContainer) return super.getRecordSchema(record); return getSchema(record.getClass()); } @Override public boolean validate(Schema schema, Object datum) { switch (schema.getType()) { case ARRAY: if (!datum.getClass().isArray()) return super.validate(schema, datum); int length = java.lang.reflect.Array.getLength(datum); for (int i = 0; i < length; i++) if (!validate(schema.getElementType(), java.lang.reflect.Array.get(datum, i))) return false; return true; default: return super.validate(schema, datum); } } static final ClassValue<ClassAccessorData> ACCESSOR_CACHE = new ClassValue<ClassAccessorData>() { @Override protected ClassAccessorData computeValue(Class<?> c) { if (!IndexedRecord.class.isAssignableFrom(c)) { return new ClassAccessorData(c); } return null; } }; static
to
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/async/utils/AsyncForEachRun.java
{ "start": 1433, "end": 1702 }
class ____ designed to work with other asynchronous interfaces and * utility classes to enable complex asynchronous workflows. It allows for * non-blocking execution of tasks, which can improve the performance and * responsiveness of HDFS operations.</p> * * <p>The
is
java
spring-projects__spring-boot
module/spring-boot-data-mongodb/src/test/java/org/springframework/boot/data/mongodb/autoconfigure/DataMongoAutoConfigurationTests.java
{ "start": 3584, "end": 15394 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, MongoAutoConfiguration.class, DataMongoAutoConfiguration.class)); @Test void templateExists() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); } @Test void whenGridFsDatabaseIsConfiguredThenGridFsTemplateIsAutoConfiguredAndUsesIt() { this.contextRunner.withPropertyValues("spring.data.mongodb.gridfs.database:grid").run((context) -> { assertThat(context).hasSingleBean(GridFsTemplate.class); GridFsTemplate template = context.getBean(GridFsTemplate.class); GridFSBucket bucket = getBucket(template); assertThat(bucket).extracting("filesCollection", InstanceOfAssertFactories.type(MongoCollection.class)) .extracting((collection) -> collection.getNamespace().getDatabaseName()) .isEqualTo("grid"); }); } @Test void whenGridFsBucketIsConfiguredThenGridFsTemplateIsAutoConfiguredAndUsesIt() { this.contextRunner.withPropertyValues("spring.data.mongodb.gridfs.bucket:test-bucket").run((context) -> { assertThat(context).hasSingleBean(GridFsTemplate.class); GridFsTemplate template = context.getBean(GridFsTemplate.class); GridFSBucket bucket = getBucket(template); assertThat(bucket.getBucketName()).isEqualTo("test-bucket"); }); } @Test void customConversions() { this.contextRunner.withUserConfiguration(CustomConversionsConfig.class).run((context) -> { MongoTemplate template = context.getBean(MongoTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(MongoClient.class, Boolean.class)) .isTrue(); }); } @Test @Deprecated(since = "4.0.0") void customBigDecimalDeprecatedRepresentation() { this.contextRunner.withPropertyValues("spring.data.mongodb.representation.big-decimal=string") .run((context) -> assertThat(context.getBean(MongoCustomConversions.class)).extracting("converters") .asInstanceOf(InstanceOfAssertFactories.LIST) .map((converter) -> converter.getClass().getName()) .anySatisfy((className) -> assertThat(className).contains("BigDecimalToStringConverter")) .anySatisfy((className) -> assertThat(className).contains("BigIntegerToStringConverter"))); } @Test void customBigDecimalRepresentation() { this.contextRunner.withPropertyValues("spring.data.mongodb.representation.big-decimal=decimal128") .run((context) -> assertThat(context.getBean(MongoCustomConversions.class)).extracting("converters") .asInstanceOf(InstanceOfAssertFactories.LIST) .map((converter) -> converter.getClass().getName()) .anySatisfy((className) -> assertThat(className).contains("BigDecimalToDecimal128Converter")) .anySatisfy((className) -> assertThat(className).contains("BigIntegerToDecimal128Converter"))); } @Test void defaultBigDecimalRepresentation() { this.contextRunner .run((context) -> assertThat(context.getBean(MongoCustomConversions.class)).extracting("converters") .asInstanceOf(InstanceOfAssertFactories.LIST) .map((converter) -> converter.getClass().getName()) .filteredOn((className) -> className.startsWith("org.springframework.data.mongodb")) .noneSatisfy((className) -> assertThat(className).contains("BigDecimalTo")) .noneSatisfy((className) -> assertThat(className).contains("BigIntegerTo"))); } @Test void usesAutoConfigurationPackageToPickUpDocumentTypes() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); String cityPackage = City.class.getPackage().getName(); AutoConfigurationPackages.register(context, cityPackage); context.register(MongoAutoConfiguration.class, DataMongoAutoConfiguration.class); try { context.refresh(); assertDomainTypesDiscovered(context.getBean(MongoMappingContext.class), City.class); } finally { context.close(); } } @Test void defaultFieldNamingStrategy() { this.contextRunner.run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); FieldNamingStrategy fieldNamingStrategy = getFieldNamingStrategy(mappingContext); assertThat(fieldNamingStrategy.getClass()).isEqualTo(PropertyNameFieldNamingStrategy.class); }); } @Test void customFieldNamingStrategy() { this.contextRunner .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) .run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); FieldNamingStrategy fieldNamingStrategy = getFieldNamingStrategy(mappingContext); assertThat(fieldNamingStrategy.getClass()).isEqualTo(CamelCaseAbbreviatingFieldNamingStrategy.class); }); } @Test void defaultAutoIndexCreation() { this.contextRunner.run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); assertThat(mappingContext.isAutoIndexCreation()).isFalse(); }); } @Test void customAutoIndexCreation() { this.contextRunner.withPropertyValues("spring.data.mongodb.autoIndexCreation:true").run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); assertThat(mappingContext.isAutoIndexCreation()).isTrue(); }); } @Test void interfaceFieldNamingStrategy() { this.contextRunner .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + FieldNamingStrategy.class.getName()) .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test void entityScanShouldSetManagedTypes() { this.contextRunner.withUserConfiguration(EntityScanConfig.class).run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); ManagedTypes managedTypes = (ManagedTypes) ReflectionTestUtils.getField(mappingContext, "managedTypes"); assertThat(managedTypes).isNotNull(); assertThat(managedTypes.toList()).containsOnly(City.class, Country.class); }); } @Test void registersDefaultSimpleTypesWithMappingContext() { this.contextRunner.run((context) -> { MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(Sample.class); assertThat(entity).isNotNull(); MongoPersistentProperty dateProperty = entity.getPersistentProperty("date"); assertThat(dateProperty).isNotNull(); assertThat(dateProperty.isEntity()).isFalse(); }); } @Test void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataMongoAutoConfiguration.class)); runner.run((context) -> assertThat(context).doesNotHaveBean(MongoTemplate.class)); } @Test void createsMongoDatabaseFactoryForPreferredMongoClient() { this.contextRunner.run((context) -> { MongoDatabaseFactory dbFactory = context.getBean(MongoDatabaseFactory.class); assertThat(dbFactory).isInstanceOf(SimpleMongoClientDatabaseFactory.class); }); } @Test void createsMongoDatabaseFactoryForFallbackMongoClient() { this.contextRunner.withUserConfiguration(FallbackMongoClientConfiguration.class).run((context) -> { MongoDatabaseFactory dbFactory = context.getBean(MongoDatabaseFactory.class); assertThat(dbFactory).isInstanceOf(SimpleMongoClientDatabaseFactory.class); }); } @Test void autoConfiguresIfUserProvidesMongoDatabaseFactoryButNoClient() { this.contextRunner.withUserConfiguration(MongoDatabaseFactoryConfiguration.class) .run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); } @Test void databaseHasDefault() { this.contextRunner.run((context) -> { MongoDatabaseFactory factory = context.getBean(MongoDatabaseFactory.class); assertThat(factory).isInstanceOf(SimpleMongoClientDatabaseFactory.class); assertThat(factory.getMongoDatabase().getName()).isEqualTo("test"); }); } @Test void databasePropertyIsUsed() { this.contextRunner.withPropertyValues("spring.mongodb.database=mydb").run((context) -> { MongoDatabaseFactory factory = context.getBean(MongoDatabaseFactory.class); assertThat(factory).isInstanceOf(SimpleMongoClientDatabaseFactory.class); assertThat(factory.getMongoDatabase().getName()).isEqualTo("mydb"); }); } @Test void databaseInUriPropertyIsUsed() { this.contextRunner.withPropertyValues("spring.mongodb.uri=mongodb://mongo.example.com/mydb").run((context) -> { MongoDatabaseFactory factory = context.getBean(MongoDatabaseFactory.class); assertThat(factory).isInstanceOf(SimpleMongoClientDatabaseFactory.class); assertThat(factory.getMongoDatabase().getName()).isEqualTo("mydb"); }); } @Test void databasePropertyOverridesUriProperty() { this.contextRunner .withPropertyValues("spring.mongodb.uri=mongodb://mongo.example.com/notused", "spring.mongodb.database=mydb") .run((context) -> { MongoDatabaseFactory factory = context.getBean(MongoDatabaseFactory.class); assertThat(factory).isInstanceOf(SimpleMongoClientDatabaseFactory.class); assertThat(factory.getMongoDatabase().getName()).isEqualTo("mydb"); }); } @Test void databasePropertyIsUsedWhenNoDatabaseInUri() { this.contextRunner .withPropertyValues("spring.mongodb.uri=mongodb://mongo.example.com/", "spring.mongodb.database=mydb") .run((context) -> { MongoDatabaseFactory factory = context.getBean(MongoDatabaseFactory.class); assertThat(factory).isInstanceOf(SimpleMongoClientDatabaseFactory.class); assertThat(factory.getMongoDatabase().getName()).isEqualTo("mydb"); }); } @Test void contextFailsWhenDatabaseNotSet() { this.contextRunner.withPropertyValues("spring.mongodb.uri=mongodb://mongo.example.com/") .run((context) -> assertThat(context).getFailure().hasMessageContaining("Database name must not be empty")); } @Test void definesPropertiesBasedConnectionDetailsByDefault() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(PropertiesMongoConnectionDetails.class)); } @Test void shouldUseCustomConnectionDetailsWhenDefined() { this.contextRunner.withBean(MongoConnectionDetails.class, () -> new MongoConnectionDetails() { @Override public ConnectionString getConnectionString() { return new ConnectionString("mongodb://localhost/testdb"); } }) .run((context) -> assertThat(context).hasSingleBean(MongoConnectionDetails.class) .doesNotHaveBean(PropertiesMongoConnectionDetails.class)); } @Test void mappingMongoConverterHasADefaultDbRefResolver() { this.contextRunner.run((context) -> { MappingMongoConverter converter = context.getBean(MappingMongoConverter.class); assertThat(converter).extracting("dbRefResolver").isInstanceOf(DefaultDbRefResolver.class); }); } private static void assertDomainTypesDiscovered(MongoMappingContext mappingContext, Class<?>... types) { ManagedTypes managedTypes = (ManagedTypes) ReflectionTestUtils.getField(mappingContext, "managedTypes"); assertThat(managedTypes).isNotNull(); assertThat(managedTypes.toList()).containsOnly(types); } @SuppressWarnings("unchecked") private GridFSBucket getBucket(GridFsTemplate template) { Supplier<GridFSBucket> field = (Supplier<GridFSBucket>) ReflectionTestUtils.getField(template, "bucketSupplier"); assertThat(field).isNotNull(); return field.get(); } private FieldNamingStrategy getFieldNamingStrategy(MongoMappingContext mappingContext) { Object field = ReflectionTestUtils.getField(mappingContext, "fieldNamingStrategy"); assertThat(field).isNotNull(); return (FieldNamingStrategy) field; } @Configuration(proxyBeanMethods = false) static
DataMongoAutoConfigurationTests
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/ServerEndpointIndexer.java
{ "start": 13586, "end": 15604 }
class ____ clazz = null; if (actualEndpointClass.isInterface()) { for (var implementor : index.getAllKnownImplementors(actualEndpointClass.name())) { if (!implementor.isInterface() && !implementor.isAbstract()) { if (clazz == null) { clazz = implementor; // keep going to recognize if there is more than one non-abstract implementor } else { // resolution is not unambiguous, this at least make behavior deterministic clazz = actualEndpointClass; break; } } } } else { for (var subClass : index.getAllKnownSubclasses(actualEndpointClass.name())) { if (!subClass.isAbstract()) { if (clazz == null) { clazz = subClass; // keep going to recognize if there is more than one non-abstract subclass } else { // resolution is not unambiguous, this at least make behavior deterministic clazz = actualEndpointClass; break; } } } } if (clazz == null) { clazz = actualEndpointClass; } // 2. go up - first impl. going up is the one invoked on the endpoint instance Queue<MethodInfo> defaultInterfaceMethods = new ArrayDeque<>(); do { // is non-abstract method declared on this class? var method = clazz.method(methodInfo.name(), methodInfo.parameterTypes()); if (method != null && !Modifier.isAbstract(method.flags())) { return method; } var interfaceWithImplMethod = findInterfaceDefaultMethod(clazz, methodInfo, index); if (interfaceWithImplMethod != null) { //
ClassInfo
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslServerAuthenticatorTest.java
{ "start": 4209, "end": 23002 }
class ____ { private final String clientId = "clientId"; @Test public void testOversizeRequest() throws IOException { TransportLayer transportLayer = mock(TransportLayer.class); Map<String, ?> configs = Collections.singletonMap(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, Collections.singletonList(SCRAM_SHA_256.mechanismName())); SaslServerAuthenticator authenticator = setupAuthenticator(configs, transportLayer, SCRAM_SHA_256.mechanismName(), new DefaultChannelMetadataRegistry()); when(transportLayer.read(any(ByteBuffer.class))).then(invocation -> { invocation.<ByteBuffer>getArgument(0).putInt(BrokerSecurityConfigs.DEFAULT_SASL_SERVER_MAX_RECEIVE_SIZE + 1); return 4; }); assertThrows(SaslAuthenticationException.class, authenticator::authenticate); verify(transportLayer).read(any(ByteBuffer.class)); } @Test public void testUnexpectedRequestTypeWithValidRequestHeader() throws IOException { TransportLayer transportLayer = mock(TransportLayer.class); Map<String, ?> configs = Collections.singletonMap(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, Collections.singletonList(SCRAM_SHA_256.mechanismName())); SaslServerAuthenticator authenticator = setupAuthenticator(configs, transportLayer, SCRAM_SHA_256.mechanismName(), new DefaultChannelMetadataRegistry()); RequestHeader header = new RequestHeader(ApiKeys.METADATA, (short) 0, clientId, 13243); ByteBuffer headerBuffer = RequestTestUtils.serializeRequestHeader(header); when(transportLayer.read(any(ByteBuffer.class))).then(invocation -> { invocation.<ByteBuffer>getArgument(0).putInt(headerBuffer.remaining()); return 4; }).then(invocation -> { // serialize only the request header. the authenticator should not parse beyond this invocation.<ByteBuffer>getArgument(0).put(headerBuffer.duplicate()); return headerBuffer.remaining(); }); assertThrows(InvalidRequestException.class, authenticator::authenticate); verify(transportLayer, times(2)).read(any(ByteBuffer.class)); } @Test public void testInvalidRequestHeader() throws IOException { TransportLayer transportLayer = mock(TransportLayer.class); Map<String, ?> configs = Collections.singletonMap(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, Collections.singletonList(SCRAM_SHA_256.mechanismName())); SaslServerAuthenticator authenticator = setupAuthenticator(configs, transportLayer, SCRAM_SHA_256.mechanismName(), new DefaultChannelMetadataRegistry()); short invalidApiKeyId = (short) (Arrays.stream(ApiKeys.values()).mapToInt(k -> k.id).max().getAsInt() + 1); ByteBuffer headerBuffer = RequestTestUtils.serializeRequestHeader(new RequestHeader( new RequestHeaderData() .setRequestApiKey(invalidApiKeyId) .setRequestApiVersion((short) 0), (short) 2)); when(transportLayer.read(any(ByteBuffer.class))).then(invocation -> { invocation.<ByteBuffer>getArgument(0).putInt(headerBuffer.remaining()); return 4; }).then(invocation -> { // serialize only the request header. the authenticator should not parse beyond this invocation.<ByteBuffer>getArgument(0).put(headerBuffer.duplicate()); return headerBuffer.remaining(); }); assertThrows(InvalidRequestException.class, authenticator::authenticate); verify(transportLayer, times(2)).read(any(ByteBuffer.class)); } @Test public void testOldestApiVersionsRequest() throws IOException { testApiVersionsRequest(ApiKeys.API_VERSIONS.oldestVersion(), ClientInformation.UNKNOWN_NAME_OR_VERSION, ClientInformation.UNKNOWN_NAME_OR_VERSION); } @Test public void testLatestApiVersionsRequest() throws IOException { testApiVersionsRequest(ApiKeys.API_VERSIONS.latestVersion(), "apache-kafka-java", AppInfoParser.getVersion()); } @Test public void testSessionExpiresAtTokenExpiryDespiteNoReauthIsSet() throws IOException { String mechanism = OAuthBearerLoginModule.OAUTHBEARER_MECHANISM; Duration tokenExpirationDuration = Duration.ofSeconds(1); SaslServer saslServer = mock(SaslServer.class); MockTime time = new MockTime(); try ( MockedStatic<?> ignored = mockSaslServer(saslServer, mechanism, time, tokenExpirationDuration); MockedStatic<?> ignored2 = mockKafkaPrincipal("[principal-type]", "[principal-name"); TransportLayer transportLayer = mockTransportLayer() ) { SaslServerAuthenticator authenticator = getSaslServerAuthenticatorForOAuth(mechanism, transportLayer, time, 0L); mockRequest(saslHandshakeRequest(mechanism), transportLayer); authenticator.authenticate(); when(saslServer.isComplete()).thenReturn(false).thenReturn(true); mockRequest(saslAuthenticateRequest(), transportLayer); authenticator.authenticate(); long atTokenExpiryNanos = time.nanoseconds() + tokenExpirationDuration.toNanos(); assertEquals(atTokenExpiryNanos, authenticator.serverSessionExpirationTimeNanos()); ByteBuffer secondResponseSent = getResponses(transportLayer).get(1); consumeSizeAndHeader(secondResponseSent); SaslAuthenticateResponse response = SaslAuthenticateResponse.parse(new ByteBufferAccessor(secondResponseSent), (short) 2); assertEquals(tokenExpirationDuration.toMillis(), response.sessionLifetimeMs()); } } @Test public void testSessionExpiresAtMaxReauthTime() throws IOException { String mechanism = OAuthBearerLoginModule.OAUTHBEARER_MECHANISM; SaslServer saslServer = mock(SaslServer.class); MockTime time = new MockTime(0, 1, 1000); long maxReauthMs = 100L; Duration tokenExpiryGreaterThanMaxReauth = Duration.ofMillis(maxReauthMs).multipliedBy(10); try ( MockedStatic<?> ignored = mockSaslServer(saslServer, mechanism, time, tokenExpiryGreaterThanMaxReauth); MockedStatic<?> ignored2 = mockKafkaPrincipal("[principal-type]", "[principal-name"); TransportLayer transportLayer = mockTransportLayer() ) { SaslServerAuthenticator authenticator = getSaslServerAuthenticatorForOAuth(mechanism, transportLayer, time, maxReauthMs); mockRequest(saslHandshakeRequest(mechanism), transportLayer); authenticator.authenticate(); when(saslServer.isComplete()).thenReturn(false).thenReturn(true); mockRequest(saslAuthenticateRequest(), transportLayer); authenticator.authenticate(); long atMaxReauthNanos = time.nanoseconds() + Duration.ofMillis(maxReauthMs).toNanos(); assertEquals(atMaxReauthNanos, authenticator.serverSessionExpirationTimeNanos()); ByteBuffer secondResponseSent = getResponses(transportLayer).get(1); consumeSizeAndHeader(secondResponseSent); SaslAuthenticateResponse response = SaslAuthenticateResponse.parse(new ByteBufferAccessor(secondResponseSent), (short) 2); assertEquals(maxReauthMs, response.sessionLifetimeMs()); } } @Test public void testSessionExpiresAtTokenExpiry() throws IOException { String mechanism = OAuthBearerLoginModule.OAUTHBEARER_MECHANISM; SaslServer saslServer = mock(SaslServer.class); MockTime time = new MockTime(0, 1, 1000); Duration tokenExpiryShorterThanMaxReauth = Duration.ofSeconds(2); long maxReauthMs = tokenExpiryShorterThanMaxReauth.multipliedBy(2).toMillis(); try ( MockedStatic<?> ignored = mockSaslServer(saslServer, mechanism, time, tokenExpiryShorterThanMaxReauth); MockedStatic<?> ignored2 = mockKafkaPrincipal("[principal-type]", "[principal-name"); TransportLayer transportLayer = mockTransportLayer() ) { SaslServerAuthenticator authenticator = getSaslServerAuthenticatorForOAuth(mechanism, transportLayer, time, maxReauthMs); mockRequest(saslHandshakeRequest(mechanism), transportLayer); authenticator.authenticate(); when(saslServer.isComplete()).thenReturn(false).thenReturn(true); mockRequest(saslAuthenticateRequest(), transportLayer); authenticator.authenticate(); long atTokenExpiryNanos = time.nanoseconds() + tokenExpiryShorterThanMaxReauth.toNanos(); assertEquals(atTokenExpiryNanos, authenticator.serverSessionExpirationTimeNanos()); ByteBuffer secondResponseSent = getResponses(transportLayer).get(1); consumeSizeAndHeader(secondResponseSent); SaslAuthenticateResponse response = SaslAuthenticateResponse.parse(new ByteBufferAccessor(secondResponseSent), (short) 2); assertEquals(tokenExpiryShorterThanMaxReauth.toMillis(), response.sessionLifetimeMs()); } } @Test public void testSessionWontExpireWithLargeExpirationTime() throws IOException { String mechanism = OAuthBearerLoginModule.OAUTHBEARER_MECHANISM; SaslServer saslServer = mock(SaslServer.class); MockTime time = new MockTime(0, 1, 1000); // set a Long.MAX_VALUE as the expiration time Duration largeExpirationTime = Duration.ofMillis(Long.MAX_VALUE); try ( MockedStatic<?> ignored = mockSaslServer(saslServer, mechanism, time, largeExpirationTime); MockedStatic<?> ignored2 = mockKafkaPrincipal("[principal-type]", "[principal-name"); TransportLayer transportLayer = mockTransportLayer() ) { SaslServerAuthenticator authenticator = getSaslServerAuthenticatorForOAuth(mechanism, transportLayer, time, largeExpirationTime.toMillis()); mockRequest(saslHandshakeRequest(mechanism), transportLayer); authenticator.authenticate(); when(saslServer.isComplete()).thenReturn(false).thenReturn(true); mockRequest(saslAuthenticateRequest(), transportLayer); Throwable t = assertThrows(IllegalArgumentException.class, authenticator::authenticate); assertEquals(ArithmeticException.class, t.getCause().getClass()); assertEquals("Cannot convert " + Long.MAX_VALUE + " millisecond to nanosecond due to arithmetic overflow", t.getMessage()); } } private SaslServerAuthenticator getSaslServerAuthenticatorForOAuth(String mechanism, TransportLayer transportLayer, Time time, Long maxReauth) { Map<String, ?> configs = Collections.singletonMap(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, Collections.singletonList(mechanism)); ChannelMetadataRegistry metadataRegistry = new DefaultChannelMetadataRegistry(); return setupAuthenticator(configs, transportLayer, mechanism, metadataRegistry, time, maxReauth); } private MockedStatic<?> mockSaslServer(SaslServer saslServer, String mechanism, Time time, Duration tokenExpirationDuration) throws SaslException { when(saslServer.getMechanismName()).thenReturn(mechanism); when(saslServer.evaluateResponse(any())).thenReturn(new byte[]{}); long millisToExpiration = tokenExpirationDuration.toMillis(); when(saslServer.getNegotiatedProperty(eq(SaslInternalConfigs.CREDENTIAL_LIFETIME_MS_SASL_NEGOTIATED_PROPERTY_KEY))) .thenReturn(time.milliseconds() + millisToExpiration); return Mockito.mockStatic(Sasl.class, (Answer<SaslServer>) invocation -> saslServer); } private MockedStatic<?> mockKafkaPrincipal(String principalType, String name) { KafkaPrincipalBuilder kafkaPrincipalBuilder = mock(KafkaPrincipalBuilder.class); when(kafkaPrincipalBuilder.build(any())).thenReturn(new KafkaPrincipal(principalType, name)); MockedStatic<ChannelBuilders> channelBuilders = Mockito.mockStatic(ChannelBuilders.class, Answers.RETURNS_MOCKS); channelBuilders.when(() -> ChannelBuilders.createPrincipalBuilder(anyMap(), any(KerberosShortNamer.class), any(SslPrincipalMapper.class)) ).thenReturn(kafkaPrincipalBuilder); return channelBuilders; } private void consumeSizeAndHeader(ByteBuffer responseBuffer) { responseBuffer.getInt(); ResponseHeader.parse(responseBuffer, (short) 1); } private List<ByteBuffer> getResponses(TransportLayer transportLayer) throws IOException { ArgumentCaptor<ByteBuffer[]> buffersCaptor = ArgumentCaptor.forClass(ByteBuffer[].class); verify(transportLayer, times(2)).write(buffersCaptor.capture()); return buffersCaptor.getAllValues().stream() .map(this::concatBuffers) .collect(Collectors.toList()); } private ByteBuffer concatBuffers(ByteBuffer[] buffers) { int combinedCapacity = 0; for (ByteBuffer buffer : buffers) { combinedCapacity += buffer.capacity(); } if (combinedCapacity > 0) { ByteBuffer concat = ByteBuffer.allocate(combinedCapacity); for (ByteBuffer buffer : buffers) { concat.put(buffer); } return safeFlip(concat); } else { return ByteBuffer.allocate(0); } } private ByteBuffer safeFlip(ByteBuffer buffer) { return (ByteBuffer) ((Buffer) buffer).flip(); } private SaslAuthenticateRequest saslAuthenticateRequest() { SaslAuthenticateRequestData authenticateRequestData = new SaslAuthenticateRequestData(); return new SaslAuthenticateRequest.Builder(authenticateRequestData).build(ApiKeys.SASL_AUTHENTICATE.latestVersion()); } private SaslHandshakeRequest saslHandshakeRequest(String mechanism) { SaslHandshakeRequestData handshakeRequestData = new SaslHandshakeRequestData(); handshakeRequestData.setMechanism(mechanism); return new SaslHandshakeRequest.Builder(handshakeRequestData).build(ApiKeys.SASL_HANDSHAKE.latestVersion()); } private TransportLayer mockTransportLayer() throws IOException { TransportLayer transportLayer = mock(TransportLayer.class, Answers.RETURNS_DEEP_STUBS); when(transportLayer.socketChannel().socket().getInetAddress()).thenReturn(InetAddress.getLoopbackAddress()); when(transportLayer.write(any(ByteBuffer[].class))).thenReturn(Long.MAX_VALUE); return transportLayer; } private void mockRequest(AbstractRequest request, TransportLayer transportLayer) throws IOException { mockRequest(new RequestHeader(request.apiKey(), request.apiKey().latestVersion(), clientId, 0), request, transportLayer); } private void mockRequest(RequestHeader header, AbstractRequest request, TransportLayer transportLayer) throws IOException { ByteBuffer headerBuffer = RequestTestUtils.serializeRequestHeader(header); ByteBuffer requestBuffer = request.serialize().buffer(); requestBuffer.rewind(); when(transportLayer.read(any(ByteBuffer.class))).then(invocation -> { invocation.<ByteBuffer>getArgument(0).putInt(headerBuffer.remaining() + requestBuffer.remaining()); return 4; }).then(invocation -> { invocation.<ByteBuffer>getArgument(0) .put(headerBuffer.duplicate()) .put(requestBuffer.duplicate()); return headerBuffer.remaining() + requestBuffer.remaining(); }); } private void testApiVersionsRequest(short version, String expectedSoftwareName, String expectedSoftwareVersion) throws IOException { TransportLayer transportLayer = mockTransportLayer(); Map<String, ?> configs = Collections.singletonMap(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, Collections.singletonList(SCRAM_SHA_256.mechanismName())); ChannelMetadataRegistry metadataRegistry = new DefaultChannelMetadataRegistry(); SaslServerAuthenticator authenticator = setupAuthenticator(configs, transportLayer, SCRAM_SHA_256.mechanismName(), metadataRegistry); RequestHeader header = new RequestHeader(ApiKeys.API_VERSIONS, version, clientId, 0); ApiVersionsRequest request = new ApiVersionsRequest.Builder().build(version); mockRequest(header, request, transportLayer); authenticator.authenticate(); assertEquals(expectedSoftwareName, metadataRegistry.clientInformation().softwareName()); assertEquals(expectedSoftwareVersion, metadataRegistry.clientInformation().softwareVersion()); verify(transportLayer, times(2)).read(any(ByteBuffer.class)); } private SaslServerAuthenticator setupAuthenticator(Map<String, ?> configs, TransportLayer transportLayer, String mechanism, ChannelMetadataRegistry metadataRegistry) { return setupAuthenticator(configs, transportLayer, mechanism, metadataRegistry, new MockTime(), null); } private SaslServerAuthenticator setupAuthenticator(Map<String, ?> configs, TransportLayer transportLayer, String mechanism, ChannelMetadataRegistry metadataRegistry, Time time, Long maxReauth) { TestJaasConfig jaasConfig = new TestJaasConfig(); jaasConfig.addEntry("jaasContext", PlainLoginModule.class.getName(), new HashMap<>()); Map<String, Subject> subjects = Collections.singletonMap(mechanism, new Subject()); Map<String, AuthenticateCallbackHandler> callbackHandlers = Collections.singletonMap( mechanism, new SaslServerCallbackHandler()); ApiVersionsResponse apiVersionsResponse = TestUtils.defaultApiVersionsResponse( ApiMessageType.ListenerType.BROKER); Map<String, Long> connectionsMaxReauthMsByMechanism = maxReauth != null ? Collections.singletonMap(mechanism, maxReauth) : Collections.emptyMap(); return new SaslServerAuthenticator(configs, callbackHandlers, "node", subjects, null, new ListenerName("ssl"), SecurityProtocol.SASL_SSL, transportLayer, connectionsMaxReauthMsByMechanism, metadataRegistry, time, version -> apiVersionsResponse); } }
SaslServerAuthenticatorTest
java
apache__flink
flink-tests/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorEventSendingCheckpointITCase.java
{ "start": 17647, "end": 19149 }
class ____ extends MiniCluster { private boolean localRpcCreated; public MiniClusterWithRpcIntercepting( final int numSlots, final Configuration configuration) { super( new MiniClusterConfiguration.Builder() .withRandomPorts() .setRpcServiceSharing(RpcServiceSharing.SHARED) .setNumTaskManagers(1) .setConfiguration(configuration) .setNumSlotsPerTaskManager(numSlots) .build()); } @Override public void start() throws Exception { super.start(); if (!localRpcCreated) { throw new Exception( "MiniClusterWithRpcIntercepting is broken, the intercepting local RPC service was not created."); } } @Override protected RpcService createLocalRpcService(Configuration configuration, RpcSystem rpcSystem) throws Exception { localRpcCreated = true; return new InterceptingRpcService( rpcSystem .localServiceBuilder(configuration) .withExecutorConfiguration( RpcUtils.getTestForkJoinExecutorConfiguration()) .createAndStart()); } } }
MiniClusterWithRpcIntercepting
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/ast/ClassElement.java
{ "start": 15616, "end": 17318 }
class ____ an interface. * * @return The methods * @since 4.0.0 */ @NonNull default List<MethodElement> getMethods() { return getEnclosedElements(ElementQuery.ALL_METHODS); } /** * Find a method with a name. * * @param name The method name * @return The method * @since 4.0.0 */ @NonNull @Experimental default Optional<MethodElement> findMethod(String name) { return getEnclosedElement(ElementQuery.ALL_METHODS.named(name)); } /** * Return the elements that match the given query. * * @param query The query to use. * @param <T> The element type * @return The fields * @since 2.3.0 */ @NonNull default <T extends Element> List<T> getEnclosedElements(@NonNull ElementQuery<T> query) { return Collections.emptyList(); } /** * Returns the enclosing type if {@link #isInner()} return {@code true}. * * @return The enclosing type if any * @since 3.0.0 */ default Optional<ClassElement> getEnclosingType() { return Optional.empty(); } /** * Return the first enclosed element matching the given query. * * @param query The query to use. * @param <T> The element type * @return The fields * @since 2.3.0 */ default <T extends Element> Optional<T> getEnclosedElement(@NonNull ElementQuery<T> query) { List<T> enclosedElements = getEnclosedElements(query); if (!enclosedElements.isEmpty()) { return Optional.of(enclosedElements.iterator().next()); } return Optional.empty(); } /** * @return Whether the
or
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java
{ "start": 17657, "end": 18023 }
class ____ extends StringParam { /** * Parameter name. */ public static final String NAME = HttpFSFileSystem.SNAPSHOT_DIFF_START_PATH; /** * Constructor. */ public SnapshotDiffStartPathParam() { super(NAME, ""); } } /** * Class for SnapshotDiffStartPath parameter. */ public static
SnapshotDiffStartPathParam
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/XAttrSetFlag.java
{ "start": 1131, "end": 2169 }
enum ____ { /** * Create a new xattr. * If the xattr exists already, exception will be thrown. */ CREATE((short) 0x01), /** * Replace a existing xattr. * If the xattr does not exist, exception will be thrown. */ REPLACE((short) 0x02); private final short flag; private XAttrSetFlag(short flag) { this.flag = flag; } short getFlag() { return flag; } public static void validate(String xAttrName, boolean xAttrExists, EnumSet<XAttrSetFlag> flag) throws IOException { if (flag == null || flag.isEmpty()) { throw new HadoopIllegalArgumentException("A flag must be specified."); } if (xAttrExists) { if (!flag.contains(REPLACE)) { throw new IOException("XAttr: " + xAttrName + " already exists. The REPLACE flag must be specified."); } } else { if (!flag.contains(CREATE)) { throw new IOException("XAttr: " + xAttrName + " does not exist. The CREATE flag must be specified."); } } } }
XAttrSetFlag
java
apache__camel
core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java
{ "start": 12290, "end": 15908 }
class ____ implements CamelContextAware { private final StringWriter buffer; private CamelContext camelContext; public BeanModelWriter(StringWriter buffer) { this.buffer = buffer; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } public void start() { // noop } public void stop() { // noop } public void writeBeans(List<BeanFactoryDefinition<?>> beans) { if (beans.isEmpty()) { return; } buffer.write("- beans:\n"); for (BeanFactoryDefinition<?> b : beans) { doWriteBeanFactoryDefinition(b); } } private void doWriteBeanFactoryDefinition(BeanFactoryDefinition<?> b) { String type = b.getType(); if (type.startsWith("#class:")) { type = type.substring(7); } buffer.write(String.format(" - name: %s%n", b.getName())); buffer.write(String.format(" type: \"%s\"%n", type)); if (b.getFactoryBean() != null) { buffer.write(String.format(" factoryBean: \"%s\"%n", b.getFactoryBean())); } if (b.getFactoryMethod() != null) { buffer.write(String.format(" factoryMethod: \"%s\"%n", b.getFactoryMethod())); } if (b.getBuilderClass() != null) { buffer.write(String.format(" builderClass: \"%s\"%n", b.getBuilderClass())); } if (b.getBuilderMethod() != null) { buffer.write(String.format(" builderMethod: \"%s\"%n", b.getBuilderMethod())); } if (b.getInitMethod() != null) { buffer.write(String.format(" initMethod: \"%s\"%n", b.getInitMethod())); } if (b.getDestroyMethod() != null) { buffer.write(String.format(" destroyMethod: \"%s\"%n", b.getDestroyMethod())); } if (b.getScriptLanguage() != null) { buffer.write(String.format(" scriptLanguage: \"%s\"%n", b.getScriptLanguage())); } if (b.getScript() != null) { buffer.write(String.format(" script: \"%s\"%n", b.getScript())); } if (b.getConstructors() != null && !b.getConstructors().isEmpty()) { buffer.write(String.format(" constructors:%n")); final AtomicInteger counter = new AtomicInteger(); b.getConstructors().forEach((key, value) -> { if (key == null) { key = counter.getAndIncrement(); } buffer.write(String.format(" %d: \"%s\"%n", key, value)); }); } if (b.getProperties() != null && !b.getProperties().isEmpty()) { buffer.write(String.format(" properties:%n")); b.getProperties().forEach((key, value) -> { if (value instanceof String) { buffer.write(String.format(" %s: \"%s\"%n", key, value)); } else { buffer.write(String.format(" %s: %s%n", key, value)); } }); } } } private static
BeanModelWriter
java
micronaut-projects__micronaut-core
websocket/src/main/java/io/micronaut/websocket/annotation/OnMessage.java
{ "start": 1286, "end": 1452 }
interface ____ { /** * The maximum size of a WebSocket payload. * * @return The max size */ int maxPayloadLength() default 65536; }
OnMessage
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/testutils/TestingClusterEntrypointProcess.java
{ "start": 1954, "end": 2749 }
class ____ extends TestJvmProcess { private final File markerFile; public TestingClusterEntrypointProcess(File markerFile) throws Exception { this.markerFile = checkNotNull(markerFile, "marker file"); } @Override public String getName() { return getClass().getCanonicalName(); } @Override public String[] getMainMethodArgs() { return new String[] {markerFile.getAbsolutePath()}; } @Override public String getEntryPointClassName() { return TestingClusterEntrypointProcessEntryPoint.class.getName(); } @Override public String toString() { return getClass().getCanonicalName(); } /** Entrypoint for the testing cluster entrypoint process. */ public static
TestingClusterEntrypointProcess
java
spring-projects__spring-boot
module/spring-boot-web-server/src/test/java/org/springframework/boot/web/server/servlet/context/ServletWebServerApplicationContextTests.java
{ "start": 26193, "end": 26365 }
class ____ extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { } } static
OrderedFilter
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/binding/BindingGraph.java
{ "start": 16993, "end": 21428 }
interface ____ { * ChildComponent childComponent(ChildModule1 childModule); * } * </code></pre> */ // TODO(b/73294201): Consider returning the resolved ExecutableType for the factory method. public final Optional<XMethodElement> factoryMethod() { return topLevelBindingGraph().network().inEdges(componentNode()).stream() .filter(edge -> edge instanceof ChildFactoryMethodEdge) .map(edge -> ((ChildFactoryMethodEdge) edge).factoryMethod().xprocessing()) // Factory methods are represented by XMethodElement (rather than XConstructorElement) // TODO(bcorso): consider adding DaggerMethodElement so this cast isn't needed. .map(XMethodElement.class::cast) .collect(toOptional()); } /** * Returns a map between the {@linkplain ComponentRequirement component requirement} and the * corresponding {@link XExecutableParameterElement} for each module parameter in the {@linkplain * BindingGraph#factoryMethod factory method}. */ // TODO(dpb): Consider disallowing modules if none of their bindings are used. public final ImmutableMap<ComponentRequirement, XExecutableParameterElement> factoryMethodParameters() { return factoryMethod().get().getParameters().stream() .collect( toImmutableMap( parameter -> ComponentRequirement.forModule(parameter.getType()), parameter -> parameter)); } /** * The types for which the component needs instances. * * <ul> * <li>component dependencies * <li>owned modules with concrete instance bindings that are used in the graph * <li>bound instances * </ul> */ @Memoized public ImmutableSet<ComponentRequirement> componentRequirements() { ImmutableSet<XTypeElement> requiredModules = stream(Traverser.forTree(BindingGraph::subgraphs).depthFirstPostOrder(this)) .flatMap(graph -> graph.bindingModules.stream()) .filter(ownedModules::contains) .collect(toImmutableSet()); ImmutableSet.Builder<ComponentRequirement> requirements = ImmutableSet.builder(); componentDescriptor().requirements().stream() .filter( requirement -> !requirement.kind().isModule() || requiredModules.contains(requirement.typeElement())) .forEach(requirements::add); if (factoryMethod().isPresent()) { requirements.addAll(factoryMethodParameters().keySet()); } return requirements.build(); } /** * Returns all {@link ComponentDescriptor}s in the {@link TopLevelBindingGraph} mapped by the * component path. */ @Memoized public ImmutableMap<ComponentPath, ComponentDescriptor> componentDescriptorsByPath() { return topLevelBindingGraph().componentNodes().stream() .map(ComponentNodeImpl.class::cast) .collect( toImmutableMap(ComponentNode::componentPath, ComponentNodeImpl::componentDescriptor)); } @Memoized public ImmutableList<BindingGraph> subgraphs() { return topLevelBindingGraph().subcomponentNodes(componentNode()).stream() .map(subcomponent -> create(Optional.of(this), subcomponent, topLevelBindingGraph())) .collect(toImmutableList()); } /** Returns the list of all {@link BindingNode}s local to this component. */ public ImmutableList<BindingNode> localBindingNodes() { return topLevelBindingGraph().bindingsByComponent().get(componentPath()); } // TODO(bcorso): This method can be costly. Consider removing this method and inlining it into its // only usage, BindingGraphJsonGenerator. public ImmutableSet<BindingNode> bindingNodes() { // Construct the set of bindings by iterating bindings from this component and then from each // successive parent. If a binding exists in multiple components, this order ensures that the // child-most binding is always chosen first. Map<Key, BindingNode> bindings = new LinkedHashMap<>(); Stream.iterate(componentPath(), ComponentPath::parent) // Stream.iterate() is infinite stream so we need limit it to the known size of the path. .limit(componentPath().components().size()) .flatMap(path -> topLevelBindingGraph().bindingsByComponent().get(path).stream()) .forEach(bindingNode -> bindings.putIfAbsent(bindingNode.key(), bindingNode)); return ImmutableSet.copyOf(bindings.values()); } }
ParentComponent
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java
{ "start": 6224, "end": 6653 }
class ____ { @Bean public MBeanServerFactoryBean server() { return new MBeanServerFactoryBean(); } @Bean @Lazy public AnnotationTestBean testBean() { AnnotationTestBean bean = new AnnotationTestBean(); bean.setName("TEST"); bean.setAge(100); return bean; } } @Configuration @EnableMBeanExport(server="server", registration=RegistrationPolicy.REPLACE_EXISTING) static
PlaceholderBasedConfiguration
java
quarkusio__quarkus
integration-tests/kafka-json-schema-apicurio2/src/main/java/io/quarkus/it/kafka/jsonschema/Pet.java
{ "start": 758, "end": 1221 }
class ____ { private String name; private String color; public Pet() { } public Pet(String name, String color) { this.name = name; this.color = color; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
Pet
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsMissingNullableTest.java
{ "start": 5045, "end": 5365 }
class ____ { @NullUnmarked public abstract boolean equals(Object o); } """) .doTest(); } @Test public void negativeConservativeNotNullMarked() { conservativeHelper .addSourceLines( "Foo.java", """ abstract
Foo
java
resilience4j__resilience4j
resilience4j-framework-common/src/test/java/io/github/resilience4j/common/bulkhead/configuration/BulkheadConfigurationPropertiesTest.java
{ "start": 1150, "end": 17278 }
class ____ { @Test public void testBulkHeadProperties() { //Given CommonBulkheadConfigurationProperties.InstanceProperties instanceProperties1 = new CommonBulkheadConfigurationProperties.InstanceProperties(); instanceProperties1.setMaxConcurrentCalls(3); instanceProperties1.setWritableStackTraceEnabled(true); assertThat(instanceProperties1.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties.InstanceProperties instanceProperties2 = new CommonBulkheadConfigurationProperties.InstanceProperties(); instanceProperties2.setMaxConcurrentCalls(2); instanceProperties2.setWritableStackTraceEnabled(false); assertThat(instanceProperties2.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties bulkheadConfigurationProperties = new CommonBulkheadConfigurationProperties(); bulkheadConfigurationProperties.getInstances().put("backend1", instanceProperties1); bulkheadConfigurationProperties.getInstances().put("backend2", instanceProperties2); Map<String, String> globalTags = new HashMap<>(); globalTags.put("testKey1", "testKet2"); bulkheadConfigurationProperties.setTags(globalTags); //Then assertThat(bulkheadConfigurationProperties.getInstances()).hasSize(2); assertThat(bulkheadConfigurationProperties.getTags()).isNotEmpty(); BulkheadConfig bulkhead1 = bulkheadConfigurationProperties .createBulkheadConfig(instanceProperties1, compositeBulkheadCustomizer(), "backend1"); assertThat(bulkhead1).isNotNull(); assertThat(bulkhead1.getMaxConcurrentCalls()).isEqualTo(3); assertThat(bulkhead1.isWritableStackTraceEnabled()).isTrue(); BulkheadConfig bulkhead2 = bulkheadConfigurationProperties .createBulkheadConfig(instanceProperties2, compositeBulkheadCustomizer(), "backend2"); assertThat(bulkhead2).isNotNull(); assertThat(bulkhead2.getMaxConcurrentCalls()).isEqualTo(2); assertThat(bulkhead2.isWritableStackTraceEnabled()).isFalse(); } @Test public void testCreateBulkHeadPropertiesWithSharedConfigs() { //Given CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); defaultProperties.setMaxConcurrentCalls(3); defaultProperties.setMaxWaitDuration(Duration.ofMillis(50)); defaultProperties.setWritableStackTraceEnabled(true); assertThat(defaultProperties.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties.InstanceProperties sharedProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); sharedProperties.setMaxConcurrentCalls(2); sharedProperties.setMaxWaitDuration(Duration.ofMillis(100L)); sharedProperties.setWritableStackTraceEnabled(false); assertThat(sharedProperties.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties.InstanceProperties backendWithDefaultConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); backendWithDefaultConfig.setBaseConfig("defaultConfig"); backendWithDefaultConfig.setMaxWaitDuration(Duration.ofMillis(200L)); backendWithDefaultConfig.setWritableStackTraceEnabled(true); assertThat(backendWithDefaultConfig.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties.InstanceProperties backendWithSharedConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); backendWithSharedConfig.setBaseConfig("sharedConfig"); backendWithSharedConfig.setMaxWaitDuration(Duration.ofMillis(300L)); backendWithSharedConfig.setWritableStackTraceEnabled(false); assertThat(backendWithSharedConfig.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties bulkheadConfigurationProperties = new CommonBulkheadConfigurationProperties(); bulkheadConfigurationProperties.getConfigs().put("defaultConfig", defaultProperties); bulkheadConfigurationProperties.getConfigs().put("sharedConfig", sharedProperties); bulkheadConfigurationProperties.getInstances() .put("backendWithDefaultConfig", backendWithDefaultConfig); bulkheadConfigurationProperties.getInstances() .put("backendWithSharedConfig", backendWithSharedConfig); //Then assertThat(bulkheadConfigurationProperties.getInstances()).hasSize(2); // Should get default config and overwrite max calls and wait time BulkheadConfig bulkhead1 = bulkheadConfigurationProperties .createBulkheadConfig(backendWithDefaultConfig, compositeBulkheadCustomizer(), "backendWithDefaultConfig"); assertThat(bulkhead1).isNotNull(); assertThat(bulkhead1.getMaxConcurrentCalls()).isEqualTo(3); assertThat(bulkhead1.getMaxWaitDuration().toMillis()).isEqualTo(200L); assertThat(bulkhead1.isWritableStackTraceEnabled()).isTrue(); // Should get shared config and overwrite wait time BulkheadConfig bulkhead2 = bulkheadConfigurationProperties .createBulkheadConfig(backendWithSharedConfig, compositeBulkheadCustomizer(), "backendWithSharedConfig"); assertThat(bulkhead2).isNotNull(); assertThat(bulkhead2.getMaxConcurrentCalls()).isEqualTo(2); assertThat(bulkhead2.getMaxWaitDuration().toMillis()).isEqualTo(300L); assertThat(bulkhead2.isWritableStackTraceEnabled()).isFalse(); // Unknown backend should get default config of Registry BulkheadConfig bulkhead3 = bulkheadConfigurationProperties .createBulkheadConfig(new CommonBulkheadConfigurationProperties.InstanceProperties(), compositeBulkheadCustomizer(), "unknown"); assertThat(bulkhead3).isNotNull(); assertThat(bulkhead3.getMaxWaitDuration().toMillis()).isEqualTo(0L); assertThat(bulkhead3.isWritableStackTraceEnabled()).isTrue(); } @Test public void testCreateBulkHeadPropertiesWithDefaultConfig() { //Given CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); defaultProperties.setMaxConcurrentCalls(3); defaultProperties.setMaxWaitDuration(Duration.ofMillis(50)); defaultProperties.setWritableStackTraceEnabled(true); assertThat(defaultProperties.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties.InstanceProperties sharedProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); sharedProperties.setMaxConcurrentCalls(2); sharedProperties.setMaxWaitDuration(Duration.ofMillis(100L)); sharedProperties.setWritableStackTraceEnabled(false); assertThat(sharedProperties.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties.InstanceProperties backendWithoutBaseConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); backendWithoutBaseConfig.setMaxWaitDuration(Duration.ofMillis(200L)); backendWithoutBaseConfig.setWritableStackTraceEnabled(true); assertThat(backendWithoutBaseConfig.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties.InstanceProperties backendWithSharedConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); backendWithSharedConfig.setBaseConfig("sharedConfig"); backendWithSharedConfig.setMaxWaitDuration(Duration.ofMillis(300L)); backendWithSharedConfig.setWritableStackTraceEnabled(false); assertThat(backendWithSharedConfig.getEventConsumerBufferSize()).isNull(); CommonBulkheadConfigurationProperties bulkheadConfigurationProperties = new CommonBulkheadConfigurationProperties(); bulkheadConfigurationProperties.getConfigs().put("default", defaultProperties); bulkheadConfigurationProperties.getConfigs().put("sharedConfig", sharedProperties); bulkheadConfigurationProperties.getInstances() .put("backendWithoutBaseConfig", backendWithoutBaseConfig); bulkheadConfigurationProperties.getInstances() .put("backendWithSharedConfig", backendWithSharedConfig); //Then assertThat(bulkheadConfigurationProperties.getInstances()).hasSize(2); // Should get default config and overwrite max calls and wait time BulkheadConfig bulkhead1 = bulkheadConfigurationProperties .createBulkheadConfig(backendWithoutBaseConfig, compositeBulkheadCustomizer(), "backendWithoutBaseConfig"); assertThat(bulkhead1).isNotNull(); assertThat(bulkhead1.getMaxConcurrentCalls()).isEqualTo(3); assertThat(bulkhead1.getMaxWaitDuration().toMillis()).isEqualTo(200L); assertThat(bulkhead1.isWritableStackTraceEnabled()).isTrue(); // Should get shared config and overwrite wait time BulkheadConfig bulkhead2 = bulkheadConfigurationProperties .createBulkheadConfig(backendWithSharedConfig, compositeBulkheadCustomizer(), "backendWithSharedConfig"); assertThat(bulkhead2).isNotNull(); assertThat(bulkhead2.getMaxConcurrentCalls()).isEqualTo(2); assertThat(bulkhead2.getMaxWaitDuration().toMillis()).isEqualTo(300L); assertThat(bulkhead2.isWritableStackTraceEnabled()).isFalse(); // Unknown backend should get default config of Registry BulkheadConfig bulkhead3 = bulkheadConfigurationProperties .createBulkheadConfig(new CommonBulkheadConfigurationProperties.InstanceProperties(), compositeBulkheadCustomizer(), "unknown"); assertThat(bulkhead3).isNotNull(); assertThat(bulkhead3.getMaxWaitDuration().toMillis()).isEqualTo(50L); assertThat(bulkhead3.isWritableStackTraceEnabled()).isTrue(); } @Test public void testCreateBulkHeadPropertiesWithUnknownConfig() { CommonBulkheadConfigurationProperties bulkheadConfigurationProperties = new CommonBulkheadConfigurationProperties(); CommonBulkheadConfigurationProperties.InstanceProperties instanceProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); instanceProperties.setBaseConfig("unknownConfig"); bulkheadConfigurationProperties.getInstances().put("backend", instanceProperties); //When assertThatThrownBy( () -> bulkheadConfigurationProperties.createBulkheadConfig(instanceProperties, compositeBulkheadCustomizer(), "unknownConfig")) .isInstanceOf(ConfigurationNotFoundException.class) .hasMessage("Configuration with name 'unknownConfig' does not exist"); } @Test(expected = IllegalArgumentException.class) public void testIllegalArgumentOnMaxConcurrentCallsLessThanOne() { CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); defaultProperties.setMaxConcurrentCalls(0); } @Test(expected = IllegalArgumentException.class) public void testIllegalArgumentOnMaxWaitDurationNegative() { CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); defaultProperties.setMaxWaitDuration(Duration.ofNanos(-1)); } @Test(expected = IllegalArgumentException.class) public void testBulkheadIllegalArgumentOnEventConsumerBufferSizeLessThanOne() { CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); defaultProperties.setEventConsumerBufferSize(0); } @Test public void testBulkheadConfigWithBaseConfig() { CommonBulkheadConfigurationProperties.InstanceProperties defaultConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); defaultConfig.setMaxConcurrentCalls(2000); defaultConfig.setMaxWaitDuration(Duration.ofMillis(100L)); CommonBulkheadConfigurationProperties.InstanceProperties sharedConfigWithDefaultConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); sharedConfigWithDefaultConfig.setMaxWaitDuration(Duration.ofMillis(1000L)); sharedConfigWithDefaultConfig.setBaseConfig("defaultConfig"); CommonBulkheadConfigurationProperties.InstanceProperties instanceWithSharedConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); instanceWithSharedConfig.setBaseConfig("sharedConfig"); CommonBulkheadConfigurationProperties bulkheadConfigurationProperties = new CommonBulkheadConfigurationProperties(); bulkheadConfigurationProperties.getConfigs().put("defaultConfig", defaultConfig); bulkheadConfigurationProperties.getConfigs().put("sharedConfig", sharedConfigWithDefaultConfig); bulkheadConfigurationProperties.getInstances().put("instanceWithSharedConfig", instanceWithSharedConfig); BulkheadConfig instance = bulkheadConfigurationProperties .createBulkheadConfig(instanceWithSharedConfig, compositeBulkheadCustomizer(), "instanceWithSharedConfig"); assertThat(instance).isNotNull(); assertThat(instance.getMaxConcurrentCalls()).isEqualTo(2000); assertThat(instance.getMaxWaitDuration()).isEqualTo(Duration.ofMillis(1000L)); } @Test public void testGetBackendPropertiesPropertiesWithoutDefaultConfig() { //Given CommonBulkheadConfigurationProperties.InstanceProperties backendWithoutBaseConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); CommonBulkheadConfigurationProperties bulkheadConfigurationProperties = new CommonBulkheadConfigurationProperties(); bulkheadConfigurationProperties.getInstances().put("backendWithoutBaseConfig", backendWithoutBaseConfig); //Then assertThat(bulkheadConfigurationProperties.getInstances()).hasSize(1); // Should get defaults CommonBulkheadConfigurationProperties.InstanceProperties bulkheadProperties = bulkheadConfigurationProperties.getBackendProperties("backendWithoutBaseConfig"); assertThat(bulkheadProperties).isNotNull(); assertThat(bulkheadProperties.getEventConsumerBufferSize()).isNull(); } @Test public void testGetBackendPropertiesPropertiesWithDefaultConfig() { //Given CommonBulkheadConfigurationProperties.InstanceProperties defaultProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); defaultProperties.setEventConsumerBufferSize(99); CommonBulkheadConfigurationProperties.InstanceProperties backendWithoutBaseConfig = new CommonBulkheadConfigurationProperties.InstanceProperties(); CommonBulkheadConfigurationProperties bulkheadConfigurationProperties = new CommonBulkheadConfigurationProperties(); bulkheadConfigurationProperties.getConfigs().put("default", defaultProperties); bulkheadConfigurationProperties.getInstances().put("backendWithoutBaseConfig", backendWithoutBaseConfig); //Then assertThat(bulkheadConfigurationProperties.getInstances()).hasSize(1); // Should get default config and overwrite enableExponentialBackoff but not enableRandomizedWait CommonBulkheadConfigurationProperties.InstanceProperties bulkheadProperties = bulkheadConfigurationProperties.getBackendProperties("backendWithoutBaseConfig"); assertThat(bulkheadProperties).isNotNull(); assertThat(bulkheadProperties.getEventConsumerBufferSize()).isEqualTo(99); } private CompositeCustomizer<BulkheadConfigCustomizer> compositeBulkheadCustomizer() { return new CompositeCustomizer<>(Collections.emptyList()); } }
BulkheadConfigurationPropertiesTest
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/AbstractHerderTest.java
{ "start": 32400, "end": 37210 }
class ____("transforms.xformA.type", infos.get("transforms.xformA.type").configValue().name()); assertTrue(infos.get("transforms.xformA.type").configValue().errors().isEmpty()); assertEquals("transforms.xformA.subconfig", infos.get("transforms.xformA.subconfig").configValue().name()); assertEquals("transforms.xformA.predicate", infos.get("transforms.xformA.predicate").configValue().name()); assertTrue(infos.get("transforms.xformA.predicate").configValue().errors().isEmpty()); assertEquals("transforms.xformA.negate", infos.get("transforms.xformA.negate").configValue().name()); assertTrue(infos.get("transforms.xformA.negate").configValue().errors().isEmpty()); assertEquals("predicates.predX.type", infos.get("predicates.predX.type").configValue().name()); assertEquals("predicates.predX.predconfig", infos.get("predicates.predX.predconfig").configValue().name()); assertEquals("predicates.predY.type", infos.get("predicates.predY.type").configValue().name()); assertFalse(infos.get("predicates.predY.type").configValue().errors().isEmpty()); verify(plugins).transformations(); verify(plugins, times(2)).predicates(); verifyValidationIsolation(); } @SuppressWarnings({"rawtypes", "unchecked"}) private PluginDesc<Predicate<?>> predicatePluginDesc() { return new PluginDesc(SamplePredicate.class, "1.0", PluginType.PREDICATE, classLoader); } @SuppressWarnings({"rawtypes", "unchecked"}) private PluginDesc<Transformation<?>> transformationPluginDesc() { return new PluginDesc(SampleTransformation.class, "1.0", PluginType.TRANSFORMATION, classLoader); } @SuppressWarnings("removal") @Test public void testConfigValidationPrincipalOnlyOverride() { final Class<? extends Connector> connectorClass = SampleSourceConnector.class; AbstractHerder herder = createConfigValidationHerder(connectorClass, new PrincipalConnectorClientConfigOverridePolicy()); Map<String, String> config = new HashMap<>(); config.put(ConnectorConfig.CONNECTOR_CLASS_CONFIG, connectorClass.getName()); config.put(ConnectorConfig.NAME_CONFIG, "connector-name"); config.put("required", "value"); // connector required config String ackConfigKey = producerOverrideKey(ProducerConfig.ACKS_CONFIG); String saslConfigKey = producerOverrideKey(SaslConfigs.SASL_JAAS_CONFIG); config.put(ackConfigKey, "none"); config.put(saslConfigKey, "jaas_config"); ConfigInfos result = herder.validateConnectorConfig(config, s -> null, false); assertEquals(ConnectorType.SOURCE, herder.connectorType(config)); // We expect there to be errors due to now allowed override policy for ACKS.... Note that these assertions depend heavily on // the config fields for SourceConnectorConfig, but we expect these to change rarely. assertEquals(SampleSourceConnector.class.getName(), result.name()); // Each transform also gets its own group List<String> expectedGroups = List.of( ConnectorConfig.COMMON_GROUP, ConnectorConfig.TRANSFORMS_GROUP, ConnectorConfig.PREDICATES_GROUP, ConnectorConfig.ERROR_GROUP, SourceConnectorConfig.TOPIC_CREATION_GROUP, SourceConnectorConfig.EXACTLY_ONCE_SUPPORT_GROUP, SourceConnectorConfig.OFFSETS_TOPIC_GROUP ); assertEquals(expectedGroups, result.groups()); assertEquals(1, result.errorCount()); // Base connector config has 19 fields, connector's configs add 7, and 2 producer overrides assertEquals(28, result.configs().size()); assertTrue(result.configs().stream().anyMatch( configInfo -> ackConfigKey.equals(configInfo.configValue().name()) && !configInfo.configValue().errors().isEmpty())); assertTrue(result.configs().stream().anyMatch( configInfo -> saslConfigKey.equals(configInfo.configValue().name()) && configInfo.configValue().errors().isEmpty())); verifyValidationIsolation(); } @Test public void testConfigValidationAllOverride() { final Class<? extends Connector> connectorClass = SampleSourceConnector.class; AbstractHerder herder = createConfigValidationHerder(connectorClass, new AllConnectorClientConfigOverridePolicy()); Map<String, String> config = new HashMap<>(); config.put(ConnectorConfig.CONNECTOR_CLASS_CONFIG, connectorClass.getName()); config.put(ConnectorConfig.NAME_CONFIG, "connector-name"); config.put("required", "value"); // connector required config // Try to test a variety of configuration types: string, int, long, boolean, list,
assertEquals
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embedded/many2one/Address.java
{ "start": 412, "end": 1162 }
class ____ { private String line1; private String line2; private String city; private Country country; private String postalCode; public String getLine1() { return line1; } public void setLine1(String line1) { this.line1 = line1; } public String getLine2() { return line2; } public void setLine2(String line2) { this.line2 = line2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @ManyToOne public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } }
Address
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/support/AnnotationConsumerInitializerTests.java
{ "start": 6527, "end": 6773 }
class ____ implements AnnotationConsumer<CsvSource> { @Nullable CsvSource annotation; @Override public void accept(CsvSource csvSource) { annotation = csvSource; } } @SuppressWarnings("unused") private static
SomeAnnotationConsumer
java
quarkusio__quarkus
extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/ClassLevelComputedPermissionsAllowedTest.java
{ "start": 4890, "end": 5458 }
class ____ { public String autodetect(String hello, String world, String exclamationMark) { return SUCCESS; } public Uni<String> autodetectNonBlocking(String hello, String world, String exclamationMark) { return Uni.createFrom().item(SUCCESS); } public String autodetect(String world) { return SUCCESS; } public Uni<String> autodetectNonBlocking(String world) { return Uni.createFrom().item(SUCCESS); } } public static
ExplicitlyMatchedParamsBean
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleSetTransactionTest.java
{ "start": 930, "end": 2134 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "set transaction name 'IGNORED_TRANS' "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("employees"))); assertEquals(0, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("departments", "department_id"))); } }
OracleSetTransactionTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/blob/TestingBlobHelpers.java
{ "start": 2369, "end": 19461 }
class ____ { private TestingBlobHelpers() { throw new UnsupportedOperationException(); } /** * Checks how many of the files given by blob keys are accessible. * * @param jobId ID of a job * @param keys blob keys to check * @param blobService BLOB store to use * @param doThrow whether exceptions should be ignored (<tt>false</tt>), or thrown * (<tt>true</tt>) * @return number of files existing at {@link BlobServer#getStorageLocation(JobID, BlobKey)} and * {@link PermanentBlobCache#getStorageLocation(JobID, BlobKey)}, respectively */ public static <T> int checkFilesExist( JobID jobId, Collection<? extends BlobKey> keys, T blobService, boolean doThrow) throws IOException { int numFiles = 0; for (BlobKey key : keys) { final File storageDir; if (blobService instanceof BlobServer) { BlobServer server = (BlobServer) blobService; storageDir = server.getStorageDir(); } else if (blobService instanceof PermanentBlobCache) { PermanentBlobCache cache = (PermanentBlobCache) blobService; storageDir = cache.getStorageDir(); } else if (blobService instanceof TransientBlobCache) { TransientBlobCache cache = (TransientBlobCache) blobService; storageDir = cache.getStorageDir(); } else { throw new UnsupportedOperationException( "unsupported BLOB service class: " + blobService.getClass().getCanonicalName()); } final File blobFile = new File( BlobUtils.getStorageLocationPath( storageDir.getAbsolutePath(), jobId, key)); if (blobFile.exists()) { ++numFiles; } else if (doThrow) { throw new IOException("File " + blobFile + " does not exist."); } } return numFiles; } /** * Checks how many of the files given by blob keys are accessible. * * @param expectedCount number of expected files in the blob service for the given job * @param jobId ID of a job * @param blobService BLOB store to use */ public static void checkFileCountForJob( int expectedCount, JobID jobId, PermanentBlobService blobService) throws IOException { final File jobDir; if (blobService instanceof BlobServer) { BlobServer server = (BlobServer) blobService; jobDir = server.getStorageLocation(jobId, new PermanentBlobKey()).getParentFile(); } else { PermanentBlobCache cache = (PermanentBlobCache) blobService; jobDir = cache.getStorageLocation(jobId, new PermanentBlobKey()).getParentFile(); } File[] blobsForJob = jobDir.listFiles(); if (blobsForJob == null) { if (expectedCount != 0) { throw new IOException("File " + jobDir + " does not exist."); } } else { assertThat(blobsForJob.length) .as("Too many/few files in job dir: " + Arrays.asList(blobsForJob)) .isEqualTo(expectedCount); } } /** * Checks the GET operation fails when the downloaded file (from HA store) is corrupt, i.e. its * content's hash does not match the {@link BlobKey}'s hash. * * @param config blob server configuration (including HA settings like {@link * HighAvailabilityOptions#HA_STORAGE_PATH} and {@link * HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt> * @param blobStore shared HA blob store to use */ public static void testGetFailsFromCorruptFile( Configuration config, BlobStore blobStore, File blobStorage) throws IOException { Random rnd = new Random(); JobID jobId = new JobID(); try (BlobServer server = new BlobServer(config, blobStorage, blobStore)) { server.start(); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put content addressable (like libraries) BlobKey key = put(server, jobId, data, PERMANENT_BLOB); assertThat(key).isNotNull(); // delete local file to make sure that the GET requests downloads from HA File blobFile = server.getStorageLocation(jobId, key); assertThat(blobFile.delete()).isTrue(); // change HA store file contents to make sure that GET requests fail byte[] data2 = Arrays.copyOf(data, data.length); data2[0] ^= 1; File tmpFile = Files.createTempFile("blob", ".jar").toFile(); try { FileUtils.writeByteArrayToFile(tmpFile, data2); blobStore.put(tmpFile, jobId, key); } finally { //noinspection ResultOfMethodCallIgnored tmpFile.delete(); } assertThatThrownBy(() -> get(server, jobId, key)) .satisfies( FlinkAssertions.anyCauseMatches(IOException.class, "data corruption")); } } /** * Checks the GET operation fails when the downloaded file (from HA store) is corrupt, i.e. its * content's hash does not match the {@link BlobKey}'s hash, using a permanent BLOB. * * @param jobId job ID * @param config blob server configuration (including HA settings like {@link * HighAvailabilityOptions#HA_STORAGE_PATH} and {@link * HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt> * @param blobStore shared HA blob store to use */ public static void testGetFailsFromCorruptFile( JobID jobId, Configuration config, BlobStore blobStore, File blobStorage) throws IOException { testGetFailsFromCorruptFile(jobId, PERMANENT_BLOB, true, config, blobStore, blobStorage); } /** * Checks the GET operation fails when the downloaded file (from {@link BlobServer} or HA store) * is corrupt, i.e. its content's hash does not match the {@link BlobKey}'s hash. * * @param jobId job ID or <tt>null</tt> if job-unrelated * @param blobType whether the BLOB should become permanent or transient * @param corruptOnHAStore whether the file should be corrupt in the HA store (<tt>true</tt>, * required <tt>highAvailability</tt> to be set) or on the {@link BlobServer}'s local store * (<tt>false</tt>) * @param config blob server configuration (including HA settings like {@link * HighAvailabilityOptions#HA_STORAGE_PATH} and {@link * HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt> * @param blobStore shared HA blob store to use */ static void testGetFailsFromCorruptFile( @Nullable JobID jobId, BlobKey.BlobType blobType, boolean corruptOnHAStore, Configuration config, BlobStore blobStore, File blobStorage) throws IOException { assertThat(!corruptOnHAStore || blobType == PERMANENT_BLOB) .as("Check HA setup for corrupt HA file") .isTrue(); Random rnd = new Random(); try (BlobServer server = new BlobServer(config, new File(blobStorage, "server"), blobStore); BlobCacheService cache = new BlobCacheService( config, new File(blobStorage, "cache"), corruptOnHAStore ? blobStore : new VoidBlobStore(), new InetSocketAddress("localhost", server.getPort()))) { server.start(); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put content addressable (like libraries) BlobKey key = put(server, jobId, data, blobType); assertThat(key).isNotNull(); // change server/HA store file contents to make sure that GET requests fail byte[] data2 = Arrays.copyOf(data, data.length); data2[0] ^= 1; if (corruptOnHAStore) { File tmpFile = Files.createTempFile("blob", ".jar").toFile(); try { FileUtils.writeByteArrayToFile(tmpFile, data2); blobStore.put(tmpFile, jobId, key); } finally { //noinspection ResultOfMethodCallIgnored tmpFile.delete(); } // delete local (correct) file on server to make sure that the GET request does not // fall back to downloading the file from the BlobServer's local store File blobFile = server.getStorageLocation(jobId, key); assertThat(blobFile.delete()).isTrue(); } else { File blobFile = server.getStorageLocation(jobId, key); assertThat(blobFile).exists(); FileUtils.writeByteArrayToFile(blobFile, data2); } // issue a GET request that fails assertThatThrownBy(() -> get(cache, jobId, key)) .satisfies( FlinkAssertions.anyCauseMatches(IOException.class, "data corruption")); } } /** * Helper to test that the {@link BlobServer} recovery from its HA store works. * * <p>Uploads two BLOBs to one {@link BlobServer} and expects a second one to be able to * retrieve them via a shared HA store upon request of a {@link BlobCacheService}. * * @param config blob server configuration (including HA settings like {@link * HighAvailabilityOptions#HA_STORAGE_PATH} and {@link * HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt> * @param blobStore shared HA blob store to use * @throws IOException in case of failures */ public static void testBlobServerRecovery( final Configuration config, final BlobStore blobStore, final File blobStorage) throws Exception { final String clusterId = config.get(HighAvailabilityOptions.HA_CLUSTER_ID); String storagePath = config.get(HighAvailabilityOptions.HA_STORAGE_PATH) + "/" + clusterId; Random rand = new Random(); try (BlobServer server0 = new BlobServer(config, new File(blobStorage, "server0"), blobStore); BlobServer server1 = new BlobServer(config, new File(blobStorage, "server1"), blobStore); // use VoidBlobStore as the HA store to force download from server[1]'s HA store BlobCacheService cache1 = new BlobCacheService( config, new File(blobStorage, "cache1"), new VoidBlobStore(), new InetSocketAddress("localhost", server1.getPort()))) { server0.start(); server1.start(); // Random data byte[] expected = new byte[1024]; rand.nextBytes(expected); byte[] expected2 = Arrays.copyOfRange(expected, 32, 288); BlobKey[] keys = new BlobKey[2]; BlobKey nonHAKey; // Put job-related HA data JobID[] jobId = new JobID[] {new JobID(), new JobID()}; keys[0] = put(server0, jobId[0], expected, PERMANENT_BLOB); // Request 1 keys[1] = put(server0, jobId[1], expected2, PERMANENT_BLOB); // Request 2 // put non-HA data nonHAKey = put(server0, jobId[0], expected2, TRANSIENT_BLOB); verifyKeyDifferentHashEquals(keys[1], nonHAKey); // check that the storage directory exists final Path blobServerPath = new Path(storagePath, "blob"); FileSystem fs = blobServerPath.getFileSystem(); assertThat(fs.exists(blobServerPath)).isTrue(); // Verify HA requests from cache1 (connected to server1) with no immediate access to the // file verifyContents(cache1, jobId[0], keys[0], expected); verifyContents(cache1, jobId[1], keys[1], expected2); // Verify non-HA file is not accessible from server1 verifyDeleted(cache1, jobId[0], nonHAKey); // Remove again server1.globalCleanupAsync(jobId[0], Executors.directExecutor()).join(); server1.globalCleanupAsync(jobId[1], Executors.directExecutor()).join(); // Verify everything is clean assertThat(fs.exists(new Path(storagePath))).isTrue(); if (fs.exists(blobServerPath)) { final org.apache.flink.core.fs.FileStatus[] recoveryFiles = fs.listStatus(blobServerPath); ArrayList<String> filenames = new ArrayList<>(recoveryFiles.length); for (org.apache.flink.core.fs.FileStatus file : recoveryFiles) { filenames.add(file.toString()); } fail("Unclean state backend: %s", filenames); } } } /** * Helper to test that the {@link BlobServer} recovery from its HA store works. * * <p>Uploads two BLOBs to one {@link BlobServer} via a {@link BlobCacheService} and expects a * second {@link BlobCacheService} to be able to retrieve them from a second {@link BlobServer} * that is configured with the same HA store. * * @param config blob server configuration (including HA settings like {@link * HighAvailabilityOptions#HA_STORAGE_PATH} and {@link * HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt> * @param blobStore shared HA blob store to use * @throws IOException in case of failures */ public static void testBlobCacheRecovery( final Configuration config, final BlobStore blobStore, final File blobStorage) throws IOException { final String clusterId = config.get(HighAvailabilityOptions.HA_CLUSTER_ID); String storagePath = config.get(HighAvailabilityOptions.HA_STORAGE_PATH) + "/" + clusterId; Random rand = new Random(); try (BlobServer server0 = new BlobServer(config, new File(blobStorage, "server0"), blobStore); BlobServer server1 = new BlobServer(config, new File(blobStorage, "server1"), blobStore); // use VoidBlobStore as the HA store to force download from each server's HA store BlobCacheService cache0 = new BlobCacheService( config, new File(blobStorage, "cache0"), new VoidBlobStore(), new InetSocketAddress("localhost", server0.getPort())); BlobCacheService cache1 = new BlobCacheService( config, new File(blobStorage, "cache1"), new VoidBlobStore(), new InetSocketAddress("localhost", server1.getPort()))) { server0.start(); server1.start(); // Random data byte[] expected = new byte[1024]; rand.nextBytes(expected); byte[] expected2 = Arrays.copyOfRange(expected, 32, 288); BlobKey[] keys = new BlobKey[2]; BlobKey nonHAKey; // Put job-related HA data JobID[] jobId = new JobID[] {new JobID(), new JobID()}; keys[0] = put(cache0, jobId[0], expected, PERMANENT_BLOB); // Request 1 keys[1] = put(cache0, jobId[1], expected2, PERMANENT_BLOB); // Request 2 // put non-HA data nonHAKey = put(cache0, jobId[0], expected2, TRANSIENT_BLOB); verifyKeyDifferentHashDifferent(keys[0], nonHAKey); verifyKeyDifferentHashEquals(keys[1], nonHAKey); // check that the storage directory exists final Path blobServerPath = new Path(storagePath, "blob"); FileSystem fs = blobServerPath.getFileSystem(); assertThat(fs.exists(blobServerPath)).isTrue(); // Verify HA requests from cache1 (connected to server1) with no immediate access to the // file verifyContents(cache1, jobId[0], keys[0], expected); verifyContents(cache1, jobId[1], keys[1], expected2); // Verify non-HA file is not accessible from server1 verifyDeleted(cache1, jobId[0], nonHAKey); } } }
TestingBlobHelpers
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableEnumCheckerTest.java
{ "start": 3731, "end": 3978 }
interface ____ { void bar(); } """) .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.Immutable; @Immutable
MyInterface
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/shuffle/ShuffleEnvironment.java
{ "start": 2192, "end": 2622 }
interface ____ method's to manage the lifecycle of the local shuffle service * environment: * * <ol> * <li>{@link ShuffleEnvironment#start} must be called before using the shuffle service * environment. * <li>{@link ShuffleEnvironment#close} is called to release the shuffle service environment. * </ol> * * <h1>Shuffle Input/Output management.</h1> * * <h2>Result partition management.</h2> * * <p>The
contains
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Job.java
{ "start": 29346, "end": 30519 }
class ____ the job. * @param cls the combiner to use * @throws IllegalStateException if the job is submitted */ public void setCombinerClass(Class<? extends Reducer> cls ) throws IllegalStateException { ensureState(JobState.DEFINE); conf.setClass(COMBINE_CLASS_ATTR, cls, Reducer.class); } /** * Set the {@link Reducer} for the job. * @param cls the <code>Reducer</code> to use * @throws IllegalStateException if the job is submitted */ public void setReducerClass(Class<? extends Reducer> cls ) throws IllegalStateException { ensureState(JobState.DEFINE); conf.setClass(REDUCE_CLASS_ATTR, cls, Reducer.class); } /** * Set the {@link Partitioner} for the job. * @param cls the <code>Partitioner</code> to use * @throws IllegalStateException if the job is submitted */ public void setPartitionerClass(Class<? extends Partitioner> cls ) throws IllegalStateException { ensureState(JobState.DEFINE); conf.setClass(PARTITIONER_CLASS_ATTR, cls, Partitioner.class); } /** * Set the key
for
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/reverse/Source.java
{ "start": 228, "end": 1257 }
class ____ { private String stringPropX; private Integer integerPropX; private String someConstantDownstream; private String propertyToIgnoreDownstream; public String getStringPropX() { return stringPropX; } public void setStringPropX(String stringPropX) { this.stringPropX = stringPropX; } public Integer getIntegerPropX() { return integerPropX; } public void setIntegerPropX(Integer integerPropX) { this.integerPropX = integerPropX; } public String getSomeConstantDownstream() { return someConstantDownstream; } public void setSomeConstantDownstream(String someConstantDownstream) { this.someConstantDownstream = someConstantDownstream; } public String getPropertyToIgnoreDownstream() { return propertyToIgnoreDownstream; } public void setPropertyToIgnoreDownstream(String propertyToIgnoreDownstream) { this.propertyToIgnoreDownstream = propertyToIgnoreDownstream; } }
Source
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/core/annotation/ExpressionTemplateSecurityAnnotationScanner.java
{ "start": 1878, "end": 2235 }
interface ____ { * String role(); * } * </pre> * * <p> * In that case, you could use an {@link ExpressionTemplateSecurityAnnotationScanner} of * type {@link org.springframework.security.access.prepost.PreAuthorize} to synthesize any * {@code @HasRole} annotation found on a given {@link AnnotatedElement}. * * <p> * Meta-annotations that use
HasRole
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/interceptor/producer/ProducerWithoutZeroParamCtorAndInterceptionTest.java
{ "start": 1788, "end": 2129 }
class ____ { private final String value; private MyNonbean(String value) { this.value = value; } @MyBinding String hello1() { return "hello1_" + value; } String hello2() { return "hello2_" + value; } } @Dependent static
MyNonbean
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/queue/RocksDBConsumeQueueStore.java
{ "start": 24677, "end": 27439 }
class ____ { protected long lastPhysicalMinOffset = 0; private final double diskSpaceWarningLevelRatio = Double.parseDouble(System.getProperty("rocketmq.broker.diskSpaceWarningLevelRatio", "0.90")); private final double diskSpaceCleanForciblyRatio = Double.parseDouble(System.getProperty("rocketmq.broker.diskSpaceCleanForciblyRatio", "0.85")); public void run() { try { this.deleteExpiredFiles(); } catch (Throwable e) { log.warn(this.getServiceName() + " service has exception. ", e); } } public String getServiceName() { return messageStore.getBrokerConfig().getIdentifier() + ConsumeQueueStore.CleanConsumeQueueService.class.getSimpleName(); } protected void deleteExpiredFiles() { long minOffset = messageStore.getCommitLog().getMinOffset(); if (minOffset > this.lastPhysicalMinOffset) { this.lastPhysicalMinOffset = minOffset; boolean spaceFull = isSpaceToDelete(); boolean timeUp = messageStore.isTimeToDelete(); if (spaceFull || timeUp) { // To delete the CQ Units whose physical offset is smaller min physical offset in commitLog. cleanExpired(minOffset); } messageStore.getIndexService().deleteExpiredFile(minOffset); } } private boolean isSpaceToDelete() { double ratio = messageStoreConfig.getDiskMaxUsedSpaceRatio() / 100.0; String storePathLogics = StorePathConfigHelper .getStorePathConsumeQueue(messageStoreConfig.getStorePathRootDir()); double logicsRatio = UtilAll.getDiskPartitionSpaceUsedPercent(storePathLogics); if (logicsRatio > diskSpaceWarningLevelRatio) { boolean diskMaybeFull = messageStore.getRunningFlags().getAndMakeLogicDiskFull(); if (diskMaybeFull) { log.error("logics disk maybe full soon " + logicsRatio + ", so mark disk full"); } } else if (logicsRatio > diskSpaceCleanForciblyRatio) { } else { boolean diskOk = messageStore.getRunningFlags().getAndMakeLogicDiskOK(); if (!diskOk) { log.info("logics disk space OK " + logicsRatio + ", so mark disk ok"); } } if (logicsRatio < 0 || logicsRatio > ratio) { log.info("logics disk maybe full soon, so reclaim space, " + logicsRatio); return true; } return false; } } }
RocksDBCleanConsumeQueueService
java
apache__camel
components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/ExchangeEventFactory.java
{ "start": 1049, "end": 1302 }
class ____ implements EventFactory<ExchangeEvent> { public static final ExchangeEventFactory INSTANCE = new ExchangeEventFactory(); @Override public ExchangeEvent newInstance() { return new ExchangeEvent(); } }
ExchangeEventFactory
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/integers/Integers_assertLessThanOrEqualTo_Test.java
{ "start": 1431, "end": 3715 }
class ____ extends IntegersBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integers.assertLessThanOrEqualTo(someInfo(), null, 8)) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_is_less_than_other() { integers.assertLessThanOrEqualTo(someInfo(), 6, 8); } @Test void should_pass_if_actual_is_equal_to_other() { integers.assertLessThanOrEqualTo(someInfo(), 6, 6); } @Test void should_fail_if_actual_is_greater_than_other() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> integers.assertLessThanOrEqualTo(info, 8, 6)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeLessOrEqual(8, 6)); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integersWithAbsValueComparisonStrategy.assertLessThanOrEqualTo(someInfo(), null, 8)) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_is_less_than_other_according_to_custom_comparison_strategy() { integersWithAbsValueComparisonStrategy.assertLessThanOrEqualTo(someInfo(), 6, -8); } @Test void should_pass_if_actual_is_equal_to_other_according_to_custom_comparison_strategy() { integersWithAbsValueComparisonStrategy.assertLessThanOrEqualTo(someInfo(), 6, -6); } @Test void should_fail_if_actual_is_greater_than_other_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> integersWithAbsValueComparisonStrategy.assertLessThanOrEqualTo(info, -8, 6)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeLessOrEqual(-8, 6, absValueComparisonStrategy)); } }
Integers_assertLessThanOrEqualTo_Test
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jndi/JndiTemplate.java
{ "start": 5178, "end": 7235 }
class ____ the returned instance. * @return object found (cannot be {@code null}; if a not so well-behaved * JNDI implementations returns null, a NamingException gets thrown) * @throws NamingException if there is no object with the given * name bound to JNDI */ @SuppressWarnings("unchecked") public <T> T lookup(String name, @Nullable Class<T> requiredType) throws NamingException { Object jndiObject = lookup(name); if (requiredType != null && !requiredType.isInstance(jndiObject)) { throw new TypeMismatchNamingException(name, requiredType, jndiObject.getClass()); } return (T) jndiObject; } /** * Bind the given object to the current JNDI context, using the given name. * @param name the JNDI name of the object * @param object the object to bind * @throws NamingException thrown by JNDI, mostly name already bound */ public void bind(final String name, final Object object) throws NamingException { if (logger.isDebugEnabled()) { logger.debug("Binding JNDI object with name [" + name + "]"); } execute(ctx -> { ctx.bind(name, object); return null; }); } /** * Rebind the given object to the current JNDI context, using the given name. * Overwrites any existing binding. * @param name the JNDI name of the object * @param object the object to rebind * @throws NamingException thrown by JNDI */ public void rebind(final String name, final Object object) throws NamingException { if (logger.isDebugEnabled()) { logger.debug("Rebinding JNDI object with name [" + name + "]"); } execute(ctx -> { ctx.rebind(name, object); return null; }); } /** * Remove the binding for the given name from the current JNDI context. * @param name the JNDI name of the object * @throws NamingException thrown by JNDI, mostly name not found */ public void unbind(final String name) throws NamingException { if (logger.isDebugEnabled()) { logger.debug("Unbinding JNDI object with name [" + name + "]"); } execute(ctx -> { ctx.unbind(name); return null; }); } }
of
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/TypeExtractor.java
{ "start": 37054, "end": 39315 }
class ____ as a type is not allowed. Use a concrete subclass (e.g. Tuple1, Tuple2, etc.) instead."); } // go up the hierarchy until we reach immediate child of Tuple (with or without // generics) // collect the types while moving up for a later top-down List<Type> typeHierarchyForSubtypes = new ArrayList<>(typeHierarchy); while (!(isClassType(curT) && typeToClass(curT).getSuperclass().equals(Tuple.class))) { typeHierarchyForSubtypes.add(curT); curT = typeToClass(curT).getGenericSuperclass(); } if (curT == Tuple0.class) { return new TupleTypeInfo(Tuple0.class); } // check if immediate child of Tuple has generics if (curT instanceof Class<?>) { throw new InvalidTypesException( "Tuple needs to be parameterized by using generics."); } typeHierarchyForSubtypes.add(curT); // create the type information for the subtypes final TypeInformation<?>[] subTypesInfo = createSubTypesInfo( t, (ParameterizedType) curT, typeHierarchyForSubtypes, in1Type, in2Type, false); // type needs to be treated a pojo due to additional fields if (subTypesInfo == null) { return analyzePojo(t, new ArrayList<>(typeHierarchy), in1Type, in2Type); } for (int i = 0; i < subTypesInfo.length; i++) { if (subTypesInfo[i] instanceof GenericTypeInfo) { LOG.info( "Tuple field #{} of type '{}' will be processed as GenericType. {}", i + 1, subTypesInfo[i].getTypeClass().getSimpleName(), GENERIC_TYPE_DOC_HINT); } } // return tuple info return new TupleTypeInfo(typeToClass(t), subTypesInfo); } // type depends on another type // e.g.
Tuple
java
quarkusio__quarkus
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/federation/base/FooApi.java
{ "start": 184, "end": 353 }
class ____ { @Query public Foo foo(int id) { var foo = new Foo(); foo.id = id; foo.name = "Name of " + id; return foo; } }
FooApi
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java
{ "start": 6834, "end": 6988 }
class ____ implements DisposableBean { boolean closed = false; @Override public void destroy() { closed = true; } } static
WithDisposableBean
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/statistics/ITestAWSStatisticCollection.java
{ "start": 1463, "end": 2395 }
class ____ extends AbstractS3ACostTest { private static final Logger LOG = LoggerFactory.getLogger(ITestAWSStatisticCollection.class); @Override public Configuration createConfiguration() { final Configuration conf = super.createConfiguration(); S3ATestUtils.removeBaseAndBucketOverrides(conf, S3EXPRESS_CREATE_SESSION); setPerformanceFlags(conf, "create"); conf.setBoolean(S3EXPRESS_CREATE_SESSION, false); return conf; } @Test public void testSDKMetricsCostOfGetFileStatusOnFile() throws Throwable { describe("Performing getFileStatus() on a file"); Path simpleFile = file(methodPath()); // and repeat on the file looking at AWS wired up stats final S3AFileSystem fs = getFileSystem(); LOG.info("Initiating GET request for {}", simpleFile); verifyMetrics(() -> fs.getFileStatus(simpleFile), with(STORE_IO_REQUEST, 1)); } }
ITestAWSStatisticCollection
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_164_window.java
{ "start": 315, "end": 1208 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "SELECT\n" + " val,\n" + " ROW_NUMBER() OVER w AS 'row_number',\n" + " RANK() OVER w AS 'rank',\n" + " DENSE_RANK() OVER w AS 'dense_rank'\n" + "FROM numbers\n" + "WINDOW w AS (ORDER BY val);"; // List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT val, ROW_NUMBER() OVER w AS \"row_number\", RANK() OVER w AS \"rank\", DENSE_RANK() OVER w AS \"dense_rank\"\n" + "FROM numbers\n" + "WINDOW w AS (ORDER BY val);", stmt.toString()); } }
MySqlSelectTest_164_window
java
apache__camel
components/camel-sjms/src/test/java/org/apache/camel/component/sjms/producer/InOutQueueProducerAsyncLoadTest.java
{ "start": 1592, "end": 4580 }
class ____ extends JmsTestSupport { private static final String TEST_DESTINATION_NAME = "in.out.queue.producer.test.InOutQueueProducerAsyncLoadTest"; private MessageConsumer mc1; private MessageConsumer mc2; public InOutQueueProducerAsyncLoadTest() { } @BeforeEach public void setupConsumers() throws Exception { mc1 = createQueueConsumer(TEST_DESTINATION_NAME + ".request"); mc2 = createQueueConsumer(TEST_DESTINATION_NAME + ".request"); mc1.setMessageListener(new MyMessageListener()); mc2.setMessageListener(new MyMessageListener()); } @AfterEach public void cleanupConsumers() throws JMSException { MyMessageListener l1 = (MyMessageListener) mc1.getMessageListener(); l1.close(); mc1.close(); MyMessageListener l2 = (MyMessageListener) mc2.getMessageListener(); l2.close(); mc2.close(); } /** * Test to verify that when using the consumer listener for the InOut producer we get the correct message back. * * @throws Exception */ @Test public void testInOutQueueProducer() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(2); for (int i = 1; i <= 5000; i++) { final int tempI = i; Runnable worker = new Runnable() { @Override public void run() { try { final String requestText = "Message " + tempI; final String responseText = "Response Message " + tempI; String response = template.requestBody("direct:start", requestText, String.class); assertNotNull(response); assertEquals(responseText, response); } catch (Exception e) { log.error("TODO Auto-generated catch block", e); } } }; executor.execute(worker); } while (context.getInflightRepository().size() > 0) { Thread.sleep(100); } executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(100); } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start") .to("log:" + TEST_DESTINATION_NAME + ".in.log?showBody=true") .to(ExchangePattern.InOut, "sjms:queue:" + TEST_DESTINATION_NAME + ".request" + "?replyTo=" + TEST_DESTINATION_NAME + ".response&concurrentConsumers=10") .threads(20) .to("log:" + TEST_DESTINATION_NAME + ".out.log?showBody=true"); } }; } protected
InOutQueueProducerAsyncLoadTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InterruptedExceptionSwallowedTest.java
{ "start": 7514, "end": 8146 }
class ____ { void test(Future<?> future) { try { throw new Exception(); } catch (Exception e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new IllegalStateException(e); } } } """) .doTest(); } @Test public void positiveSimpleCase() { compilationHelper .addSourceLines( "Test.java", """ import java.util.concurrent.Future;
Test
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/ExtensionCatalogResolver.java
{ "start": 1682, "end": 2100 }
class ____ { public static ExtensionCatalogResolver empty() { final ExtensionCatalogResolver resolver = new ExtensionCatalogResolver(); resolver.registries = Collections.emptyList(); resolver.log = MessageWriter.info(); return resolver; } public static Builder builder() { return new ExtensionCatalogResolver().new Builder(); } public
ExtensionCatalogResolver
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/OperationType.java
{ "start": 836, "end": 985 }
enum ____ { /** * A read operation. */ READ, /** * A write operation. */ WRITE, /** * A delete operation. */ DELETE }
OperationType