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
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/jdk/UntypedDeserializationTest.java
{ "start": 3192, "end": 3382 }
class ____ { protected Object value; @JsonCreator // delegating public DelegatingUntyped(Object v) { value = v; } } static
DelegatingUntyped
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java
{ "start": 299, "end": 1813 }
class ____<T> implements StrategyRegistration<T> { private final Class<T> strategyRole; private final Class<? extends T> strategyImplementation; private final Iterable<String> selectorNames; /** * Constructs a SimpleStrategyRegistrationImpl. * * @param strategyRole The strategy contract * @param strategyImplementation The strategy implementation class * @param selectorNames The selection/registration names for this implementation */ public SimpleStrategyRegistrationImpl( Class<T> strategyRole, Class<? extends T> strategyImplementation, Iterable<String> selectorNames) { this.strategyRole = strategyRole; this.strategyImplementation = strategyImplementation; this.selectorNames = selectorNames; } /** * Constructs a SimpleStrategyRegistrationImpl. * * @param strategyRole The strategy contract * @param strategyImplementation The strategy implementation class * @param selectorNames The selection/registration names for this implementation */ public SimpleStrategyRegistrationImpl( Class<T> strategyRole, Class<? extends T> strategyImplementation, String... selectorNames) { this( strategyRole, strategyImplementation, Arrays.asList( selectorNames ) ); } @Override public Class<T> getStrategyRole() { return strategyRole; } @Override public Iterable<String> getSelectorNames() { return selectorNames; } @Override public Class<? extends T> getStrategyImplementation() { return strategyImplementation; } }
SimpleStrategyRegistrationImpl
java
quarkusio__quarkus
extensions/reactive-mysql-client/deployment/src/test/java/io/quarkus/reactive/mysql/client/ConfigUrlMissingNamedDatasourceHealthCheckTest.java
{ "start": 254, "end": 1328 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .overrideConfigKey("quarkus.datasource.health.enabled", "true") // The URL won't be missing if dev services are enabled .overrideConfigKey("quarkus.devservices.enabled", "false") // We need at least one build-time property for the datasource, // otherwise it's considered unconfigured at build time... .overrideConfigKey("quarkus.datasource.ds-1.db-kind", "mysql"); @Test public void testDataSourceHealthCheckExclusion() { RestAssured.when().get("/q/health/ready") .then() // A datasource without a URL is inactive, and thus not checked for health. // Note however we have checks in place to fail on startup if such a datasource is injected statically. .body("status", CoreMatchers.equalTo("UP")) .body("checks[0].data.ds-1", CoreMatchers.nullValue()); } }
ConfigUrlMissingNamedDatasourceHealthCheckTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/sql/TestMigrate.java
{ "start": 8382, "end": 10630 }
class ____ { private Date snapshotDate; private String dbName; private String sqlId; private StringBuilder sqlText = new StringBuilder(); private Integer piece; private Integer commandType; private Date lastSnapshotDate; private Long dbPk; private String result; public String getResult() { return result; } public void setResult(String result) { this.result = result; } public Date getSnapshotDate() { return snapshotDate; } public void setSnapshotDate(Date snapshotDate) { this.snapshotDate = snapshotDate; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public String getSqlId() { return sqlId; } public void setSqlId(String sqlId) { this.sqlId = sqlId; } public String getSqlText() { return sqlText.toString(); } public void setSqlText(String sqlText) { if (sqlText == null) { sqlText = ""; } this.sqlText = new StringBuilder(sqlText); } public void appendSqlText(String sqlText) { this.sqlText.append(sqlText); } public Integer getPiece() { return piece; } public void setPiece(Integer piece) { this.piece = piece; } public Integer getCommandType() { return commandType; } public void setCommandType(Integer commandType) { this.commandType = commandType; } public Date getLastSnapshotDate() { return lastSnapshotDate; } public void setLastSnapshotDate(Date lastSnapshotDate) { this.lastSnapshotDate = lastSnapshotDate; } public Long getDbPk() { return dbPk; } public void setDbPk(Long dbPk) { this.dbPk = dbPk; } public String toString() { return JSONUtils.toJSONString(this); } } }
Record
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/injectionstrategy/spring/setter/SpringSetterMapperTest.java
{ "start": 2145, "end": 4606 }
class ____ { @RegisterExtension final GeneratedSource generatedSource = new GeneratedSource(); @Autowired private CustomerRecordSpringSetterMapper customerRecordMapper; private ConfigurableApplicationContext context; @BeforeEach public void springUp() { context = new AnnotationConfigApplicationContext( getClass() ); context.getAutowireCapableBeanFactory().autowireBean( this ); } @AfterEach public void springDown() { if ( context != null ) { context.close(); } } @ProcessorTest public void shouldConvertToTarget() throws Exception { // given CustomerEntity customerEntity = new CustomerEntity(); customerEntity.setName( "Samuel" ); customerEntity.setGender( Gender.MALE ); CustomerRecordEntity customerRecordEntity = new CustomerRecordEntity(); customerRecordEntity.setCustomer( customerEntity ); customerRecordEntity.setRegistrationDate( createDate( "31-08-1982 10:20:56" ) ); // when CustomerRecordDto customerRecordDto = customerRecordMapper.asTarget( customerRecordEntity ); // then assertThat( customerRecordDto ).isNotNull(); assertThat( customerRecordDto.getCustomer() ).isNotNull(); assertThat( customerRecordDto.getCustomer().getName() ).isEqualTo( "Samuel" ); assertThat( customerRecordDto.getCustomer().getGender() ).isEqualTo( GenderDto.M ); assertThat( customerRecordDto.getRegistrationDate() ).isNotNull(); assertThat( customerRecordDto.getRegistrationDate() ).hasToString( "1982-08-31T10:20:56.000+02:00" ); } @ProcessorTest public void shouldHaveSetterInjection() { String method = "@Autowired" + lineSeparator() + " public void setGenderSpringSetterMapper(GenderSpringSetterMapper genderSpringSetterMapper) {" + lineSeparator() + " this.genderSpringSetterMapper = genderSpringSetterMapper;" + lineSeparator() + " }"; generatedSource.forMapper( CustomerSpringSetterMapper.class ) .content() .contains( "private GenderSpringSetterMapper genderSpringSetterMapper;" ) .contains( method ); } private Date createDate(String date) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat( "dd-M-yyyy hh:mm:ss" ); return sdf.parse( date ); } }
SpringSetterMapperTest
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/ReifierStrategy.java
{ "start": 936, "end": 1502 }
class ____ { private static final List<Runnable> CLEARERS = new ArrayList<>(); public static void addReifierClearer(Runnable strategy) { CLEARERS.add(strategy); } /** * DANGER: Clears the refifiers map. After this the JVM with Camel cannot add new routes (using same classloader to * load this class). Clearing this map allows Camel to reduce memory footprint. */ public static void clearReifiers() { for (Runnable run : CLEARERS) { run.run(); } CLEARERS.clear(); } }
ReifierStrategy
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java
{ "start": 1049, "end": 5714 }
class ____ implements JdkApplicationProtocolNegotiator { private final List<String> protocols; private final ProtocolSelectorFactory selectorFactory; private final ProtocolSelectionListenerFactory listenerFactory; private final SslEngineWrapperFactory wrapperFactory; /** * Create a new instance. * @param wrapperFactory Determines which application protocol will be used by wrapping the SSLEngine in use. * @param selectorFactory How the peer selecting the protocol should behave. * @param listenerFactory How the peer being notified of the selected protocol should behave. * @param protocols The order of iteration determines the preference of support for protocols. */ JdkBaseApplicationProtocolNegotiator(SslEngineWrapperFactory wrapperFactory, ProtocolSelectorFactory selectorFactory, ProtocolSelectionListenerFactory listenerFactory, Iterable<String> protocols) { this(wrapperFactory, selectorFactory, listenerFactory, toList(protocols)); } /** * Create a new instance. * @param wrapperFactory Determines which application protocol will be used by wrapping the SSLEngine in use. * @param selectorFactory How the peer selecting the protocol should behave. * @param listenerFactory How the peer being notified of the selected protocol should behave. * @param protocols The order of iteration determines the preference of support for protocols. */ JdkBaseApplicationProtocolNegotiator(SslEngineWrapperFactory wrapperFactory, ProtocolSelectorFactory selectorFactory, ProtocolSelectionListenerFactory listenerFactory, String... protocols) { this(wrapperFactory, selectorFactory, listenerFactory, toList(protocols)); } /** * Create a new instance. * @param wrapperFactory Determines which application protocol will be used by wrapping the SSLEngine in use. * @param selectorFactory How the peer selecting the protocol should behave. * @param listenerFactory How the peer being notified of the selected protocol should behave. * @param protocols The order of iteration determines the preference of support for protocols. */ private JdkBaseApplicationProtocolNegotiator(SslEngineWrapperFactory wrapperFactory, ProtocolSelectorFactory selectorFactory, ProtocolSelectionListenerFactory listenerFactory, List<String> protocols) { this.wrapperFactory = checkNotNull(wrapperFactory, "wrapperFactory"); this.selectorFactory = checkNotNull(selectorFactory, "selectorFactory"); this.listenerFactory = checkNotNull(listenerFactory, "listenerFactory"); this.protocols = Collections.unmodifiableList(checkNotNull(protocols, "protocols")); } @Override public List<String> protocols() { return protocols; } @Override public ProtocolSelectorFactory protocolSelectorFactory() { return selectorFactory; } @Override public ProtocolSelectionListenerFactory protocolListenerFactory() { return listenerFactory; } @Override public SslEngineWrapperFactory wrapperFactory() { return wrapperFactory; } static final ProtocolSelectorFactory FAIL_SELECTOR_FACTORY = new ProtocolSelectorFactory() { @Override public ProtocolSelector newSelector(SSLEngine engine, Set<String> supportedProtocols) { return new FailProtocolSelector((JdkSslEngine) engine, supportedProtocols); } }; static final ProtocolSelectorFactory NO_FAIL_SELECTOR_FACTORY = new ProtocolSelectorFactory() { @Override public ProtocolSelector newSelector(SSLEngine engine, Set<String> supportedProtocols) { return new NoFailProtocolSelector((JdkSslEngine) engine, supportedProtocols); } }; static final ProtocolSelectionListenerFactory FAIL_SELECTION_LISTENER_FACTORY = new ProtocolSelectionListenerFactory() { @Override public ProtocolSelectionListener newListener(SSLEngine engine, List<String> supportedProtocols) { return new FailProtocolSelectionListener((JdkSslEngine) engine, supportedProtocols); } }; static final ProtocolSelectionListenerFactory NO_FAIL_SELECTION_LISTENER_FACTORY = new ProtocolSelectionListenerFactory() { @Override public ProtocolSelectionListener newListener(SSLEngine engine, List<String> supportedProtocols) { return new NoFailProtocolSelectionListener((JdkSslEngine) engine, supportedProtocols); } }; static
JdkBaseApplicationProtocolNegotiator
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SnmpComponentBuilderFactory.java
{ "start": 6777, "end": 7927 }
class ____ extends AbstractComponentBuilder<SnmpComponent> implements SnmpComponentBuilder { @Override protected SnmpComponent buildConcreteComponent() { return new SnmpComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "bridgeErrorHandler": ((SnmpComponent) component).setBridgeErrorHandler((boolean) value); return true; case "lazyStartProducer": ((SnmpComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((SnmpComponent) component).setAutowiredEnabled((boolean) value); return true; case "healthCheckConsumerEnabled": ((SnmpComponent) component).setHealthCheckConsumerEnabled((boolean) value); return true; case "healthCheckProducerEnabled": ((SnmpComponent) component).setHealthCheckProducerEnabled((boolean) value); return true; default: return false; } } } }
SnmpComponentBuilderImpl
java
resilience4j__resilience4j
resilience4j-bulkhead/src/test/java/io/github/resilience4j/bulkhead/BulkheadFutureTest.java
{ "start": 609, "end": 8790 }
class ____ { private HelloWorldService helloWorldService; private Future<String> future; private BulkheadConfig config; @Before @SuppressWarnings("unchecked") public void setUp() { helloWorldService = mock(HelloWorldService.class); future = mock(Future.class); config = BulkheadConfig.custom() .maxConcurrentCalls(1) .build(); } @Test public void shouldDecorateSupplierAndReturnWithSuccess() throws Exception { Bulkhead bulkhead = Bulkhead.of("test", config); given(future.get()).willReturn("Hello world"); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); String result = supplier.get().get(); assertThat(result).isEqualTo("Hello world"); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).should(times(1)).get(); } @Test public void shouldDecorateSupplierAndReturnWithSuccessAndTimeout() throws Exception { Bulkhead bulkhead = Bulkhead.of("test", config); given(future.get(anyLong(), any(TimeUnit.class))).willReturn("Hello world"); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); String result = supplier.get().get(5, TimeUnit.SECONDS); assertThat(result).isEqualTo("Hello world"); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).should(times(1)).get(anyLong(), any(TimeUnit.class)); } @Test public void shouldDecorateFutureAndBulkheadApplyOnceOnMultipleFutureEval() throws Exception { Bulkhead bulkhead = Bulkhead.of("test", config); given(future.get(anyLong(), any(TimeUnit.class))).willReturn("Hello world"); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); Future<String> decoratedFuture = supplier.get(); decoratedFuture.get(5, TimeUnit.SECONDS); decoratedFuture.get(5, TimeUnit.SECONDS); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).should(times(2)).get(anyLong(), any(TimeUnit.class)); } @Test public void shouldDecorateFutureAndBulkheadApplyOnceOnMultipleFutureEvalFailure() throws Exception { Bulkhead bulkhead = Bulkhead.of("test", config); given(future.get()).willThrow(new ExecutionException(new RuntimeException("Hello world"))); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); Future<String> decoratedFuture = supplier.get(); catchThrowable(decoratedFuture::get); catchThrowable(decoratedFuture::get); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).should(times(2)).get(); } @Test public void shouldDecorateSupplierAndReturnWithExceptionAtAsyncStage() throws Exception { Bulkhead bulkhead = Bulkhead.of("test", config); given(future.get()).willThrow(new ExecutionException(new RuntimeException("BAM!"))); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); Throwable thrown = catchThrowable(() -> supplier.get().get()); assertThat(thrown).isInstanceOf(ExecutionException.class) .hasCauseInstanceOf(RuntimeException.class); assertThat(thrown.getCause().getMessage()).isEqualTo("BAM!"); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).should(times(1)).get(); } @Test public void shouldDecorateSupplierAndReturnWithExceptionAtSyncStage() { Bulkhead bulkhead = Bulkhead.of("test", config); given(helloWorldService.returnHelloWorldFuture()).willThrow(new RuntimeException("BAM!")); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); Throwable thrown = catchThrowable(() -> supplier.get().get()); assertThat(thrown).isInstanceOf(RuntimeException.class) .hasMessage("BAM!"); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).shouldHaveNoInteractions(); } @Test public void shouldReturnFailureWithBulkheadFullException() throws Exception { // tag::bulkheadFullException[] BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(2).build(); Bulkhead bulkhead = Bulkhead.of("test", config); bulkhead.tryAcquirePermission(); bulkhead.tryAcquirePermission(); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isZero(); given(future.get()).willReturn("Hello world"); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead.decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); Throwable thrown = catchThrowable(() -> supplier.get().get()); assertThat(thrown).isInstanceOf(ExecutionException.class) .hasCauseInstanceOf(BulkheadFullException.class); then(helloWorldService).shouldHaveNoInteractions(); then(future).shouldHaveNoInteractions(); // end::bulkheadFullException[] } @Test public void shouldReturnFailureWithFutureCancellationException() throws Exception { Bulkhead bulkhead = Bulkhead.of("test", config); given(future.get()).willThrow(new CancellationException()); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); Throwable thrown = catchThrowable(() -> supplier.get().get()); assertThat(thrown).isInstanceOf(CancellationException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).should(times(1)).get(); } @Test public void shouldReturnFailureWithFutureTimeoutException() throws Exception { Bulkhead bulkhead = Bulkhead.of("test", config); given(future.get(anyLong(), any(TimeUnit.class))).willThrow(new TimeoutException()); given(helloWorldService.returnHelloWorldFuture()).willReturn(future); Supplier<Future<String>> supplier = Bulkhead .decorateFuture(bulkhead, helloWorldService::returnHelloWorldFuture); Throwable thrown = catchThrowable(() -> supplier.get().get(5, TimeUnit.SECONDS)); assertThat(thrown).isInstanceOf(TimeoutException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldFuture(); then(future).should(times(1)).get(anyLong(), any(TimeUnit.class)); } }
BulkheadFutureTest
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java
{ "start": 9554, "end": 15889 }
class ____ ajc-compiled target class -> already weaved. return false; } try { try { return obtainPointcutExpression().couldMatchJoinPointsInType(targetClass); } catch (ReflectionWorldException ex) { logger.debug("PointcutExpression matching rejected target class - trying fallback expression", ex); // Actually this is still a "maybe" - treat the pointcut as dynamic if we don't know enough yet PointcutExpression fallbackExpression = getFallbackPointcutExpression(targetClass); if (fallbackExpression != null) { return fallbackExpression.couldMatchJoinPointsInType(targetClass); } } } catch (IllegalArgumentException | IllegalStateException | UnsupportedPointcutPrimitiveException ex) { this.pointcutParsingFailed = true; if (logger.isDebugEnabled()) { logger.debug("Pointcut parser rejected expression [" + getExpression() + "]: " + ex); } } catch (Throwable ex) { logger.debug("PointcutExpression matching rejected target class", ex); } return false; } @Override public boolean matches(Method method, Class<?> targetClass, boolean hasIntroductions) { ShadowMatch shadowMatch = getTargetShadowMatch(method, targetClass); // Special handling for this, target, @this, @target, @annotation // in Spring - we can optimize since we know we have exactly this class, // and there will never be matching subclass at runtime. if (shadowMatch.alwaysMatches()) { return true; } else if (shadowMatch.neverMatches()) { return false; } else { // the maybe case if (hasIntroductions) { return true; } // A match test returned maybe - if there are any subtype sensitive variables // involved in the test (this, target, at_this, at_target, at_annotation) then // we say this is not a match as in Spring there will never be a different // runtime subtype. RuntimeTestWalker walker = getRuntimeTestWalker(shadowMatch); return (!walker.testsSubtypeSensitiveVars() || walker.testTargetInstanceOfResidue(targetClass)); } } @Override public boolean matches(Method method, Class<?> targetClass) { return matches(method, targetClass, false); } @Override public boolean isRuntime() { return obtainPointcutExpression().mayNeedDynamicTest(); } @Override public boolean matches(Method method, Class<?> targetClass, @Nullable Object... args) { ShadowMatch shadowMatch = getTargetShadowMatch(method, targetClass); // Bind Spring AOP proxy to AspectJ "this" and Spring AOP target to AspectJ target, // consistent with return of MethodInvocationProceedingJoinPoint ProxyMethodInvocation pmi = null; Object targetObject = null; Object thisObject = null; try { MethodInvocation curr = ExposeInvocationInterceptor.currentInvocation(); if (curr.getMethod() == method) { targetObject = curr.getThis(); if (!(curr instanceof ProxyMethodInvocation currPmi)) { throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + curr); } pmi = currPmi; thisObject = pmi.getProxy(); } } catch (IllegalStateException ex) { // No current invocation... if (logger.isDebugEnabled()) { logger.debug("Could not access current invocation - matching with limited context: " + ex); } } try { JoinPointMatch joinPointMatch = shadowMatch.matchesJoinPoint(thisObject, targetObject, args); /* * Do a final check to see if any this(TYPE) kind of residue match. For * this purpose, we use the original method's (proxy method's) shadow to * ensure that 'this' is correctly checked against. Without this check, * we get incorrect match on this(TYPE) where TYPE matches the target * type but not 'this' (as would be the case of JDK dynamic proxies). * <p>See SPR-2979 for the original bug. */ if (pmi != null && thisObject != null) { // there is a current invocation RuntimeTestWalker originalMethodResidueTest = getRuntimeTestWalker(getShadowMatch(method, method)); if (!originalMethodResidueTest.testThisInstanceOfResidue(thisObject.getClass())) { return false; } if (joinPointMatch.matches()) { bindParameters(pmi, joinPointMatch); } } return joinPointMatch.matches(); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to evaluate join point for arguments " + Arrays.toString(args) + " - falling back to non-match", ex); } return false; } } protected @Nullable String getCurrentProxiedBeanName() { return ProxyCreationContext.getCurrentProxiedBeanName(); } /** * Get a new pointcut expression based on a target class's loader rather than the default. */ private @Nullable PointcutExpression getFallbackPointcutExpression(Class<?> targetClass) { try { ClassLoader classLoader = targetClass.getClassLoader(); if (classLoader != null && classLoader != this.pointcutClassLoader) { return buildPointcutExpression(classLoader); } } catch (Throwable ex) { logger.debug("Failed to create fallback PointcutExpression", ex); } return null; } private RuntimeTestWalker getRuntimeTestWalker(ShadowMatch shadowMatch) { if (shadowMatch instanceof DefensiveShadowMatch defensiveShadowMatch) { return new RuntimeTestWalker(defensiveShadowMatch.primary); } return new RuntimeTestWalker(shadowMatch); } private void bindParameters(ProxyMethodInvocation invocation, JoinPointMatch jpm) { // Note: Can't use JoinPointMatch.getClass().getName() as the key, since // Spring AOP does all the matching at a join point, and then all the invocations // under this scenario, if we just use JoinPointMatch as the key, then // 'last man wins' which is not what we want at all. // Using the expression is guaranteed to be safe, since 2 identical expressions // are guaranteed to bind in exactly the same way. invocation.setUserAttribute(resolveExpression(), jpm); } private ShadowMatch getTargetShadowMatch(Method method, Class<?> targetClass) { Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); if (targetMethod.getDeclaringClass().isInterface() && targetMethod.getDeclaringClass() != targetClass && obtainPointcutExpression().getPointcutExpression().contains("." + targetMethod.getName() + "(")) { // Try to build the most specific
for
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/bcextensions/InterceptorInfoImpl.java
{ "start": 294, "end": 1335 }
class ____ extends BeanInfoImpl implements InterceptorInfo { private final io.quarkus.arc.processor.InterceptorInfo arcInterceptorInfo; InterceptorInfoImpl(org.jboss.jandex.IndexView jandexIndex, org.jboss.jandex.MutableAnnotationOverlay annotationOverlay, io.quarkus.arc.processor.InterceptorInfo arcInterceptorInfo) { super(jandexIndex, annotationOverlay, arcInterceptorInfo); this.arcInterceptorInfo = arcInterceptorInfo; } @Override public Integer priority() { return arcInterceptorInfo.getPriority(); } @Override public Collection<AnnotationInfo> interceptorBindings() { return arcInterceptorInfo.getBindings() .stream() .map(it -> new AnnotationInfoImpl(jandexIndex, annotationOverlay, it)) .collect(Collectors.toUnmodifiableSet()); } @Override public boolean intercepts(InterceptionType interceptionType) { return arcInterceptorInfo.intercepts(interceptionType); } }
InterceptorInfoImpl
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/EmbeddableAndFetchModeSelectTest.java
{ "start": 8941, "end": 9098 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") Integer id; String name; } @Embeddable public static
EntityD
java
elastic__elasticsearch
modules/ingest-common/src/internalClusterTest/java/org/elasticsearch/ingest/common/IngestRestartIT.java
{ "start": 2977, "end": 3213 }
class ____ extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(IngestCommonPlugin.class, CustomScriptPlugin.class); } public static
IngestRestartIT
java
elastic__elasticsearch
x-pack/plugin/enrich/src/main/java/org/elasticsearch/xpack/enrich/rest/RestExecuteEnrichPolicyAction.java
{ "start": 897, "end": 1722 }
class ____ extends BaseRestHandler { @Override public List<Route> routes() { return List.of(new Route(POST, "/_enrich/policy/{name}/_execute"), new Route(PUT, "/_enrich/policy/{name}/_execute")); } @Override public String getName() { return "execute_enrich_policy"; } @Override protected RestChannelConsumer prepareRequest(final RestRequest restRequest, final NodeClient client) { final var request = new ExecuteEnrichPolicyAction.Request(RestUtils.getMasterNodeTimeout(restRequest), restRequest.param("name")); request.setWaitForCompletion(restRequest.paramAsBoolean("wait_for_completion", true)); return channel -> client.execute(ExecuteEnrichPolicyAction.INSTANCE, request, new RestToXContentListener<>(channel)); } }
RestExecuteEnrichPolicyAction
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/ParallelFluxNameTest.java
{ "start": 1013, "end": 2481 }
class ____ { @Test public void parallelism() { ParallelFlux<Integer> source = Flux.range(1, 4).parallel(3); ParallelFluxName<Integer> test = new ParallelFluxName<>(source, "foo", null); assertThat(test.parallelism()) .isEqualTo(3) .isEqualTo(source.parallelism()); } @Test public void scanOperator() throws Exception { Tuple2<String, String> tag1 = Tuples.of("foo", "oof"); Tuple2<String, String> tag2 = Tuples.of("bar", "rab"); List<Tuple2<String, String>> tags = Arrays.asList(tag1, tag2); ParallelFlux<Integer> source = Flux.range(1, 4).parallel(3); ParallelFluxName<Integer> test = new ParallelFluxName<>(source, "foo", tags); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source); assertThat(test.scan(Scannable.Attr.PREFETCH)) .isEqualTo(256) .isEqualTo(source.getPrefetch()); assertThat(test.scan(Scannable.Attr.NAME)).isEqualTo("foo"); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); final Stream<Tuple2<String, String>> scannedTags = test.scan(Scannable.Attr.TAGS); assertThat(scannedTags).isNotNull(); assertThat(scannedTags).containsExactlyInAnyOrder(tag1, tag2); } @Test public void scanOperatorNullTags() throws Exception { ParallelFlux<Integer> source = Flux.range(1, 4).parallel(3); ParallelFluxName<Integer> test = new ParallelFluxName<>(source, "foo", null); assertThat(test.scan(Scannable.Attr.TAGS)).isNull(); } }
ParallelFluxNameTest
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/internal/security/certprovider/CertificateProviderRegistry.java
{ "start": 989, "end": 3040 }
class ____ { private static CertificateProviderRegistry instance; private final LinkedHashMap<String, CertificateProviderProvider> providers = new LinkedHashMap<>(); @VisibleForTesting public CertificateProviderRegistry() { } /** Returns the singleton registry. */ public static synchronized CertificateProviderRegistry getInstance() { if (instance == null) { instance = new CertificateProviderRegistry(); // TODO(sanjaypujare): replace with Java's SPI mechanism and META-INF resource instance.register(new FileWatcherCertificateProviderProvider()); } return instance; } /** * Register a {@link CertificateProviderProvider}. * * <p>If a provider with the same {@link CertificateProviderProvider#getName name} was already * registered, this method will overwrite that provider. */ public synchronized void register(CertificateProviderProvider certificateProviderProvider) { checkNotNull(certificateProviderProvider, "certificateProviderProvider"); providers.put(certificateProviderProvider.getName(), certificateProviderProvider); } /** * Deregisters a provider. No-op if the provider is not in the registry. * * @param certificateProviderProvider the provider that was added to the registry via * {@link #register}. */ public synchronized void deregister(CertificateProviderProvider certificateProviderProvider) { checkNotNull(certificateProviderProvider, "certificateProviderProvider"); providers.remove(certificateProviderProvider.getName()); } /** * Returns the CertificateProviderProvider for the given name, or {@code null} if no * provider is found. Each provider declares its name via {@link * CertificateProviderProvider#getName}. This is an internal method of the Registry * *only* used by the framework. */ @Nullable synchronized CertificateProviderProvider getProvider(String name) { return providers.get(checkNotNull(name, "name")); } }
CertificateProviderRegistry
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/impl/converter/CoreTypeConverterRegistry.java
{ "start": 16991, "end": 24506 }
class ____ converter if (fallback.isCanPromote()) { // add it as a known type converter since we found a fallback that could do it addOrReplaceTypeConverter(tc, typeConvertible); } // return converted value return rc; } } return null; } private static Object doConvert( Class<?> type, Exchange exchange, Object value, boolean tryConvert, TypeConverter converter) { if (tryConvert) { return converter.tryConvertTo(type, exchange, value); } else { return converter.convertTo(type, exchange, value); } } public TypeConverter getTypeConverter(Class<?> toType, Class<?> fromType) { return converters.get(new TypeConvertible<>(fromType, toType)); } @Override public void addConverter(TypeConvertible<?, ?> typeConvertible, TypeConverter typeConverter) { converters.put(typeConvertible, typeConverter); } @Override public void addBulkTypeConverters(BulkTypeConverters bulkTypeConverters) { // NO-OP } public void addTypeConverter(Class<?> toType, Class<?> fromType, TypeConverter typeConverter) { LOG.trace("Adding type converter: {}", typeConverter); final TypeConvertible<?, ?> typeConvertible = new TypeConvertible<>(fromType, toType); addOrReplaceTypeConverter(typeConverter, typeConvertible); } private void addOrReplaceTypeConverter(TypeConverter typeConverter, TypeConvertible<?, ?> typeConvertible) { TypeConverter converter = converters.get(typeConvertible); if (converter == MISS_CONVERTER) { // we have previously attempted to convert but missed, so add this converter converters.put(typeConvertible, typeConverter); return; } // only override it if its different // as race conditions can lead to many threads trying to promote the same fallback converter if (typeConverter != converter) { // add the converter unless we should ignore boolean add = true; // if converter is not null then a duplicate exists if (converter != null) { add = onTypeConverterExists(typeConverter, typeConvertible, converter); } if (add) { converters.put(typeConvertible, typeConverter); } } } private boolean onTypeConverterExists( TypeConverter typeConverter, TypeConvertible<?, ?> typeConvertible, TypeConverter converter) { if (typeConverterExists == TypeConverterExists.Override) { CamelLogger logger = new CamelLogger(LOG, typeConverterExistsLoggingLevel); logger.log("Overriding type converter from: " + converter + " to: " + typeConverter); return true; } else if (typeConverterExists == TypeConverterExists.Ignore) { CamelLogger logger = new CamelLogger(LOG, typeConverterExistsLoggingLevel); logger.log("Ignoring duplicate type converter from: " + converter + " to: " + typeConverter); return false; } // we should fail throw new TypeConverterExistsException(typeConvertible.getTo(), typeConvertible.getFrom()); } public boolean removeTypeConverter(Class<?> toType, Class<?> fromType) { LOG.trace("Removing type converter from: {} to: {}", fromType, toType); final TypeConverter removed = converters.remove(new TypeConvertible<>(fromType, toType)); return removed != null; } @Override public void addTypeConverters(Object typeConverters) { throw new UnsupportedOperationException(); } public void addFallbackTypeConverter(TypeConverter typeConverter, boolean canPromote) { LOG.trace("Adding fallback type converter: {} which can promote: {}", typeConverter, canPromote); // add in top of fallback as the toString() fallback will nearly always be able to convert // the last one which is add to the FallbackTypeConverter will be called at the first place fallbackConverters.add(0, new FallbackTypeConverter(typeConverter, canPromote)); } public TypeConverter lookup(Class<?> toType, Class<?> fromType) { return doLookup(toType, fromType); } @Override public Map<Class<?>, TypeConverter> lookup(Class<?> toType) { Map<Class<?>, TypeConverter> answer = new LinkedHashMap<>(); for (var e : converters.entrySet()) { Class<?> target = e.getKey().getTo(); if (target == toType) { answer.put(e.getKey().getFrom(), e.getValue()); } } return answer; } @Deprecated(since = "4.0.0") protected TypeConverter getOrFindTypeConverter(Class<?> toType, Class<?> fromType) { TypeConvertible<?, ?> typeConvertible = new TypeConvertible<>(fromType, toType); TypeConverter converter = converters.get(typeConvertible); if (converter == null) { // converter not found, try to lookup then converter = lookup(toType, fromType); if (converter != null) { converters.put(typeConvertible, converter); } } return converter; } protected TypeConverter doLookup(Class<?> toType, Class<?> fromType) { return TypeResolverHelper.doLookup(toType, fromType, converters); } protected TypeConversionException createTypeConversionException( Exchange exchange, Class<?> type, Object value, Throwable cause) { if (cause instanceof TypeConversionException tce) { if (tce.getToType() == type) { return (TypeConversionException) cause; } } Object body; // extract the body for logging which allows to limit the message body in the exception/stacktrace // and also can be used to turn off logging sensitive message data if (exchange != null) { body = MessageHelper.extractValueForLogging(value, exchange.getIn()); } else { body = value; } return new TypeConversionException(body, type, cause); } public Statistics getStatistics() { return statistics; } public int size() { return converters.size(); } public LoggingLevel getTypeConverterExistsLoggingLevel() { return typeConverterExistsLoggingLevel; } public void setTypeConverterExistsLoggingLevel(LoggingLevel typeConverterExistsLoggingLevel) { this.typeConverterExistsLoggingLevel = typeConverterExistsLoggingLevel; } public TypeConverterExists getTypeConverterExists() { return typeConverterExists; } public void setTypeConverterExists(TypeConverterExists typeConverterExists) { this.typeConverterExists = typeConverterExists; } @Override protected void doBuild() throws Exception { super.doBuild(); CamelContextAware.trySetCamelContext(enumTypeConverter, getCamelContext()); } @Override protected void doStop() throws Exception { super.doStop(); // log utilization statistics when stopping, including mappings statistics.logMappingStatisticsMessage(converters, MISS_CONVERTER); statistics.reset(); } /** * Represents a fallback type converter */ public static
type
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/version/InheritanceVersionedParentTest.java
{ "start": 1218, "end": 2761 }
class ____ { @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final Drupelet drupelet = new Drupelet(); session.persist( drupelet ); final Raspberry raspberry = new Raspberry( 1L, "green" ); raspberry.getDrupelets().add( drupelet ); session.persist( raspberry ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> session.createQuery( "from Raspberry", Raspberry.class ) .getResultList() .forEach( r -> { r.getDrupelets().clear(); session.remove( r ); } ) ); } @Test public void testUpdateBasic(SessionFactoryScope scope) { final Long prev = scope.fromTransaction( session -> { final Raspberry raspberry = session.find( Raspberry.class, 1L ); raspberry.setMaturity( "ripe" ); return raspberry.getVersion(); } ); scope.inTransaction( session -> assertThat( session.find( Raspberry.class, 1L ).getVersion() ).isEqualTo( prev + 1 ) ); } @Test public void testUpdateAssociation(SessionFactoryScope scope) { final Long prev = scope.fromTransaction( session -> { final Raspberry raspberry = session.find( Raspberry.class, 1L ); raspberry.getDrupelets().clear(); return raspberry.getVersion(); } ); scope.inTransaction( session -> assertThat( session.find( Raspberry.class, 1L ).getVersion() ).isEqualTo( prev + 1 ) ); } @Entity( name = "VersionedFruit" ) @Inheritance( strategy = InheritanceType.JOINED ) public static abstract
InheritanceVersionedParentTest
java
elastic__elasticsearch
x-pack/plugin/security/qa/security-trial/src/javaRestTest/java/org/elasticsearch/xpack/security/apikey/ApiKeyRestIT.java
{ "start": 56906, "end": 57747 }
interface ____ Request authenticateRequest1 = new Request("GET", "/_security/_authenticate"); authenticateRequest1.setOptions( authenticateRequest1.getOptions().toBuilder().addHeader("Authorization", "ApiKey " + createResponse.evaluate("encoded")) ); final ResponseException authenticateError1 = expectThrows( ResponseException.class, () -> client().performRequest(authenticateRequest1) ); assertThat(authenticateError1.getResponse().getStatusLine().getStatusCode(), equalTo(401)); assertThat( authenticateError1.getMessage(), containsString("authentication expected API key type of [rest], but API key [" + apiKeyId + "] has type [cross_cluster]") ); // Not allowed as secondary authentication on the REST
final
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringAggregateFromWireTapTest.java
{ "start": 1056, "end": 1336 }
class ____ extends AggregateFromWireTapTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringAggregateFromWireTapTest.xml"); } }
SpringAggregateFromWireTapTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricsSystemImpl.java
{ "start": 3352, "end": 21759 }
enum ____ { NORMAL, STANDBY } private final Map<String, MetricsSourceAdapter> sources; private final Map<String, MetricsSource> allSources; private final Map<String, MetricsSinkAdapter> sinks; private final Map<String, MetricsSink> allSinks; // The callback list is used by register(Callback callback), while // the callback map is used by register(String name, String desc, T sink) private final List<Callback> callbacks; private final Map<String, Callback> namedCallbacks; private final MetricsCollectorImpl collector; private final MetricsRegistry registry = new MetricsRegistry(MS_NAME); @Metric({"Snapshot", "Snapshot stats"}) MutableStat snapshotStat; @Metric({"Publish", "Publishing stats"}) MutableStat publishStat; @Metric("Dropped updates by all sinks") MutableCounterLong droppedPubAll; private final List<MetricsTag> injectedTags; // Things that are changed by init()/start()/stop() private String prefix; private MetricsFilter sourceFilter; private MetricsConfig config; private Map<String, MetricsConfig> sourceConfigs, sinkConfigs; private boolean monitoring = false; private Timer timer; private long period; // milliseconds private long logicalTime; // number of timer invocations * period private ObjectName mbeanName; private boolean publishSelfMetrics = true; private MetricsSourceAdapter sysSource; private int refCount = 0; // for mini cluster mode /** * Construct the metrics system * @param prefix for the system */ public MetricsSystemImpl(String prefix) { this.prefix = prefix; allSources = Maps.newHashMap(); sources = Maps.newLinkedHashMap(); allSinks = Maps.newHashMap(); sinks = Maps.newLinkedHashMap(); sourceConfigs = Maps.newHashMap(); sinkConfigs = Maps.newHashMap(); callbacks = Lists.newArrayList(); namedCallbacks = Maps.newHashMap(); injectedTags = Lists.newArrayList(); collector = new MetricsCollectorImpl(); if (prefix != null) { // prefix could be null for default ctor, which requires init later initSystemMBean(); } } /** * Construct the system but not initializing (read config etc.) it. */ public MetricsSystemImpl() { this(null); } /** * Initialized the metrics system with a prefix. * @param prefix the system will look for configs with the prefix * @return the metrics system object itself */ @Override public synchronized MetricsSystem init(String prefix) { if (monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(this.prefix +" metrics system already initialized!"); return this; } this.prefix = checkNotNull(prefix, "prefix"); ++refCount; if (monitoring) { // in mini cluster mode LOG.debug("{} metrics system started (again)", prefix); return this; } switch (initMode()) { case NORMAL: try { start(); } catch (MetricsConfigException e) { // Configuration errors (e.g., typos) should not be fatal. // We can always start the metrics system later via JMX. LOG.warn("Metrics system not started: "+ e.getMessage()); LOG.debug("Stacktrace: ", e); } break; case STANDBY: LOG.debug("{} metrics system started in standby mode", prefix); } initSystemMBean(); return this; } @Override public synchronized void start() { checkNotNull(prefix, "prefix"); if (monitoring) { LOG.warn(prefix +" metrics system already started!", new MetricsException("Illegal start")); return; } for (Callback cb : callbacks) cb.preStart(); for (Callback cb : namedCallbacks.values()) cb.preStart(); configure(prefix); startTimer(); monitoring = true; LOG.debug("{} metrics system started", prefix); for (Callback cb : callbacks) cb.postStart(); for (Callback cb : namedCallbacks.values()) cb.postStart(); } @Override public synchronized void stop() { if (!monitoring && !DefaultMetricsSystem.inMiniClusterMode()) { LOG.warn(prefix +" metrics system not yet started!", new MetricsException("Illegal stop")); return; } if (!monitoring) { // in mini cluster mode LOG.debug("{} metrics system stopped (again)", prefix); return; } for (Callback cb : callbacks) cb.preStop(); for (Callback cb : namedCallbacks.values()) cb.preStop(); LOG.debug("Stopping {} metrics system...", prefix); stopTimer(); stopSources(); stopSinks(); clearConfigs(); monitoring = false; LOG.debug("{} metrics system stopped.", prefix); for (Callback cb : callbacks) cb.postStop(); for (Callback cb : namedCallbacks.values()) cb.postStop(); } @Override public synchronized <T> T register(String name, String desc, T source) { MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(source); final MetricsSource s = sb.build(); MetricsInfo si = sb.info(); String name2 = name == null ? si.name() : name; final String finalDesc = desc == null ? si.description() : desc; final String finalName = // be friendly to non-metrics tests DefaultMetricsSystem.sourceName(name2, !monitoring); allSources.put(finalName, s); LOG.debug(finalName +", "+ finalDesc); if (monitoring) { registerSource(finalName, finalDesc, s); } // We want to re-register the source to pick up new config when the // metrics system restarts. register(finalName, new AbstractCallback() { @Override public void postStart() { registerSource(finalName, finalDesc, s); } }); return source; } @Override public synchronized void unregisterSource(String name) { if (sources.containsKey(name)) { sources.get(name).stop(); sources.remove(name); } if (allSources.containsKey(name)) { allSources.remove(name); } if (namedCallbacks.containsKey(name)) { namedCallbacks.remove(name); } DefaultMetricsSystem.removeSourceName(name); } synchronized void registerSource(String name, String desc, MetricsSource source) { checkNotNull(config, "config"); MetricsConfig conf = sourceConfigs.get(name); MetricsSourceAdapter sa = new MetricsSourceAdapter(prefix, name, desc, source, injectedTags, period, conf != null ? conf : config.subset(SOURCE_KEY)); sources.put(name, sa); sa.start(); LOG.debug("Registered source "+ name); } @Override public synchronized <T extends MetricsSink> T register(final String name, final String description, final T sink) { LOG.debug(name +", "+ description); if (allSinks.containsKey(name)) { if(sinks.get(name) == null) { registerSink(name, description, sink); } else { LOG.warn("Sink "+ name +" already exists!"); } return sink; } if (config != null) { registerSink(name, description, sink); } // We want to re-register the sink to pick up new config // when the metrics system restarts. register(name, new AbstractCallback() { @Override public void postStart() { register(name, description, sink); } }); return sink; } synchronized void registerSink(String name, String desc, MetricsSink sink) { checkNotNull(config, "config"); MetricsConfig conf = sinkConfigs.get(name); MetricsSinkAdapter sa = conf != null ? newSink(name, desc, sink, conf) : newSink(name, desc, sink, config.subset(SINK_KEY)); sinks.put(name, sa); allSinks.put(name, sink); sa.start(); LOG.debug("Registered sink {}", name); } @Override public synchronized void register(final Callback callback) { callbacks.add((Callback) getProxyForCallback(callback)); } private synchronized void register(String name, final Callback callback) { namedCallbacks.put(name, (Callback) getProxyForCallback(callback)); } private Object getProxyForCallback(final Callback callback) { return Proxy.newProxyInstance(callback.getClass().getClassLoader(), new Class<?>[] { Callback.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return method.invoke(callback, args); } catch (Exception e) { // These are not considered fatal. LOG.warn("Caught exception in callback " + method.getName(), e); } return null; } }); } @Override public synchronized void startMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.startMBeans(); } } @Override public synchronized void stopMetricsMBeans() { for (MetricsSourceAdapter sa : sources.values()) { sa.stopMBeans(); } } @Override public synchronized String currentConfig() { PropertiesConfiguration saver = new PropertiesConfiguration(); StringWriter writer = new StringWriter(); saver.copy(config); try { saver.write(writer); } catch (Exception e) { throw new MetricsConfigException("Error stringify config", e); } return writer.toString(); } private synchronized void startTimer() { if (timer != null) { LOG.warn(prefix +" metrics system timer already started!"); return; } logicalTime = 0; long millis = period; timer = new Timer("Timer for '"+ prefix +"' metrics system", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { onTimerEvent(); } catch (Exception e) { LOG.warn("Error invoking metrics timer", e); } } }, millis, millis); LOG.debug("Scheduled Metric snapshot period at {} second(s).", period / 1000); } synchronized void onTimerEvent() { logicalTime += period; if (sinks.size() > 0) { publishMetrics(sampleMetrics(), false); } } /** * Requests an immediate publish of all metrics from sources to sinks. */ @Override public synchronized void publishMetricsNow() { if (sinks.size() > 0) { publishMetrics(sampleMetrics(), true); } } /** * Sample all the sources for a snapshot of metrics/tags * @return the metrics buffer containing the snapshot */ @VisibleForTesting public synchronized MetricsBuffer sampleMetrics() { collector.clear(); MetricsBufferBuilder bufferBuilder = new MetricsBufferBuilder(); for (Entry<String, MetricsSourceAdapter> entry : sources.entrySet()) { if (sourceFilter == null || sourceFilter.accepts(entry.getKey())) { snapshotMetrics(entry.getValue(), bufferBuilder); } } if (publishSelfMetrics) { snapshotMetrics(sysSource, bufferBuilder); } MetricsBuffer buffer = bufferBuilder.get(); return buffer; } private void snapshotMetrics(MetricsSourceAdapter sa, MetricsBufferBuilder bufferBuilder) { long startTime = Time.monotonicNow(); bufferBuilder.add(sa.name(), sa.getMetrics(collector, true)); collector.clear(); snapshotStat.add(Time.monotonicNow() - startTime); LOG.debug("Snapshotted source "+ sa.name()); } /** * Publish a metrics snapshot to all the sinks * @param buffer the metrics snapshot to publish * @param immediate indicates that we should publish metrics immediately * instead of using a separate thread. */ synchronized void publishMetrics(MetricsBuffer buffer, boolean immediate) { int dropped = 0; for (MetricsSinkAdapter sa : sinks.values()) { long startTime = Time.monotonicNow(); boolean result; if (immediate) { result = sa.putMetricsImmediate(buffer); } else { result = sa.putMetrics(buffer, logicalTime); } dropped += result ? 0 : 1; publishStat.add(Time.monotonicNow() - startTime); } droppedPubAll.incr(dropped); } private synchronized void stopTimer() { if (timer == null) { LOG.warn(prefix +" metrics system timer already stopped!"); return; } timer.cancel(); timer = null; } private synchronized void stopSources() { for (Entry<String, MetricsSourceAdapter> entry : sources.entrySet()) { MetricsSourceAdapter sa = entry.getValue(); LOG.debug("Stopping metrics source "+ entry.getKey() + ": class=" + sa.source().getClass()); sa.stop(); } sysSource.stop(); sources.clear(); } private synchronized void stopSinks() { for (Entry<String, MetricsSinkAdapter> entry : sinks.entrySet()) { MetricsSinkAdapter sa = entry.getValue(); LOG.debug("Stopping metrics sink "+ entry.getKey() + ": class=" + sa.sink().getClass()); sa.stop(); } sinks.clear(); } private synchronized void configure(String prefix) { config = MetricsConfig.create(prefix); configureSinks(); configureSources(); configureSystem(); } private synchronized void configureSystem() { injectedTags.add(Interns.tag(MsInfo.Hostname, getHostname())); } private synchronized void configureSinks() { sinkConfigs = config.getInstanceConfigs(SINK_KEY); long confPeriodMillis = 0; for (Entry<String, MetricsConfig> entry : sinkConfigs.entrySet()) { MetricsConfig conf = entry.getValue(); int sinkPeriod = conf.getInt(PERIOD_KEY, PERIOD_DEFAULT); // Support configuring periodMillis for testing. long sinkPeriodMillis = conf.getLong(PERIOD_MILLIS_KEY, sinkPeriod * 1000); confPeriodMillis = confPeriodMillis == 0 ? sinkPeriodMillis : ArithmeticUtils.gcd(confPeriodMillis, sinkPeriodMillis); String clsName = conf.getClassName(""); if (clsName == null) continue; // sink can be registered later on String sinkName = entry.getKey(); try { MetricsSinkAdapter sa = newSink(sinkName, conf.getString(DESC_KEY, sinkName), conf); sa.start(); sinks.put(sinkName, sa); allSinks.put(sinkName, sa.sink()); } catch (Exception e) { LOG.warn("Error creating sink '"+ sinkName +"'", e); } } long periodSec = config.getInt(PERIOD_KEY, PERIOD_DEFAULT); period = confPeriodMillis > 0 ? confPeriodMillis : config.getLong(PERIOD_MILLIS_KEY, periodSec * 1000); } static MetricsSinkAdapter newSink(String name, String desc, MetricsSink sink, MetricsConfig conf) { return new MetricsSinkAdapter(name, desc, sink, conf.getString(CONTEXT_KEY), conf.getFilter(SOURCE_FILTER_KEY), conf.getFilter(RECORD_FILTER_KEY), conf.getFilter(METRIC_FILTER_KEY), conf.getInt(PERIOD_KEY, PERIOD_DEFAULT) * 1000, conf.getInt(QUEUE_CAPACITY_KEY, QUEUE_CAPACITY_DEFAULT), conf.getInt(RETRY_DELAY_KEY, RETRY_DELAY_DEFAULT), conf.getFloat(RETRY_BACKOFF_KEY, RETRY_BACKOFF_DEFAULT), conf.getInt(RETRY_COUNT_KEY, RETRY_COUNT_DEFAULT)); } static MetricsSinkAdapter newSink(String name, String desc, MetricsConfig conf) { return newSink(name, desc, (MetricsSink) conf.getPlugin(""), conf); } private void configureSources() { sourceFilter = config.getFilter(PREFIX_DEFAULT + SOURCE_FILTER_KEY); sourceConfigs = config.getInstanceConfigs(SOURCE_KEY); registerSystemSource(); } private void clearConfigs() { sinkConfigs.clear(); sourceConfigs.clear(); injectedTags.clear(); config = null; } static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (Exception e) { LOG.error("Error getting localhost name. Using 'localhost'...", e); } return "localhost"; } private void registerSystemSource() { MetricsConfig sysConf = sourceConfigs.get(MS_NAME); sysSource = new MetricsSourceAdapter(prefix, MS_STATS_NAME, MS_STATS_DESC, MetricsAnnotations.makeSource(this), injectedTags, period, sysConf == null ? config.subset(SOURCE_KEY) : sysConf); sysSource.start(); } @Override public synchronized void getMetrics(MetricsCollector builder, boolean all) { MetricsRecordBuilder rb = builder.addRecord(MS_NAME) .addGauge(MsInfo.NumActiveSources, sources.size()) .addGauge(MsInfo.NumAllSources, allSources.size()) .addGauge(MsInfo.NumActiveSinks, sinks.size()) .addGauge(MsInfo.NumAllSinks, allSinks.size()); for (MetricsSinkAdapter sa : sinks.values()) { sa.snapshot(rb, all); } registry.snapshot(rb, all); } private void initSystemMBean() { checkNotNull(prefix, "prefix should not be null here!"); if (mbeanName == null) { mbeanName = MBeans.register(prefix, MS_CONTROL_NAME, this); } } @Override public synchronized boolean shutdown() { LOG.debug("refCount="+ refCount); if (refCount <= 0) { LOG.debug("Redundant shutdown", new Throwable()); return true; // already shutdown } if (--refCount > 0) return false; if (monitoring) { try { stop(); } catch (Exception e) { LOG.warn("Error stopping the metrics system", e); } } allSources.clear(); allSinks.clear(); callbacks.clear(); namedCallbacks.clear(); if (mbeanName != null) { MBeans.unregister(mbeanName); mbeanName = null; } LOG.debug("{} metrics system shutdown complete.", prefix); return true; } @Override public MetricsSource getSource(String name) { return allSources.get(name); } @VisibleForTesting MetricsSourceAdapter getSourceAdapter(String name) { return sources.get(name); } @VisibleForTesting public MetricsSinkAdapter getSinkAdapter(String name) { return sinks.get(name); } private InitMode initMode() { LOG.debug("from system property: "+ System.getProperty(MS_INIT_MODE_KEY)); LOG.debug("from environment variable: "+ System.getenv(MS_INIT_MODE_KEY)); String m = System.getProperty(MS_INIT_MODE_KEY); String m2 = m == null ? System.getenv(MS_INIT_MODE_KEY) : m; return InitMode.valueOf( StringUtils.toUpperCase((m2 == null ? InitMode.NORMAL.name() : m2))); } }
InitMode
java
grpc__grpc-java
api/src/context/java/io/grpc/Context.java
{ "start": 33794, "end": 34534 }
interface ____ { /** * Notifies that a context was cancelled. * * @param context the newly cancelled context. */ void cancelled(Context context); } /** * Key for indexing values stored in a context. Keys use reference equality and Context does not * provide a mechanism to loop over Keys. This means there is no way to access a Key's value from * a Context without having access to the Key instance itself. This allows strong control over * what code can get/set a key in the Context. For example, you might manage access to Key similar * to a ThreadLocal using Java visibility (private/protected). Generally Keys are stored in static * fields. */ public static final
CancellationListener
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/support/broadcast/BroadcastRequest.java
{ "start": 974, "end": 3357 }
class ____<Request extends BroadcastRequest<Request>> extends LegacyActionRequest implements IndicesRequest.Replaceable { public static final IndicesOptions DEFAULT_INDICES_OPTIONS = IndicesOptions.strictExpandOpenAndForbidClosed(); protected String[] indices; private IndicesOptions indicesOptions; @Nullable // if timeout is infinite private TimeValue timeout; public BroadcastRequest(StreamInput in) throws IOException { super(in); indices = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); timeout = in.readOptionalTimeValue(); } protected BroadcastRequest(String... indices) { this(indices, IndicesOptions.strictExpandOpenAndForbidClosed()); } protected BroadcastRequest(String[] indices, IndicesOptions indicesOptions) { this(indices, indicesOptions, null); } protected BroadcastRequest(String[] indices, IndicesOptions indicesOptions, @Nullable TimeValue timeout) { this.indices = indices; this.indicesOptions = indicesOptions; this.timeout = timeout; } @Override public String[] indices() { return indices; } @SuppressWarnings("unchecked") @Override public final Request indices(String... indices) { this.indices = indices; return (Request) this; } @Override public ActionRequestValidationException validate() { return null; } @Override public IndicesOptions indicesOptions() { return indicesOptions; } @SuppressWarnings("unchecked") public final Request indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return (Request) this; } @Nullable // if timeout is infinite public TimeValue timeout() { return timeout; } @SuppressWarnings("unchecked") public final Request timeout(@Nullable TimeValue timeout) { this.timeout = timeout; return (Request) this; } @Override public boolean includeDataStreams() { return true; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArrayNullable(indices); indicesOptions.writeIndicesOptions(out); out.writeOptionalTimeValue(timeout); } }
BroadcastRequest
java
elastic__elasticsearch
libs/native/src/main/java/org/elasticsearch/nativeaccess/NativeAccess.java
{ "start": 678, "end": 3348 }
interface ____ { /** * Get the one and only instance of {@link NativeAccess} which is specific to the running platform and JVM. */ static NativeAccess instance() { return NativeAccessHolder.INSTANCE; } /** * Determine whether this JVM is running as the root user. * * @return true if running as root, or false if unsure */ boolean definitelyRunningAsRoot(); /** * Return limits for the current process. */ ProcessLimits getProcessLimits(); /** * Attempt to lock this process's virtual memory address space into physical RAM. */ void tryLockMemory(); /** * Return whether locking memory was successful, or false otherwise. */ boolean isMemoryLocked(); /** * Attempts to install a system call filter to block process execution. */ void tryInstallExecSandbox(); /** * Return whether installing the exec system call filters was successful, and to what degree. */ ExecSandboxState getExecSandboxState(); Systemd systemd(); /** * Returns an accessor to zstd compression functions. * @return an object used to compress and decompress bytes using zstd */ Zstd getZstd(); /** * Retrieves the actual number of bytes of disk storage used to store a specified file. * * @param path the path to the file * @return an {@link OptionalLong} that contains the number of allocated bytes on disk for the file, or empty if the size is invalid */ OptionalLong allocatedSizeInBytes(Path path); void tryPreallocate(Path file, long size); /** * Returns an accessor for native functions only available on Windows, or {@code null} if not on Windows. */ default WindowsFunctions getWindowsFunctions() { return null; } /* * Returns the vector similarity functions, or an empty optional. */ Optional<VectorSimilarityFunctions> getVectorSimilarityFunctions(); /** * Creates a new {@link CloseableByteBuffer} using a shared arena. The buffer can be used * across multiple threads. * @param len the number of bytes the buffer should allocate * @return the buffer */ CloseableByteBuffer newSharedBuffer(int len); /** * Creates a new {@link CloseableByteBuffer} using a confined arena. The buffer must be * used within the same thread that it is created. * @param len the number of bytes the buffer should allocate * @return the buffer */ CloseableByteBuffer newConfinedBuffer(int len); /** * Possible stats for execution filtering. */
NativeAccess
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/converter/UriTypeConverter.java
{ "start": 1148, "end": 1688 }
class ____ { private UriTypeConverter() { // utility class } @Converter(order = 1) public static String toString(final URI value) { return value.toString(); } @Converter(order = 2) public static URI toUri(final CharSequence value) { final String stringValue = String.valueOf(value); try { return new URI(stringValue); } catch (final URISyntaxException e) { throw new TypeConversionException(value, URI.class, e); } } }
UriTypeConverter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e3/b3/DependentId.java
{ "start": 286, "end": 387 }
class ____ implements Serializable { @Column(length = 32) String name; EmployeeId empPK; }
DependentId
java
spring-projects__spring-framework
spring-core/src/testFixtures/java/org/springframework/core/testfixture/aot/generate/value/ExampleClass$$GeneratedBy.java
{ "start": 765, "end": 823 }
class ____$$GeneratedBy extends ExampleClass { }
ExampleClass
java
quarkusio__quarkus
independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/JandexUtil.java
{ "start": 1081, "end": 2585 }
class ____ { public final static DotName DOTNAME_OBJECT = DotName.createSimple(Object.class.getName()); public final static DotName DOTNAME_RECORD = DotName.createSimple("java.lang.Record"); private JandexUtil() { } public static Index createIndex(Path path) { Indexer indexer = new Indexer(); try (Stream<Path> files = Files.walk(path)) { files.forEach(new Consumer<Path>() { @Override public void accept(Path path) { if (path.toString().endsWith(".class")) { try (InputStream in = Files.newInputStream(path)) { indexer.index(in); } catch (IOException e) { throw new RuntimeException(e); } } } }); } catch (IOException e) { throw new RuntimeException(e); } return indexer.complete(); } public static IndexView createCalculatingIndex(Path path) { Index index = createIndex(path); return new CalculatingIndexView(index, Thread.currentThread().getContextClassLoader(), new ConcurrentHashMap<>()); } public static IndexView createCalculatingIndex(IndexView index) { return new CalculatingIndexView(index, Thread.currentThread().getContextClassLoader(), new ConcurrentHashMap<>()); } /** * Returns the captured generic types of an
JandexUtil
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java
{ "start": 13873, "end": 14408 }
class ____ extends PrioritizedRunnable { private final int result; private final List<Integer> results; private final CountDownLatch latch; Job(int result, Priority priority, List<Integer> results, CountDownLatch latch) { super(priority); this.result = result; this.results = results; this.latch = latch; } @Override public void run() { results.add(result); latch.countDown(); } } static
Job
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/interpretation/UUIDBasedIdInterpretationTest.java
{ "start": 3266, "end": 3335 }
class ____ { @Id @GeneratedValue private UUID id; } }
UuidIdEntity
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/embedded/EmbeddedCheckQueryExecutedTest.java
{ "start": 4687, "end": 5058 }
class ____ { private Integer id; private LegalStructure owner; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public LegalStructure getOwner() { return owner; } public void setOwner(LegalStructure owner) { this.owner = owner; } } @Embeddable public static
InternetProvider
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/ParameterHandler.java
{ "start": 666, "end": 6006 }
class ____ implements ServerRestHandler { private static final Logger log = Logger.getLogger(ParameterHandler.class); private final int index; private final String defaultValue; private final ParameterExtractor extractor; private final ParameterConverter converter; private final ParameterType parameterType; private final boolean isCollection; private final boolean isOptional; public ParameterHandler(int index, String defaultValue, ParameterExtractor extractor, ParameterConverter converter, ParameterType parameterType, boolean isCollection, boolean isOptional) { this.index = index; this.defaultValue = defaultValue; this.extractor = extractor; this.converter = converter; this.parameterType = parameterType; this.isCollection = isCollection; this.isOptional = isOptional; } @Override public void handle(ResteasyReactiveRequestContext requestContext) { // needed because user provided ParamConverter classes could use request scoped CDI beans requestContext.requireCDIRequestScope(); try { Object result = extractor.extractParameter(requestContext); if (result instanceof ParameterExtractor.ParameterCallback) { requestContext.suspend(); ((ParameterExtractor.ParameterCallback) result).setListener(new BiConsumer<Object, Throwable>() { @Override public void accept(Object o, Throwable throwable) { if (throwable != null) { requestContext.resume(throwable); } else { handleResult(o, requestContext, true); } } }); } else { handleResult(result, requestContext, false); } } catch (Exception e) { log.debug("Error occurred during parameter extraction", e); if (e instanceof WebApplicationException) { throw e; } else { throw new WebApplicationException(e, 400); } } } private void handleResult(Object result, ResteasyReactiveRequestContext requestContext, boolean needsResume) { // empty collections should still get their default value if (defaultValue != null && (result == null || (isCollection && ((Collection) result).isEmpty()))) { result = defaultValue; } Throwable toThrow = null; if (converter != null && ((result != null) || isOptional)) { // spec says: /* * 3.2 Fields and Bean Properties * if the field or property is annotated with @MatrixParam, @QueryParam or @PathParam then an implementation * MUST generate an instance of NotFoundException (404 status) that wraps the thrown exception and no * entity; if the field or property is annotated with @HeaderParam or @CookieParam then an implementation * MUST generate an instance of BadRequestException (400 status) that wraps the thrown exception and * no entity. * 3.3.2 Parameters * Exceptions thrown during construction of @FormParam annotated parameter values are treated the same as if * the parameter were annotated with @HeaderParam. */ switch (parameterType) { case COOKIE: case HEADER: case FORM: try { result = converter.convert(result); } catch (WebApplicationException x) { toThrow = x; } catch (Throwable x) { log.debug("Unable to handle parameter", x); toThrow = new BadRequestException(x); } break; case MATRIX: case PATH: case QUERY: try { result = converter.convert(result); } catch (WebApplicationException x) { toThrow = x; } catch (Throwable x) { log.debug("Unable to handle parameter", x); toThrow = new NotFoundException(x); } break; default: try { result = converter.convert(result); } catch (Throwable x) { log.debug("Unable to handle parameter", x); toThrow = x; } break; } } if (toThrow == null) { requestContext.getParameters()[index] = result; } if (needsResume) { if (toThrow == null) { requestContext.resume(); } else { requestContext.resume(toThrow); } } else if (toThrow != null) { throw sneakyThrow(toThrow); } } public static <E extends Throwable> RuntimeException sneakyThrow(Throwable e) throws E { throw (E) e; } }
ParameterHandler
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/merge/PropertyMergeTest.java
{ "start": 981, "end": 1112 }
class ____ { public AB loc = new AB(1, 2); } // another variant where all we got is a getter static
NonMergeConfig
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/BaseAssertionsTest.java
{ "start": 1140, "end": 5270 }
class ____ { { setRemoveAssertJRelatedElementsFromStackTrace(false); } private static final int ACCESS_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; static final Comparator<Method> IGNORING_DECLARING_CLASS_AND_METHOD_NAME = internalMethodComparator(false, true); static final Comparator<Method> IGNORING_DECLARING_CLASS_AND_RETURN_TYPE = internalMethodComparator(true, false); static final Comparator<Method> IGNORING_DECLARING_CLASS_ONLY = internalMethodComparator(false, false); static final Comparator<Method> IGNORING_DECLARING_CLASS_RETURN_TYPE_AND_METHOD_NAME = internalMethodComparator(true, true); // Object is ignored because of the AssertProvider static final Class<?>[] SPECIAL_IGNORED_RETURN_TYPES = array(AssertDelegateTarget.class, FactoryBasedNavigableListAssert.class, FactoryBasedNavigableIterableAssert.class, Object.class); static Method[] findMethodsWithName(Class<?> clazz, String name, Class<?>... ignoredReturnTypes) { Set<Class<?>> ignoredReturnTypesSet = newLinkedHashSet(ignoredReturnTypes); return Arrays.stream(clazz.getMethods()) .filter(method -> method.getName().equals(name)) .filter(method -> !ignoredReturnTypesSet.contains(method.getReturnType())) .toArray(Method[]::new); } private static Comparator<Method> internalMethodComparator(final boolean ignoreReturnType, final boolean ignoreMethodName) { return (method1, method2) -> { // the methods should be with the same access type // static vs not static is not important Soft vs Not Soft assertions boolean equal = (ACCESS_MODIFIERS & method1.getModifiers() & method2.getModifiers()) != 0; equal = equal && (ignoreReturnType || sameGenericReturnType(method1, method2)); equal = equal && (ignoreMethodName || sameMethodName(method1, method2)); equal = equal && sameGenericParameterTypes(method1, method2); return equal ? 0 : 1; }; } /** * Checks if the methods have same generic parameter types. * * @param method1 the first method * @param method2 the second method * @return {@code true} if the methods have same generic parameters, {@code false} otherwise */ private static boolean sameGenericParameterTypes(Method method1, Method method2) { Type[] pTypes1 = method1.getGenericParameterTypes(); Type[] pTypes2 = method2.getGenericParameterTypes(); if (pTypes1.length != pTypes2.length) { return false; } for (int i = 0; i < pTypes1.length; i++) { if (!sameType(pTypes1[i], pTypes2[i])) { return false; } } return true; } /** * Checks if the methods have the same name. * * @param method1 the first method * @param method2 the second method * @return {@code true} if the methods have the same name, {@code false} otherwise */ private static boolean sameMethodName(Method method1, Method method2) { return method1.getName().equals(method2.getName()); } /** * Checks if the methods have same generic return type. * * @param method1 the first method * @param method2 the second method * @return {@code true} if the methods have same generic return type, {@code false} otherwise. */ private static boolean sameGenericReturnType(Method method1, Method method2) { return sameType(method1.getGenericReturnType(), method2.getGenericReturnType()); } /** * Checks if the types are equal. * * @param type1 the first type * @param type2 the second type * @return {@code true} if the types are equal, {@code false} otherwise */ private static boolean sameType(Type type1, Type type2) { return canonize(type1).equals(canonize(type2)); } }
BaseAssertionsTest
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/FlinkFilterJoinRule.java
{ "start": 18965, "end": 19872 }
class ____ extends FlinkFilterJoinRule<FlinkJoinConditionPushRule.FlinkFilterJoinRuleConfig> { /** Creates a JoinConditionPushRule. */ protected FlinkJoinConditionPushRule(FlinkFilterJoinRuleConfig config) { super(config); } @Override public boolean matches(RelOptRuleCall call) { Join join = call.rel(0); return !isEventTimeTemporalJoin(join.getCondition()) && super.matches(call); } @Override public void onMatch(RelOptRuleCall call) { Join join = call.rel(0); perform(call, null, join); } /** Rule configuration. */ @Value.Immutable(singleton = false) @Value.Style( get = {"is*", "get*"}, init = "with*", defaults = @Value.Immutable(copy = false)) public
FlinkJoinConditionPushRule
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/helper/JsonCustomResourceTypeTestcase.java
{ "start": 1654, "end": 3248 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(JsonCustomResourceTypeTestcase.class); private final WebTarget path; private final BufferedClientResponse response; private final JSONObject parsedResponse; public JsonCustomResourceTypeTestcase(WebTarget path, BufferedClientResponse response) throws JSONException { this.path = path; verifyStatus(response); this.response = response; String entity = response.getEntity(String.class); this.parsedResponse = new JSONObject(entity); } private void verifyStatus(BufferedClientResponse response) { String responseStr = response.getEntity(String.class); String exceptMessgae = String.format("HTTP status should be 200, " + "status info:{} response as string:{}", response.getStatusInfo(), responseStr); assertEquals(200, response.getStatus(), exceptMessgae); } public void verify(Consumer<JSONObject> verifier) { assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getType().toString()); logResponse(); String responseStr = response.getEntity(String.class); if (responseStr == null || responseStr.isEmpty()) { throw new IllegalStateException("Response is null or empty!"); } verifier.accept(parsedResponse); } private void logResponse() { String responseStr = response.getEntity(String.class); LOG.info("Raw response from service URL {}: {}", path, responseStr); LOG.info("Parsed response from service URL {}: {}", path, parsedResponse); } }
JsonCustomResourceTypeTestcase
java
google__auto
value/src/main/java/com/google/auto/value/processor/AutoAnnotationProcessor.java
{ "start": 19676, "end": 22955 }
class ____ acquire an implementation of the new member method * which just returns the default value. The {@code serialVersionUID} will not change, which makes * sense because the instance fields haven't changed, and instances that were serialized before * the new member was added should deserialize fine. On the other hand, if you then add a * parameter to the {@code @AutoAnnotation} method for the new member, the implementation class * will acquire a new instance field, and we will compute a different {@code serialVersionUID}. * That's because an instance serialized before that change would not have a value for the new * instance field, which would end up zero or null. Users don't expect annotation methods to * return null so that would be bad. * * <p>We could instead add a {@code readObject(ObjectInputStream)} method that would check that * all of the instance fields are really present in the deserialized instance, and perhaps replace * them with their default values from the annotation if not. That seems a lot more complicated * than is justified, though, especially since the instance fields are final and would have to be * set in the deserialized object through reflection. */ private static long computeSerialVersionUid( ImmutableMap<String, Member> members, ImmutableMap<String, Parameter> parameters) { // TypeMirror.toString() isn't fully specified so it could potentially differ between // implementations. Our member.getType() string comes from TypeEncoder and is predictable, but // it includes `...` markers around fully-qualified type names, which are used to handle // imports. So we remove those markers below. String namesAndTypesString = members.entrySet().stream() .filter(e -> parameters.containsKey(e.getKey())) .map(e -> immutableEntry(e.getKey(), e.getValue().getType().replace("`", ""))) .sorted(comparing(Map.Entry::getKey)) .map(e -> e.getKey() + ":" + e.getValue()) .collect(joining(";")); return Hashing.murmur3_128().hashUnencodedChars(namesAndTypesString).asLong(); } private void writeSourceFile(String className, String text, TypeElement originatingType) { try { JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(className, originatingType); try (Writer writer = sourceFile.openWriter()) { writer.write(text); } } catch (IOException e) { // This should really be an error, but we make it a warning in the hope of resisting Eclipse // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=367599. If that bug manifests, we may get // invoked more than once for the same file, so ignoring the ability to overwrite it is the // right thing to do. If we are unable to write for some other reason, we should get a compile // error later because user code will have a reference to the code we were supposed to // generate (new AutoValue_Foo() or whatever) and that reference will be undefined. processingEnv .getMessager() .printMessage( Diagnostic.Kind.WARNING, "Could not write generated class " + className + ": " + e); } } public static
will
java
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/json/TestMaxErrorSize.java
{ "start": 317, "end": 3168 }
class ____ extends tools.jackson.core.unittest.JacksonCoreTestBase { private final static int EXPECTED_MAX_TOKEN_LEN = 256; // ParserBase.MAX_ERROR_TOKEN_LENGTH private final JsonFactory JSON_F = newStreamFactory(); @Test void longErrorMessage() throws Exception { _testLongErrorMessage(MODE_INPUT_STREAM); _testLongErrorMessage(MODE_INPUT_STREAM_THROTTLED); } @Test void longErrorMessageReader() throws Exception { _testLongErrorMessage(MODE_READER); } private void _testLongErrorMessage(int mode) { final String DOC = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; assertTrue(DOC.length() > 256); JsonParser jp = createParser(JSON_F, mode, DOC); try { jp.nextToken(); fail("Expected an exception for unrecognized token"); } catch (StreamReadException jpe) { String msg = jpe.getMessage(); final String expectedPrefix = "Unrecognized token '"; final String expectedSuffix = "...': was expecting"; verifyException(jpe, expectedPrefix); verifyException(jpe, expectedSuffix); assertTrue(msg.contains(expectedSuffix)); int tokenLen = msg.indexOf (expectedSuffix) - expectedPrefix.length(); assertEquals(EXPECTED_MAX_TOKEN_LEN, tokenLen); } jp.close(); } @Test void shortErrorMessage() throws Exception { _testShortErrorMessage(MODE_INPUT_STREAM); _testShortErrorMessage(MODE_INPUT_STREAM_THROTTLED); _testShortErrorMessage(MODE_READER); } public void _testShortErrorMessage(int mode) { final String DOC = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; assertTrue(DOC.length() < 256); JsonParser p = createParser(JSON_F, mode, DOC); try { p.nextToken(); fail("Expected an exception for unrecognized token"); } catch (StreamReadException jpe) { String msg = jpe.getMessage(); final String expectedPrefix = "Unrecognized token '"; final String expectedSuffix = "': was expecting"; verifyException(jpe, expectedPrefix); verifyException(jpe, expectedSuffix); int tokenLen = msg.indexOf(expectedSuffix) - expectedPrefix.length(); assertEquals(DOC.length(), tokenLen); } p.close(); } }
TestMaxErrorSize
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/processor/internals/InternalTopicManagerTest.java
{ "start": 101286, "end": 101511 }
class ____ extends DescribeTopicsResult { MockDescribeTopicsResult(final Map<String, KafkaFuture<TopicDescription>> futures) { super(null, futures); } } private static
MockDescribeTopicsResult
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/discovery/DiscoverySelectorResolverTests.java
{ "start": 37659, "end": 37784 }
class ____ { @Test void test3() { } @Test void test4() { } } @SuppressWarnings("NewClassNamingConvention")
YourTestClass
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
{ "start": 16013, "end": 18543 }
class ____ { // empty } assertEquals("X", ClassUtils.getCanonicalName(new Object() { // empty }.getClass(), "X")); assertEquals("X", ClassUtils.getCanonicalName(Named.class, "X")); assertEquals("org.apache.commons.lang3.ClassUtilsTest.Inner", ClassUtils.getCanonicalName(Inner.class, "X")); assertEquals("X", ClassUtils.getCanonicalName((Object) null, "X")); assertEquals(OBJECT_CANONICAL_NAME, ClassUtils.getCanonicalName(new Object())); } @Test void test_getClass() { // assertEquals("org.apache.commons.lang3.ClassUtils", ClassUtils.getName(ClassLoader.class, "@")); } @Test void test_getName_Class() { assertEquals("org.apache.commons.lang3.ClassUtils", ClassUtils.getName(ClassUtils.class)); assertEquals("java.util.Map$Entry", ClassUtils.getName(Map.Entry.class)); assertEquals("", ClassUtils.getName((Class<?>) null)); assertEquals("[Ljava.lang.String;", ClassUtils.getName(String[].class)); assertEquals("[Ljava.util.Map$Entry;", ClassUtils.getName(Map.Entry[].class)); // Primitives assertEquals("boolean", ClassUtils.getName(boolean.class)); assertEquals("byte", ClassUtils.getName(byte.class)); assertEquals("char", ClassUtils.getName(char.class)); assertEquals("short", ClassUtils.getName(short.class)); assertEquals("int", ClassUtils.getName(int.class)); assertEquals("long", ClassUtils.getName(long.class)); assertEquals("float", ClassUtils.getName(float.class)); assertEquals("double", ClassUtils.getName(double.class)); // Primitive Arrays assertEquals("[Z", ClassUtils.getName(boolean[].class)); assertEquals("[B", ClassUtils.getName(byte[].class)); assertEquals("[C", ClassUtils.getName(char[].class)); assertEquals("[S", ClassUtils.getName(short[].class)); assertEquals("[I", ClassUtils.getName(int[].class)); assertEquals("[J", ClassUtils.getName(long[].class)); assertEquals("[F", ClassUtils.getName(float[].class)); assertEquals("[D", ClassUtils.getName(double[].class)); // Arrays of arrays of ... assertEquals("[[Ljava.lang.String;", ClassUtils.getName(String[][].class)); assertEquals("[[[Ljava.lang.String;", ClassUtils.getName(String[][][].class)); assertEquals("[[[[Ljava.lang.String;", ClassUtils.getName(String[][][][].class)); // Inner types final
Named
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/cluster/api/async/NodeSelectionListAsyncCommands.java
{ "start": 1252, "end": 16974 }
interface ____<K, V> { /** * Atomically returns and removes the first/last element (head/tail depending on the where from argument) of the list stored * at source, and pushes the element at the first/last element (head/tail depending on the whereto argument) of the list * stored at destination. When source is empty, Redis will block the connection until another client pushes to it or until * timeout is reached. * * @param source the source key. * @param destination the destination type: key. * @param args command arguments to configure source and destination directions. * @param timeout the timeout in seconds. * @return V bulk-string-reply the element being popped and pushed. * @since 6.1 */ AsyncExecutions<V> blmove(K source, K destination, LMoveArgs args, long timeout); /** * Atomically returns and removes the first/last element (head/tail depending on the where from argument) of the list stored * at source, and pushes the element at the first/last element (head/tail depending on the whereto argument) of the list * stored at destination. When source is empty, Redis will block the connection until another client pushes to it or until * timeout is reached. * * @param source the source key. * @param destination the destination type: key. * @param args command arguments to configure source and destination directions. * @param timeout the timeout in seconds. * @return V bulk-string-reply the element being popped and pushed. * @since 6.1.3 */ AsyncExecutions<V> blmove(K source, K destination, LMoveArgs args, double timeout); /** * Remove and get the first/last elements in a list, or block until one is available. * * @param timeout the timeout in seconds. * @param args the additional command arguments. * @param keys the keys. * @return KeyValue&lt;K,V&gt; array-reply specifically. {@code null} when {@code key} does not exist or the timeout was * exceeded. * @since 6.2 */ AsyncExecutions<KeyValue<K, List<V>>> blmpop(long timeout, LMPopArgs args, K... keys); /** * Remove and get the first/last elements in a list, or block until one is available. * * @param timeout the timeout in seconds. * @param args the additional command arguments. * @param keys the keys. * @return KeyValue&lt;K,V&gt; array-reply specifically. {@code null} when {@code key} does not exist or the timeout was * exceeded. * @since 6.2 */ AsyncExecutions<KeyValue<K, List<V>>> blmpop(double timeout, LMPopArgs args, K... keys); /** * Remove and get the first element in a list, or block until one is available. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue&lt;K,V&gt; array-reply specifically: * * A {@code null} multi-bulk when no element could be popped and the timeout expired. A two-element multi-bulk with * the first element being the name of the key where an element was popped and the second element being the value of * the popped element. */ AsyncExecutions<KeyValue<K, V>> blpop(long timeout, K... keys); /** * Remove and get the first element in a list, or block until one is available. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue&lt;K,V&gt; array-reply specifically: * * A {@code null} multi-bulk when no element could be popped and the timeout expired. A two-element multi-bulk with * the first element being the name of the key where an element was popped and the second element being the value of * the popped element. * @since 6.1.3 */ AsyncExecutions<KeyValue<K, V>> blpop(double timeout, K... keys); /** * Remove and get the last element in a list, or block until one is available. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue&lt;K,V&gt; array-reply specifically: * * A {@code null} multi-bulk when no element could be popped and the timeout expired. A two-element multi-bulk with * the first element being the name of the key where an element was popped and the second element being the value of * the popped element. */ AsyncExecutions<KeyValue<K, V>> brpop(long timeout, K... keys); /** * Remove and get the last element in a list, or block until one is available. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue&lt;K,V&gt; array-reply specifically: * * A {@code null} multi-bulk when no element could be popped and the timeout expired. A two-element multi-bulk with * the first element being the name of the key where an element was popped and the second element being the value of * the popped element. * @since 6.1.3 */ AsyncExecutions<KeyValue<K, V>> brpop(double timeout, K... keys); /** * Pop a value from a list, push it to another list and return it; or block until one is available. * * @param timeout the timeout in seconds. * @param source the source key. * @param destination the destination type: key. * @return V bulk-string-reply the element being popped from {@code source} and pushed to {@code destination}. If * {@code timeout} is reached, a. */ AsyncExecutions<V> brpoplpush(long timeout, K source, K destination); /** * Pop a value from a list, push it to another list and return it; or block until one is available. * * @param timeout the timeout in seconds. * @param source the source key. * @param destination the destination type: key. * @return V bulk-string-reply the element being popped from {@code source} and pushed to {@code destination}. If * {@code timeout} is reached, a. * @since 6.1.3 */ AsyncExecutions<V> brpoplpush(double timeout, K source, K destination); /** * Get an element from a list by its index. * * @param key the key. * @param index the index type: long. * @return V bulk-string-reply the requested element, or {@code null} when {@code index} is out of range. */ AsyncExecutions<V> lindex(K key, long index); /** * Insert an element before or after another element in a list. * * @param key the key. * @param before the before. * @param pivot the pivot. * @param value the value. * @return Long integer-reply the length of the list after the insert operation, or {@code -1} when the value {@code pivot} * was not found. */ AsyncExecutions<Long> linsert(K key, boolean before, V pivot, V value); /** * Get the length of a list. * * @param key the key. * @return Long integer-reply the length of the list at {@code key}. */ AsyncExecutions<Long> llen(K key); /** * Atomically returns and removes the first/last element (head/tail depending on the where from argument) of the list stored * at source, and pushes the element at the first/last element (head/tail depending on the whereto argument) of the list * stored at destination. * * @param source the source key. * @param destination the destination type: key. * @param args command arguments to configure source and destination directions. * @return V bulk-string-reply the element being popped and pushed. * @since 6.1 */ AsyncExecutions<V> lmove(K source, K destination, LMoveArgs args); /** * Remove and get the first/last elements in a list. * * @param args the additional command arguments. * @param keys the keys. * @return KeyValue&lt;K,V&gt; array-reply specifically. {@code null} when {@code key} does not exist. * @since 6.2 */ AsyncExecutions<KeyValue<K, List<V>>> lmpop(LMPopArgs args, K... keys); /** * Remove and get the first element in a list. * * @param key the key. * @return V bulk-string-reply the value of the first element, or {@code null} when {@code key} does not exist. */ AsyncExecutions<V> lpop(K key); /** * Remove and get the first {@code count} elements in a list. * * @param key the key. * @param count the number of elements to return. * @return @return List&lt;V&gt; array-reply list of the first {@code count} elements, or {@code null} when {@code key} does * not exist. * @since 6.1 */ AsyncExecutions<List<V>> lpop(K key, long count); /** * Return the index of matching elements inside a Redis list. By default, when no options are given, it will scan the list * from head to tail, looking for the first match of "element". If the element is found, its index (the zero-based position * in the list) is returned. Otherwise, if no match is found, {@code null} is returned. The returned elements indexes are * always referring to what {@link #lindex(java.lang.Object, long)} would return. So first element from head is {@code 0}, * and so forth. * * @param key the key. * @param value the element to search for. * @return V integer-reply representing the matching element, or null if there is no match. * @since 5.3.2 */ AsyncExecutions<Long> lpos(K key, V value); /** * Return the index of matching elements inside a Redis list. By default, when no options are given, it will scan the list * from head to tail, looking for the first match of "element". If the element is found, its index (the zero-based position * in the list) is returned. Otherwise, if no match is found, {@code null} is returned. The returned elements indexes are * always referring to what {@link #lindex(java.lang.Object, long)} would return. So first element from head is {@code 0}, * and so forth. * * @param key the key. * @param value the element to search for. * @param args command arguments to configure{@code FIRST} and {@code MAXLEN} options. * @return V integer-reply representing the matching element, or null if there is no match. * @since 5.3.2 */ AsyncExecutions<Long> lpos(K key, V value, LPosArgs args); /** * Return the index of matching elements inside a Redis list using the {@code COUNT} option. By default, when no options are * given, it will scan the list from head to tail, looking for the first match of "element". The returned elements indexes * are always referring to what {@link #lindex(java.lang.Object, long)} would return. So first element from head is * {@code 0}, and so forth. * * @param key the key. * @param value the element to search for. * @param count limit the number of matches. * @return V integer-reply representing the matching elements, or empty if there is no match. * @since 5.3.2 */ AsyncExecutions<List<Long>> lpos(K key, V value, int count); /** * Return the index of matching elements inside a Redis list using the {@code COUNT} option. By default, when no options are * given, it will scan the list from head to tail, looking for the first match of "element". The returned elements indexes * are always referring to what {@link #lindex(java.lang.Object, long)} would return. So first element from head is * {@code 0}, and so forth. * * @param key the key. * @param value the element to search for. * @param count limit the number of matches. * @param args command arguments to configure{@code FIRST} and {@code MAXLEN} options. * @return V integer-reply representing the matching elements, or empty if there is no match. * @since 5.3.2 */ AsyncExecutions<List<Long>> lpos(K key, V value, int count, LPosArgs args); /** * Prepend one or multiple values to a list. * * @param key the key. * @param values the value. * @return Long integer-reply the length of the list after the push operations. */ AsyncExecutions<Long> lpush(K key, V... values); /** * Prepend values to a list, only if the list exists. * * @param key the key. * @param values the values. * @return Long integer-reply the length of the list after the push operation. */ AsyncExecutions<Long> lpushx(K key, V... values); /** * Get a range of elements from a list. * * @param key the key. * @param start the start type: long. * @param stop the stop type: long. * @return List&lt;V&gt; array-reply list of elements in the specified range. */ AsyncExecutions<List<V>> lrange(K key, long start, long stop); /** * Get a range of elements from a list. * * @param channel the channel. * @param key the key. * @param start the start type: long. * @param stop the stop type: long. * @return Long count of elements in the specified range. */ AsyncExecutions<Long> lrange(ValueStreamingChannel<V> channel, K key, long start, long stop); /** * Remove elements from a list. * * @param key the key. * @param count the count type: long. * @param value the value. * @return Long integer-reply the number of removed elements. */ AsyncExecutions<Long> lrem(K key, long count, V value); /** * Set the value of an element in a list by its index. * * @param key the key. * @param index the index type: long. * @param value the value. * @return String simple-string-reply. */ AsyncExecutions<String> lset(K key, long index, V value); /** * Trim a list to the specified range. * * @param key the key. * @param start the start type: long. * @param stop the stop type: long. * @return String simple-string-reply. */ AsyncExecutions<String> ltrim(K key, long start, long stop); /** * Remove and get the last element in a list. * * @param key the key. * @return V bulk-string-reply the value of the last element, or {@code null} when {@code key} does not exist. */ AsyncExecutions<V> rpop(K key); /** * Remove and get the last {@code count} elements in a list. * * @param key the key. * @param count the number of elements to return. * @return List&lt;V&gt; array-reply list of the last {@code count} elements, or {@code null} when {@code key} does not * exist. * @since 6.1 */ AsyncExecutions<List<V>> rpop(K key, long count); /** * Remove the last element in a list, append it to another list and return it. * * @param source the source key. * @param destination the destination type: key. * @return V bulk-string-reply the element being popped and pushed. */ AsyncExecutions<V> rpoplpush(K source, K destination); /** * Append one or multiple values to a list. * * @param key the key. * @param values the value. * @return Long integer-reply the length of the list after the push operation. */ AsyncExecutions<Long> rpush(K key, V... values); /** * Append values to a list, only if the list exists. * * @param key the key. * @param values the values. * @return Long integer-reply the length of the list after the push operation. */ AsyncExecutions<Long> rpushx(K key, V... values); }
NodeSelectionListAsyncCommands
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/timeline/TimelineEntity.java
{ "start": 1572, "end": 2269 }
class ____ contains the the meta information of some conceptual entity * and its related events. The entity can be an application, an application * attempt, a container or whatever the user-defined object. * </p> * * <p> * Primary filters will be used to index the entities in * <code>TimelineStore</code>, such that users should carefully choose the * information they want to store as the primary filters. The remaining can be * stored as other information. * </p> */ @XmlRootElement(name = "entity") @XmlAccessorType(XmlAccessType.NONE) @Public @Evolving @JsonIgnoreProperties(ignoreUnknown = true, value = {"relatedEntitiesJAXB", "primaryFiltersJAXB", "otherInfoJAXB"}) public
that
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/iterative/event/IterationEventWithAggregators.java
{ "start": 3942, "end": 6404 }
class ____ not a value sublass."); } try (DataInputViewStreamWrapper in = new DataInputViewStreamWrapper( new ByteArrayInputStream(serializedData[i]))) { v.read(in); } catch (IOException e) { throw new RuntimeException( "Error while deserializing the user-defined aggregate class.", e); } aggregates[i] = v; } } return this.aggregates; } @Override public void write(DataOutputView out) throws IOException { int num = this.aggNames.length; out.writeInt(num); ByteArrayOutputStream boas = new ByteArrayOutputStream(); DataOutputViewStreamWrapper bufferStream = new DataOutputViewStreamWrapper(boas); for (int i = 0; i < num; i++) { // aggregator name and type out.writeUTF(this.aggNames[i]); out.writeUTF(this.aggregates[i].getClass().getName()); // aggregator value indirect as a byte array this.aggregates[i].write(bufferStream); bufferStream.flush(); byte[] bytes = boas.toByteArray(); out.writeInt(bytes.length); out.write(bytes); boas.reset(); } bufferStream.close(); boas.close(); } @Override public void read(DataInputView in) throws IOException { int num = in.readInt(); if (num == 0) { this.aggNames = NO_STRINGS; this.aggregates = NO_VALUES; } else { if (this.aggNames == null || num > this.aggNames.length) { this.aggNames = new String[num]; } if (this.classNames == null || num > this.classNames.length) { this.classNames = new String[num]; } if (this.serializedData == null || num > this.serializedData.length) { this.serializedData = new byte[num][]; } for (int i = 0; i < num; i++) { this.aggNames[i] = in.readUTF(); this.classNames[i] = in.readUTF(); int len = in.readInt(); byte[] data = new byte[len]; this.serializedData[i] = data; in.readFully(data); } this.aggregates = null; } } }
is
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/AsyncVectorSearchFunction.java
{ "start": 1141, "end": 1322 }
class ____ {@link AsyncTableFunction} for asynchronous vector search. * * <p>The output type of this table function is fixed as {@link RowData}. */ @PublicEvolving public abstract
of
java
apache__camel
core/camel-console/src/main/java/org/apache/camel/impl/console/ProcessorDevConsole.java
{ "start": 1893, "end": 17749 }
class ____ extends AbstractDevConsole { private static final Logger LOG = LoggerFactory.getLogger(ProcessorDevConsole.class); /** * Filters the processors matching by processor id, route id, or route group, and source location */ public static final String FILTER = "filter"; /** * Limits the number of entries displayed */ public static final String LIMIT = "limit"; /** * Action to perform such as start,stop,suspend,resume,enable,disable on one or more processors */ public static final String ACTION = "action"; public ProcessorDevConsole() { super("camel", "processor", "Processor", "Processor information"); } @Override protected String doCallText(Map<String, Object> options) { String action = (String) options.get(ACTION); String filter = (String) options.get(FILTER); String limit = (String) options.get(LIMIT); final int max = limit == null ? Integer.MAX_VALUE : Integer.parseInt(limit); if (action != null) { doAction(getCamelContext(), action, filter); return ""; } ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class); final StringBuilder sb = new StringBuilder(); final AtomicInteger counter = new AtomicInteger(); for (Route r : getCamelContext().getRoutes()) { ManagedRouteMBean mrb = mcc.getManagedRoute(r.getRouteId()); includeProcessorsText(mrb, sb, filter, max, counter); sb.append("\n"); sb.append("\n"); } return sb.toString(); } private void includeProcessorsText(ManagedRouteMBean mrb, StringBuilder sb, String filter, int max, AtomicInteger counter) { ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class); Collection<String> ids; try { ids = mrb.processorIds(); } catch (Exception e) { return; } // sort by index List<ManagedProcessorMBean> mps = new ArrayList<>(); for (String id : ids) { ManagedProcessorMBean mp = mcc.getManagedProcessor(id); if (mp != null && accept(mp, filter)) { mps.add(mp); } } // sort processors by index mps.sort(Comparator.comparingInt(ManagedProcessorMBean::getIndex)); includeProcessorsText(getCamelContext(), sb, max, counter, mps); } public static void includeProcessorsText( CamelContext camelContext, StringBuilder sb, int max, AtomicInteger counter, List<ManagedProcessorMBean> mps) { for (ManagedProcessorMBean mp : mps) { if (counter != null && counter.incrementAndGet() > max) { return; } sb.append("\n"); sb.append(String.format("\n Route Id: %s", mp.getRouteId())); sb.append(String.format("\n Id: %s", mp.getProcessorId())); if (mp.getNodePrefixId() != null) { sb.append(String.format("\n Node Prefix Id: %s", mp.getNodePrefixId())); } if (mp.getDescription() != null) { sb.append(String.format("\n Description: %s", mp.getDescription())); } if (mp.getNote() != null) { sb.append(String.format("\n Note: %s", mp.getNote())); } sb.append(String.format("\n Processor: %s", mp.getProcessorName())); if (mp.getStepId() != null) { sb.append(String.format("\n Step Id: %s", mp.getStepId())); } sb.append(String.format("\n Level: %d", mp.getLevel())); if (mp.getSourceLocation() != null) { String loc = mp.getSourceLocation(); if (mp.getSourceLineNumber() != null) { loc += ":" + mp.getSourceLineNumber(); } sb.append(String.format("\n Source: %s", loc)); } // processors which can send to a destination (such as to/toD/poll etc) String destination = getDestination(camelContext, mp); if (destination != null) { sb.append(String.format("\n Uri: %s", destination)); } sb.append(String.format("\n State: %s", mp.getState())); sb.append(String.format("\n Disabled: %s", mp.getDisabled())); sb.append(String.format("\n Total: %s", mp.getExchangesTotal())); sb.append(String.format("\n Failed: %s", mp.getExchangesFailed())); sb.append(String.format("\n Inflight: %s", mp.getExchangesInflight())); long idle = mp.getIdleSince(); if (idle > 0) { sb.append(String.format("\n Idle Since: %s", TimeUtils.printDuration(idle))); } else { sb.append(String.format("\n Idle Since: %s", "")); } sb.append(String.format("\n Mean Time: %s", TimeUtils.printDuration(mp.getMeanProcessingTime(), true))); sb.append(String.format("\n Max Time: %s", TimeUtils.printDuration(mp.getMaxProcessingTime(), true))); sb.append(String.format("\n Min Time: %s", TimeUtils.printDuration(mp.getMinProcessingTime(), true))); if (mp.getExchangesTotal() > 0) { sb.append(String.format("\n Last Time: %s", TimeUtils.printDuration(mp.getLastProcessingTime(), true))); sb.append( String.format("\n Delta Time: %s", TimeUtils.printDuration(mp.getDeltaProcessingTime(), true))); } Date last = mp.getLastExchangeCompletedTimestamp(); if (last != null) { String ago = TimeUtils.printSince(last.getTime()); sb.append(String.format("\n Since Last Completed: %s", ago)); } last = mp.getLastExchangeFailureTimestamp(); if (last != null) { String ago = TimeUtils.printSince(last.getTime()); sb.append(String.format("\n Since Last Failed: %s", ago)); } } } @Override protected JsonObject doCallJson(Map<String, Object> options) { String action = (String) options.get(ACTION); String filter = (String) options.get(FILTER); String limit = (String) options.get(LIMIT); final int max = limit == null ? Integer.MAX_VALUE : Integer.parseInt(limit); if (action != null) { doAction(getCamelContext(), action, filter); return new JsonObject(); } JsonObject root = new JsonObject(); JsonArray arr = new JsonArray(); ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class); for (Route r : getCamelContext().getRoutes()) { ManagedRouteMBean mrb = mcc.getManagedRoute(r.getRouteId()); includeProcessorsJson(mrb, arr, filter, max); } root.put("processors", arr); return root; } private void includeProcessorsJson(ManagedRouteMBean mrb, JsonArray arr, String filter, int max) { ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class); Collection<String> ids; try { ids = mrb.processorIds(); } catch (Exception e) { return; } // sort by index List<ManagedProcessorMBean> mps = new ArrayList<>(); for (String id : ids) { ManagedProcessorMBean mp = mcc.getManagedProcessor(id); if (mp != null && accept(mp, filter)) { mps.add(mp); } } // sort processors by index mps.sort(Comparator.comparingInt(ManagedProcessorMBean::getIndex)); // include processors into the array includeProcessorsJSon(getCamelContext(), arr, max, mps); } public static void includeProcessorsJSon( CamelContext camelContext, JsonArray arr, int max, List<ManagedProcessorMBean> mps) { for (int i = 0; i < mps.size(); i++) { ManagedProcessorMBean mp = mps.get(i); if (arr.size() > max) { return; } JsonObject jo = new JsonObject(); arr.add(jo); jo.put("routeId", mp.getRouteId()); jo.put("id", mp.getProcessorId()); if (mp.getNodePrefixId() != null) { jo.put("nodePrefixId", mp.getNodePrefixId()); } if (mp.getDescription() != null) { jo.put("description", mp.getDescription()); } if (mp.getNote() != null) { jo.put("note", mp.getNote()); } if (mp.getSourceLocation() != null) { String loc = mp.getSourceLocation(); if (mp.getSourceLineNumber() != null) { loc += ":" + mp.getSourceLineNumber(); } jo.put("source", loc); } jo.put("state", mp.getState()); jo.put("disabled", mp.getDisabled()); if (mp.getStepId() != null) { jo.put("stepId", mp.getStepId()); } // calculate end line number ManagedProcessorMBean mp2 = i < mps.size() - 1 ? mps.get(i + 1) : null; Integer end = mp2 != null ? mp2.getSourceLineNumber() : null; if (mp.getSourceLineNumber() != null) { if (end == null) { end = mp.getSourceLineNumber() + 5; } else { // clip so we do not read ahead to far, as we just want a snippet of the source code end = Math.min(mp.getSourceLineNumber() + 5, end); } } JsonArray ca = new JsonArray(); List<String> lines = ConsoleHelper.loadSourceLines(camelContext, mp.getSourceLocation(), mp.getSourceLineNumber(), end); Integer pos = mp.getSourceLineNumber(); for (String line : lines) { JsonObject c = new JsonObject(); c.put("line", pos); c.put("code", Jsoner.escape(line)); if (pos != null && pos.equals(mp.getSourceLineNumber())) { c.put("match", true); } ca.add(c); if (pos != null) { pos++; } } if (!ca.isEmpty()) { jo.put("code", ca); } jo.put("processor", mp.getProcessorName()); jo.put("level", mp.getLevel()); // processors which can send to a destination (such as to/toD/poll etc) String destination = getDestination(camelContext, mp); if (destination != null) { jo.put("uri", destination); } final JsonObject stats = getStatsObject(mp); jo.put("statistics", stats); } } private static String getDestination(CamelContext camelContext, ManagedProcessorMBean mp) { // processors which can send to a destination (such as to/toD/poll etc) String kind = mp.getProcessorName(); if ("dynamicRouter".equals(kind) || "enrich".equals(kind) || "pollEnrich".equals(kind) || "poll".equals(kind) || "toD".equals(kind) || "to".equals(kind) || "wireTap".equals(kind)) { ManagedCamelContext mcc = camelContext.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class); ManagedDestinationAware mda = mcc.getManagedProcessor(mp.getProcessorId(), ManagedDestinationAware.class); if (mda != null) { return mda.getDestination(); } } return null; } private static JsonObject getStatsObject(ManagedProcessorMBean mp) { JsonObject stats = new JsonObject(); stats.put("idleSince", mp.getIdleSince()); stats.put("exchangesTotal", mp.getExchangesTotal()); stats.put("exchangesFailed", mp.getExchangesFailed()); stats.put("exchangesInflight", mp.getExchangesInflight()); stats.put("meanProcessingTime", mp.getMeanProcessingTime()); stats.put("maxProcessingTime", mp.getMaxProcessingTime()); stats.put("minProcessingTime", mp.getMinProcessingTime()); if (mp.getExchangesTotal() > 0) { stats.put("lastProcessingTime", mp.getLastProcessingTime()); stats.put("deltaProcessingTime", mp.getDeltaProcessingTime()); } Date last = mp.getLastExchangeCreatedTimestamp(); if (last != null) { stats.put("lastCreatedExchangeTimestamp", last.getTime()); } last = mp.getLastExchangeCompletedTimestamp(); if (last != null) { stats.put("lastCompletedExchangeTimestamp", last.getTime()); } last = mp.getLastExchangeFailureTimestamp(); if (last != null) { stats.put("lastFailedExchangeTimestamp", last.getTime()); } return stats; } private static boolean accept(ManagedProcessorMBean mrb, String filter) { if (filter == null || filter.isBlank()) { return true; } String onlyName = LoggerHelper.sourceNameOnly(mrb.getSourceLocation()); return PatternHelper.matchPattern(mrb.getProcessorId(), filter) || PatternHelper.matchPattern(mrb.getRouteId(), filter) || PatternHelper.matchPattern(mrb.getSourceLocationShort(), filter) || PatternHelper.matchPattern(onlyName, filter); } protected void doAction(CamelContext camelContext, String command, String filter) { if (filter == null) { filter = "*"; } String[] patterns = filter.split(","); List<ManagedProcessorMBean> mps = new ArrayList<>(); ManagedCamelContext mcc = getCamelContext().getCamelContextExtension().getContextPlugin(ManagedCamelContext.class); for (Route r : getCamelContext().getRoutes()) { ManagedRouteMBean mrb = mcc.getManagedRoute(r.getRouteId()); try { for (String id : mrb.processorIds()) { mps.add(mcc.getManagedProcessor(id)); } } catch (Exception e) { // ignore } } // find matching IDs mps = mps.stream() .filter(mp -> { for (String p : patterns) { if (PatternHelper.matchPattern(mp.getProcessorId(), p) || PatternHelper.matchPattern(mp.getRouteId(), p)) { return true; } } return false; }) .toList(); for (ManagedProcessorMBean mp : mps) { try { if ("start".equals(command)) { mp.start(); } else if ("stop".equals(command)) { mp.stop(); } else if ("disable".equals(command)) { mp.disable(); } else if ("enable".equals(command)) { mp.enable(); } } catch (Exception e) { LOG.warn("Error {} processor: {} due to: {}. This exception is ignored.", command, mp.getProcessorId(), e.getMessage(), e); } } } }
ProcessorDevConsole
java
elastic__elasticsearch
x-pack/plugin/fleet/src/test/java/org/elasticsearch/xpack/fleet/FleetTests.java
{ "start": 753, "end": 3009 }
class ____ extends ESTestCase { public Collection<SystemIndexDescriptor> getSystemIndexDescriptors() { SystemIndexPlugin plugin = new Fleet(); return plugin.getSystemIndexDescriptors(Settings.EMPTY); } public void testSystemIndexDescriptorFormats() { for (SystemIndexDescriptor descriptor : getSystemIndexDescriptors()) { assertTrue(descriptor.isAutomaticallyManaged()); } } public void testFleetIndexNames() { final Collection<SystemIndexDescriptor> fleetDescriptors = getSystemIndexDescriptors(); assertThat( fleetDescriptors.stream().map(SystemIndexDescriptor::getIndexPattern).collect(Collectors.toList()), containsInAnyOrder( ".fleet-servers*", ".fleet-policies-[0-9]+*", ".fleet-agents*", ".fleet-actions~(-results*)", ".fleet-policies-leader*", ".fleet-enrollment-api-keys*", ".fleet-artifacts*", ".fleet-secrets*", ".integration_knowledge*" ) ); assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-servers"))); assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-policies"))); assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-policies-leader"))); assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-agents"))); assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-actions"))); assertFalse(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-actions-results"))); assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".fleet-secrets"))); assertTrue(fleetDescriptors.stream().anyMatch(d -> d.matchesIndexPattern(".integration_knowledge"))); } public void testFleetFeature() { Fleet module = new Fleet(); Feature fleet = Feature.fromSystemIndexPlugin(module, Settings.EMPTY); SystemIndices systemIndices = new SystemIndices(List.of(fleet)); assertNotNull(systemIndices); } }
FleetTests
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext11_no_adaptive/NoAdaptiveExtImpl.java
{ "start": 871, "end": 1007 }
class ____ implements NoAdaptiveExt { public String echo(String s) { return "NoAdaptiveExtImpl-echo"; } }
NoAdaptiveExtImpl
java
elastic__elasticsearch
libs/entitlement/asm-provider/src/test/java/org/elasticsearch/entitlement/instrumentation/impl/InstrumenterTests.java
{ "start": 3452, "end": 3552 }
class ____ not extend this class, but it will implement {@link Testable}. */ public static
will
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ProvidedStorageMap.java
{ "start": 2480, "end": 2649 }
class ____ us to manage and multiplex between storages local to * datanodes, and provided storage. */ @InterfaceAudience.Private @InterfaceStability.Unstable public
allows
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/profile/UnlessBuildProfileAllAnyTest.java
{ "start": 4053, "end": 4436 }
class ____ implements UnlessBuildProfileBean { @Override public String profile() { return "allOf-dev,allOf-test,allOf-build"; } } // Not active, the "test" and "build" are active, and either profile fail the anyOf match @ApplicationScoped @UnlessBuildProfile(anyOf = { "dev", "test", "build" }) public static
AllOfDevTestBuildBean
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java
{ "start": 962, "end": 2524 }
class ____ { @Test void readAllWhenSimpleStreamReturnsEvents() throws Exception { List<LogUpdateEvent> events = readAll("log-update-event.stream"); assertThat(events).hasSize(7); assertThat(events.get(0)) .hasToString("Analyzing image '307c032c4ceaa6330b6c02af945a1fe56a8c3c27c28268574b217c1d38b093cf'"); assertThat(events.get(1)) .hasToString("Writing metadata for uncached layer 'org.cloudfoundry.openjdk:openjdk-jre'"); assertThat(events.get(2)) .hasToString("Using cached launch layer 'org.cloudfoundry.jvmapplication:executable-jar'"); } @Test void readAllWhenAnsiStreamReturnsEvents() throws Exception { List<LogUpdateEvent> events = readAll("log-update-event-ansi.stream"); assertThat(events).hasSize(20); assertThat(events.get(0).toString()).isEmpty(); assertThat(events.get(1)).hasToString("Cloud Foundry OpenJDK Buildpack v1.0.64"); assertThat(events.get(2)).hasToString(" OpenJDK JRE 11.0.5: Reusing cached layer"); } @Test void readSucceedsWhenStreamTypeIsInvalid() throws IOException { List<LogUpdateEvent> events = readAll("log-update-event-invalid-stream-type.stream"); assertThat(events).hasSize(1); assertThat(events.get(0)).hasToString("Stream type is out of bounds. Must be >= 0 and < 3, but was 3"); } private List<LogUpdateEvent> readAll(String name) throws IOException { List<LogUpdateEvent> events = new ArrayList<>(); try (InputStream inputStream = getClass().getResourceAsStream(name)) { LogUpdateEvent.readAll(inputStream, events::add); } return events; } }
LogUpdateEventTests
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProxyFactory.java
{ "start": 1006, "end": 1427 }
class ____ implements ProxyFactory { @Override public <T> T getProxy(Invoker<T> invoker) throws RpcException { return null; } @Override public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { return null; } @Override public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException { return null; } }
MockProxyFactory
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/scan/SpringComponentScanWithDeprecatedPackagesTest.java
{ "start": 1304, "end": 2342 }
class ____ extends ContextTestSupport { private AbstractApplicationContext applicationContext; @Override @BeforeEach public void setUp() throws Exception { super.setUp(); applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/spring/config/scan/componentScanWithPackages.xml"); context = applicationContext.getBean("camelContext", ModelCamelContext.class); template = context.createProducerTemplate(); } @Override @AfterEach public void tearDown() throws Exception { // we're done so let's properly close the application context IOHelper.close(applicationContext); super.tearDown(); } @Test public void testSpringComponentScanFeature() throws InterruptedException { template.sendBody("direct:start", "request"); MockEndpoint mock = getMockEndpoint("mock:end"); mock.expectedMessageCount(1); mock.assertIsSatisfied(); } }
SpringComponentScanWithDeprecatedPackagesTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/BeanPipelineTest.java
{ "start": 3060, "end": 3402 }
class ____ { public void doNotUseMe(String body) { fail("Should not invoce me"); } public void withAnnotations(@Headers Map<String, Object> headers, @Body String body) { assertEquals("Hello World from James", body); assertEquals("James", headers.get("from")); } } }
BazBean
java
quarkusio__quarkus
extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/runtime/MongoClients.java
{ "start": 13369, "end": 21916 }
class ____ implements Block<ServerSettings.Builder> { public ServerSettingsBuilder(MongoClientConfig config) { this.config = config; } private final MongoClientConfig config; @Override public void apply(ServerSettings.Builder builder) { if (config.heartbeatFrequency().isPresent()) { builder.heartbeatFrequency((int) config.heartbeatFrequency().get().toMillis(), TimeUnit.MILLISECONDS); } } } private MongoClientSettings createMongoConfiguration(String name, MongoClientConfig config, boolean isReactive) { if (config == null) { throw new RuntimeException("mongo config is missing for creating mongo client."); } CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry(); MongoClientSettings.Builder settings = MongoClientSettings.builder(); if (isReactive) { switch (config.reactiveTransport()) { case NETTY: // we supports just NIO for now if (!vertx.isNativeTransportEnabled()) { configureNettyTransport(settings); } break; case MONGO: // no-op since this is the default behaviour break; } reactiveContextProviders.stream().findAny().ifPresent(settings::contextProvider); } ConnectionString connectionString; Optional<String> maybeConnectionString = config.connectionString(); if (maybeConnectionString.isPresent()) { connectionString = new ConnectionString(maybeConnectionString.get()); settings.applyConnectionString(connectionString); } configureCodecRegistry(defaultCodecRegistry, settings); List<CommandListener> commandListenerList = new ArrayList<>(); for (CommandListener commandListener : commandListeners) { commandListenerList.add(commandListener); } settings.commandListenerList(commandListenerList); config.applicationName().ifPresent(settings::applicationName); if (config.credentials() != null) { MongoCredential credential = createMongoCredential(config); if (credential != null) { settings.credential(credential); } } if (config.writeConcern() != null) { WriteConcernConfig wc = config.writeConcern(); WriteConcern concern = (wc.safe() ? WriteConcern.ACKNOWLEDGED : WriteConcern.UNACKNOWLEDGED) .withJournal(wc.journal()); if (wc.wTimeout().isPresent()) { concern = concern.withWTimeout(wc.wTimeout().get().toMillis(), TimeUnit.MILLISECONDS); } Optional<String> maybeW = wc.w(); if (maybeW.isPresent()) { String w = maybeW.get(); if ("majority".equalsIgnoreCase(w)) { concern = concern.withW(w); } else { int wInt = Integer.parseInt(w); concern = concern.withW(wInt); } } settings.writeConcern(concern); settings.retryWrites(wc.retryWrites()); } if (config.tls() || config.tlsConfigurationName().isPresent()) { settings.applyToSslSettings(new SslSettingsBuilder(config, tlsConfigurationRegistry, mongoClientSupport.isDisableSslSupport())); } settings.applyToClusterSettings(new ClusterSettingBuilder(config)); settings.applyToConnectionPoolSettings( new ConnectionPoolSettingsBuilder(config, mongoClientSupport.getConnectionPoolListeners())); settings.applyToServerSettings(new ServerSettingsBuilder(config)); settings.applyToSocketSettings(new SocketSettingsBuilder(config)); if (config.readPreference().isPresent()) { settings.readPreference(ReadPreference.valueOf(config.readPreference().get())); } if (config.readConcern().isPresent()) { settings.readConcern(new ReadConcern(ReadConcernLevel.fromString(config.readConcern().get()))); } if (config.uuidRepresentation().isPresent()) { settings.uuidRepresentation(config.uuidRepresentation().get()); } settings = customize(name, settings); return settings.build(); } private void configureNettyTransport(MongoClientSettings.Builder settings) { var nettyStreaming = TransportSettings.nettyBuilder() .allocator(VertxByteBufAllocator.POOLED_ALLOCATOR) .eventLoopGroup(vertx.nettyEventLoopGroup()) .socketChannelClass(NioSocketChannel.class).build(); settings.transportSettings(nettyStreaming); } private boolean doesNotHaveClientNameQualifier(Bean<?> bean) { for (Annotation qualifier : bean.getQualifiers()) { if (qualifier.annotationType().equals(MongoClientName.class)) { return false; } } return true; } private MongoClientSettings.Builder customize(String name, MongoClientSettings.Builder settings) { // If the client name is the default one, we use a customizer that does not have the MongoClientName qualifier. // Otherwise, we use the one that has the qualifier. // Note that at build time, we check that we have at most one customizer per client, including for the default one. if (MongoConfig.isDefaultClient(name)) { var maybe = customizers.handlesStream() .filter(h -> doesNotHaveClientNameQualifier(h.getBean())) .findFirst(); // We have at most one customizer without the qualifier. if (maybe.isEmpty()) { return settings; } else { return maybe.get().get().customize(settings); } } else { Instance<MongoClientCustomizer> selected = customizers.select(MongoClientName.Literal.of(name)); if (selected.isResolvable()) { // We can use resolvable, as we have at most one customizer per client return selected.get().customize(settings); } return settings; } } private void configureCodecRegistry(CodecRegistry defaultCodecRegistry, MongoClientSettings.Builder settings) { List<CodecProvider> providers = new ArrayList<>(); for (CodecProvider codecProvider : codecProviders) { providers.add(codecProvider); } // add pojo codec provider with automatic capabilities // it always needs to be the last codec provided PojoCodecProvider.Builder pojoCodecProviderBuilder = PojoCodecProvider.builder() .automatic(true) .conventions(Conventions.DEFAULT_CONVENTIONS); // register bson discriminators ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); for (String bsonDiscriminator : mongoClientSupport.getBsonDiscriminators()) { try { pojoCodecProviderBuilder .register(ClassModel.builder(Class.forName(bsonDiscriminator, true, classLoader)) .enableDiscriminator(true).build()); } catch (ClassNotFoundException e) { // Ignore } } // register property codec provider for (PropertyCodecProvider propertyCodecProvider : propertyCodecProviders) { pojoCodecProviderBuilder.register(propertyCodecProvider); } CodecRegistry registry = !providers.isEmpty() ? fromRegistries(fromProviders(providers), defaultCodecRegistry, fromProviders(pojoCodecProviderBuilder.build())) : fromRegistries(defaultCodecRegistry, fromProviders(pojoCodecProviderBuilder.build())); settings.codecRegistry(registry); } private static List<ServerAddress> parseHosts(List<String> addresses) { if (addresses.isEmpty()) { return Collections.singletonList(new ServerAddress(ServerAddress.defaultHost(), ServerAddress.defaultPort())); } return addresses.stream() .map(String::trim) .map(new addressParser()).collect(Collectors.toList()); } private static
ServerSettingsBuilder
java
google__guice
core/test/com/google/inject/ImplicitBindingTest.java
{ "start": 9176, "end": 9388 }
class ____ implements Provider<String> { static final String TEST_VALUE = "This is to verify it all works"; @Override public String get() { return TEST_VALUE; } } static
TestStringProvider
java
google__dagger
javatests/dagger/android/support/functional/AllControllersAreDirectChildrenOfApplication.java
{ "start": 4833, "end": 5050 }
class ____ { @Provides @IntoSet static Class<?> addToComponentHierarchy() { return ActivitySubcomponent.class; } } @Subcomponent.Builder abstract
ActivityModule
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/aggs/frequentitemsets/FrequentItemSetsAggregationBuilderTests.java
{ "start": 1568, "end": 10958 }
class ____ extends AbstractXContentSerializingTestCase<FrequentItemSetsAggregationBuilder> { public static FrequentItemSetsAggregationBuilder randomFrequentItemsSetsAggregationBuilder() { int numberOfFields = randomIntBetween(1, 20); Set<String> fieldNames = new HashSet<String>(numberOfFields); while (fieldNames.size() < numberOfFields) { fieldNames.add(randomAlphaOfLength(5)); } List<MultiValuesSourceFieldConfig> fields = fieldNames.stream().map(name -> { MultiValuesSourceFieldConfig.Builder field = new MultiValuesSourceFieldConfig.Builder(); field.setFieldName(randomAlphaOfLength(5)); if (randomBoolean()) { field.setMissing(randomAlphaOfLength(5)); } if (randomBoolean()) { field.setIncludeExclude(randomIncludeExclude()); } return field.build(); }).collect(Collectors.toList()); return new FrequentItemSetsAggregationBuilder( randomAlphaOfLength(5), fields, randomDoubleBetween(0.0, 1.0, false), randomIntBetween(1, 20), randomIntBetween(1, 20), randomBoolean() ? QueryBuilders.termQuery(randomAlphaOfLength(10), randomAlphaOfLength(10)) : null, randomFrom(EXECUTION_HINT_ALLOWED_MODES) ); } @Override protected FrequentItemSetsAggregationBuilder doParseInstance(XContentParser parser) throws IOException { assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); AggregatorFactories.Builder parsed = AggregatorFactories.parseAggregators(parser); assertThat(parsed.getAggregatorFactories(), hasSize(1)); assertThat(parsed.getPipelineAggregatorFactories(), hasSize(0)); FrequentItemSetsAggregationBuilder agg = (FrequentItemSetsAggregationBuilder) parsed.getAggregatorFactories().iterator().next(); assertNull(parser.nextToken()); assertNotNull(agg); return agg; } @Override protected Reader<FrequentItemSetsAggregationBuilder> instanceReader() { return FrequentItemSetsAggregationBuilder::new; } @Override protected FrequentItemSetsAggregationBuilder createTestInstance() { return randomFrequentItemsSetsAggregationBuilder(); } @Override protected FrequentItemSetsAggregationBuilder mutateInstance(FrequentItemSetsAggregationBuilder instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { return new NamedWriteableRegistry(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedWriteables()); } @Override protected NamedXContentRegistry xContentRegistry() { List<NamedXContentRegistry.Entry> namedXContent = new ArrayList<>(); namedXContent.add( new NamedXContentRegistry.Entry( BaseAggregationBuilder.class, new ParseField(FrequentItemSetsAggregationBuilder.NAME), (p, n) -> FrequentItemSetsAggregationBuilder.PARSER.apply(p, (String) n) ) ); namedXContent.addAll(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedXContents()); return new NamedXContentRegistry(namedXContent); } public void testValidation() { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> new FrequentItemSetsAggregationBuilder( "fi", List.of( new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldA").build(), new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldB").build() ), 1.2, randomIntBetween(1, 20), randomIntBetween(1, 20), null, randomFrom(EXECUTION_HINT_ALLOWED_MODES) ) ); assertEquals("[minimum_support] must be greater than 0 and less or equal to 1. Found [1.2] in [fi]", e.getMessage()); e = expectThrows( IllegalArgumentException.class, () -> new FrequentItemSetsAggregationBuilder( "fi", List.of( new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldA").build(), new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldB").build() ), randomDoubleBetween(0.0, 1.0, false), -4, randomIntBetween(1, 20), null, randomFrom(EXECUTION_HINT_ALLOWED_MODES) ) ); assertEquals("[minimum_set_size] must be greater than 0. Found [-4] in [fi]", e.getMessage()); e = expectThrows( IllegalArgumentException.class, () -> new FrequentItemSetsAggregationBuilder( "fi", List.of( new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldA").build(), new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldB").build() ), randomDoubleBetween(0.0, 1.0, false), randomIntBetween(1, 20), -2, null, randomFrom(EXECUTION_HINT_ALLOWED_MODES) ) ); assertEquals("[size] must be greater than 0. Found [-2] in [fi]", e.getMessage()); e = expectThrows(IllegalArgumentException.class, () -> new FrequentItemSetsAggregationBuilder( "fi", List.of( new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldA").build(), new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldB").build() ), randomDoubleBetween(0.0, 1.0, false), randomIntBetween(1, 20), randomIntBetween(1, 20), null, randomFrom(EXECUTION_HINT_ALLOWED_MODES) ).subAggregation(AggregationBuilders.avg("fieldA"))); assertEquals("Aggregator [fi] of type [frequent_item_sets] cannot accept sub-aggregations", e.getMessage()); e = expectThrows( IllegalArgumentException.class, () -> new FrequentItemSetsAggregationBuilder( "fi", List.of( new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldA").build(), new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldB").build() ), randomDoubleBetween(0.0, 1.0, false), randomIntBetween(1, 20), randomIntBetween(1, 20), null, randomFrom(EXECUTION_HINT_ALLOWED_MODES) ).subAggregations(new AggregatorFactories.Builder().addAggregator(AggregationBuilders.avg("fieldA"))) ); assertEquals("Aggregator [fi] of type [frequent_item_sets] cannot accept sub-aggregations", e.getMessage()); e = expectThrows( IllegalArgumentException.class, () -> new FrequentItemSetsAggregationBuilder( "fi", List.of( new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldA").build(), new MultiValuesSourceFieldConfig.Builder().setFieldName("fieldB").build() ), randomDoubleBetween(0.0, 1.0, false), randomIntBetween(1, 20), randomIntBetween(1, 20), null, "wrong-execution-mode" ) ); assertEquals("[execution_hint] must be one of [global_ordinals,map]. Found [wrong-execution-mode]", e.getMessage()); } private static IncludeExclude randomIncludeExclude() { switch (randomInt(7)) { case 0: return new IncludeExclude("incl*de", null, null, null); case 1: return new IncludeExclude("incl*de", "excl*de", null, null); case 2: return new IncludeExclude("incl*de", null, null, new TreeSet<>(Set.of(newBytesRef("exclude")))); case 3: return new IncludeExclude(null, "excl*de", null, null); case 4: return new IncludeExclude(null, "excl*de", new TreeSet<>(Set.of(newBytesRef("include"))), null); case 5: return new IncludeExclude(null, null, new TreeSet<>(Set.of(newBytesRef("include"))), null); case 6: return new IncludeExclude( null, null, new TreeSet<>(Set.of(newBytesRef("include"))), new TreeSet<>(Set.of(newBytesRef("exclude"))) ); default: return new IncludeExclude(null, null, null, new TreeSet<>(Set.of(newBytesRef("exclude")))); } } public void testSupportsParallelCollection() { FrequentItemSetsAggregationBuilder frequentItemSetsAggregationBuilder = randomFrequentItemsSetsAggregationBuilder(); assertFalse(frequentItemSetsAggregationBuilder.supportsParallelCollection(null)); } }
FrequentItemSetsAggregationBuilderTests
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/ParamsRequestCondition.java
{ "start": 1303, "end": 4425 }
class ____ extends AbstractRequestCondition<ParamsRequestCondition> { private final Set<ParamExpression> expressions; /** * Create a new instance from the given param expressions. * @param params expressions with syntax defined in {@link RequestMapping#params()}; * if 0, the condition will match to every request. */ public ParamsRequestCondition(String... params) { this.expressions = parseExpressions(params); } private static Set<ParamExpression> parseExpressions(String... params) { if (ObjectUtils.isEmpty(params)) { return Collections.emptySet(); } Set<ParamExpression> result = CollectionUtils.newLinkedHashSet(params.length); for (String param : params) { result.add(new ParamExpression(param)); } return result; } private ParamsRequestCondition(Set<ParamExpression> conditions) { this.expressions = conditions; } /** * Return the contained request parameter expressions. */ public Set<NameValueExpression<String>> getExpressions() { return new LinkedHashSet<>(this.expressions); } @Override protected Collection<ParamExpression> getContent() { return this.expressions; } @Override protected String getToStringInfix() { return " && "; } /** * Returns a new instance with the union of the param expressions * from "this" and the "other" instance. */ @Override public ParamsRequestCondition combine(ParamsRequestCondition other) { if (other.isEmpty()) { return this; } else if (isEmpty()) { return other; } Set<ParamExpression> set = new LinkedHashSet<>(this.expressions); set.addAll(other.expressions); return new ParamsRequestCondition(set); } /** * Returns "this" instance if the request matches all param expressions; * or {@code null} otherwise. */ @Override public @Nullable ParamsRequestCondition getMatchingCondition(ServerWebExchange exchange) { for (ParamExpression expression : this.expressions) { if (!expression.match(exchange)) { return null; } } return this; } /** * Compare to another condition based on parameter expressions. A condition * is considered to be a more specific match, if it has: * <ol> * <li>A greater number of expressions. * <li>A greater number of non-negated expressions with a concrete value. * </ol> * <p>It is assumed that both instances have been obtained via * {@link #getMatchingCondition(ServerWebExchange)} and each instance * contains the matching parameter expressions only or is otherwise empty. */ @Override public int compareTo(ParamsRequestCondition other, ServerWebExchange exchange) { int result = other.expressions.size() - this.expressions.size(); if (result != 0) { return result; } return (int) (getValueMatchCount(other.expressions) - getValueMatchCount(this.expressions)); } private long getValueMatchCount(Set<ParamExpression> expressions) { long count = 0; for (ParamExpression e : expressions) { if (e.getValue() != null && !e.isNegated()) { count++; } } return count; } /** * Parses and matches a single param expression to a request. */ static
ParamsRequestCondition
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/anthropic/completion/AnthropicChatCompletionServiceSettings.java
{ "start": 1546, "end": 4945 }
class ____ extends FilteredXContentObject implements ServiceSettings, AnthropicRateLimitServiceSettings { public static final String NAME = "anthropic_completion_service_settings"; // The rate limit for build tier 1 is 50 request per minute // Details are here https://docs.anthropic.com/en/api/rate-limits private static final RateLimitSettings DEFAULT_RATE_LIMIT_SETTINGS = new RateLimitSettings(50); public static AnthropicChatCompletionServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) { ValidationException validationException = new ValidationException(); String modelId = extractRequiredString(map, MODEL_ID, ModelConfigurations.SERVICE_SETTINGS, validationException); RateLimitSettings rateLimitSettings = RateLimitSettings.of( map, DEFAULT_RATE_LIMIT_SETTINGS, validationException, AnthropicService.NAME, context ); if (validationException.validationErrors().isEmpty() == false) { throw validationException; } return new AnthropicChatCompletionServiceSettings(modelId, rateLimitSettings); } private final String modelId; private final RateLimitSettings rateLimitSettings; public AnthropicChatCompletionServiceSettings(String modelId, @Nullable RateLimitSettings ratelimitSettings) { this.modelId = Objects.requireNonNull(modelId); this.rateLimitSettings = Objects.requireNonNullElse(ratelimitSettings, DEFAULT_RATE_LIMIT_SETTINGS); } public AnthropicChatCompletionServiceSettings(StreamInput in) throws IOException { this.modelId = in.readString(); rateLimitSettings = new RateLimitSettings(in); } @Override public RateLimitSettings rateLimitSettings() { return rateLimitSettings; } @Override public String modelId() { return modelId; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); toXContentFragmentOfExposedFields(builder, params); builder.endObject(); return builder; } @Override protected XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException { builder.field(MODEL_ID, modelId); rateLimitSettings.toXContent(builder, params); return builder; } @Override public String getWriteableName() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersions.V_8_14_0; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(modelId); rateLimitSettings.writeTo(out); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; AnthropicChatCompletionServiceSettings that = (AnthropicChatCompletionServiceSettings) object; return Objects.equals(modelId, that.modelId) && Objects.equals(rateLimitSettings, that.rateLimitSettings); } @Override public int hashCode() { return Objects.hash(modelId, rateLimitSettings); } }
AnthropicChatCompletionServiceSettings
java
google__dagger
javatests/dagger/internal/codegen/InjectConstructorFactoryGeneratorTest.java
{ "start": 62073, "end": 62652 }
class ____ {", " @FooBaseFieldQualifier @Inject String injectField;", "", " @Inject", " FooBase(@FooBaseConstructorQualifier int i) {}", "", " @Inject", " void injectMethod(@FooBaseMethodQualifier float f) {}", "}"); Source fooBaseFieldQualifier = CompilerTests.javaSource( "test.FooBaseFieldQualifier", "package test;", "", "import javax.inject.Qualifier;", "", "@Qualifier", "@
FooBase
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ClassPathResource.java
{ "start": 5712, "end": 6460 }
class ____ resource. * * @return the resolved URL, or {@code null} if not resolvable */ protected URL resolveUrl() { try { if (this.clazz != null) { return this.clazz.getResource(this.path); } else if (this.classLoader != null) { return this.classLoader.getResource(this.path); } else { return ClassLoader.getSystemResource(this.path); } } catch (IllegalArgumentException ex) { // Should not happen according to the JDK's contract: // see https://github.com/openjdk/jdk/pull/2662 return null; } } /** * This implementation opens an InputStream for the given
path
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactedInterceptSendToEndpointTest.java
{ "start": 1090, "end": 2756 }
class ____ extends TransactionalClientDataSourceTest { @Override @Test public void testTransactionSuccess() throws Exception { MockEndpoint intercepted = getMockEndpoint("mock:intercepted"); intercepted.expectedBodiesReceived("Hello World"); super.testTransactionSuccess(); assertMockEndpointsSatisfied(); } @Override @Test public void testTransactionRollback() throws Exception { MockEndpoint intercepted = getMockEndpoint("mock:intercepted"); intercepted.expectedBodiesReceived("Tiger in Action"); super.testTransactionRollback(); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() throws Exception { interceptSendToEndpoint("direct:(foo|bar)").to("mock:intercepted"); from("direct:okay") .transacted() .to("direct:foo") .setBody(constant("Tiger in Action")).bean("bookService") .setBody(constant("Elephant in Action")).bean("bookService"); from("direct:fail") .transacted() .setBody(constant("Tiger in Action")).bean("bookService") .to("direct:bar") .setBody(constant("Donkey in Action")).bean("bookService"); from("direct:foo").to("log:okay"); from("direct:bar").to("mock:fail"); } }; } }
TransactedInterceptSendToEndpointTest
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/EscapingTest.java
{ "start": 3522, "end": 3736 }
class ____ { public RawString getFoo() { return new RawString("<span>"); } @Override public String toString() { return "<h1>Item</h1>"; } } }
Item
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/config/PropertiesUtil.java
{ "start": 70, "end": 1359 }
class ____ { private static final String OS_NAME = "os.name"; private static final String USER_HOME = "user.home"; private static final String WINDOWS = "windows"; private static final String FALSE = "false"; private static final String TRUE = "true"; private PropertiesUtil() { } public static boolean isWindows() { return getProperty(OS_NAME).toLowerCase(Locale.ENGLISH).contains(WINDOWS); } public static String getUserHome() { return getProperty(USER_HOME); } public static String getProperty(final String name, String defValue) { assert name != null : "name is null"; return System.getProperty(name, defValue); } public static String getProperty(final String name) { assert name != null : "name is null"; return System.getProperty(name); } public static final Boolean getBooleanOrNull(String name) { final String value = getProperty(name); return value == null ? null : Boolean.parseBoolean(value); } public static final boolean getBoolean(String name, boolean notFoundValue) { final String value = getProperty(name, (notFoundValue ? TRUE : FALSE)); return value.isEmpty() || Boolean.parseBoolean(value); } }
PropertiesUtil
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/quarkustest-added-with-serviceloader/deployment/src/main/java/org/acme/it/tck/deployment/TCKProcessor.java
{ "start": 1014, "end": 2188 }
class ____ annotated with @QuarkusTest. To avoid overriding each test class * to add the annotation, we register the QuarkusTextExtension globally via JUnit ServiceLoader and create a bean * for each test class. */ @BuildStep public void testBeans( CombinedIndexBuildItem combinedIndex, BuildProducer<AdditionalBeanBuildItem> additionalBeans, BuildProducer<AnnotationsTransformerBuildItem> annotationsTransformer) { annotationsTransformer.produce(new AnnotationsTransformerBuildItem(new AnnotationsTransformer() { @Override public boolean appliesTo(final AnnotationTarget.Kind kind) { return CLASS.equals(kind); } @Override public void transform(final TransformationContext context) { String className = context.getTarget().asClass().name().toString(); if ("org.acme.tck.HelloResourceTest".equals(className)) { context.transform() .add(ApplicationScoped.class) .done(); } } })); } }
is
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/tracing/Tracing.java
{ "start": 1280, "end": 3749 }
interface ____ { /** * @return the {@link TracerProvider}. */ TracerProvider getTracerProvider(); /** * @return the {@link TraceContextProvider} supplying the initial {@link TraceContext} (i.e. if there is no active span). */ TraceContextProvider initialTraceContextProvider(); /** * Returns {@code true} if tracing is enabled. * * @return {@code true} if tracing is enabled. */ boolean isEnabled(); /** * Returns {@code true} if tags for {@link Tracer.Span}s should include the command arguments. * * @return {@code true} if tags for {@link Tracer.Span}s should include the command arguments. * @since 5.2 */ boolean includeCommandArgsInSpanTags(); /** * Create an {@link Endpoint} given {@link SocketAddress}. * * @param socketAddress the remote address. * @return the {@link Endpoint} for {@link SocketAddress}. */ Endpoint createEndpoint(SocketAddress socketAddress); /** * Returns a {@link TracerProvider} that is disabled. * * @return a disabled {@link TracerProvider}. */ static Tracing disabled() { return NoOpTracing.INSTANCE; } /** * Gets the {@link TraceContextProvider} from Reactor {@link Context}. * * @return the {@link TraceContextProvider}. */ static Mono<TraceContextProvider> getContext() { return Mono.deferContextual(Mono::justOrEmpty).filter(c -> c.hasKey(TraceContextProvider.class)) .map(c -> c.get(TraceContextProvider.class)); } /** * Clears the {@code Mono<TracerProvider>} from Reactor {@link Context}. * * @return Return a {@link Function} that clears the {@link TraceContextProvider} context. */ static Function<Context, Context> clearContext() { return context -> context.delete(TraceContextProvider.class); } /** * Creates a Reactor {@link Context} that contains the {@code Mono<TraceContextProvider>}. that can be merged into another * {@link Context}. * * @param supplier the {@link TraceContextProvider} to set in the returned Reactor {@link Context}. * @return a Reactor {@link Context} that contains the {@code Mono<TraceContextProvider>}. */ static Context withTraceContextProvider(TraceContextProvider supplier) { return Context.of(TraceContextProvider.class, supplier); } /** * Value object
Tracing
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/support/converter/JacksonJsonMessageConverter.java
{ "start": 5184, "end": 5661 }
class ____. * <p>Default is none. <b>NOTE: This property needs to be set in order to allow * for converting from an incoming message to a Java object.</b> * @see #setTypeIdMappings */ public void setTypeIdPropertyName(String typeIdPropertyName) { this.typeIdPropertyName = typeIdPropertyName; } /** * Specify mappings from type ids to Java classes, if desired. * This allows for synthetic ids in the type id message property, * instead of transferring Java
name
java
quarkusio__quarkus
integration-tests/infinispan-client/src/main/java/io/quarkus/it/infinispan/client/MagazineMarshaller.java
{ "start": 211, "end": 1346 }
class ____ implements MessageMarshaller<Magazine> { @Override public Magazine readFrom(ProtoStreamReader reader) throws IOException { String name = reader.readString("name"); YearMonth yearMonth = YearMonth.of(reader.readInt("publicationYear"), reader.readInt("publicationMonth")); List<String> stories = reader.readCollection("stories", new ArrayList<>(), String.class); return new Magazine(name, yearMonth, stories); } @Override public void writeTo(ProtoStreamWriter writer, Magazine magazine) throws IOException { writer.writeString("name", magazine.getName()); YearMonth yearMonth = magazine.getPublicationYearMonth(); writer.writeInt("publicationYear", yearMonth.getYear()); writer.writeInt("publicationMonth", yearMonth.getMonthValue()); writer.writeCollection("stories", magazine.getStories(), String.class); } @Override public Class<? extends Magazine> getJavaClass() { return Magazine.class; } @Override public String getTypeName() { return "magazine_sample.Magazine"; } }
MagazineMarshaller
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/commit/CommitterFaultInjectionImpl.java
{ "start": 1331, "end": 3500 }
class ____ extends PathOutputCommitter implements CommitterFaultInjection { private Set<Faults> faults; private boolean resetOnFailure; public CommitterFaultInjectionImpl(Path outputPath, JobContext context, boolean resetOnFailure, Faults... faults) throws IOException { super(outputPath, context); setFaults(faults); this.resetOnFailure = resetOnFailure; } @Override public void setFaults(Faults... faults) { this.faults = new HashSet<>(faults.length); Collections.addAll(this.faults, faults); } /** * Fail if the condition is in the set of faults, may optionally reset * it before failing. * @param condition condition to check for * @throws Failure if the condition is faulting */ private void maybeFail(Faults condition) throws Failure { if (faults.contains(condition)) { if (resetOnFailure) { faults.remove(condition); } throw new Failure(); } } @Override public Path getWorkPath() throws IOException { maybeFail(Faults.getWorkPath); return null; } @Override public Path getOutputPath() { return null; } @Override public void setupJob(JobContext jobContext) throws IOException { maybeFail(Faults.setupJob); } @Override public void setupTask(TaskAttemptContext taskContext) throws IOException { maybeFail(Faults.setupTask); } @Override public boolean needsTaskCommit(TaskAttemptContext taskContext) throws IOException { maybeFail(Faults.needsTaskCommit); return false; } @Override public void commitTask(TaskAttemptContext taskContext) throws IOException { maybeFail(Faults.commitTask); } @Override public void abortTask(TaskAttemptContext taskContext) throws IOException { maybeFail(Faults.abortTask); } @Override public void commitJob(JobContext jobContext) throws IOException { maybeFail(Faults.commitJob); } @Override public void abortJob(JobContext jobContext, JobStatus.State state) throws IOException { maybeFail(Faults.abortJob); } /** * The exception raised on failure. */ public static
CommitterFaultInjectionImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/MissingRuntimeRetentionTest.java
{ "start": 2468, "end": 2771 }
interface ____ {} /** A scoping (@ScopingAnnotation) annotation with SOURCE retention. */ @ScopeAnnotation @Target({TYPE, METHOD}) // BUG: Diagnostic contains: @Retention(RUNTIME) @Retention(SOURCE) public @
TestAnnotation1
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RObjectAsync.java
{ "start": 780, "end": 7385 }
interface ____ { /** * Returns number of seconds spent since last write or read operation over this object. * * @return number of seconds */ RFuture<Long> getIdleTimeAsync(); /** * Returns count of references over this object. * * @return count of reference */ RFuture<Integer> getReferenceCountAsync(); /** * Returns the logarithmic access frequency counter over this object. * * @return frequency counter */ RFuture<Integer> getAccessFrequencyAsync(); /** * Returns the internal encoding for the Redis object * * @return internal encoding */ RFuture<ObjectEncoding> getInternalEncodingAsync(); /** * Returns bytes amount used by object in Redis memory. * * @return size in bytes */ RFuture<Long> sizeInMemoryAsync(); /** * Restores object using its state returned by {@link #dumpAsync()} method. * * @param state - state of object * @return void */ RFuture<Void> restoreAsync(byte[] state); /** * Restores object using its state returned by {@link #dumpAsync()} method and set time to live for it. * * @param state - state of object * @param timeToLive - time to live of the object * @param timeUnit - time unit * @return void */ RFuture<Void> restoreAsync(byte[] state, long timeToLive, TimeUnit timeUnit); /** * Restores and replaces object if it already exists. * * @param state - state of the object * @return void */ RFuture<Void> restoreAndReplaceAsync(byte[] state); /** * Restores and replaces object if it already exists and set time to live for it. * * @param state - state of the object * @param timeToLive - time to live of the object * @param timeUnit - time unit * @return void */ RFuture<Void> restoreAndReplaceAsync(byte[] state, long timeToLive, TimeUnit timeUnit); /** * Returns dump of object * * @return dump */ RFuture<byte[]> dumpAsync(); /** * Update the last access time of an object in async mode. * * @return <code>true</code> if object was touched else <code>false</code> */ RFuture<Boolean> touchAsync(); /** * Transfer object from source Redis instance to destination Redis instance * in async mode * * @param host - destination host * @param port - destination port * @param database - destination database * @param timeout - maximum idle time in any moment of the communication with the destination instance in milliseconds * @return void */ RFuture<Void> migrateAsync(String host, int port, int database, long timeout); /** * Copy object from source Redis instance to destination Redis instance * in async mode * * @param host - destination host * @param port - destination port * @param database - destination database * @param timeout - maximum idle time in any moment of the communication with the destination instance in milliseconds * @return void */ RFuture<Void> copyAsync(String host, int port, int database, long timeout); /** * Copy this object instance to the new instance with a defined name. * * @param destination name of the destination instance * @return <code>true</code> if this object instance was copied else <code>false</code> */ RFuture<Boolean> copyAsync(String destination); /** * Copy this object instance to the new instance with a defined name and database. * * @param destination name of the destination instance * @param database database number * @return <code>true</code> if this object instance was copied else <code>false</code> */ RFuture<Boolean> copyAsync(String destination, int database); /** * Copy this object instance to the new instance with a defined name, and replace it if it already exists. * * @param destination name of the destination instance * @return <code>true</code> if this object instance was copied else <code>false</code> */ RFuture<Boolean> copyAndReplaceAsync(String destination); /** * Copy this object instance to the new instance with a defined name and database, and replace it if it already exists. * * @param destination name of the destination instance * @param database database number * @return <code>true</code> if this object instance was copied else <code>false</code> */ RFuture<Boolean> copyAndReplaceAsync(String destination, int database); /** * Move object to another database in async mode * * @param database - number of Redis database * @return <code>true</code> if key was moved <code>false</code> if not */ RFuture<Boolean> moveAsync(int database); /** * Delete object in async mode * * @return <code>true</code> if object was deleted <code>false</code> if not */ RFuture<Boolean> deleteAsync(); /** * Delete the objects. * Actual removal will happen later asynchronously. * <p> * Requires Redis 4.0+ * * @return <code>true</code> if it was exist and deleted else <code>false</code> */ RFuture<Boolean> unlinkAsync(); /** * Rename current object key to <code>newName</code> * in async mode * * @param newName - new name of object * @return void */ RFuture<Void> renameAsync(String newName); /** * Rename current object key to <code>newName</code> * in async mode only if new key is not exists * * @param newName - new name of object * @return <code>true</code> if object has been renamed successfully and <code>false</code> otherwise */ RFuture<Boolean> renamenxAsync(String newName); /** * Check object existence in async mode. * * @return <code>true</code> if object exists and <code>false</code> otherwise */ RFuture<Boolean> isExistsAsync(); /** * Adds object event listener * * @see org.redisson.api.ExpiredObjectListener * @see org.redisson.api.DeletedObjectListener * * @param listener - object event listener * @return listener id */ RFuture<Integer> addListenerAsync(ObjectListener listener); /** * Removes object event listener * * @param listenerId - listener id */ RFuture<Void> removeListenerAsync(int listenerId); }
RObjectAsync
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java
{ "start": 17836, "end": 18511 }
enum ____ { ONE, TWO, THREE } boolean m(boolean f, Case c) { if (f) { switch (c) { case ONE: case TWO: case THREE: return true; } return false; } else { return false; } } } """) .doTest(); } @Test public void notExhaustive2Unrecognized() { refactoringTestHelper .addInputLines( "Test.java", """
Case
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java
{ "start": 7607, "end": 7880 }
class ____. * * @param fileName properties file name. for example: <code>dubbo.properties</code>, <code>METE-INF/conf/foo.properties</code> * @param allowMultiFile if <code>false</code>, throw {@link IllegalStateException} when found multi file on the
path
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableCapability.java
{ "start": 1298, "end": 3634 }
enum ____ { /** * Signals that the table supports reads in batch execution mode. */ BATCH_READ, /** * Signals that the table supports reads in micro-batch streaming execution mode. */ MICRO_BATCH_READ, /** * Signals that the table supports reads in continuous streaming execution mode. */ CONTINUOUS_READ, /** * Signals that the table supports append writes in batch execution mode. * <p> * Tables that return this capability must support appending data and may also support additional * write modes, like {@link #TRUNCATE}, {@link #OVERWRITE_BY_FILTER}, and * {@link #OVERWRITE_DYNAMIC}. */ BATCH_WRITE, /** * Signals that the table supports append writes in streaming execution mode. * <p> * Tables that return this capability must support appending data and may also support additional * write modes, like {@link #TRUNCATE}, {@link #OVERWRITE_BY_FILTER}, and * {@link #OVERWRITE_DYNAMIC}. */ STREAMING_WRITE, /** * Signals that the table can be truncated in a write operation. * <p> * Truncating a table removes all existing rows. * <p> * See {@link org.apache.spark.sql.connector.write.SupportsTruncate}. */ TRUNCATE, /** * Signals that the table can replace existing data that matches a filter with appended data in * a write operation. * <p> * See {@link org.apache.spark.sql.connector.write.SupportsOverwriteV2}. */ OVERWRITE_BY_FILTER, /** * Signals that the table can dynamically replace existing data partitions with appended data in * a write operation. * <p> * See {@link org.apache.spark.sql.connector.write.SupportsDynamicOverwrite}. */ OVERWRITE_DYNAMIC, /** * Signals that the table accepts input of any schema in a write operation. */ ACCEPT_ANY_SCHEMA, /** * Signals that table supports Spark altering the schema if necessary * as part of an operation. */ AUTOMATIC_SCHEMA_EVOLUTION, /** * Signals that the table supports append writes using the V1 InsertableRelation interface. * <p> * Tables that return this capability must create a V1Write and may also support additional * write modes, like {@link #TRUNCATE}, and {@link #OVERWRITE_BY_FILTER}, but cannot support * {@link #OVERWRITE_DYNAMIC}. */ V1_BATCH_WRITE }
TableCapability
java
apache__camel
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/EndpointHelper.java
{ "start": 4621, "end": 6551 }
class ____ implements Comparator<BaseOptionModel> { @Override public int compare(BaseOptionModel o1, BaseOptionModel o2) { String name1 = o1.getName(); String name2 = o2.getName(); String label1 = !Strings.isNullOrEmpty(o1.getLabel()) ? o1.getLabel() : "common"; String label2 = !Strings.isNullOrEmpty(o2.getLabel()) ? o2.getLabel() : "common"; String group1 = o1.getGroup(); String group2 = o2.getGroup(); // if same label or group then sort by name if (label1.equalsIgnoreCase(label2) || group1.equalsIgnoreCase(group2)) { return name1.compareToIgnoreCase(name2); } int score1 = groupScore(group1); int score2 = groupScore(group2); if (score1 < score2) { return -1; } else if (score2 < score1) { return 1; } else { int score = group1.compareToIgnoreCase(group2); if (score == 0) { // compare by full label and name score = label1.compareToIgnoreCase(label2); if (score == 0) { score = name1.compareToIgnoreCase(name2); } } return score; } } } private static int groupScore(String group) { switch (group) { case "common": return 1; case "common (advanced)": return 2; case "consumer": return 3; case "consumer (advanced)": return 4; case "producer": return 5; case "producer (advanced)": return 6; default: return 9; } } private static final
EndpointOptionGroupAndLabelComparator
java
alibaba__nacos
ai/src/test/java/com/alibaba/nacos/ai/config/McpServerIndexConfigurationTest.java
{ "start": 2464, "end": 3178 }
class ____ { @org.springframework.beans.factory.annotation.Autowired(required = false) private McpServerIndex mcpServerIndex; @Test void shouldInjectCachedMcpServerIndexWhenCacheEnabled() { assertNotNull(mcpServerIndex, "McpServerIndex should be injected"); assertInstanceOf(CachedMcpServerIndex.class, mcpServerIndex, "Should be CachedMcpServerIndex when cache enabled"); } } @Nested @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {McpServerIndexConfiguration.class, TestConfig.class}) @TestPropertySource(properties = {"nacos.mcp.cache.enabled=false"})
CacheEnabled
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/CalendarUtils.java
{ "start": 1325, "end": 6950 }
class ____ initialized and is based on the current time in the * default time zone with the default {@link Category#FORMAT} locale. * * @see CalendarUtils#getInstance() */ public static final CalendarUtils INSTANCE = getInstance(); /** * Creates a new instance based on the current time in the default time zone with the default {@link Category#FORMAT} locale. * * @return a new instance. * @since 3.14.0 */ public static CalendarUtils getInstance() { return new CalendarUtils(Calendar.getInstance()); } /** * Gets a CalendarUtils using the default time zone and specified locale. The {@code CalendarUtils} returned is based on the current time in the * default time zone with the given locale. * * @param locale the locale for the week data * @return a Calendar. */ static CalendarUtils getInstance(final Locale locale) { return new CalendarUtils(Calendar.getInstance(locale), locale); } /** * Converts a Calendar to a LocalDateTime. * * @param calendar the Calendar to convert. * @return a LocalDateTime. * @since 3.17.0 */ public static LocalDateTime toLocalDateTime(final Calendar calendar) { return LocalDateTime.ofInstant(calendar.toInstant(), toZoneId(calendar)); } /** * Converts a Calendar to a OffsetDateTime. * * @param calendar the Calendar to convert. * @return a OffsetDateTime. * @since 3.17.0 */ public static OffsetDateTime toOffsetDateTime(final Calendar calendar) { return OffsetDateTime.ofInstant(calendar.toInstant(), toZoneId(calendar)); } /** * Converts a Calendar to a ZonedDateTime. * * @param calendar the Calendar to convert. * @return a ZonedDateTime. * @since 3.17.0 */ public static ZonedDateTime toZonedDateTime(final Calendar calendar) { return ZonedDateTime.ofInstant(calendar.toInstant(), toZoneId(calendar)); } private static ZoneId toZoneId(final Calendar calendar) { return calendar.getTimeZone().toZoneId(); } private final Calendar calendar; private final Locale locale; /** * Creates an instance for the given Calendar. * * @param calendar A Calendar. */ public CalendarUtils(final Calendar calendar) { this(calendar, Locale.getDefault()); } /** * Creates an instance for the given Calendar. * * @param calendar A Calendar. * @param locale A Locale. */ CalendarUtils(final Calendar calendar, final Locale locale) { this.calendar = Objects.requireNonNull(calendar, "calendar"); this.locale = Objects.requireNonNull(locale, "locale"); } /** * Gets the current day of month. * * @return the current day of month. */ public int getDayOfMonth() { return calendar.get(Calendar.DAY_OF_MONTH); } /** * Gets the current day of year. * * @return the current day of year. * @since 3.13.0 */ public int getDayOfYear() { return calendar.get(Calendar.DAY_OF_YEAR); } /** * Gets the current month. * * @return the current month. */ public int getMonth() { return calendar.get(Calendar.MONTH); } /** * Gets month names in the requested style. * @param style Must be a valid {@link Calendar#getDisplayNames(int, int, Locale)} month style. * @return Styled names of months */ String[] getMonthDisplayNames(final int style) { // Unfortunately standalone month names are not available in DateFormatSymbols, // so we have to extract them. final Map<String, Integer> displayNames = calendar.getDisplayNames(Calendar.MONTH, style, locale); if (displayNames == null) { return null; } final String[] monthNames = new String[displayNames.size()]; displayNames.forEach((k, v) -> monthNames[v] = k); return monthNames; } /** * Gets full standalone month names as used in "LLLL" date formatting. * @return Long names of months */ String[] getStandaloneLongMonthNames() { return getMonthDisplayNames(Calendar.LONG_STANDALONE); } /** * Gets short standalone month names as used in "LLLL" date formatting. * @return Short names of months */ String[] getStandaloneShortMonthNames() { return getMonthDisplayNames(Calendar.SHORT_STANDALONE); } /** * Gets the current year. * * @return the current year. */ public int getYear() { return calendar.get(Calendar.YEAR); } /** * Converts this instance to a {@link LocalDate}. * * @return a LocalDate. * @since 3.18.0 */ public LocalDate toLocalDate() { return toLocalDateTime().toLocalDate(); } /** * Converts this instance to a {@link LocalDateTime}. * * @return a LocalDateTime. * @since 3.17.0 */ public LocalDateTime toLocalDateTime() { return toLocalDateTime(calendar); } /** * Converts this instance to a {@link OffsetDateTime}. * * @return a OffsetDateTime. * @since 3.17.0 */ public OffsetDateTime toOffsetDateTime() { return toOffsetDateTime(calendar); } /** * Converts this instance to a {@link ZonedDateTime}. * * @return a ZonedDateTime. * @since 3.17.0 */ public ZonedDateTime toZonedDateTime() { return toZonedDateTime(calendar); } }
is
java
alibaba__nacos
plugin/datasource/src/test/java/com/alibaba/nacos/plugin/datasource/impl/mysql/HistoryConfigInfoMapperByMySqlTest.java
{ "start": 1243, "end": 5879 }
class ____ { int startRow = 0; int pageSize = 5; int limitSize = 6; long lastMaxId = 644; Timestamp startTime = new Timestamp(System.currentTimeMillis()); Timestamp endTime = new Timestamp(System.currentTimeMillis()); String publishType = "formal"; MapperContext context; private HistoryConfigInfoMapperByMySql historyConfigInfoMapperByMySql; @BeforeEach void setUp() throws Exception { historyConfigInfoMapperByMySql = new HistoryConfigInfoMapperByMySql(); context = new MapperContext(startRow, pageSize); context.putWhereParameter(FieldConstant.START_TIME, startTime); context.putWhereParameter(FieldConstant.END_TIME, endTime); context.putWhereParameter(FieldConstant.LIMIT_SIZE, limitSize); context.putWhereParameter(FieldConstant.LAST_MAX_ID, lastMaxId); context.putWhereParameter(FieldConstant.PAGE_SIZE, pageSize); context.putWhereParameter(FieldConstant.PUBLISH_TYPE, publishType); } @Test void testRemoveConfigHistory() { MapperResult mapperResult = historyConfigInfoMapperByMySql.removeConfigHistory(context); assertEquals("DELETE FROM his_config_info WHERE gmt_modified < ? LIMIT ?", mapperResult.getSql()); assertArrayEquals(new Object[] {startTime, limitSize}, mapperResult.getParamList().toArray()); } @Test void testFindConfigHistoryCountByTime() { MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryCountByTime(context); assertEquals("SELECT count(*) FROM his_config_info WHERE gmt_modified < ?", mapperResult.getSql()); assertArrayEquals(new Object[] {startTime}, mapperResult.getParamList().toArray()); } @Test void testFindDeletedConfig() { MapperResult mapperResult = historyConfigInfoMapperByMySql.findDeletedConfig(context); assertEquals( "SELECT id, nid, data_id, group_id, app_name, content, md5, gmt_create, gmt_modified, src_user, src_ip," + " op_type, tenant_id, publish_type, gray_name, ext_info, encrypted_data_key FROM his_config_info WHERE op_type = 'D' AND " + "publish_type = ? and gmt_modified >= ? and nid > ? order by nid limit ? ", mapperResult.getSql()); assertArrayEquals(new Object[] {publishType, startTime, lastMaxId, pageSize}, mapperResult.getParamList().toArray()); } @Test void testFindConfigHistoryFetchRows() { Object dataId = "dataId"; Object groupId = "groupId"; Object tenantId = "tenantId"; context.putWhereParameter(FieldConstant.DATA_ID, dataId); context.putWhereParameter(FieldConstant.GROUP_ID, groupId); context.putWhereParameter(FieldConstant.TENANT_ID, tenantId); context.putWhereParameter(FieldConstant.DATA_ID, dataId); MapperResult mapperResult = historyConfigInfoMapperByMySql.findConfigHistoryFetchRows(context); assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,publish_type,gray_name," + "op_type,gmt_create,gmt_modified FROM his_config_info " + "WHERE data_id = ? AND group_id = ? AND tenant_id = ? ORDER BY nid DESC"); assertArrayEquals(new Object[] {dataId, groupId, tenantId}, mapperResult.getParamList().toArray()); } @Test void testDetailPreviousConfigHistory() { Object id = "1"; context.putWhereParameter(FieldConstant.ID, id); MapperResult mapperResult = historyConfigInfoMapperByMySql.detailPreviousConfigHistory(context); assertEquals(mapperResult.getSql(), "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,publish_type" + ",gray_name,ext_info,gmt_create,gmt_modified,encrypted_data_key " + "FROM his_config_info WHERE nid = (SELECT max(nid) FROM his_config_info WHERE id = ?)"); assertArrayEquals(new Object[] {id}, mapperResult.getParamList().toArray()); } @Test void testGetTableName() { String tableName = historyConfigInfoMapperByMySql.getTableName(); assertEquals(TableConstant.HIS_CONFIG_INFO, tableName); } @Test void testGetDataSource() { String dataSource = historyConfigInfoMapperByMySql.getDataSource(); assertEquals(DataSourceConstant.MYSQL, dataSource); } }
HistoryConfigInfoMapperByMySqlTest
java
apache__camel
components/camel-ai/camel-langchain4j-tools/src/main/java/org/apache/camel/component/langchain4j/tools/LangChain4jTools.java
{ "start": 871, "end": 1089 }
class ____ { public static final String SCHEME = "langchain4j-tools"; public static final String NO_TOOLS_CALLED_HEADER = "LangChain4jToolsNoToolsCalled"; private LangChain4jTools() { } }
LangChain4jTools
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/iterable/IterableAssert_haveAtLeastOne_Test.java
{ "start": 1045, "end": 1489 }
class ____ extends IterableAssertBaseTest { private static final Condition<Object> condition = new TestCondition<>(); @Override protected ConcreteIterableAssert<Object> invoke_api_method() { return assertions.haveAtLeastOne(condition); } @Override protected void verify_internal_effects() { verify(iterables).assertHaveAtLeast(getInfo(assertions), getActual(assertions), 1, condition); } }
IterableAssert_haveAtLeastOne_Test
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.java
{ "start": 1044, "end": 1334 }
class ____ extends FileConsumerPreMoveTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.xml"); } public static
SpringFileConsumerPreMoveTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/reservedstate/service/ReservedStateUpdateTask.java
{ "start": 1950, "end": 13767 }
class ____<T extends ReservedStateHandler<?>> implements ClusterStateTaskListener { private static final Logger logger = LogManager.getLogger(ReservedStateUpdateTask.class); private final String namespace; private final ReservedStateChunk stateChunk; private final ReservedStateVersionCheck versionCheck; private final Map<String, T> handlers; private final SequencedCollection<String> updateSequence; private final Consumer<ErrorState> errorReporter; private final ActionListener<ActionResponse.Empty> listener; /** * @param updateSequence the names of handlers corresponding to configuration sections present in the source, * in the order they should be processed according to their dependencies. * It equals the result of applying {@link #orderedStateHandlers} to {@code stateChunk.state().keySet()} * but the caller will typically also need it for a <i>trial run</i>, so we avoid computing it twice. */ public ReservedStateUpdateTask( String namespace, ReservedStateChunk stateChunk, ReservedStateVersionCheck versionCheck, Map<String, T> handlers, SequencedCollection<String> updateSequence, Consumer<ErrorState> errorReporter, ActionListener<ActionResponse.Empty> listener ) { this.namespace = namespace; this.stateChunk = stateChunk; this.versionCheck = versionCheck; this.handlers = handlers; this.updateSequence = updateSequence; this.errorReporter = errorReporter; this.listener = listener; // We can't assert the order here, even if we'd like to, because in general, // there is not necessarily one unique correct order. // But we can at least assert that updateSequence has the right elements. assert Set.copyOf(updateSequence).equals(stateChunk.state().keySet()) : "updateSequence is supposed to be computed from stateChunk.state().keySet(): " + updateSequence + " vs " + stateChunk.state().keySet(); } @Override public void onFailure(Exception e) { listener.onFailure(e); } ActionListener<ActionResponse.Empty> listener() { return listener; } protected abstract Optional<ProjectId> projectId(); protected abstract TransformState transform(T handler, Object state, TransformState transformState) throws Exception; protected abstract ClusterState remove(T handler, TransformState prevState) throws Exception; abstract ClusterState execute(ClusterState currentState); /** * Produces a new state {@code S} with the reserved state info in {@code reservedStateMap} * @return A tuple of the new state and new reserved state metadata, or {@code null} if no changes are required. */ final Tuple<ClusterState, ReservedStateMetadata> execute(ClusterState state, Map<String, ReservedStateMetadata> reservedStateMap) { Map<String, Object> reservedState = stateChunk.state(); ReservedStateVersion reservedStateVersion = stateChunk.metadata(); ReservedStateMetadata reservedStateMetadata = reservedStateMap.get(namespace); if (checkMetadataVersion(projectId(), namespace, reservedStateMetadata, reservedStateVersion, versionCheck) == false) { return null; } var reservedMetadataBuilder = new ReservedStateMetadata.Builder(namespace).version(reservedStateVersion.version()); List<String> errors = new ArrayList<>(); // First apply the updates to transform the cluster state for (var handlerName : updateSequence) { T handler = handlers.get(handlerName); try { Set<String> existingKeys = keysForHandler(reservedStateMetadata, handlerName); TransformState transformState = transform(handler, reservedState.get(handlerName), new TransformState(state, existingKeys)); state = transformState.state(); reservedMetadataBuilder.putHandler(new ReservedStateHandlerMetadata(handlerName, transformState.keys())); } catch (Exception e) { errors.add(format("Error processing %s state change: %s", handler.name(), stackTrace(e))); } } // Now, any existing handler not listed in updateSequence must have been removed. // We do removals after updates in case one of the updated handlers depends on one of these, // to give that handler a chance to clean up before its dependency vanishes. if (reservedStateMetadata != null) { Set<String> toRemove = new HashSet<>(reservedStateMetadata.handlers().keySet()); toRemove.removeAll(updateSequence); SequencedSet<String> removalSequence = orderedStateHandlers(toRemove, handlers).reversed(); for (var handlerName : removalSequence) { T handler = handlers.get(handlerName); try { Set<String> existingKeys = keysForHandler(reservedStateMetadata, handlerName); state = remove(handler, new TransformState(state, existingKeys)); } catch (Exception e) { errors.add(format("Error processing %s state removal: %s", handler.name(), stackTrace(e))); } } } checkAndThrowOnError(errors, reservedStateVersion, versionCheck); // Remove the last error if we had previously encountered any in prior processing of reserved state reservedMetadataBuilder.errorMetadata(null); return Tuple.tuple(state, reservedMetadataBuilder.build()); } private void checkAndThrowOnError(List<String> errors, ReservedStateVersion version, ReservedStateVersionCheck versionCheck) { // Any errors should be discovered through validation performed in the transform calls if (errors.isEmpty() == false) { logger.debug("Error processing state change request for [{}] with the following errors [{}]", namespace, errors); var errorState = new ErrorState( projectId(), namespace, version.version(), versionCheck, errors, ReservedStateErrorMetadata.ErrorKind.VALIDATION ); /* * It doesn't matter this reporter needs to re-access the base state, * any updates set by this task will just be discarded when the below exception is thrown, * and we just need to set the error state once */ errorReporter.accept(errorState); throw new IllegalStateException("Error processing state change request for " + namespace + ", errors: " + errorState); } } static Set<String> keysForHandler(ReservedStateMetadata reservedStateMetadata, String handlerName) { if (reservedStateMetadata == null || reservedStateMetadata.handlers().get(handlerName) == null) { return Collections.emptySet(); } return reservedStateMetadata.handlers().get(handlerName).keys(); } static boolean checkMetadataVersion( Optional<ProjectId> projectId, String namespace, ReservedStateMetadata existingMetadata, ReservedStateVersion reservedStateVersion, ReservedStateVersionCheck versionCheck ) { if (reservedStateVersion.buildVersion().isFutureVersion()) { logger.warn( () -> format( "Reserved %s version [%s] for namespace [%s] is not compatible with this Elasticsearch node", projectId.map(p -> "project state [" + p + "]").orElse("cluster state"), reservedStateVersion.buildVersion(), namespace ) ); return false; } Long newVersion = reservedStateVersion.version(); if (newVersion.equals(ReservedStateMetadata.EMPTY_VERSION)) { return true; } // require a regular positive version, reject any special version if (newVersion <= 0L) { logger.warn( () -> format( "Not updating reserved %s for namespace [%s], because version [%s] is less or equal to 0", projectId.map(p -> "project state [" + p + "]").orElse("cluster state"), namespace, newVersion ) ); return false; } if (existingMetadata == null) { return true; } Long currentVersion = existingMetadata.version(); if (versionCheck.test(currentVersion, newVersion)) { return true; } logger.warn( () -> format( "Not updating reserved %s for namespace [%s], because version [%s] is %s the current metadata version [%s]", projectId.map(p -> "project state [" + p + "]").orElse("cluster state"), namespace, newVersion, switch (versionCheck) { case HIGHER_OR_SAME_VERSION -> "less than"; case HIGHER_VERSION_ONLY -> "less than or equal to"; }, currentVersion ) ); return false; } /** * Returns the given {@code handlerNames} in order of their handler dependencies. */ static SequencedSet<String> orderedStateHandlers( Collection<String> handlerNames, Map<String, ? extends ReservedStateHandler<?>> handlersByName ) { LinkedHashSet<String> orderedHandlers = new LinkedHashSet<>(); for (String key : handlerNames) { addStateHandler(handlersByName, key, handlerNames, orderedHandlers, new LinkedHashSet<>()); } assert Set.copyOf(handlerNames).equals(orderedHandlers); return orderedHandlers; } /** * @param inProgress a sequenced set so that "cycle found" error message can list the handlers * in an order that demonstrates the cycle */ private static void addStateHandler( Map<String, ? extends ReservedStateHandler<?>> handlers, String key, Collection<String> keys, SequencedSet<String> ordered, SequencedSet<String> inProgress ) { if (ordered.contains(key)) { // already added by another dependent handler return; } if (false == inProgress.add(key)) { StringBuilder msg = new StringBuilder("Cycle found in settings dependencies: "); inProgress.forEach(s -> { msg.append(s); msg.append(" -> "); }); msg.append(key); throw new IllegalStateException(msg.toString()); } ReservedStateHandler<?> handler = handlers.get(key); if (handler == null) { throw new IllegalStateException("Unknown handler type: " + key); } for (String dependency : handler.dependencies()) { if (keys.contains(dependency) == false) { throw new IllegalStateException("Missing handler dependency definition: " + key + " -> " + dependency); } addStateHandler(handlers, dependency, keys, ordered, inProgress); } for (String dependency : handler.optionalDependencies()) { if (keys.contains(dependency)) { addStateHandler(handlers, dependency, keys, ordered, inProgress); } } inProgress.remove(key); ordered.add(key); } }
ReservedStateUpdateTask
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestUserDefinedCounters.java
{ "start": 2005, "end": 4430 }
class ____<K, V> extends IdentityMapper<K, V> { public void map(K key, V value, OutputCollector<K, V> output, Reporter reporter) throws IOException { output.collect(key, value); reporter.incrCounter(EnumCounter.MAP_RECORDS, 1); reporter.incrCounter("StringCounter", "MapRecords", 1); } } private void cleanAndCreateInput(FileSystem fs) throws IOException { fs.delete(INPUT_DIR, true); fs.delete(OUTPUT_DIR, true); OutputStream os = fs.create(INPUT_FILE); Writer wr = new OutputStreamWriter(os); wr.write("hello1\n"); wr.write("hello2\n"); wr.write("hello3\n"); wr.write("hello4\n"); wr.close(); } @Test public void testMapReduceJob() throws Exception { JobConf conf = new JobConf(TestUserDefinedCounters.class); conf.setJobName("UserDefinedCounters"); FileSystem fs = FileSystem.get(conf); cleanAndCreateInput(fs); conf.setInputFormat(TextInputFormat.class); conf.setMapOutputKeyClass(LongWritable.class); conf.setMapOutputValueClass(Text.class); conf.setOutputFormat(TextOutputFormat.class); conf.setOutputKeyClass(LongWritable.class); conf.setOutputValueClass(Text.class); conf.setMapperClass(CountingMapper.class); conf.setReducerClass(IdentityReducer.class); FileInputFormat.setInputPaths(conf, INPUT_DIR); FileOutputFormat.setOutputPath(conf, OUTPUT_DIR); RunningJob runningJob = JobClient.runJob(conf); Path[] outputFiles = FileUtil.stat2Paths( fs.listStatus(OUTPUT_DIR, new Utils.OutputFileUtils.OutputFilesFilter())); if (outputFiles.length > 0) { InputStream is = fs.open(outputFiles[0]); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = reader.readLine(); int counter = 0; while (line != null) { counter++; assertTrue(line.contains("hello")); line = reader.readLine(); } reader.close(); assertEquals(4, counter); } verifyCounters(runningJob, 4); } public static void verifyCounters(RunningJob runningJob, int expected) throws IOException { assertEquals(expected, runningJob.getCounters().getCounter(EnumCounter.MAP_RECORDS)); assertEquals(expected, runningJob.getCounters().getGroup("StringCounter") .getCounter("MapRecords")); } }
CountingMapper
java
apache__dubbo
dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ReflectionTypeDescriberRegistrar.java
{ "start": 920, "end": 1012 }
interface ____ { List<TypeDescriber> getTypeDescribers(); }
ReflectionTypeDescriberRegistrar
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateFunctionTest_3.java
{ "start": 1021, "end": 6761 }
class ____ extends OracleTest { public void test_types() throws Exception { String sql = // "FUNCTION FN_LGN_CHK(USERINFO IN VARCHAR2)\n" + " RETURN VARCHAR2 IS\n" + " -- Author : yuguoq\n" + " -- Created : 2013-10-14\n" + " -- Purpose : ??????\n" + " RESULT VARCHAR2(20);\n" + " TYPE TYPE_ARRAY IS VARRAY(3) OF VARCHAR2(50);\n" + " VAR_ARRAY TYPE_ARRAY := TYPE_ARRAY();\n" + " CURSOR VALUECURSOR IS\n" + " SELECT *\n" + " FROM TABLE(CAST(FN_SPLIT(USERINFO, ',') AS TY_STR_SPLIT))\n" + " WHERE ROWNUM < 4;\n" + " CURPOLICYINFO VALUECURSOR%ROWTYPE; ---??????\n" + " I INTEGER := 1;\n" + "BEGIN\n" + " OPEN VALUECURSOR; ---open cursor\n" + " LOOP\n" + " --deal with extraction data from DB\n" + " FETCH VALUECURSOR\n" + " INTO CURPOLICYINFO;\n" + " EXIT WHEN VALUECURSOR%NOTFOUND;\n" + " VAR_ARRAY.EXTEND;\n" + " VAR_ARRAY(I) := CURPOLICYINFO.COLUMN_VALUE;\n" + " I := I + 1;\n" + " END LOOP;\n" + " if VAR_ARRAY.count <> 3 then\n" + " RESULT := '1';\n" + " else\n" + " IF VAR_ARRAY(3) = md5(VAR_ARRAY(1) || VAR_ARRAY(2)) THEN\n" + " RESULT := VAR_ARRAY(1);\n" + " ELSE\n" + " RESULT := '1';\n" + " END IF;\n" + " end if;\n" + " RETURN(RESULT);\n" + "EXCEPTION\n" + " WHEN OTHERS THEN\n" + " CLOSE VALUECURSOR;\n" + " DBMS_OUTPUT.PUT_LINE(SQLERRM);\n" + " IF VALUECURSOR%ISOPEN THEN\n" + " --close cursor\n" + " CLOSE VALUECURSOR;\n" + " END IF;\n" + "END FN_LGN_CHK;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); assertEquals("FUNCTION FN_LGN_CHK (\n" + "\tUSERINFO IN VARCHAR2\n" + ")\n" + "RETURN VARCHAR2\n" + "IS\n" + "RESULT VARCHAR2(20);\n" + "\tTYPE TYPE_ARRAY IS VARRAY(3) OF VARCHAR2(50);\n" + "\tVAR_ARRAY TYPE_ARRAY := TYPE_ARRAY();\n" + "\tCURSOR VALUECURSOR IS\n" + "\t\tSELECT *\n" + "\t\tFROM TABLE(CAST(FN_SPLIT(USERINFO, ',') AS TY_STR_SPLIT))\n" + "\t\tWHERE ROWNUM < 4;\n" + "\tCURPOLICYINFO VALUECURSOR%ROWTYPE;\n" + "\tI INTEGER := 1;\n" + "BEGIN\n" + "\tOPEN VALUECURSOR;\n" + "\tLOOP\n" + "\t\tFETCH VALUECURSOR INTO CURPOLICYINFO;\n" + "\t\tEXIT WHEN VALUECURSOR%NOTFOUND;\n" + "\t\tVAR_ARRAY.EXTEND;\n" + "\t\tVAR_ARRAY(I) := CURPOLICYINFO.COLUMN_VALUE;\n" + "\t\tI := I + 1;\n" + "\tEND LOOP;\n" + "\tIF VAR_ARRAY.count <> 3 THEN\n" + "\t\tRESULT := '1';\n" + "\tELSE\n" + "\t\tIF VAR_ARRAY(3) = md5(VAR_ARRAY(1) || VAR_ARRAY(2)) THEN\n" + "\t\t\tRESULT := VAR_ARRAY(1);\n" + "\t\tELSE\n" + "\t\t\tRESULT := '1';\n" + "\t\tEND IF;\n" + "\tEND IF;\n" + "\tRETURN (RESULT);\n" + "EXCEPTION\n" + "\tWHEN OTHERS THEN\n" + "\t\tCLOSE VALUECURSOR;\n" + "\t\tDBMS_OUTPUT.PUT_LINE(SQLERRM);\n" + "\t\tIF VALUECURSOR % ISOPEN THEN\n" + "\t\t\tCLOSE VALUECURSOR;\n" + "\t\tEND IF;\n" + "END;", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.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(1, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("orders", "order_total"))); } }
OracleCreateFunctionTest_3
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/TopicNameExtractor.java
{ "start": 854, "end": 1003 }
interface ____ allows to dynamically determine the name of the Kafka topic to send at the sink node of the topology. */ @FunctionalInterface public
that
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/AddRequestHeaderGatewayFilterFactory.java
{ "start": 1219, "end": 2263 }
class ____ extends AbstractNameValueGatewayFilterFactory { @Override public GatewayFilter apply(NameValueConfig config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String name = Objects.requireNonNull(config.getName(), "name must not be null"); String rawValue = Objects.requireNonNull(config.getValue(), "value must not be null"); String value = ServerWebExchangeUtils.expand(exchange, rawValue); ServerHttpRequest request = exchange.getRequest() .mutate() .headers(httpHeaders -> httpHeaders.add(name, value)) .build(); return chain.filter(exchange.mutate().request(request).build()); } @Override public String toString() { String name = config.getName(); String value = config.getValue(); return filterToStringCreator(AddRequestHeaderGatewayFilterFactory.this) .append(name != null ? name : "", value != null ? value : "") .toString(); } }; } }
AddRequestHeaderGatewayFilterFactory
java
apache__spark
sql/hive/src/main/java/org/apache/hadoop/hive/ql/exec/SparkDefaultUDFMethodResolver.java
{ "start": 1319, "end": 2338 }
class ____ the UDF. */ private final Class<? extends UDF> udfClass; /** * Constructor. This constructor extract udfClass from {@link DefaultUDFMethodResolver} */ @SuppressWarnings("unchecked") public SparkDefaultUDFMethodResolver(DefaultUDFMethodResolver wrapped) { try { Field udfClassField = wrapped.getClass().getDeclaredField("udfClass"); udfClassField.setAccessible(true); this.udfClass = (Class<? extends UDF>) udfClassField.get(wrapped); } catch (ReflectiveOperationException rethrow) { throw new RuntimeException(rethrow); } } /** * Gets the evaluate method for the UDF given the parameter types. * * @param argClasses * The list of the argument types that need to matched with the * evaluate function signature. */ @Override public Method getEvalMethod(List<TypeInfo> argClasses) throws UDFArgumentException { return HiveFunctionRegistryUtils.getMethodInternal(udfClass, "evaluate", false, argClasses); } }
of
java
apache__camel
components/camel-thrift/src/test/java/org/apache/camel/component/thrift/generated/Calculator.java
{ "start": 151246, "end": 157542 }
enum ____ implements org.apache.thrift.TFieldIdEnum { ; private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch (fieldId) { default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } @Override public short getThriftFieldId() { return _thriftId; } @Override public java.lang.String getFieldName() { return _fieldName; } } public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(zip_args.class, metaDataMap); } public zip_args() { } /** * Performs a deep copy on <i>other</i>. */ public zip_args(zip_args other) { } @Override public zip_args deepCopy() { return new zip_args(this); } @Override public void clear() { } @Override public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { } } @org.apache.thrift.annotation.Nullable @Override public java.lang.Object getFieldValue(_Fields field) { switch (field) { } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ @Override public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof zip_args) return this.equals((zip_args) that); return false; } public boolean equals(zip_args that) { if (that == null) return false; if (this == that) return true; return true; } @Override public int hashCode() { int hashCode = 1; return hashCode; } @Override public int compareTo(zip_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; return 0; } @org.apache.thrift.annotation.Nullable @Override public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } @Override public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } @Override public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("zip_args("); boolean first = true; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static
_Fields
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/utils/ThreadLocalCache.java
{ "start": 1128, "end": 1949 }
class ____<K, V> { private static final int DEFAULT_CACHE_SIZE = 64; private final ThreadLocal<BoundedMap<K, V>> cache = new ThreadLocal<>(); private final int maxSizePerThread; protected ThreadLocalCache() { this(DEFAULT_CACHE_SIZE); } protected ThreadLocalCache(int maxSizePerThread) { this.maxSizePerThread = maxSizePerThread; } public V get(K key) { BoundedMap<K, V> map = cache.get(); if (map == null) { map = new BoundedMap<>(maxSizePerThread); cache.set(map); } V value = map.get(key); if (value == null) { value = getNewInstance(key); map.put(key, value); } return value; } public abstract V getNewInstance(K key); private static
ThreadLocalCache
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RBuckets.java
{ "start": 753, "end": 1569 }
interface ____ extends RBucketsAsync { /** * Returns Redis object mapped by key. Result Map is not contains * key-value entry for null values. * * @param <V> type of value * @param keys - keys * @return Map with name of bucket as key and bucket as value */ <V> Map<String, V> get(String... keys); /** * Try to save objects mapped by Redis key. * If at least one of them is already exist then * don't set none of them. * * @param buckets - map of buckets * @return <code>true</code> if object has been set overwise <code>false</code> */ boolean trySet(Map<String, ?> buckets); /** * Saves objects mapped by Redis key. * * @param buckets - map of buckets */ void set(Map<String, ?> buckets); }
RBuckets
java
quarkusio__quarkus
extensions/kafka-streams/runtime/src/main/java/io/quarkus/kafka/streams/runtime/TopologySupplier.java
{ "start": 158, "end": 327 }
class ____ implements Supplier<Topology> { @Override public Topology get() { return Arc.container().instance(Topology.class).get(); } }
TopologySupplier
java
apache__camel
components/camel-schematron/src/main/java/org/apache/camel/component/schematron/SchematronEndpoint.java
{ "start": 6066, "end": 6741 }
class ____ of this component to work in OSGi environments Class<TransformerFactory> factoryClass = getCamelContext().getClassResolver().resolveMandatoryClass(SAXON_TRANSFORMER_FACTORY_CLASS_NAME, TransformerFactory.class, SchematronComponent.class.getClassLoader()); LOG.debug("Using TransformerFactoryClass {}", factoryClass); transformerFactory = getCamelContext().getInjector().newInstance(factoryClass); transformerFactory.setURIResolver(new ClassPathURIResolver(Constants.SCHEMATRON_TEMPLATES_ROOT_DIR, this.uriResolver)); transformerFactory.setAttribute(LINE_NUMBERING, true); } }
loader
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/sql/join/JoinReorderITCase.java
{ "start": 1850, "end": 3284 }
class ____ extends JoinReorderITCaseBase { private StreamExecutionEnvironment env; @AfterEach public void after() { super.after(); StreamTestSink.clear(); } @Override protected TableEnvironment getTableEnvironment() { EnvironmentSettings settings = EnvironmentSettings.newInstance().inStreamingMode().build(); env = StreamExecutionEnvironment.getExecutionEnvironment(); return StreamTableEnvironment.create(env, settings); } @Override protected void assertEquals(String query, List<String> expectedList) { StreamTableEnvironment streamTableEnvironment = (StreamTableEnvironment) tEnv; Table table = streamTableEnvironment.sqlQuery(query); TestingRetractSink sink = new TestingRetractSink(); streamTableEnvironment .toRetractStream(table, Row.class) .map(JavaScalaConversionUtil::toScala, TypeInformation.of(Tuple2.class)) .addSink((SinkFunction) sink); try { env.execute(); } catch (Exception e) { throw new RuntimeException(e); } List<String> results = JavaScalaConversionUtil.toJava(sink.getRetractResults()); results = new ArrayList<>(results); results.sort(String::compareTo); expectedList.sort(String::compareTo); assertThat(results).isEqualTo(expectedList); } }
JoinReorderITCase
java
quarkusio__quarkus
extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/OpenApiDocumentHolder.java
{ "start": 104, "end": 217 }
interface ____ { public byte[] getJsonDocument(); public byte[] getYamlDocument(); }
OpenApiDocumentHolder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/CatchFailTest.java
{ "start": 4735, "end": 5160 }
class ____ { public void test() throws Exception { try { System.err.println(); } catch (Error e) { } } } """) .doTest(); } @Test public void negative_nonTest() { testHelper .addInputLines( "in/Foo.java", """ import org.junit.Test;
Test
java
hibernate__hibernate-orm
hibernate-community-dialects/src/test/java/org/hibernate/community/dialect/unit/sequence/DerbyTenFiveDialectSequenceInformationExtractorTest.java
{ "start": 671, "end": 1136 }
class ____ extends AbstractSequenceInformationExtractorTest { @Override public Dialect getDialect() { return new DerbyLegacyDialect( DatabaseVersion.make( 10, 5 ) ); } @Override public String expectedQuerySequencesString() { return null; } @Override public Class<? extends SequenceInformationExtractor> expectedSequenceInformationExtractor() { return SequenceInformationExtractorNoOpImpl.class; } }
DerbyTenFiveDialectSequenceInformationExtractorTest
java
apache__camel
components/camel-huawei/camel-huaweicloud-dms/src/main/java/org/apache/camel/component/huaweicloud/dms/models/ClientConfigurations.java
{ "start": 1084, "end": 5053 }
class ____ { private String operation; private String engine; private String instanceId; private String name; private String engineVersion; private String specification; private Integer storageSpace; private Integer partitionNum; private String accessUser; private String password; private String vpcId; private String securityGroupId; private String subnetId; private String availableZones; private String productId; private String kafkaManagerUser; private String kafkaManagerPassword; private String storageSpecCode; public ClientConfigurations() { } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } public String getEngine() { return engine; } public void setEngine(String engine) { this.engine = engine; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEngineVersion() { return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } public String getSpecification() { return specification; } public void setSpecification(String specification) { this.specification = specification; } public Integer getStorageSpace() { return storageSpace; } public void setStorageSpace(Integer storageSpace) { this.storageSpace = storageSpace; } public Integer getPartitionNum() { return partitionNum; } public void setPartitionNum(Integer partitionNum) { this.partitionNum = partitionNum; } public String getAccessUser() { return accessUser; } public void setAccessUser(String accessUser) { this.accessUser = accessUser; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getVpcId() { return vpcId; } public void setVpcId(String vpcId) { this.vpcId = vpcId; } public String getSecurityGroupId() { return securityGroupId; } public void setSecurityGroupId(String securityGroupId) { this.securityGroupId = securityGroupId; } public String getSubnetId() { return subnetId; } public void setSubnetId(String subnetId) { this.subnetId = subnetId; } public String getAvailableZones() { return availableZones; } public Collection<String> getAvailableZonesAsList() { if (availableZones != null) { return List.of(availableZones.split(",")); } else { return null; } } public void setAvailableZones(String availableZones) { this.availableZones = availableZones; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getKafkaManagerUser() { return kafkaManagerUser; } public void setKafkaManagerUser(String kafkaManagerUser) { this.kafkaManagerUser = kafkaManagerUser; } public String getKafkaManagerPassword() { return kafkaManagerPassword; } public void setKafkaManagerPassword(String kafkaManagerPassword) { this.kafkaManagerPassword = kafkaManagerPassword; } public String getStorageSpecCode() { return storageSpecCode; } public void setStorageSpecCode(String storageSpecCode) { this.storageSpecCode = storageSpecCode; } }
ClientConfigurations