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
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java
{ "start": 3656, "end": 24474 }
class ____ extends AbstractApplicationEventListenerTests { @Test void multicastSimpleEvent() { multicastEvent(true, ApplicationListener.class, new ContextRefreshedEvent(new StaticApplicationContext()), null); multicastEvent(true, ApplicationListener.class, new ContextClosedEvent(new StaticApplicationContext()), null); } @Test void multicastGenericEvent() { multicastEvent(true, StringEventListener.class, createGenericTestEvent("test"), ResolvableType.forClassWithGenerics(GenericTestEvent.class, String.class)); } @Test void multicastGenericEventWrongType() { multicastEvent(false, StringEventListener.class, createGenericTestEvent(123L), ResolvableType.forClassWithGenerics(GenericTestEvent.class, Long.class)); } @Test void multicastGenericEventWildcardSubType() { multicastEvent(false, StringEventListener.class, createGenericTestEvent("test"), getGenericApplicationEventType("wildcardEvent")); } @Test void multicastConcreteTypeGenericListener() { multicastEvent(true, StringEventListener.class, new StringEvent(this, "test"), null); } @Test void multicastConcreteWrongTypeGenericListener() { multicastEvent(false, StringEventListener.class, new LongEvent(this, 123L), null); } @Test void multicastSmartGenericTypeGenericListener() { multicastEvent(true, StringEventListener.class, new SmartGenericTestEvent<>(this, "test"), null); } @Test void multicastSmartGenericWrongTypeGenericListener() { multicastEvent(false, StringEventListener.class, new SmartGenericTestEvent<>(this, 123L), null); } private void multicastEvent(boolean match, Class<?> listenerType, ApplicationEvent event, ResolvableType eventType) { @SuppressWarnings("unchecked") ApplicationListener<ApplicationEvent> listener = (ApplicationListener<ApplicationEvent>) mock(listenerType); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.addApplicationListener(listener); if (eventType != null) { smc.multicastEvent(event, eventType); } else { smc.multicastEvent(event); } int invocation = (match ? 1 : 0); verify(listener, times(invocation)).onApplicationEvent(event); } @Test void simpleApplicationEventMulticasterWithTaskExecutor() { @SuppressWarnings("unchecked") ApplicationListener<ApplicationEvent> listener = mock(); willReturn(true).given(listener).supportsAsyncExecution(); ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext()); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); AtomicBoolean invoked = new AtomicBoolean(); smc.setTaskExecutor(command -> { invoked.set(true); command.run(); command.run(); }); smc.addApplicationListener(listener); smc.multicastEvent(evt); assertThat(invoked.get()).isTrue(); verify(listener, times(2)).onApplicationEvent(evt); } @Test void simpleApplicationEventMulticasterWithTaskExecutorAndNonAsyncListener() { @SuppressWarnings("unchecked") ApplicationListener<ApplicationEvent> listener = mock(); willReturn(false).given(listener).supportsAsyncExecution(); ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext()); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); AtomicBoolean invoked = new AtomicBoolean(); smc.setTaskExecutor(command -> { invoked.set(true); command.run(); command.run(); }); smc.addApplicationListener(listener); smc.multicastEvent(evt); assertThat(invoked.get()).isFalse(); verify(listener, times(1)).onApplicationEvent(evt); } @Test void simpleApplicationEventMulticasterWithException() { @SuppressWarnings("unchecked") ApplicationListener<ApplicationEvent> listener = mock(); ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext()); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.addApplicationListener(listener); RuntimeException thrown = new RuntimeException(); willThrow(thrown).given(listener).onApplicationEvent(evt); assertThatRuntimeException() .isThrownBy(() -> smc.multicastEvent(evt)) .isSameAs(thrown); } @Test void simpleApplicationEventMulticasterWithErrorHandler() { @SuppressWarnings("unchecked") ApplicationListener<ApplicationEvent> listener = mock(); ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext()); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.setErrorHandler(TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER); smc.addApplicationListener(listener); willThrow(new RuntimeException()).given(listener).onApplicationEvent(evt); smc.multicastEvent(evt); } @Test void orderedListeners() { MyOrderedListener1 listener1 = new MyOrderedListener1(); MyOrderedListener2 listener2 = new MyOrderedListener2(listener1); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.addApplicationListener(listener2); smc.addApplicationListener(listener1); smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); assertThat(listener1.seenEvents).hasSize(2); } @Test void orderedListenersWithAnnotation() { MyOrderedListener3 listener1 = new MyOrderedListener3(); MyOrderedListener4 listener2 = new MyOrderedListener4(listener1); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.addApplicationListener(listener2); smc.addApplicationListener(listener1); smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); assertThat(listener1.seenEvents).hasSize(2); } @Test @SuppressWarnings("unchecked") public void proxiedListeners() { MyOrderedListener1 listener1 = new MyOrderedListener1(); MyOrderedListener2 listener2 = new MyOrderedListener2(listener1); ApplicationListener<ApplicationEvent> proxy1 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener1).getProxy(); ApplicationListener<ApplicationEvent> proxy2 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener2).getProxy(); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.addApplicationListener(proxy1); smc.addApplicationListener(proxy2); smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); assertThat(listener1.seenEvents).hasSize(2); } @Test @SuppressWarnings("unchecked") public void proxiedListenersMixedWithTargetListeners() { MyOrderedListener1 listener1 = new MyOrderedListener1(); MyOrderedListener2 listener2 = new MyOrderedListener2(listener1); ApplicationListener<ApplicationEvent> proxy1 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener1).getProxy(); ApplicationListener<ApplicationEvent> proxy2 = (ApplicationListener<ApplicationEvent>) new ProxyFactory(listener2).getProxy(); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.addApplicationListener(listener1); smc.addApplicationListener(listener2); smc.addApplicationListener(proxy1); smc.addApplicationListener(proxy2); smc.multicastEvent(new MyEvent(this)); smc.multicastEvent(new MyOtherEvent(this)); assertThat(listener1.seenEvents).hasSize(2); } /** * Regression test for <a href="https://github.com/spring-projects/spring-framework/issues/28283">issue 28283</a>, * where event listeners proxied due to, for example, * <ul> * <li>{@code @Transactional} annotations in their methods or</li> * <li>being targeted by aspects</li> * </ul> * were added to the list of application listener beans twice (both proxy and unwrapped target). */ @Test void eventForSelfInjectedProxiedListenerFiredOnlyOnce() { AbstractApplicationContext context = new AnnotationConfigApplicationContext( MyAspect.class, MyEventListener.class, MyEventPublisher.class); context.getBean(MyEventPublisher.class).publishMyEvent("hello"); assertThat(context.getBean(MyEventListener.class).eventCount).isEqualTo(1); context.close(); } @Test void testEventPublicationInterceptor() throws Throwable { MethodInvocation invocation = mock(); ApplicationContext ctx = mock(); EventPublicationInterceptor interceptor = new EventPublicationInterceptor(); interceptor.setApplicationEventClass(MyEvent.class); interceptor.setApplicationEventPublisher(ctx); interceptor.afterPropertiesSet(); given(invocation.proceed()).willReturn(new Object()); given(invocation.getThis()).willReturn(new Object()); interceptor.invoke(invocation); verify(ctx).publishEvent(isA(MyEvent.class)); } @Test void listenersInApplicationContext() { StaticApplicationContext context = new StaticApplicationContext(); context.registerBeanDefinition("listener1", new RootBeanDefinition(MyOrderedListener1.class)); RootBeanDefinition listener2 = new RootBeanDefinition(MyOrderedListener2.class); listener2.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference("listener1")); listener2.setLazyInit(true); context.registerBeanDefinition("listener2", listener2); context.refresh(); assertThat(context.getDefaultListableBeanFactory().containsSingleton("listener2")).isFalse(); MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class); MyOtherEvent event1 = new MyOtherEvent(context); context.publishEvent(event1); assertThat(context.getDefaultListableBeanFactory().containsSingleton("listener2")).isFalse(); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); assertThat(context.getDefaultListableBeanFactory().containsSingleton("listener2")).isTrue(); MyEvent event3 = new MyEvent(context); context.publishEvent(event3); MyOtherEvent event4 = new MyOtherEvent(context); context.publishEvent(event4); assertThat(listener1.seenEvents).contains(event1, event2, event3, event4); listener1.seenEvents.clear(); context.publishEvent(event1); context.publishEvent(event2); context.publishEvent(event3); context.publishEvent(event4); assertThat(listener1.seenEvents).contains(event1, event2, event3, event4); AbstractApplicationEventMulticaster multicaster = context.getBean(AbstractApplicationEventMulticaster.class); assertThat(multicaster.retrieverCache).hasSize(2); context.close(); } @Test void listenersInApplicationContextWithPayloadEvents() { StaticApplicationContext context = new StaticApplicationContext(); context.registerBeanDefinition("listener", new RootBeanDefinition(MyPayloadListener.class)); context.refresh(); MyPayloadListener listener = context.getBean("listener", MyPayloadListener.class); context.publishEvent("event1"); context.publishEvent("event2"); context.publishEvent("event3"); context.publishEvent("event4"); assertThat(listener.seenPayloads).contains("event1", "event2", "event3", "event4"); AbstractApplicationEventMulticaster multicaster = context.getBean(AbstractApplicationEventMulticaster.class); assertThat(multicaster.retrieverCache).hasSize(2); context.close(); } @Test void listenersInApplicationContextWithNestedChild() { StaticApplicationContext context = new StaticApplicationContext(); RootBeanDefinition nestedChild = new RootBeanDefinition(StaticApplicationContext.class); nestedChild.getPropertyValues().add("parent", context); nestedChild.setInitMethodName("refresh"); context.registerBeanDefinition("nestedChild", nestedChild); RootBeanDefinition listener1Def = new RootBeanDefinition(MyOrderedListener1.class); listener1Def.setDependsOn("nestedChild"); context.registerBeanDefinition("listener1", listener1Def); context.refresh(); MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); assertThat(listener1.seenEvents).contains(event1); SimpleApplicationEventMulticaster multicaster = context.getBean(SimpleApplicationEventMulticaster.class); assertThat(multicaster.getApplicationListeners()).isNotEmpty(); context.close(); assertThat(multicaster.getApplicationListeners()).isEmpty(); } @Test void nonSingletonListenerInApplicationContext() { StaticApplicationContext context = new StaticApplicationContext(); RootBeanDefinition listener = new RootBeanDefinition(MyNonSingletonListener.class); listener.setScope(BeanDefinition.SCOPE_PROTOTYPE); context.registerBeanDefinition("listener", listener); context.refresh(); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); MyOtherEvent event2 = new MyOtherEvent(context); context.publishEvent(event2); MyEvent event3 = new MyEvent(context); context.publishEvent(event3); MyOtherEvent event4 = new MyOtherEvent(context); context.publishEvent(event4); assertThat(MyNonSingletonListener.seenEvents).contains(event1, event2, event3, event4); MyNonSingletonListener.seenEvents.clear(); context.publishEvent(event1); context.publishEvent(event2); context.publishEvent(event3); context.publishEvent(event4); assertThat(MyNonSingletonListener.seenEvents).contains(event1, event2, event3, event4); MyNonSingletonListener.seenEvents.clear(); AbstractApplicationEventMulticaster multicaster = context.getBean(AbstractApplicationEventMulticaster.class); assertThat(multicaster.retrieverCache).hasSize(3); context.close(); } @Test void listenerAndBroadcasterWithCircularReference() { StaticApplicationContext context = new StaticApplicationContext(); context.registerBeanDefinition("broadcaster", new RootBeanDefinition(BeanThatBroadcasts.class)); RootBeanDefinition listenerDef = new RootBeanDefinition(BeanThatListens.class); listenerDef.getConstructorArgumentValues().addGenericArgumentValue(new RuntimeBeanReference("broadcaster")); context.registerBeanDefinition("listener", listenerDef); context.refresh(); BeanThatBroadcasts broadcaster = context.getBean("broadcaster", BeanThatBroadcasts.class); context.publishEvent(new MyEvent(context)); assertThat(broadcaster.receivedCount).as("The event was not received by the listener").isEqualTo(2); context.close(); } @Test void innerBeanAsListener() { StaticApplicationContext context = new StaticApplicationContext(); RootBeanDefinition listenerDef = new RootBeanDefinition(TestBean.class); listenerDef.getPropertyValues().add("friends", new RootBeanDefinition(BeanThatListens.class)); context.registerBeanDefinition("listener", listenerDef); context.refresh(); context.publishEvent(new MyEvent(this)); context.publishEvent(new MyEvent(this)); TestBean listener = context.getBean(TestBean.class); assertThat(((BeanThatListens) listener.getFriends().iterator().next()).getEventCount()).isEqualTo(3); context.close(); } @Test void anonymousClassAsListener() { final Set<MyEvent> seenEvents = new HashSet<>(); StaticApplicationContext context = new StaticApplicationContext(); context.addApplicationListener((MyEvent event) -> seenEvents.add(event)); context.refresh(); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); context.publishEvent(new MyOtherEvent(context)); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); assertThat(seenEvents).contains(event1, event2); context.close(); } @Test void lambdaAsListener() { final Set<MyEvent> seenEvents = new HashSet<>(); StaticApplicationContext context = new StaticApplicationContext(); ApplicationListener<MyEvent> listener = seenEvents::add; context.addApplicationListener(listener); context.refresh(); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); context.publishEvent(new MyOtherEvent(context)); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); assertThat(seenEvents).contains(event1, event2); context.close(); } @Test void lambdaAsListenerWithErrorHandler() { final Set<MyEvent> seenEvents = new HashSet<>(); StaticApplicationContext context = new StaticApplicationContext(); SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(); multicaster.setErrorHandler(ReflectionUtils::rethrowRuntimeException); context.getBeanFactory().registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, multicaster); ApplicationListener<MyEvent> listener = seenEvents::add; context.addApplicationListener(listener); context.refresh(); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); context.publishEvent(new MyOtherEvent(context)); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); assertThat(seenEvents).containsExactlyInAnyOrder(event1, event2); context.close(); } @Test void lambdaAsListenerWithJava8StyleClassCastMessage() { StaticApplicationContext context = new StaticApplicationContext(); ApplicationListener<ApplicationEvent> listener = event -> { throw new ClassCastException(event.getClass().getName()); }; context.addApplicationListener(listener); context.refresh(); context.publishEvent(new MyEvent(context)); context.close(); } @Test void lambdaAsListenerWithJava9StyleClassCastMessage() { StaticApplicationContext context = new StaticApplicationContext(); ApplicationListener<ApplicationEvent> listener = event -> { throw new ClassCastException("spring.context/" + event.getClass().getName()); }; context.addApplicationListener(listener); context.refresh(); context.publishEvent(new MyEvent(context)); context.close(); } @Test @SuppressWarnings("unchecked") void addListenerWithConsumer() { Consumer<ContextRefreshedEvent> consumer = mock(Consumer.class); GenericApplicationContext context = new GenericApplicationContext(); context.addApplicationListener(GenericApplicationListener.forEventType( ContextRefreshedEvent.class, consumer)); context.refresh(); ArgumentCaptor<ContextRefreshedEvent> captor = ArgumentCaptor.forClass(ContextRefreshedEvent.class); verify(consumer).accept(captor.capture()); assertThat(captor.getValue().getApplicationContext()).isSameAs(context); verifyNoMoreInteractions(consumer); } @Test void beanPostProcessorPublishesEvents() { GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition("listener", new RootBeanDefinition(BeanThatListens.class)); context.registerBeanDefinition("messageSource", new RootBeanDefinition(StaticMessageSource.class)); context.registerBeanDefinition("postProcessor", new RootBeanDefinition(EventPublishingBeanPostProcessor.class)); context.refresh(); context.publishEvent(new MyEvent(this)); BeanThatListens listener = context.getBean(BeanThatListens.class); assertThat(listener.getEventCount()).isEqualTo(4); context.close(); } @Test void initMethodPublishesEvent() { // gh-25799 GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition("listener", new RootBeanDefinition(BeanThatListens.class)); context.registerBeanDefinition("messageSource", new RootBeanDefinition(StaticMessageSource.class)); context.registerBeanDefinition("initMethod", new RootBeanDefinition(EventPublishingInitMethod.class)); context.refresh(); context.publishEvent(new MyEvent(this)); BeanThatListens listener = context.getBean(BeanThatListens.class); assertThat(listener.getEventCount()).isEqualTo(3); context.close(); } @Test void initMethodPublishesAsyncEvent() { // gh-25799 GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition("listener", new RootBeanDefinition(BeanThatListens.class)); context.registerBeanDefinition("messageSource", new RootBeanDefinition(StaticMessageSource.class)); context.registerBeanDefinition("initMethod", new RootBeanDefinition(AsyncEventPublishingInitMethod.class)); context.refresh(); context.publishEvent(new MyEvent(this)); BeanThatListens listener = context.getBean(BeanThatListens.class); assertThat(listener.getEventCount()).isEqualTo(3); context.close(); } @Test void initMethodPublishesAsyncEventBeforeListenerInitialized() { // gh-20904 GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition("messageSource", new RootBeanDefinition(StaticMessageSource.class)); context.registerBeanDefinition("initMethod", new RootBeanDefinition(AsyncEventPublishingInitMethod.class)); context.registerBeanDefinition("listener", new RootBeanDefinition(BeanThatListens.class)); context.refresh(); context.publishEvent(new MyEvent(this)); BeanThatListens listener = context.getBean(BeanThatListens.class); assertThat(listener.getEventCount()).isEqualTo(3); context.close(); } @SuppressWarnings("serial") public static
ApplicationContextEventTests
java
junit-team__junit5
junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/Constants.java
{ "start": 4980, "end": 5586 }
class ____ (<em>FQCN</em>) of each extension. * Any dot ({@code .}) in a pattern will match against a dot ({@code .}) * or a dollar sign ({@code $}) in a FQCN. Any asterisk ({@code *}) will match * against one or more characters in a FQCN. All other characters in a pattern * will be matched one-to-one against a FQCN. * * <h4>Examples</h4> * * <ul> * <li>{@code *}: excludes all extensions. * <li>{@code org.junit.*}: excludes every extension under the {@code org.junit} * base package and any of its subpackages. * <li>{@code *.MyExtension}: excludes every extension whose simple
name
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java
{ "start": 26441, "end": 26647 }
interface ____ { @AliasFor("basePackage") String value() default ""; @AliasFor("value") String basePackage() default ""; } @Retention(RetentionPolicy.RUNTIME) @ControllerAdvice @
ControllerAdvice
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/RandomAlgorithms.java
{ "start": 2209, "end": 2997 }
class ____ implements IndexMapper { int[] mapping; DenseIndexMapper(int size) { mapping = new int[size]; for (int i=0; i<size; ++i) { mapping[i] = i; } } public int get(int pos) { if ( (pos < 0) || (pos>=mapping.length) ) { throw new IndexOutOfBoundsException(); } return mapping[pos]; } public void swap(int a, int b) { if (a == b) return; int valA = get(a); int valB = get(b); mapping[a]=valB; mapping[b]=valA; } public int getSize() { return mapping.length; } public void reset() { return; } } /** * Iteratively pick random numbers from pool 0..n-1. Each number can only be * picked once. */ public static
DenseIndexMapper
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractUdfStreamOperator.java
{ "start": 2303, "end": 6746 }
class ____<OUT, F extends Function> extends AbstractStreamOperator<OUT> implements OutputTypeConfigurable<OUT>, UserFunctionProvider<F> { private static final long serialVersionUID = 1L; /** The user function. */ protected final F userFunction; public AbstractUdfStreamOperator(F userFunction) { this(null, userFunction); } protected AbstractUdfStreamOperator(StreamOperatorParameters<OUT> parameters, F userFunction) { super(parameters); this.userFunction = requireNonNull(userFunction); checkUdfCheckpointingPreconditions(); } /** * Gets the user function executed in this operator. * * @return The user function of this operator. */ public F getUserFunction() { return userFunction; } // ------------------------------------------------------------------------ // operator life cycle // ------------------------------------------------------------------------ @Override protected void setup( StreamTask<?, ?> containingTask, StreamConfig config, Output<StreamRecord<OUT>> output) { super.setup(containingTask, config, output); FunctionUtils.setFunctionRuntimeContext(userFunction, getRuntimeContext()); } @Override public void snapshotState(StateSnapshotContext context) throws Exception { super.snapshotState(context); StreamingFunctionUtils.snapshotFunctionState( context, getOperatorStateBackend(), userFunction); } @Override public void initializeState(StateInitializationContext context) throws Exception { super.initializeState(context); StreamingFunctionUtils.restoreFunctionState(context, userFunction); } @Override public void open() throws Exception { super.open(); FunctionUtils.openFunction(userFunction, DefaultOpenContext.INSTANCE); } @Override public void finish() throws Exception { super.finish(); if (userFunction instanceof SinkFunction) { ((SinkFunction<?>) userFunction).finish(); } } @Override public void close() throws Exception { super.close(); FunctionUtils.closeFunction(userFunction); } // ------------------------------------------------------------------------ // checkpointing and recovery // ------------------------------------------------------------------------ @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { super.notifyCheckpointComplete(checkpointId); if (userFunction instanceof CheckpointListener) { ((CheckpointListener) userFunction).notifyCheckpointComplete(checkpointId); } } @Override public void notifyCheckpointAborted(long checkpointId) throws Exception { super.notifyCheckpointAborted(checkpointId); if (userFunction instanceof CheckpointListener) { ((CheckpointListener) userFunction).notifyCheckpointAborted(checkpointId); } } // ------------------------------------------------------------------------ // Output type configuration // ------------------------------------------------------------------------ @Override public void setOutputType(TypeInformation<OUT> outTypeInfo, ExecutionConfig executionConfig) { StreamingFunctionUtils.setOutputType(userFunction, outTypeInfo, executionConfig); } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ /** * Since the streaming API does not implement any parametrization of functions via a * configuration, the config returned here is actually empty. * * @return The user function parameters (currently empty) */ public Configuration getUserFunctionParameters() { return new Configuration(); } private void checkUdfCheckpointingPreconditions() { if (userFunction instanceof CheckpointedFunction && userFunction instanceof ListCheckpointed) { throw new IllegalStateException( "User functions are not allowed to implement " + "CheckpointedFunction AND ListCheckpointed."); } } }
AbstractUdfStreamOperator
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_cduym.java
{ "start": 295, "end": 1572 }
class ____ extends TestCase { protected void setUp() throws Exception { ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_cduym"); } @SuppressWarnings("rawtypes") public void test0() { List<A> as = new ArrayList<A>(); A a1 = new A(); a1.setA(1000); a1.setB(2000l); a1.setC("xxx"); as.add(a1); as.add(a1); String text = JSON.toJSONString(as, SerializerFeature.WriteClassName); System.out.println(text); List<?> target = (List) JSON.parseObject(text, Object.class); Assert.assertSame(target.get(0), target.get(1)); } public void test1() { List<A> as = new ArrayList<A>(); A a1 = new A(); a1.setA(1000); a1.setB(2000l); a1.setC("xxx"); as.add(a1); as.add(a1); Demo o = new Demo(); o.setAs(as); String text = JSON.toJSONString(o, SerializerFeature.WriteClassName); System.out.println(text); Demo target = (Demo) JSON.parseObject(text, Object.class); Assert.assertSame(((List)target.getAs()).get(0), ((List)target.getAs()).get(1)); } public static
Bug_for_cduym
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/ProductViewTest.java
{ "start": 138, "end": 439 }
class ____ extends TestCase { public void test_parse() throws Exception { String text = "{\"code\":0,\"message\":\"Register Successfully!\",\"status\":\"OK\"}"; Map map = JSON.parseObject(text, Map.class); System.out.println(map.get("code").getClass()); } }
ProductViewTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/TestCodecFactory.java
{ "start": 2935, "end": 3084 }
class ____ extends BaseCodec { @Override public String getDefaultExtension() { return ".foo.bar"; } } private static
FooBarCodec
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java
{ "start": 10037, "end": 10174 }
class ____ { } @ImportOne @ImportTwo @ImportAutoConfiguration(exclude = AnotherImportedAutoConfiguration.class) static
MultipleImports
java
apache__flink
flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/util/LogLevelExtension.java
{ "start": 1660, "end": 4566 }
class ____ implements BeforeAllCallback, AfterAllCallback { public static final boolean LOGGING_ENABLED = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME).isErrorEnabled(); private Map<String, Level> testLevels = new HashMap<>(); private List<Runnable> resetActions = new ArrayList<>(); private static final Map<Level, org.apache.logging.log4j.Level> SLF_TO_LOG4J = new HashMap<>(); private LoggerContext log4jContext; static { SLF_TO_LOG4J.put(Level.ERROR, org.apache.logging.log4j.Level.ERROR); SLF_TO_LOG4J.put(Level.WARN, org.apache.logging.log4j.Level.WARN); SLF_TO_LOG4J.put(Level.INFO, org.apache.logging.log4j.Level.INFO); SLF_TO_LOG4J.put(Level.DEBUG, org.apache.logging.log4j.Level.DEBUG); SLF_TO_LOG4J.put(Level.TRACE, org.apache.logging.log4j.Level.TRACE); } @Override public void beforeAll(ExtensionContext context) throws Exception { if (!LOGGING_ENABLED) { return; } for (Map.Entry<String, Level> levelEntry : testLevels.entrySet()) { final Logger logger = LoggerFactory.getLogger(levelEntry.getKey()); if (logger instanceof Log4jLogger) { setLog4jLevel(levelEntry.getKey(), levelEntry.getValue()); } else { throw new UnsupportedOperationException("Cannot change log level of " + logger); } } if (log4jContext != null) { log4jContext.updateLoggers(); } } private void setLog4jLevel(String logger, Level level) { if (log4jContext == null) { log4jContext = (LoggerContext) LogManager.getContext(false); } final Configuration conf = log4jContext.getConfiguration(); LoggerConfig loggerConfig = conf.getLoggers().get(logger); if (loggerConfig != null) { final org.apache.logging.log4j.Level oldLevel = loggerConfig.getLevel(); loggerConfig.setLevel(SLF_TO_LOG4J.get(level)); resetActions.add(() -> loggerConfig.setLevel(oldLevel)); } else { conf.addLogger(logger, new LoggerConfig(logger, SLF_TO_LOG4J.get(level), true)); resetActions.add(() -> conf.removeLogger(logger)); } } @Override public void afterAll(ExtensionContext context) throws Exception { resetActions.forEach(Runnable::run); if (log4jContext != null) { log4jContext.updateLoggers(); } } public LogLevelExtension set(Class<?> clazz, Level level) { return set(clazz.getName(), level); } public LogLevelExtension set(Package logPackage, Level level) { return set(logPackage.getName(), level); } public LogLevelExtension set(String classOrPackageName, Level level) { testLevels.put(classOrPackageName, level); return this; } }
LogLevelExtension
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/security/oauthbearer/internals/expiring/ExpiringCredentialRefreshingLogin.java
{ "start": 1419, "end": 1660 }
class ____ responsible for refreshing logins for both Kafka client and * server when the login is a type that has a limited lifetime/will expire. The * credentials for the login must implement {@link ExpiringCredential}. */ public abstract
is
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2347/Issue2347Test.java
{ "start": 675, "end": 1573 }
class ____ { @ExpectedCompilationOutcome(value = CompilationResult.FAILED, diagnostics = { @Diagnostic( type = ErroneousClassWithPrivateMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 41, message = "Cannot create an implementation for mapper PrivateInterfaceMapper," + " because it is a private interface." ), @Diagnostic( type = ErroneousClassWithPrivateMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 47, message = "Cannot create an implementation for mapper PrivateClassMapper," + " because it is a private class." ) } ) @ProcessorTest public void shouldGenerateCompileErrorWhenMapperIsPrivate() { } }
Issue2347Test
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_62_optimized.java
{ "start": 1086, "end": 2511 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "SELECT * from t where t ! = 1"; System.out.println(sql); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcConstants.MYSQL, SQLParserFeature.OptimizedForParameterized); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); { String output = SQLUtils.toMySqlString(stmt); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE t != 1", // output); } { String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION); assertEquals("select *\n" + "from t\n" + "where t != 1", // output); } { String output = SQLUtils.toMySqlString(stmt, new SQLUtils.FormatOption(true, true, true)); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE t != ?", // output); } } }
MySqlSelectTest_62_optimized
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transport/actions/TransportGetWatchAction.java
{ "start": 1863, "end": 5271 }
class ____ extends WatcherTransportAction<GetWatchRequest, GetWatchResponse> { private final WatchParser parser; private final Clock clock; private final Client client; @Inject public TransportGetWatchAction( TransportService transportService, ActionFilters actionFilters, XPackLicenseState licenseState, WatchParser parser, ClockHolder clockHolder, Client client ) { super(GetWatchAction.NAME, transportService, actionFilters, licenseState, GetWatchRequest::new); this.parser = parser; this.clock = clockHolder.clock; this.client = client; } @Override protected void doExecute(GetWatchRequest request, ActionListener<GetWatchResponse> listener) { GetRequest getRequest = new GetRequest(Watch.INDEX, request.getId()).preference(Preference.LOCAL.type()).realtime(true); executeAsyncWithOrigin( client.threadPool().getThreadContext(), WATCHER_ORIGIN, getRequest, ActionListener.<GetResponse>wrap(getResponse -> { if (getResponse.isExists()) { try (XContentBuilder builder = jsonBuilder()) { // When we return the watch via the Get Watch REST API, we want to return the watch as was specified in // the put api, we don't include the status in the watch source itself, but as a separate top level field, // so that it indicates the status is managed by watcher itself. ZonedDateTime now = clock.instant().atZone(ZoneOffset.UTC); Watch watch = parser.parseWithSecrets( request.getId(), true, getResponse.getSourceAsBytesRef(), now, XContentType.JSON, getResponse.getSeqNo(), getResponse.getPrimaryTerm() ); watch.toXContent(builder, WatcherParams.builder().hideSecrets(true).includeStatus(false).build()); watch.status().version(getResponse.getVersion()); listener.onResponse( new GetWatchResponse( watch.id(), getResponse.getVersion(), watch.getSourceSeqNo(), watch.getSourcePrimaryTerm(), watch.status(), new XContentSource(BytesReference.bytes(builder), XContentType.JSON) ) ); } } else { listener.onResponse(new GetWatchResponse(request.getId())); } }, e -> { // special case. This API should not care if the index is missing or not, // it should respond with the watch not being found if (e instanceof IndexNotFoundException) { listener.onResponse(new GetWatchResponse(request.getId())); } else { listener.onFailure(e); } }), client::get ); } }
TransportGetWatchAction
java
google__dagger
javatests/dagger/internal/codegen/AssistedFactoryErrorsTest.java
{ "start": 24618, "end": 24771 }
class ____ {", " @AssistedInject", " Foo(@Assisted int i) {}", "", " @AssistedFactory", "
Foo
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistration.java
{ "start": 1393, "end": 10403 }
class ____ { private final String[] pathPatterns; private final List<String> locationValues = new ArrayList<>(); private final List<Resource> locationsResources = new ArrayList<>(); private @Nullable Integer cachePeriod; private @Nullable CacheControl cacheControl; private @Nullable ResourceChainRegistration resourceChainRegistration; private boolean useLastModified = true; private @Nullable Function<Resource, String> etagGenerator; private boolean optimizeLocations = false; /** * Create a {@link ResourceHandlerRegistration} instance. * @param pathPatterns one or more resource URL path patterns */ public ResourceHandlerRegistration(String... pathPatterns) { Assert.notEmpty(pathPatterns, "At least one path pattern is required for resource handling."); this.pathPatterns = pathPatterns; } /** * Add one or more resource locations from which to serve static content. * Each location must point to a valid directory. Multiple locations may * be specified as a comma-separated list, and the locations will be checked * for a given resource in the order specified. * <p>For example, {{@code "/"}, {@code "classpath:/META-INF/public-web-resources/"}} * allows resources to be served both from the web application root and * from any JAR on the classpath that contains a * {@code /META-INF/public-web-resources/} directory, with resources in the * web application root taking precedence. * <p>For {@link org.springframework.core.io.UrlResource URL-based resources} * (for example, files, HTTP URLs, etc) this method supports a special prefix to * indicate the charset associated with the URL so that relative paths * appended to it can be encoded correctly, for example, * {@code [charset=Windows-31J]https://example.org/path}. * @return the same {@link ResourceHandlerRegistration} instance, for * chained method invocation */ public ResourceHandlerRegistration addResourceLocations(String... locations) { this.locationValues.addAll(Arrays.asList(locations)); return this; } /** * Configure locations to serve static resources from based on pre-resolved * {@code Resource} references. * @param locations the resource locations to use * @return the same {@link ResourceHandlerRegistration} instance, for * chained method invocation * @since 5.3.3 */ public ResourceHandlerRegistration addResourceLocations(Resource... locations) { this.locationsResources.addAll(Arrays.asList(locations)); return this; } /** * Specify the cache period for the resources served by the resource handler, in seconds. The default is to not * send any cache headers but to rely on last-modified timestamps only. Set to 0 in order to send cache headers * that prevent caching, or to a positive number of seconds to send cache headers with the given max-age value. * @param cachePeriod the time to cache resources in seconds * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation */ public ResourceHandlerRegistration setCachePeriod(Integer cachePeriod) { this.cachePeriod = cachePeriod; return this; } /** * Specify the {@link org.springframework.http.CacheControl} which should be used * by the resource handler. * <p>Setting a custom value here will override the configuration set with {@link #setCachePeriod}. * @param cacheControl the CacheControl configuration to use * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation * @since 4.2 */ public ResourceHandlerRegistration setCacheControl(CacheControl cacheControl) { this.cacheControl = cacheControl; return this; } /** * Set whether the {@link Resource#lastModified()} information should be used to drive HTTP responses. * <p>This configuration is set to {@code true} by default. * @param useLastModified whether the "last modified" resource information should be used * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation * @since 5.3 * @see ResourceHttpRequestHandler#setUseLastModified */ public ResourceHandlerRegistration setUseLastModified(boolean useLastModified) { this.useLastModified = useLastModified; return this; } /** * Configure a generator function that will be used to create the ETag information, * given a {@link Resource} that is about to be written to the response. * <p>This function should return a String that will be used as an argument in * {@link ServerWebExchange#checkNotModified(String)}, or {@code null} if no value * can be generated for the given resource. * @param etagGenerator the HTTP ETag generator function to use. * @since 6.1 * @see ResourceHttpRequestHandler#setEtagGenerator(Function) */ public ResourceHandlerRegistration setEtagGenerator(@Nullable Function<Resource, String> etagGenerator) { this.etagGenerator = etagGenerator; return this; } /** * Set whether to optimize the specified locations through an existence check on startup, * filtering non-existing directories upfront so that they do not have to be checked * on every resource access. * <p>The default is {@code false}, for defensiveness against zip files without directory * entries which are unable to expose the existence of a directory upfront. Switch this flag to * {@code true} for optimized access in case of a consistent jar layout with directory entries. * @param optimizeLocations whether to optimize the locations through an existence check on startup * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation * @since 5.3.13 * @see ResourceHttpRequestHandler#setOptimizeLocations */ public ResourceHandlerRegistration setOptimizeLocations(boolean optimizeLocations) { this.optimizeLocations = optimizeLocations; return this; } /** * Configure a chain of resource resolvers and transformers to use. This * can be useful, for example, to apply a version strategy to resource URLs. * <p>If this method is not invoked, by default only a simple * {@link PathResourceResolver} is used in order to match URL paths to * resources under the configured locations. * @param cacheResources whether to cache the result of resource resolution; * setting this to "true" is recommended for production (and "false" for * development, especially when applying a version strategy) * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation * @since 4.1 */ public ResourceChainRegistration resourceChain(boolean cacheResources) { this.resourceChainRegistration = new ResourceChainRegistration(cacheResources); return this.resourceChainRegistration; } /** * Configure a chain of resource resolvers and transformers to use. This * can be useful, for example, to apply a version strategy to resource URLs. * <p>If this method is not invoked, by default only a simple * {@link PathResourceResolver} is used in order to match URL paths to * resources under the configured locations. * @param cacheResources whether to cache the result of resource resolution; * setting this to "true" is recommended for production (and "false" for * development, especially when applying a version strategy * @param cache the cache to use for storing resolved and transformed resources; * by default a {@link org.springframework.cache.concurrent.ConcurrentMapCache} * is used. Since Resources aren't serializable and can be dependent on the * application host, one should not use a distributed cache but rather an * in-memory cache. * @return the same {@link ResourceHandlerRegistration} instance, for chained method invocation * @since 4.1 */ public ResourceChainRegistration resourceChain(boolean cacheResources, Cache cache) { this.resourceChainRegistration = new ResourceChainRegistration(cacheResources, cache); return this.resourceChainRegistration; } /** * Return the URL path patterns for the resource handler. */ protected String[] getPathPatterns() { return this.pathPatterns; } /** * Return a {@link ResourceHttpRequestHandler} instance. */ protected ResourceHttpRequestHandler getRequestHandler() { ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); if (this.resourceChainRegistration != null) { handler.setResourceResolvers(this.resourceChainRegistration.getResourceResolvers()); handler.setResourceTransformers(this.resourceChainRegistration.getResourceTransformers()); } handler.setLocationValues(this.locationValues); handler.setLocations(this.locationsResources); if (this.cacheControl != null) { handler.setCacheControl(this.cacheControl); } else if (this.cachePeriod != null) { handler.setCacheSeconds(this.cachePeriod); } handler.setUseLastModified(this.useLastModified); handler.setEtagGenerator(this.etagGenerator); handler.setOptimizeLocations(this.optimizeLocations); return handler; } }
ResourceHandlerRegistration
java
apache__flink
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlClientSyntaxHighlighter.java
{ "start": 1622, "end": 6122 }
class ____ extends DefaultHighlighter { private static final Logger LOG = LoggerFactory.getLogger(SqlClientSyntaxHighlighter.class); private static final Set<String> KEYWORDS = Collections.unmodifiableSet( Arrays.stream(FlinkSqlParserImplConstants.tokenImage) .map(t -> t.replaceAll("\"", "")) .collect(Collectors.toSet())); private final Executor executor; public SqlClientSyntaxHighlighter(Executor executor) { this.executor = executor; } @Override public AttributedString highlight(LineReader reader, String buffer) { ReadableConfig configuration = executor.getSessionConfig(); final SyntaxHighlightStyle.BuiltInStyle style = SyntaxHighlightStyle.BuiltInStyle.fromString( configuration.get(SqlClientOptions.DISPLAY_DEFAULT_COLOR_SCHEMA)); if (style == SyntaxHighlightStyle.BuiltInStyle.DEFAULT) { return super.highlight(reader, buffer); } final String dialectName = configuration.get(TableConfigOptions.TABLE_SQL_DIALECT); final SqlDialect dialect = SqlDialect.HIVE.name().equalsIgnoreCase(dialectName) ? SqlDialect.HIVE : SqlDialect.DEFAULT; return getHighlightedOutput(buffer, style.getHighlightStyle(), dialect); } static AttributedString getHighlightedOutput( String buffer, SyntaxHighlightStyle style, SqlDialect dialect) { final AttributedStringBuilder highlightedOutput = new AttributedStringBuilder(); SqlClientParserState prevParseState = SqlClientParserState.DEFAULT; SqlClientParserState currentParseState = SqlClientParserState.DEFAULT; final StringBuilder word = new StringBuilder(); for (int i = 0; i < buffer.length(); i++) { final char currentChar = buffer.charAt(i); if (prevParseState == SqlClientParserState.DEFAULT) { currentParseState = SqlClientParserState.computeStateAt(buffer, i, dialect); if (currentParseState == SqlClientParserState.DEFAULT) { if (isPartOfWord(currentChar)) { word.append(currentChar); } else { handleWord(word, highlightedOutput, currentParseState, style); highlightedOutput.append(currentChar); word.setLength(0); } } else { handleWord(word, highlightedOutput, SqlClientParserState.DEFAULT, style); currentParseState.getStyleSetter().accept(highlightedOutput, style); highlightedOutput.append(currentParseState.getStart()); i += currentParseState.getStart().length() - 1; } } else { if (currentParseState.isEndMarkerOfState(buffer, i)) { highlightedOutput .append(word) .append(currentParseState.getEnd()) .style(style.getDefaultStyle()); word.setLength(0); i += currentParseState.getEnd().length() - 1; currentParseState = SqlClientParserState.DEFAULT; } else { word.append(currentChar); } } prevParseState = currentParseState; } handleWord(word, highlightedOutput, currentParseState, style); return highlightedOutput.toAttributedString(); } private static boolean isPartOfWord(char c) { return Character.isLetterOrDigit(c) || c == '_' || c == '$'; } private static void handleWord( StringBuilder word, AttributedStringBuilder highlightedOutput, SqlClientParserState currentState, SyntaxHighlightStyle style) { final String wordStr = word.toString(); if (currentState == SqlClientParserState.DEFAULT) { if (KEYWORDS.contains(wordStr.toUpperCase(Locale.ROOT))) { highlightedOutput.style(style.getKeywordStyle()); } else { highlightedOutput.style(style.getDefaultStyle()); } } highlightedOutput.append(wordStr).style(style.getDefaultStyle()); word.setLength(0); } }
SqlClientSyntaxHighlighter
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/execution/librarycache/BlobLibraryCacheManager.java
{ "start": 16004, "end": 17594 }
class ____. // NOTE: the original collections may contain duplicates and may not already be Set // collections with fast checks whether an item is contained in it. // lazy construction of a new set for faster comparisons if (libraries.size() != requiredLibraries.size() || !new HashSet<>(requiredLibraries).containsAll(libraries)) { throw new IllegalStateException( "The library registration references a different set of library BLOBs than" + " previous registrations for this job:\nold:" + libraries + "\nnew:" + requiredLibraries); } // lazy construction of a new set with String representations of the URLs if (classPaths.size() != requiredClassPaths.size() || !requiredClassPaths.stream() .map(URL::toString) .collect(Collectors.toSet()) .containsAll(classPaths)) { throw new IllegalStateException( "The library registration references a different set of library BLOBs than" + " previous registrations for this job:\nold:" + classPaths + "\nnew:" + requiredClassPaths); } } /** * Release the
paths
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/NettyHttpComponentBuilderFactory.java
{ "start": 6318, "end": 54807 }
interface ____ its name, such as eth0 to join a multicast group. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common (advanced) * * @param networkInterface the value to set * @return the dsl builder */ default NettyHttpComponentBuilder networkInterface(java.lang.String networkInterface) { doSetProperty("networkInterface", networkInterface); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default NettyHttpComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * If the clientMode is true, netty consumer will connect the address as * a TCP client. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param clientMode the value to set * @return the dsl builder */ default NettyHttpComponentBuilder clientMode(boolean clientMode) { doSetProperty("clientMode", clientMode); return this; } /** * If enabled and an Exchange failed processing on the consumer side the * response's body won't contain the exception's stack trace. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param muteException the value to set * @return the dsl builder */ default NettyHttpComponentBuilder muteException(boolean muteException) { doSetProperty("muteException", muteException); return this; } /** * Used only in clientMode in consumer, the consumer will attempt to * reconnect on disconnection if this is enabled. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer * * @param reconnect the value to set * @return the dsl builder */ default NettyHttpComponentBuilder reconnect(boolean reconnect) { doSetProperty("reconnect", reconnect); return this; } /** * Used if reconnect and clientMode is enabled. The interval in milli * seconds to attempt reconnection. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 10000 * Group: consumer * * @param reconnectInterval the value to set * @return the dsl builder */ default NettyHttpComponentBuilder reconnectInterval(int reconnectInterval) { doSetProperty("reconnectInterval", reconnectInterval); return this; } /** * Allows to configure a backlog for netty consumer (server). Note the * backlog is just a best effort depending on the OS. Setting this * option to a value such as 200, 500 or 1000, tells the TCP stack how * long the accept queue can be If this option is not configured, then * the backlog depends on OS setting. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: consumer (advanced) * * @param backlog the value to set * @return the dsl builder */ default NettyHttpComponentBuilder backlog(int backlog) { doSetProperty("backlog", backlog); return this; } /** * When netty works on nio mode, it uses default bossCount parameter * from Netty, which is 1. User can use this option to override the * default bossCount from Netty. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: consumer (advanced) * * @param bossCount the value to set * @return the dsl builder */ default NettyHttpComponentBuilder bossCount(int bossCount) { doSetProperty("bossCount", bossCount); return this; } /** * Set the BossGroup which could be used for handling the new connection * of the server side across the NettyEndpoint. * * The option is a: * &lt;code&gt;io.netty.channel.EventLoopGroup&lt;/code&gt; type. * * Group: consumer (advanced) * * @param bossGroup the value to set * @return the dsl builder */ default NettyHttpComponentBuilder bossGroup(io.netty.channel.EventLoopGroup bossGroup) { doSetProperty("bossGroup", bossGroup); return this; } /** * Setting to choose Multicast over UDP. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer (advanced) * * @param broadcast the value to set * @return the dsl builder */ default NettyHttpComponentBuilder broadcast(boolean broadcast) { doSetProperty("broadcast", broadcast); return this; } /** * If sync is enabled then this option dictates NettyConsumer if it * should disconnect where there is no reply to send back. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer (advanced) * * @param disconnectOnNoReply the value to set * @return the dsl builder */ default NettyHttpComponentBuilder disconnectOnNoReply(boolean disconnectOnNoReply) { doSetProperty("disconnectOnNoReply", disconnectOnNoReply); return this; } /** * To use the given custom EventExecutorGroup. * * The option is a: * &lt;code&gt;io.netty.util.concurrent.EventExecutorGroup&lt;/code&gt; * type. * * Group: consumer (advanced) * * @param executorService the value to set * @return the dsl builder */ default NettyHttpComponentBuilder executorService(io.netty.util.concurrent.EventExecutorGroup executorService) { doSetProperty("executorService", executorService); return this; } /** * Sets a maximum thread pool size for the netty consumer ordered thread * pool. The default size is 2 x cpu_core plus 1. Setting this value to * eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher * value, which then will override and be used. For example if there are * 8 cores, then the consumer thread pool will be 17. This thread pool * is used to route messages received from Netty by Camel. We use a * separate thread pool to ensure ordering of messages and also in case * some messages will block, then nettys worker threads (event loop) * wont be affected. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: consumer (advanced) * * @param maximumPoolSize the value to set * @return the dsl builder */ default NettyHttpComponentBuilder maximumPoolSize(int maximumPoolSize) { doSetProperty("maximumPoolSize", maximumPoolSize); return this; } /** * To use a custom NettyServerBootstrapFactory. * * The option is a: * &lt;code&gt;org.apache.camel.component.netty.NettyServerBootstrapFactory&lt;/code&gt; type. * * Group: consumer (advanced) * * @param nettyServerBootstrapFactory the value to set * @return the dsl builder */ default NettyHttpComponentBuilder nettyServerBootstrapFactory(org.apache.camel.component.netty.NettyServerBootstrapFactory nettyServerBootstrapFactory) { doSetProperty("nettyServerBootstrapFactory", nettyServerBootstrapFactory); return this; } /** * If sync is enabled this option dictates NettyConsumer which logging * level to use when logging a there is no reply to send back. * * The option is a: * &lt;code&gt;org.apache.camel.LoggingLevel&lt;/code&gt; type. * * Default: WARN * Group: consumer (advanced) * * @param noReplyLogLevel the value to set * @return the dsl builder */ default NettyHttpComponentBuilder noReplyLogLevel(org.apache.camel.LoggingLevel noReplyLogLevel) { doSetProperty("noReplyLogLevel", noReplyLogLevel); return this; } /** * If the server (NettyConsumer) catches an * java.nio.channels.ClosedChannelException then its logged using this * logging level. This is used to avoid logging the closed channel * exceptions, as clients can disconnect abruptly and then cause a flood * of closed exceptions in the Netty server. * * The option is a: * &lt;code&gt;org.apache.camel.LoggingLevel&lt;/code&gt; type. * * Default: DEBUG * Group: consumer (advanced) * * @param serverClosedChannelExceptionCaughtLogLevel the value to set * @return the dsl builder */ default NettyHttpComponentBuilder serverClosedChannelExceptionCaughtLogLevel(org.apache.camel.LoggingLevel serverClosedChannelExceptionCaughtLogLevel) { doSetProperty("serverClosedChannelExceptionCaughtLogLevel", serverClosedChannelExceptionCaughtLogLevel); return this; } /** * If the server (NettyConsumer) catches an exception then its logged * using this logging level. * * The option is a: * &lt;code&gt;org.apache.camel.LoggingLevel&lt;/code&gt; type. * * Default: WARN * Group: consumer (advanced) * * @param serverExceptionCaughtLogLevel the value to set * @return the dsl builder */ default NettyHttpComponentBuilder serverExceptionCaughtLogLevel(org.apache.camel.LoggingLevel serverExceptionCaughtLogLevel) { doSetProperty("serverExceptionCaughtLogLevel", serverExceptionCaughtLogLevel); return this; } /** * To use a custom ServerInitializerFactory. * * The option is a: * &lt;code&gt;org.apache.camel.component.netty.ServerInitializerFactory&lt;/code&gt; type. * * Group: consumer (advanced) * * @param serverInitializerFactory the value to set * @return the dsl builder */ default NettyHttpComponentBuilder serverInitializerFactory(org.apache.camel.component.netty.ServerInitializerFactory serverInitializerFactory) { doSetProperty("serverInitializerFactory", serverInitializerFactory); return this; } /** * Whether to use ordered thread pool, to ensure events are processed * orderly on the same channel. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer (advanced) * * @param usingExecutorService the value to set * @return the dsl builder */ default NettyHttpComponentBuilder usingExecutorService(boolean usingExecutorService) { doSetProperty("usingExecutorService", usingExecutorService); return this; } /** * Time to wait for a socket connection to be available. Value is in * milliseconds. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 10000 * Group: producer * * @param connectTimeout the value to set * @return the dsl builder */ default NettyHttpComponentBuilder connectTimeout(int connectTimeout) { doSetProperty("connectTimeout", connectTimeout); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default NettyHttpComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Allows to use a timeout for the Netty producer when calling a remote * server. By default no timeout is in use. The value is in milli * seconds, so eg 30000 is 30 seconds. The requestTimeout is using * Netty's ReadTimeoutHandler to trigger the timeout. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Group: producer * * @param requestTimeout the value to set * @return the dsl builder */ default NettyHttpComponentBuilder requestTimeout(long requestTimeout) { doSetProperty("requestTimeout", requestTimeout); return this; } /** * To use a custom ClientInitializerFactory. * * The option is a: * &lt;code&gt;org.apache.camel.component.netty.ClientInitializerFactory&lt;/code&gt; type. * * Group: producer (advanced) * * @param clientInitializerFactory the value to set * @return the dsl builder */ default NettyHttpComponentBuilder clientInitializerFactory(org.apache.camel.component.netty.ClientInitializerFactory clientInitializerFactory) { doSetProperty("clientInitializerFactory", clientInitializerFactory); return this; } /** * To use a custom correlation manager to manage how request and reply * messages are mapped when using request/reply with the netty producer. * This should only be used if you have a way to map requests together * with replies such as if there is correlation ids in both the request * and reply messages. This can be used if you want to multiplex * concurrent messages on the same channel (aka connection) in netty. * When doing this you must have a way to correlate the request and * reply messages so you can store the right reply on the inflight Camel * Exchange before its continued routed. We recommend extending the * TimeoutCorrelationManagerSupport when you build custom correlation * managers. This provides support for timeout and other complexities * you otherwise would need to implement as well. See also the * producerPoolEnabled option for more details. * * The option is a: * &lt;code&gt;org.apache.camel.component.netty.NettyCamelStateCorrelationManager&lt;/code&gt; type. * * Group: producer (advanced) * * @param correlationManager the value to set * @return the dsl builder */ default NettyHttpComponentBuilder correlationManager(org.apache.camel.component.netty.NettyCamelStateCorrelationManager correlationManager) { doSetProperty("correlationManager", correlationManager); return this; } /** * Channels can be lazily created to avoid exceptions, if the remote * server is not up and running when the Camel producer is started. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: producer (advanced) * * @param lazyChannelCreation the value to set * @return the dsl builder */ default NettyHttpComponentBuilder lazyChannelCreation(boolean lazyChannelCreation) { doSetProperty("lazyChannelCreation", lazyChannelCreation); return this; } /** * Sets the value for the blockWhenExhausted configuration attribute. It * determines whether to block when the borrowObject() method is invoked * when the pool is exhausted (the maximum number of active objects has * been reached). * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: producer (advanced) * * @param producerPoolBlockWhenExhausted the value to set * @return the dsl builder */ default NettyHttpComponentBuilder producerPoolBlockWhenExhausted(boolean producerPoolBlockWhenExhausted) { doSetProperty("producerPoolBlockWhenExhausted", producerPoolBlockWhenExhausted); return this; } /** * Whether producer pool is enabled or not. Important: If you turn this * off then a single shared connection is used for the producer, also if * you are doing request/reply. That means there is a potential issue * with interleaved responses if replies comes back out-of-order. * Therefore you need to have a correlation id in both the request and * reply messages so you can properly correlate the replies to the Camel * callback that is responsible for continue processing the message in * Camel. To do this you need to implement * NettyCamelStateCorrelationManager as correlation manager and * configure it via the correlationManager option. See also the * correlationManager option for more details. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: producer (advanced) * * @param producerPoolEnabled the value to set * @return the dsl builder */ default NettyHttpComponentBuilder producerPoolEnabled(boolean producerPoolEnabled) { doSetProperty("producerPoolEnabled", producerPoolEnabled); return this; } /** * Sets the cap on the number of idle instances in the pool. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 100 * Group: producer (advanced) * * @param producerPoolMaxIdle the value to set * @return the dsl builder */ default NettyHttpComponentBuilder producerPoolMaxIdle(int producerPoolMaxIdle) { doSetProperty("producerPoolMaxIdle", producerPoolMaxIdle); return this; } /** * Sets the cap on the number of objects that can be allocated by the * pool (checked out to clients, or idle awaiting checkout) at a given * time. Use a negative value for no limit. Be careful to not set this * value too low (such as 1) as the pool must have space to create a * producer such as when performing retries. Be mindful that the option * producerPoolBlockWhenExhausted is default true, and the pool will * then block when there is no space, which can lead to the application * to hang. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: -1 * Group: producer (advanced) * * @param producerPoolMaxTotal the value to set * @return the dsl builder */ default NettyHttpComponentBuilder producerPoolMaxTotal(int producerPoolMaxTotal) { doSetProperty("producerPoolMaxTotal", producerPoolMaxTotal); return this; } /** * Sets the maximum duration (value in millis) the borrowObject() method * should block before throwing an exception when the pool is exhausted * and producerPoolBlockWhenExhausted is true. When less than 0, the * borrowObject() method may block indefinitely. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: -1 * Group: producer (advanced) * * @param producerPoolMaxWait the value to set * @return the dsl builder */ default NettyHttpComponentBuilder producerPoolMaxWait(long producerPoolMaxWait) { doSetProperty("producerPoolMaxWait", producerPoolMaxWait); return this; } /** * Sets the minimum amount of time (value in millis) an object may sit * idle in the pool before it is eligible for eviction by the idle * object evictor. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 300000 * Group: producer (advanced) * * @param producerPoolMinEvictableIdle the value to set * @return the dsl builder */ default NettyHttpComponentBuilder producerPoolMinEvictableIdle(long producerPoolMinEvictableIdle) { doSetProperty("producerPoolMinEvictableIdle", producerPoolMinEvictableIdle); return this; } /** * Sets the minimum number of instances allowed in the producer pool * before the evictor thread (if active) spawns new objects. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: producer (advanced) * * @param producerPoolMinIdle the value to set * @return the dsl builder */ default NettyHttpComponentBuilder producerPoolMinIdle(int producerPoolMinIdle) { doSetProperty("producerPoolMinIdle", producerPoolMinIdle); return this; } /** * This option supports connection less udp sending which is a real fire * and forget. A connected udp send receive the PortUnreachableException * if no one is listen on the receiving port. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param udpConnectionlessSending the value to set * @return the dsl builder */ default NettyHttpComponentBuilder udpConnectionlessSending(boolean udpConnectionlessSending) { doSetProperty("udpConnectionlessSending", udpConnectionlessSending); return this; } /** * If the useByteBuf is true, netty producer will turn the message body * into ByteBuf before sending it out. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer (advanced) * * @param useByteBuf the value to set * @return the dsl builder */ default NettyHttpComponentBuilder useByteBuf(boolean useByteBuf) { doSetProperty("useByteBuf", useByteBuf); return this; } /** * Only used for TCP when transferExchange is true. When set to true, * serializable objects in headers and properties will be added to the * exchange. Otherwise Camel will exclude any non-serializable objects * and log it at WARN level. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param allowSerializedHeaders the value to set * @return the dsl builder */ default NettyHttpComponentBuilder allowSerializedHeaders(boolean allowSerializedHeaders) { doSetProperty("allowSerializedHeaders", allowSerializedHeaders); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default NettyHttpComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * To use an explicit ChannelGroup. * * The option is a: * &lt;code&gt;io.netty.channel.group.ChannelGroup&lt;/code&gt; type. * * Group: advanced * * @param channelGroup the value to set * @return the dsl builder */ default NettyHttpComponentBuilder channelGroup(io.netty.channel.group.ChannelGroup channelGroup) { doSetProperty("channelGroup", channelGroup); return this; } /** * To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter * headers. * * The option is a: * &lt;code&gt;org.apache.camel.spi.HeaderFilterStrategy&lt;/code&gt; * type. * * Group: advanced * * @param headerFilterStrategy the value to set * @return the dsl builder */ default NettyHttpComponentBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Whether to use native transport instead of NIO. Native transport * takes advantage of the host operating system and is only supported on * some platforms. You need to add the netty JAR for the host operating * system you are using. See more details at: * http://netty.io/wiki/native-transports.html. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param nativeTransport the value to set * @return the dsl builder */ default NettyHttpComponentBuilder nativeTransport(boolean nativeTransport) { doSetProperty("nativeTransport", nativeTransport); return this; } /** * To use a custom * org.apache.camel.component.netty.http.NettyHttpBinding for binding * to/from Netty and Camel Message API. * * The option is a: * &lt;code&gt;org.apache.camel.component.netty.http.NettyHttpBinding&lt;/code&gt; type. * * Group: advanced * * @param nettyHttpBinding the value to set * @return the dsl builder */ default NettyHttpComponentBuilder nettyHttpBinding(org.apache.camel.component.netty.http.NettyHttpBinding nettyHttpBinding) { doSetProperty("nettyHttpBinding", nettyHttpBinding); return this; } /** * Allows to configure additional netty options using option. as prefix. * For example option.child.keepAlive=false. See the Netty documentation * for possible options that can be used. This is a multi-value option * with prefix: option. * * The option is a: &lt;code&gt;java.util.Map&amp;lt;java.lang.String, * java.lang.Object&amp;gt;&lt;/code&gt; type. * * Group: advanced * * @param options the value to set * @return the dsl builder */ default NettyHttpComponentBuilder options(java.util.Map<java.lang.String, java.lang.Object> options) { doSetProperty("options", options); return this; } /** * The TCP/UDP buffer sizes to be used during inbound communication. * Size is bytes. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 65536 * Group: advanced * * @param receiveBufferSize the value to set * @return the dsl builder */ default NettyHttpComponentBuilder receiveBufferSize(int receiveBufferSize) { doSetProperty("receiveBufferSize", receiveBufferSize); return this; } /** * Configures the buffer size predictor. See details at Jetty * documentation and this mail thread. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: advanced * * @param receiveBufferSizePredictor the value to set * @return the dsl builder */ default NettyHttpComponentBuilder receiveBufferSizePredictor(int receiveBufferSizePredictor) { doSetProperty("receiveBufferSizePredictor", receiveBufferSizePredictor); return this; } /** * The TCP/UDP buffer sizes to be used during outbound communication. * Size is bytes. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 65536 * Group: advanced * * @param sendBufferSize the value to set * @return the dsl builder */ default NettyHttpComponentBuilder sendBufferSize(int sendBufferSize) { doSetProperty("sendBufferSize", sendBufferSize); return this; } /** * Shutdown await timeout in milliseconds. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 100 * Group: advanced * * @param shutdownTimeout the value to set * @return the dsl builder */ default NettyHttpComponentBuilder shutdownTimeout(int shutdownTimeout) { doSetProperty("shutdownTimeout", shutdownTimeout); return this; } /** * Only used for TCP. You can transfer the exchange over the wire * instead of just the body. The following fields are transferred: In * body, Out body, fault body, In headers, Out headers, fault headers, * exchange properties, exchange exception. This requires that the * objects are serializable. Camel will exclude any non-serializable * objects and log it at WARN level. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param transferExchange the value to set * @return the dsl builder */ default NettyHttpComponentBuilder transferExchange(boolean transferExchange) { doSetProperty("transferExchange", transferExchange); return this; } /** * For UDP only. If enabled the using byte array codec instead of Java * serialization protocol. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param udpByteArrayCodec the value to set * @return the dsl builder */ default NettyHttpComponentBuilder udpByteArrayCodec(boolean udpByteArrayCodec) { doSetProperty("udpByteArrayCodec", udpByteArrayCodec); return this; } /** * Path to unix domain socket to use instead of inet socket. Host and * port parameters will not be used, however required. It is ok to set * dummy values for them. Must be used with nativeTransport=true and * clientMode=false. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: advanced * * @param unixDomainSocketPath the value to set * @return the dsl builder */ default NettyHttpComponentBuilder unixDomainSocketPath(java.lang.String unixDomainSocketPath) { doSetProperty("unixDomainSocketPath", unixDomainSocketPath); return this; } /** * When netty works on nio mode, it uses default workerCount parameter * from Netty (which is cpu_core_threads x 2). User can use this option * to override the default workerCount from Netty. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Group: advanced * * @param workerCount the value to set * @return the dsl builder */ default NettyHttpComponentBuilder workerCount(int workerCount) { doSetProperty("workerCount", workerCount); return this; } /** * To use a explicit EventLoopGroup as the boss thread pool. For example * to share a thread pool with multiple consumers or producers. By * default each consumer or producer has their own worker pool with 2 x * cpu count core threads. * * The option is a: * &lt;code&gt;io.netty.channel.EventLoopGroup&lt;/code&gt; type. * * Group: advanced * * @param workerGroup the value to set * @return the dsl builder */ default NettyHttpComponentBuilder workerGroup(io.netty.channel.EventLoopGroup workerGroup) { doSetProperty("workerGroup", workerGroup); return this; } /** * The netty component installs a default codec if both, encoder/decoder * is null and textline is false. Setting allowDefaultCodec to false * prevents the netty component from installing a default codec as the * first element in the filter chain. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: codec * * @param allowDefaultCodec the value to set * @return the dsl builder */ default NettyHttpComponentBuilder allowDefaultCodec(boolean allowDefaultCodec) { doSetProperty("allowDefaultCodec", allowDefaultCodec); return this; } /** * Whether or not to auto append missing end delimiter when sending * using the textline codec. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: codec * * @param autoAppendDelimiter the value to set * @return the dsl builder */ default NettyHttpComponentBuilder autoAppendDelimiter(boolean autoAppendDelimiter) { doSetProperty("autoAppendDelimiter", autoAppendDelimiter); return this; } /** * The max line length to use for the textline codec. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1024 * Group: codec * * @param decoderMaxLineLength the value to set * @return the dsl builder */ default NettyHttpComponentBuilder decoderMaxLineLength(int decoderMaxLineLength) { doSetProperty("decoderMaxLineLength", decoderMaxLineLength); return this; } /** * A list of decoders to be used. You can use a String which have values * separated by comma, and have the values be looked up in the Registry. * Just remember to prefix the value with # so Camel knows it should * lookup. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: codec * * @param decoders the value to set * @return the dsl builder */ default NettyHttpComponentBuilder decoders(java.lang.String decoders) { doSetProperty("decoders", decoders); return this; } /** * The delimiter to use for the textline codec. Possible values are LINE * and NULL. * * The option is a: * &lt;code&gt;org.apache.camel.component.netty.TextLineDelimiter&lt;/code&gt; type. * * Default: LINE * Group: codec * * @param delimiter the value to set * @return the dsl builder */ default NettyHttpComponentBuilder delimiter(org.apache.camel.component.netty.TextLineDelimiter delimiter) { doSetProperty("delimiter", delimiter); return this; } /** * A list of encoders to be used. You can use a String which have values * separated by comma, and have the values be looked up in the Registry. * Just remember to prefix the value with # so Camel knows it should * lookup. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: codec * * @param encoders the value to set * @return the dsl builder */ default NettyHttpComponentBuilder encoders(java.lang.String encoders) { doSetProperty("encoders", encoders); return this; } /** * The encoding (a charset name) to use for the textline codec. If not * provided, Camel will use the JVM default Charset. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: codec * * @param encoding the value to set * @return the dsl builder */ default NettyHttpComponentBuilder encoding(java.lang.String encoding) { doSetProperty("encoding", encoding); return this; } /** * Only used for TCP. If no codec is specified, you can use this flag to * indicate a text line based codec; if not specified or the value is * false, then Object Serialization is assumed over TCP - however only * Strings are allowed to be serialized by default. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: codec * * @param textline the value to set * @return the dsl builder */ default NettyHttpComponentBuilder textline(boolean textline) { doSetProperty("textline", textline); return this; } /** * Which protocols to enable when using SSL. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: TLSv1.2,TLSv1.3 * Group: security * * @param enabledProtocols the value to set * @return the dsl builder */ default NettyHttpComponentBuilder enabledProtocols(java.lang.String enabledProtocols) { doSetProperty("enabledProtocols", enabledProtocols); return this; } /** * To enable/disable hostname verification on SSLEngine. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param hostnameVerification the value to set * @return the dsl builder */ default NettyHttpComponentBuilder hostnameVerification(boolean hostnameVerification) { doSetProperty("hostnameVerification", hostnameVerification); return this; } /** * Keystore format to be used for payload encryption. Defaults to JKS if * not set. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param keyStoreFormat the value to set * @return the dsl builder */ default NettyHttpComponentBuilder keyStoreFormat(java.lang.String keyStoreFormat) { doSetProperty("keyStoreFormat", keyStoreFormat); return this; } /** * Client side certificate keystore to be used for encryption. Is loaded * by default from classpath, but you can prefix with classpath:, file:, * or http: to load the resource from different systems. * * This option can also be loaded from an existing file, by prefixing * with file: or classpath: followed by the location of the file. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param keyStoreResource the value to set * @return the dsl builder */ default NettyHttpComponentBuilder keyStoreResource(java.lang.String keyStoreResource) { doSetProperty("keyStoreResource", keyStoreResource); return this; } /** * Configures whether the server needs client authentication when using * SSL. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param needClientAuth the value to set * @return the dsl builder */ default NettyHttpComponentBuilder needClientAuth(boolean needClientAuth) { doSetProperty("needClientAuth", needClientAuth); return this; } /** * Password to use for the keyStore and trustStore. The same password * must be configured for both resources. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param passphrase the value to set * @return the dsl builder */ default NettyHttpComponentBuilder passphrase(java.lang.String passphrase) { doSetProperty("passphrase", passphrase); return this; } /** * Refers to a * org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration * for configuring secure web resources. * * The option is a: * &lt;code&gt;org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration&lt;/code&gt; type. * * Group: security * * @param securityConfiguration the value to set * @return the dsl builder */ default NettyHttpComponentBuilder securityConfiguration(org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration securityConfiguration) { doSetProperty("securityConfiguration", securityConfiguration); return this; } /** * Security provider to be used for payload encryption. Defaults to * SunX509 if not set. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param securityProvider the value to set * @return the dsl builder */ default NettyHttpComponentBuilder securityProvider(java.lang.String securityProvider) { doSetProperty("securityProvider", securityProvider); return this; } /** * Setting to specify whether SSL encryption is applied to this * endpoint. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param ssl the value to set * @return the dsl builder */ default NettyHttpComponentBuilder ssl(boolean ssl) { doSetProperty("ssl", ssl); return this; } /** * When enabled and in SSL mode, then the Netty consumer will enrich the * Camel Message with headers having information about the client * certificate such as subject name, issuer name, serial number, and the * valid date range. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param sslClientCertHeaders the value to set * @return the dsl builder */ default NettyHttpComponentBuilder sslClientCertHeaders(boolean sslClientCertHeaders) { doSetProperty("sslClientCertHeaders", sslClientCertHeaders); return this; } /** * To configure security using SSLContextParameters. * * The option is a: * &lt;code&gt;org.apache.camel.support.jsse.SSLContextParameters&lt;/code&gt; type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default NettyHttpComponentBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * Reference to a
by
java
spring-projects__spring-framework
spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java
{ "start": 798, "end": 1187 }
class ____ extends AbstractEntityManagerFactoryBeanTests { @Test void testHookIsCalled() { DummyEntityManagerFactoryBean demf = new DummyEntityManagerFactoryBean(mockEmf); demf.afterPropertiesSet(); checkInvariants(demf); // Should trigger close method expected by EntityManagerFactory mock demf.destroy(); verify(mockEmf).close(); } }
EntityManagerFactoryBeanSupportTests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/TimeBetweenLogStatsMillisTest2.java
{ "start": 166, "end": 784 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { System.setProperty("druid.timeBetweenLogStatsMillis", "1000"); dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); } protected void tearDown() throws Exception { JdbcUtils.close(dataSource); System.clearProperty("druid.timeBetweenLogStatsMillis"); } public void test_0() throws Exception { dataSource.init(); assertEquals(1000, dataSource.getTimeBetweenLogStatsMillis()); } }
TimeBetweenLogStatsMillisTest2
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Over.java
{ "start": 990, "end": 1436 }
class ____ creating an over window. Similar to SQL, over window aggregates compute an * aggregate for each input row over a range of its neighboring rows. * * <p>Java Example: * * <pre>{@code * Over.partitionBy("a").orderBy("rowtime").preceding("unbounded_range").as("w") * }</pre> * * <p>Scala Example: * * <pre>{@code * Over partitionBy 'a orderBy 'rowtime preceding UNBOUNDED_RANGE as 'w * }</pre> */ @PublicEvolving public final
for
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerLogs.java
{ "start": 1315, "end": 2861 }
class ____ extends HttpServerFunctionalTest { static final Logger LOG = LoggerFactory.getLogger(TestHttpServerLogs.class); private static HttpServer2 server; @BeforeAll public static void setup() throws Exception { } private void startServer(Configuration conf) throws Exception { server = createTestServer(conf); server.start(); baseUrl = getServerURL(server); LOG.info("HTTP server started: "+ baseUrl); } @AfterAll public static void cleanup() throws Exception { if (server != null && server.isAlive()) { server.stop(); } } @Test public void testLogsEnabled() throws Exception { Configuration conf = new Configuration(); conf.setBoolean( CommonConfigurationKeysPublic.HADOOP_HTTP_LOGS_ENABLED, true); startServer(conf); InetSocketAddress inetSocketAddress = Objects.requireNonNull(server.getConnectorAddress(0)); URL url = new URL("http://" + NetUtils.getHostPortString(inetSocketAddress) + "/logs"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); assertEquals(HttpStatus.SC_OK, conn.getResponseCode()); } @Test public void testLogsDisabled() throws Exception { Configuration conf = new Configuration(); conf.setBoolean( CommonConfigurationKeysPublic.HADOOP_HTTP_LOGS_ENABLED, false); startServer(conf); URL url = new URL(baseUrl + "/logs"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); assertEquals(HttpStatus.SC_NOT_FOUND, conn.getResponseCode()); } }
TestHttpServerLogs
java
apache__kafka
tools/src/main/java/org/apache/kafka/tools/PushHttpMetricsReporter.java
{ "start": 7379, "end": 11324 }
class ____ implements Runnable { @Override public void run() { long now = currentTimeMillis.get(); final List<MetricValue> samples; synchronized (lock) { samples = new ArrayList<>(metrics.size()); for (KafkaMetric metric : metrics.values()) { MetricName name = metric.metricName(); samples.add(new MetricValue(name.name(), name.group(), name.tags(), metric.metricValue())); } } MetricsReport report = new MetricsReport(new MetricClientInfo(host, clientId, now), samples); log.trace("Reporting {} metrics to {}", samples.size(), url); HttpURLConnection connection = null; try { connection = newHttpConnection(url); connection.setRequestMethod("POST"); // connection.getResponseCode() implicitly calls getInputStream, so always set to true. // On the other hand, leaving this out breaks nothing. connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json"); byte[] data = json.writeValueAsBytes(report); connection.setRequestProperty("Content-Length", Integer.toString(data.length)); connection.setRequestProperty("Accept", "*/*"); connection.setUseCaches(false); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()) { os.write(data); os.flush(); } int responseCode = connection.getResponseCode(); if (responseCode >= 400) { InputStream is = connection.getErrorStream(); String msg = readResponse(is); log.error("Error reporting metrics, {}: {}", responseCode, msg); } else if (responseCode >= 300) { log.error("PushHttpMetricsReporter does not currently support redirects, saw {}", responseCode); } else { log.info("Finished reporting metrics with response code {}", responseCode); } } catch (Throwable t) { log.error("Error reporting metrics", t); } finally { if (connection != null) { connection.disconnect(); } } } } // Static package-private so unit tests can use a mock connection static HttpURLConnection newHttpConnection(URL url) throws IOException { return (HttpURLConnection) url.openConnection(); } // Static package-private so unit tests can mock reading response static String readResponse(InputStream is) { try (Scanner s = new Scanner(is, StandardCharsets.UTF_8).useDelimiter("\\A")) { return s.hasNext() ? s.next() : ""; } } private record MetricsReport(@JsonProperty("client") MetricClientInfo client, @JsonProperty("metrics") Collection<MetricValue> metrics) { } private record MetricClientInfo(@JsonProperty("host") String host, @JsonProperty("client_id") String clientId, @JsonProperty("time") long time) { } private record MetricValue(@JsonProperty("name") String name, @JsonProperty("group") String group, @JsonProperty("tags") Map<String, String> tags, @JsonProperty("value") Object value) { } // The signature for getInt changed from returning int to Integer so to remain compatible with 0.8.2.2 jars // for system tests we replace it with a custom version that works for all versions. private static
HttpReporter
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/seda/SedaWaitForTaskCompleteTest.java
{ "start": 1150, "end": 2591 }
class ____ extends ContextTestSupport { @Test public void testInOut() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); String out = template.requestBody("direct:start", "Hello World", String.class); assertEquals("Bye World", out); assertMockEndpointsSatisfied(); } @Test public void testInOnly() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); // we send an in only but we use Always to wait for it to complete // and since the route changes the payload we can get the response // anyway Exchange out = template.send("direct:start", new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("Hello World"); exchange.setPattern(ExchangePattern.InOnly); } }); assertEquals("Bye World", out.getIn().getBody()); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").to("seda:foo?waitForTaskToComplete=Always"); from("seda:foo?waitForTaskToComplete=Always").transform(constant("Bye World")).to("mock:result"); } }; } }
SedaWaitForTaskCompleteTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java
{ "start": 26799, "end": 27302 }
class ____ {} @Nullable Inner getMessage(boolean b, Inner i) { return b ? i : null; } } """) .doTest(); } @Test public void limitation_staticFinalFieldInitializedLater() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java", """ package com.google.errorprone.bugpatterns.nullness; abstract
Inner
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/spi/PostDeleteEvent.java
{ "start": 342, "end": 754 }
class ____ extends AbstractPostDatabaseOperationEvent { private final Object[] deletedState; public PostDeleteEvent( Object entity, Object id, Object[] deletedState, EntityPersister persister, SharedSessionContractImplementor source) { super( source, entity, id, persister ); this.deletedState = deletedState; } public Object[] getDeletedState() { return deletedState; } }
PostDeleteEvent
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/interceptor/ApplicationScopedInterceptorTest.java
{ "start": 3871, "end": 4315 }
class ____ implements Interceptor { private static final List<ApplicationScopedInterceptor> instances = Collections.synchronizedList(new ArrayList<>()); private static final List<Object> loadedIds = Collections.synchronizedList(new ArrayList<>()); public ApplicationScopedInterceptor() { if (!ClientProxy.class.isAssignableFrom(getClass())) { // Disregard CDI proxies extending this
ApplicationScopedInterceptor
java
google__dagger
javatests/dagger/functional/assisted/AssistedFactoryWithMultibindingsTest.java
{ "start": 2405, "end": 3145 }
interface ____ { MultibindingFoo createFoo(AssistedDep factoryAssistedDep1); } @Test public void testAssistedFactoryWithMultibinding() { AssistedDep assistedDep1 = new AssistedDep(); ParentComponent parent = DaggerAssistedFactoryWithMultibindingsTest_ParentComponent.create(); ChildComponent child = parent.childComponent().build(); MultibindingFoo foo1 = parent.multibindingFooFactory().createFoo(assistedDep1); MultibindingFoo foo2 = child.multibindingFooFactory().createFoo(assistedDep1); assertThat(foo1.assistedDep()).isEqualTo(foo2.assistedDep); assertThat(foo1.stringSet()).containsExactly("parent"); assertThat(foo2.stringSet()).containsExactly("child", "parent"); } }
MultibindingFooFactory
java
hibernate__hibernate-orm
hibernate-vector/src/main/java/org/hibernate/vector/SparseByteVector.java
{ "start": 273, "end": 5789 }
class ____ extends AbstractSparseVector<Byte> { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private final int size; private int[] indices = EMPTY_INT_ARRAY; private byte[] data = EMPTY_BYTE_ARRAY; public SparseByteVector(int size) { if ( size <= 0 ) { throw new IllegalArgumentException( "size must be greater than zero" ); } this.size = size; } public SparseByteVector(List<Byte> list) { if ( list instanceof SparseByteVector sparseVector ) { size = sparseVector.size; indices = sparseVector.indices.clone(); data = sparseVector.data.clone(); } else { if ( list == null ) { throw new IllegalArgumentException( "list cannot be null" ); } if ( list.isEmpty() ) { throw new IllegalArgumentException( "list cannot be empty" ); } int size = 0; int[] indices = new int[list.size()]; byte[] data = new byte[list.size()]; for ( int i = 0; i < list.size(); i++ ) { final Byte b = list.get( i ); if ( b != null && b != 0 ) { indices[size] = i; data[size] = b; size++; } } this.size = list.size(); this.indices = Arrays.copyOf( indices, size ); this.data = Arrays.copyOf( data, size ); } } public SparseByteVector(byte[] denseVector) { if ( denseVector == null ) { throw new IllegalArgumentException( "denseVector cannot be null" ); } if ( denseVector.length == 0 ) { throw new IllegalArgumentException( "denseVector cannot be empty" ); } int size = 0; int[] indices = new int[denseVector.length]; byte[] data = new byte[denseVector.length]; for ( int i = 0; i < denseVector.length; i++ ) { final byte b = denseVector[i]; if ( b != 0 ) { indices[size] = i; data[size] = b; size++; } } this.size = denseVector.length; this.indices = Arrays.copyOf( indices, size ); this.data = Arrays.copyOf( data, size ); } public SparseByteVector(int size, int[] indices, byte[] data) { this( validateData( data, size ), validateIndices( indices, data.length, size ), size ); } private SparseByteVector(byte[] data, int[] indices, int size) { this.size = size; this.indices = indices; this.data = data; } public SparseByteVector(String string) { final ParsedVector<Byte> parsedVector = parseSparseVector( string, (s, start, end) -> Byte.parseByte( s.substring( start, end ) ) ); this.size = parsedVector.size(); this.indices = parsedVector.indices(); this.data = toByteArray( parsedVector.elements() ); } private static byte[] toByteArray(List<Byte> elements) { final byte[] result = new byte[elements.size()]; for ( int i = 0; i < elements.size(); i++ ) { result[i] = elements.get(i); } return result; } private static byte[] validateData(byte[] data, int size) { if ( size == 0 ) { throw new IllegalArgumentException( "size cannot be 0" ); } if ( data == null ) { throw new IllegalArgumentException( "data cannot be null" ); } if ( size < data.length ) { throw new IllegalArgumentException( "size cannot be smaller than data size" ); } for ( int i = 0; i < data.length; i++ ) { if ( data[i] == 0 ) { throw new IllegalArgumentException( "data[" + i + "] == 0" ); } } return data; } @Override public SparseByteVector clone() { return new SparseByteVector( data.clone(), indices.clone(), size ); } @Override public Byte get(int index) { final int foundIndex = Arrays.binarySearch( indices, index ); return foundIndex < 0 ? 0 : data[foundIndex]; } @Override public Byte set(int index, Byte element) { final int foundIndex = Arrays.binarySearch( indices, index ); if ( foundIndex < 0 ) { if ( element != null && element != 0 ) { final int[] newIndices = new int[indices.length + 1]; final byte[] newData = new byte[data.length + 1]; final int insertionPoint = -foundIndex - 1; System.arraycopy( indices, 0, newIndices, 0, insertionPoint ); System.arraycopy( data, 0, newData, 0, insertionPoint ); newIndices[insertionPoint] = index; newData[insertionPoint] = element; System.arraycopy( indices, insertionPoint, newIndices, insertionPoint + 1, indices.length - insertionPoint ); System.arraycopy( data, insertionPoint, newData, insertionPoint + 1, data.length - insertionPoint ); this.indices = newIndices; this.data = newData; } return null; } else { final byte oldValue = data[foundIndex]; if ( element != null && element != 0 ) { data[foundIndex] = element; } else { final int[] newIndices = new int[indices.length - 1]; final byte[] newData = new byte[data.length - 1]; System.arraycopy( indices, 0, newIndices, 0, foundIndex ); System.arraycopy( data, 0, newData, 0, foundIndex ); System.arraycopy( indices, foundIndex + 1, newIndices, foundIndex, indices.length - foundIndex - 1 ); System.arraycopy( data, foundIndex + 1, newData, foundIndex, data.length - foundIndex - 1 ); this.indices = newIndices; this.data = newData; } return oldValue; } } public byte[] toDenseVector() { final byte[] result = new byte[this.size]; for ( int i = 0; i < indices.length; i++ ) { result[indices[i]] = data[i]; } return result; } @Override public int[] indices() { return indices; } public byte[] bytes() { return data; } @Override public int size() { return size; } @Override public String toString() { return "[" + size + "," + Arrays.toString( indices ) + "," + Arrays.toString( data ) + "]"; } }
SparseByteVector
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/datageneration/FieldDataGenerator.java
{ "start": 686, "end": 779 }
interface ____ { Object generateValue(Map<String, Object> fieldMapping); }
FieldDataGenerator
java
processing__processing4
app/src/processing/app/tools/CreateFont.java
{ "start": 22850, "end": 23231 }
class ____ on the net, though I've lost the // link. If you run across the original version, please let me know so that // the original author can be credited properly. It was from a snippet // collection, but it seems to have been picked up so many places with others // placing their copyright on it, that I haven't been able to determine the // original author. [fry 20100216]
found
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/deployment/src/test/java/io/quarkus/restclient/exception/SubResourceTest.java
{ "start": 1110, "end": 4119 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(SubResourceTest.class, ClientRootResource.class, ClientSubResource.class, ServerResource.class, TestExceptionMapper.class, TestException.class) .addAsResource(new StringAsset(ClientRootResource.class.getName() + "/mp-rest/url=${test.url}\n"), "application.properties")); @RestClient ClientRootResource clientRootResource; /** * Creates a REST client with an attached exception mapper. The exception mapper will throw a {@link TestException}. * This test invokes a call to the root resource. * */ @Test public void rootResourceExceptionMapper() { try (Response ignored = clientRootResource.fromRoot()) { fail("fromRoot() should have thrown a TestException"); } catch (TestException expected) { assertEquals("RootResource failed on purpose", expected.getMessage()); } } /** * Creates a REST client with an attached exception mapper. The exception mapper will throw a {@link TestException}. * This test invokes a call to the sub-resource. The sub-resource then invokes an additional call which should also * result in a {@link TestException} thrown. * * @throws Exception if a test error occurs */ @Test public void subResourceExceptionMapper() throws Exception { try (Response ignored = clientRootResource.subResource().fromSub()) { fail("fromSub() should have thrown a TestException"); } catch (TestException expected) { assertEquals("SubResource failed on purpose", expected.getMessage()); } } /** * This test invokes a call to the sub-resource. The sub-resource then invokes an additional call which should * return the header value for {@code test-header}. * */ @Test public void subResourceWithHeader() { try (Response response = clientRootResource.subResource().withHeader()) { assertEquals(OK, response.getStatusInfo()); assertEquals("SubResourceHeader", response.readEntity(String.class)); } } /** * This test invokes a call to the sub-resource. The sub-resource then invokes an additional call which should * return the header value for {@code test-global-header}. * * @throws Exception if a test error occurs */ @Test public void subResourceWithGlobalHeader() throws Exception { try (Response response = clientRootResource.subResource().withGlobalHeader()) { assertEquals(OK, response.getStatusInfo()); assertEquals("GlobalSubResourceHeader", response.readEntity(String.class)); } } @RegisterRestClient @RegisterProvider(TestExceptionMapper.class) @Path("/root") public
SubResourceTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/admin/indices/settings/put/UpdateSettingsRequestTests.java
{ "start": 1256, "end": 7985 }
class ____ extends AbstractXContentTestCase<UpdateSettingsRequest> { /** True if the setting should be enclosed in a settings map. */ private final boolean enclosedSettings; /** True if the request should contain unknown top-level properties. */ private final boolean unknownFields; public UpdateSettingsRequestTests() { this(randomBoolean(), false); } private UpdateSettingsRequestTests(boolean enclosedSettings, boolean unknownFields) { this.enclosedSettings = enclosedSettings; this.unknownFields = unknownFields; } final UpdateSettingsRequestTests withEnclosedSettings() { return new UpdateSettingsRequestTests(true, unknownFields); } final UpdateSettingsRequestTests withoutEnclosedSettings() { return new UpdateSettingsRequestTests(false, unknownFields); } final UpdateSettingsRequestTests withUnknownFields() { return new UpdateSettingsRequestTests(enclosedSettings, true); } final UpdateSettingsRequestTests withoutUnknownFields() { return new UpdateSettingsRequestTests(enclosedSettings, false); } @Override protected UpdateSettingsRequest createTestInstance() { return createTestInstance(enclosedSettings); } private static UpdateSettingsRequest createTestInstance(boolean enclosedSettings) { UpdateSettingsRequest testRequest = UpdateSettingsRequestSerializationTests.createTestItem(); if (randomBoolean()) { testRequest.reopen(true); } if (enclosedSettings) { UpdateSettingsRequest requestWithEnclosingSettings = new UpdateSettingsRequest(testRequest.settings()) { public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.startObject("settings"); this.settings().toXContent(builder, params); builder.endObject(); builder.endObject(); return builder; } }; requestWithEnclosingSettings.reopen(testRequest.reopen()); return requestWithEnclosingSettings; } return testRequest; } @Override protected UpdateSettingsRequest doParseInstance(XContentParser parser) throws IOException { if (mixedRequest() == false) { return new UpdateSettingsRequest().fromXContent(parser); } else { ElasticsearchParseException e = expectThrows( ElasticsearchParseException.class, () -> (new UpdateSettingsRequest()).fromXContent(parser) ); assertThat(e.getMessage(), equalTo("mix of settings map and top-level properties")); return null; } } @Override protected boolean supportsUnknownFields() { // if the settings are enclosed as a "settings" object // then all other top-level elements will be ignored during the parsing return enclosedSettings && unknownFields; } @Override protected Predicate<String> getRandomFieldsExcludeFilter() { if (enclosedSettings) { return field -> field.startsWith("settings"); } return Predicates.always(); } @Override protected void assertEqualInstances(UpdateSettingsRequest expectedInstance, UpdateSettingsRequest newInstance) { // here only the settings should be tested, as this test covers explicitly only the XContent parsing // the rest of the request fields are tested by the SerializingTests if (mixedRequest() == false) { super.assertEqualInstances( new UpdateSettingsRequest(expectedInstance.settings()), new UpdateSettingsRequest(newInstance.settings()) ); } else { assertThat(newInstance, nullValue()); // sanity } } @Override protected boolean assertToXContentEquivalence() { // if enclosedSettings are used, disable the XContentEquivalence check as the // parsed.toXContent is not equivalent to the test instance return enclosedSettings == false; } final boolean mixedRequest() { return enclosedSettings && unknownFields; } public void testWithEnclosedSettingsWithUnknownFields() throws IOException { testFromXContent((new UpdateSettingsRequestTests()).withEnclosedSettings().withUnknownFields()); } public void testWithEnclosedSettingsWithoutUnknownFields() throws IOException { testFromXContent((new UpdateSettingsRequestTests()).withEnclosedSettings().withoutUnknownFields()); } public void testWithoutEnclosedSettingsWithoutUnknownFields() throws IOException { testFromXContent((new UpdateSettingsRequestTests()).withoutEnclosedSettings().withoutUnknownFields()); } private static void testFromXContent(UpdateSettingsRequestTests test) throws IOException { AbstractXContentTestCase.testFromXContent( NUMBER_OF_TEST_RUNS / 2, test::createTestInstance, test.supportsUnknownFields(), test.getShuffleFieldsExceptions(), test.getRandomFieldsExcludeFilter(), test::createParser, test::doParseInstance, test::assertEqualInstances, test.assertToXContentEquivalence(), test.getToXContentParams() ); } /** Tests that mixed requests, containing both an enclosed settings and top-level fields, generate a validation error message. */ public void testMixedFields() throws Exception { UpdateSettingsRequestTests test = (new UpdateSettingsRequestTests()).withEnclosedSettings().withUnknownFields(); UpdateSettingsRequest updateSettingsRequest = test.createTestInstance(); XContentType xContentType = randomFrom(XContentType.values()); BytesReference originalXContent = XContentHelper.toXContent(updateSettingsRequest, xContentType, ToXContent.EMPTY_PARAMS, false); BytesReference updatedXContent = XContentTestUtils.insertRandomFields( xContentType, originalXContent, test.getRandomFieldsExcludeFilter(), random() ); XContentParser parser = test.createParser(XContentFactory.xContent(xContentType), updatedXContent); ElasticsearchParseException e = expectThrows( ElasticsearchParseException.class, () -> (new UpdateSettingsRequest()).fromXContent(parser) ); assertThat(e.getMessage(), equalTo("mix of settings map and top-level properties")); } }
UpdateSettingsRequestTests
java
elastic__elasticsearch
distribution/tools/plugin-cli/src/test/java/org/elasticsearch/plugins/cli/ListPluginsCommandTests.java
{ "start": 1376, "end": 9296 }
class ____ extends CommandTestCase { private Path home; private Environment env; @Before public void initEnv() throws Exception { home = createTempDir(); Files.createDirectories(home.resolve("plugins")); Settings settings = Settings.builder().put("path.home", home).build(); env = TestEnvironment.newEnvironment(settings); } private static String buildMultiline(String... args) { return Arrays.stream(args).collect(Collectors.joining(System.lineSeparator(), "", System.lineSeparator())); } private static void buildFakePlugin(final Environment env, final String description, final String name, final String classname) throws IOException { buildFakePlugin(env, description, name, classname, false); } private static void buildFakePlugin( final Environment env, final String description, final String name, final String classname, final boolean hasNativeController ) throws IOException { PluginTestUtil.writePluginProperties( env.pluginsDir().resolve(name), "description", description, "name", name, "version", "1.0", "elasticsearch.version", Version.CURRENT.toString(), "java.version", "1.8", "classname", classname, "has.native.controller", Boolean.toString(hasNativeController) ); } public void testPluginsDirMissing() throws Exception { Files.delete(env.pluginsDir()); IOException e = expectThrows(IOException.class, () -> execute()); assertEquals("Plugins directory missing: " + env.pluginsDir(), e.getMessage()); } public void testNoPlugins() throws Exception { execute(); assertTrue(terminal.getOutput(), terminal.getOutput().isEmpty()); } public void testOnePlugin() throws Exception { buildFakePlugin(env, "fake desc", "fake", "org.fake"); execute(); assertEquals(buildMultiline("fake"), terminal.getOutput()); } public void testTwoPlugins() throws Exception { buildFakePlugin(env, "fake desc", "fake1", "org.fake"); buildFakePlugin(env, "fake desc 2", "fake2", "org.fake"); execute(); assertEquals(buildMultiline("fake1", "fake2"), terminal.getOutput()); } public void testPluginWithVerbose() throws Exception { buildFakePlugin(env, "fake desc", "fake_plugin", "org.fake"); execute("-v"); assertEquals( buildMultiline( "Plugins directory: " + env.pluginsDir(), "fake_plugin", "- Plugin information:", "Name: fake_plugin", "Description: fake desc", "Version: 1.0", "Elasticsearch Version: " + Version.CURRENT.toString(), "Java Version: 1.8", "Native Controller: false", "Licensed: false", "Extended Plugins: []", " * Classname: org.fake" ), terminal.getOutput() ); } public void testPluginWithNativeController() throws Exception { buildFakePlugin(env, "fake desc 1", "fake_plugin1", "org.fake", true); execute("-v"); assertEquals( buildMultiline( "Plugins directory: " + env.pluginsDir(), "fake_plugin1", "- Plugin information:", "Name: fake_plugin1", "Description: fake desc 1", "Version: 1.0", "Elasticsearch Version: " + Version.CURRENT.toString(), "Java Version: 1.8", "Native Controller: true", "Licensed: false", "Extended Plugins: []", " * Classname: org.fake" ), terminal.getOutput() ); } public void testPluginWithVerboseMultiplePlugins() throws Exception { buildFakePlugin(env, "fake desc 1", "fake_plugin1", "org.fake"); buildFakePlugin(env, "fake desc 2", "fake_plugin2", "org.fake2"); execute("-v"); assertEquals( buildMultiline( "Plugins directory: " + env.pluginsDir(), "fake_plugin1", "- Plugin information:", "Name: fake_plugin1", "Description: fake desc 1", "Version: 1.0", "Elasticsearch Version: " + Version.CURRENT.toString(), "Java Version: 1.8", "Native Controller: false", "Licensed: false", "Extended Plugins: []", " * Classname: org.fake", "fake_plugin2", "- Plugin information:", "Name: fake_plugin2", "Description: fake desc 2", "Version: 1.0", "Elasticsearch Version: " + Version.CURRENT.toString(), "Java Version: 1.8", "Native Controller: false", "Licensed: false", "Extended Plugins: []", " * Classname: org.fake2" ), terminal.getOutput() ); } public void testPluginWithoutVerboseMultiplePlugins() throws Exception { buildFakePlugin(env, "fake desc 1", "fake_plugin1", "org.fake"); buildFakePlugin(env, "fake desc 2", "fake_plugin2", "org.fake2"); execute(); assertEquals(buildMultiline("fake_plugin1", "fake_plugin2"), terminal.getOutput()); } public void testPluginWithoutDescriptorFile() throws Exception { final Path pluginDir = env.pluginsDir().resolve("fake1"); Files.createDirectories(pluginDir); var e = expectThrows(IllegalStateException.class, () -> execute()); assertThat(e.getMessage(), equalTo("Plugin [fake1] is missing a descriptor properties file.")); } public void testPluginWithWrongDescriptorFile() throws Exception { final Path pluginDir = env.pluginsDir().resolve("fake1"); PluginTestUtil.writePluginProperties(pluginDir, "description", "fake desc"); var e = expectThrows(IllegalArgumentException.class, () -> execute()); assertThat(e.getMessage(), startsWith("property [name] is missing for plugin")); } public void testExistingIncompatiblePlugin() throws Exception { PluginTestUtil.writePluginProperties( env.pluginsDir().resolve("fake_plugin1"), "description", "fake desc 1", "name", "fake_plugin1", "version", "1.0", "elasticsearch.version", "1.0.0", "java.version", System.getProperty("java.specification.version"), "classname", "org.fake1" ); buildFakePlugin(env, "fake desc 2", "fake_plugin2", "org.fake2"); execute(); String message = "plugin [fake_plugin1] was built for Elasticsearch version 1.0.0 but version " + Version.CURRENT + " is required"; assertThat(terminal.getOutput().lines().toList(), equalTo(List.of("fake_plugin1", "fake_plugin2"))); assertThat(terminal.getErrorOutput(), containsString("WARNING: " + message)); terminal.reset(); execute("-s"); assertThat(terminal.getOutput().lines().toList(), equalTo(List.of("fake_plugin1", "fake_plugin2"))); assertThat(terminal.getErrorOutput(), emptyString()); } @Override protected Command newCommand() { return new ListPluginsCommand() { @Override protected Environment createEnv(OptionSet options, ProcessInfo processInfo) { return env; } }; } }
ListPluginsCommandTests
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/TransportCodec.java
{ "start": 1664, "end": 3341 }
class ____ extends AbstractCodec { @Override public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { OutputStream output = new ChannelBufferOutputStream(buffer); ObjectOutput objectOutput = getSerialization(channel).serialize(channel.getUrl(), output); encodeData(channel, objectOutput, message); objectOutput.flushBuffer(); if (objectOutput instanceof Cleanable) { ((Cleanable) objectOutput).cleanup(); } } @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { InputStream input = new ChannelBufferInputStream(buffer); ObjectInput objectInput = getSerialization(channel).deserialize(channel.getUrl(), input); Object object = decodeData(channel, objectInput); if (objectInput instanceof Cleanable) { ((Cleanable) objectInput).cleanup(); } return object; } protected void encodeData(Channel channel, ObjectOutput output, Object message) throws IOException { encodeData(output, message); } protected Object decodeData(Channel channel, ObjectInput input) throws IOException { return decodeData(input); } protected void encodeData(ObjectOutput output, Object message) throws IOException { output.writeObject(message); } protected Object decodeData(ObjectInput input) throws IOException { try { return input.readObject(); } catch (ClassNotFoundException e) { throw new IOException("ClassNotFoundException: " + StringUtils.toString(e)); } } }
TransportCodec
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cid/Customer.java
{ "start": 284, "end": 1442 }
class ____ { private String customerId; private String name; private String address; private List orders = new ArrayList(); /** * @return Returns the address. */ public String getAddress() { return address; } /** * @param address The address to set. */ public void setAddress(String address) { this.address = address; } /** * @return Returns the customerId. */ public String getCustomerId() { return customerId; } /** * @param customerId The customerId to set. */ public void setCustomerId(String customerId) { this.customerId = customerId; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } /** * @return Returns the orders. */ public List getOrders() { return orders; } /** * @param orders The orders to set. */ public void setOrders(List orders) { this.orders = orders; } public Order generateNewOrder(BigDecimal total) { Order order = new Order(this); order.setOrderDate( new GregorianCalendar() ); order.setTotal( total ); return order; } }
Customer
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/JAnsiTextRenderer.java
{ "start": 2900, "end": 13610 }
class ____ implements TextRenderer { private static final Logger LOGGER = StatusLogger.getLogger(); public static final Map<String, String> DefaultExceptionStyleMap; static final Map<String, String> DEFAULT_MESSAGE_STYLE_MAP; private static final Map<String, Map<String, String>> PREFEDINED_STYLE_MAPS; private static final String BEGIN_TOKEN = "@|"; private static final String END_TOKEN = "|@"; // The length of AnsiEscape.CSI private static final int CSI_LENGTH = 2; private static Map.Entry<String, String> entry(final String name, final AnsiEscape... codes) { final StringBuilder sb = new StringBuilder(AnsiEscape.CSI.getCode()); for (final AnsiEscape code : codes) { sb.append(code.getCode()); } return new AbstractMap.SimpleImmutableEntry<>(name, sb.toString()); } @SafeVarargs private static <V> Map<String, V> ofEntries(final Map.Entry<String, V>... entries) { final Map<String, V> map = new HashMap<>(entries.length); for (final Map.Entry<String, V> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return Collections.unmodifiableMap(map); } static { // Default style: Spock final Map<String, String> spock = ofEntries( entry("Prefix", WHITE), entry("Name", BG_RED, WHITE), entry("NameMessageSeparator", BG_RED, WHITE), entry("Message", BG_RED, WHITE, BOLD), entry("At", WHITE), entry("CauseLabel", WHITE), entry("Text", WHITE), entry("More", WHITE), entry("Suppressed", WHITE), // StackTraceElement entry("StackTraceElement.ClassLoaderName", WHITE), entry("StackTraceElement.ClassLoaderSeparator", WHITE), entry("StackTraceElement.ModuleName", WHITE), entry("StackTraceElement.ModuleVersionSeparator", WHITE), entry("StackTraceElement.ModuleVersion", WHITE), entry("StackTraceElement.ModuleNameSeparator", WHITE), entry("StackTraceElement.ClassName", YELLOW), entry("StackTraceElement.ClassMethodSeparator", YELLOW), entry("StackTraceElement.MethodName", YELLOW), entry("StackTraceElement.NativeMethod", YELLOW), entry("StackTraceElement.FileName", RED), entry("StackTraceElement.LineNumber", RED), entry("StackTraceElement.Container", RED), entry("StackTraceElement.ContainerSeparator", WHITE), entry("StackTraceElement.UnknownSource", RED), // ExtraClassInfo entry("ExtraClassInfo.Inexact", YELLOW), entry("ExtraClassInfo.Container", YELLOW), entry("ExtraClassInfo.ContainerSeparator", YELLOW), entry("ExtraClassInfo.Location", YELLOW), entry("ExtraClassInfo.Version", YELLOW)); // Style: Kirk final Map<String, String> kirk = ofEntries( entry("Prefix", WHITE), entry("Name", BG_RED, YELLOW, BOLD), entry("NameMessageSeparator", BG_RED, YELLOW), entry("Message", BG_RED, WHITE, BOLD), entry("At", WHITE), entry("CauseLabel", WHITE), entry("Text", WHITE), entry("More", WHITE), entry("Suppressed", WHITE), // StackTraceElement entry("StackTraceElement.ClassLoaderName", WHITE), entry("StackTraceElement.ClassLoaderSeparator", WHITE), entry("StackTraceElement.ModuleName", WHITE), entry("StackTraceElement.ModuleVersionSeparator", WHITE), entry("StackTraceElement.ModuleVersion", WHITE), entry("StackTraceElement.ModuleNameSeparator", WHITE), entry("StackTraceElement.ClassName", BG_RED, WHITE), entry("StackTraceElement.ClassMethodSeparator", BG_RED, YELLOW), entry("StackTraceElement.MethodName", BG_RED, YELLOW), entry("StackTraceElement.NativeMethod", BG_RED, YELLOW), entry("StackTraceElement.FileName", RED), entry("StackTraceElement.LineNumber", RED), entry("StackTraceElement.Container", RED), entry("StackTraceElement.ContainerSeparator", WHITE), entry("StackTraceElement.UnknownSource", RED), // ExtraClassInfo entry("ExtraClassInfo.Inexact", YELLOW), entry("ExtraClassInfo.Container", WHITE), entry("ExtraClassInfo.ContainerSeparator", WHITE), entry("ExtraClassInfo.Location", YELLOW), entry("ExtraClassInfo.Version", YELLOW)); // Save DefaultExceptionStyleMap = spock; DEFAULT_MESSAGE_STYLE_MAP = Collections.emptyMap(); Map<String, Map<String, String>> predefinedStyleMaps = new HashMap<>(); predefinedStyleMaps.put("Spock", spock); predefinedStyleMaps.put("Kirk", kirk); PREFEDINED_STYLE_MAPS = Collections.unmodifiableMap(predefinedStyleMaps); } private final String beginToken; private final int beginTokenLen; private final String endToken; private final int endTokenLen; private final Map<String, String> styleMap; public JAnsiTextRenderer(final String[] formats, final Map<String, String> defaultStyleMap) { // The format string is a list of whitespace-separated expressions: // Key=AnsiEscape(,AnsiEscape)* if (formats.length > 1) { final String stylesStr = formats[1]; final Map<String, String> map = AnsiEscape.createMap( stylesStr.split("\\s", -1), new String[] {"BeginToken", "EndToken", "Style"}, ","); // Handle the special tokens beginToken = Objects.toString(map.remove("BeginToken"), BEGIN_TOKEN); endToken = Objects.toString(map.remove("EndToken"), END_TOKEN); final String predefinedStyle = map.remove("Style"); // Create style map final Map<String, String> styleMap = new HashMap<>(map.size() + defaultStyleMap.size()); defaultStyleMap.forEach((k, v) -> styleMap.put(toRootUpperCase(k), v)); if (predefinedStyle != null) { final Map<String, String> predefinedMap = PREFEDINED_STYLE_MAPS.get(predefinedStyle); if (predefinedMap != null) { map.putAll(predefinedMap); } else { LOGGER.warn( "Unknown predefined map name {}, pick one of {}", predefinedStyle, PREFEDINED_STYLE_MAPS.keySet()); } } styleMap.putAll(map); this.styleMap = Collections.unmodifiableMap(styleMap); } else { beginToken = BEGIN_TOKEN; endToken = END_TOKEN; this.styleMap = Collections.unmodifiableMap(defaultStyleMap); } beginTokenLen = beginToken.length(); endTokenLen = endToken.length(); } /** * Renders the given input with the given names which can be ANSI code names or Log4j style names. * * @param input * The input to render * @param styleNames * ANSI code names or Log4j style names. */ private void render(final String input, final StringBuilder output, final String... styleNames) { boolean first = true; for (final String styleName : styleNames) { final String escape = styleMap.get(toRootUpperCase(styleName)); if (escape != null) { merge(escape, output, first); } else { merge(AnsiEscape.createSequence(styleName), output, first); } first = false; } output.append(input).append(AnsiEscape.getDefaultStyle()); } private static void merge(final String escapeSequence, final StringBuilder output, final boolean first) { if (first) { output.append(escapeSequence); } else { // Delete the trailing AnsiEscape.SUFFIX output.setLength(output.length() - 1); output.append(AnsiEscape.SEPARATOR.getCode()); output.append(escapeSequence.substring(CSI_LENGTH)); } } // EXACT COPY OF StringBuilder version of the method but typed as String for input @Override public void render(final String input, final StringBuilder output, final String styleName) throws IllegalArgumentException { render(input, output, styleName.split(",", -1)); } @Override public void render(final StringBuilder input, final StringBuilder output) throws IllegalArgumentException { int pos = 0; int beginTokenPos, endTokenPos; while (true) { beginTokenPos = input.indexOf(beginToken, pos); if (beginTokenPos == -1) { output.append(pos == 0 ? input : input.substring(pos, input.length())); return; } output.append(input.substring(pos, beginTokenPos)); endTokenPos = input.indexOf(endToken, beginTokenPos); if (endTokenPos == -1) { LOGGER.warn( "Missing matching end token {} for token at position {}: '{}'", endToken, beginTokenPos, input); output.append(beginTokenPos == 0 ? input : input.substring(beginTokenPos, input.length())); return; } beginTokenPos += beginTokenLen; final String spec = input.substring(beginTokenPos, endTokenPos); final String[] items = spec.split("\\s", 2); if (items.length == 1) { LOGGER.warn("Missing argument in ANSI escape specification '{}'", spec); output.append(beginToken).append(spec).append(endToken); } else { render(items[1], output, items[0].split(",", -1)); } pos = endTokenPos + endTokenLen; } } public Map<String, String> getStyleMap() { return styleMap; } @Override public String toString() { return "AnsiMessageRenderer [beginToken=" + beginToken + ", beginTokenLen=" + beginTokenLen + ", endToken=" + endToken + ", endTokenLen=" + endTokenLen + ", styleMap=" + styleMap + "]"; } }
JAnsiTextRenderer
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java
{ "start": 79885, "end": 80047 }
class ____ { @Autowired Example example; @Bean ExampleConfigurer configurer() { return (example) -> { }; } } static
ExampleConsumerConfiguration
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/AnnotationBeanNameGeneratorTests.java
{ "start": 8607, "end": 8693 }
class ____ { } @TestRestController(" ") static
ComposedControllerAnnotationWithoutName
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/persistence/ElasticsearchMappings.java
{ "start": 2760, "end": 9675 }
class ____ { /** * String constants used in mappings */ public static final String ENABLED = "enabled"; public static final String ANALYZER = "analyzer"; public static final String WHITESPACE = "whitespace"; public static final String NESTED = "nested"; public static final String COPY_TO = "copy_to"; public static final String PATH = "path"; public static final String PROPERTIES = "properties"; public static final String TYPE = "type"; public static final String DYNAMIC = "dynamic"; /** * Name of the custom 'all' field for results */ public static final String ALL_FIELD_VALUES = "all_field_values"; /** * Name of the Elasticsearch field by which documents are sorted by default */ public static final String ES_DOC = "_doc"; /** * The configuration document type */ public static final String CONFIG_TYPE = "config_type"; /** * Elasticsearch data types */ public static final String BOOLEAN = "boolean"; public static final String DATE = "date"; public static final String DOUBLE = "double"; public static final String INTEGER = "integer"; public static final String KEYWORD = "keyword"; public static final String LONG = "long"; public static final String TEXT = "text"; private static final Logger logger = LogManager.getLogger(ElasticsearchMappings.class); private ElasticsearchMappings() {} static String[] mappingRequiresUpdate(ClusterState state, String[] concreteIndices, int minVersion) { List<String> indicesToUpdate = new ArrayList<>(); Map<String, MappingMetadata> currentMapping = state.metadata() .getProject() .findMappings(concreteIndices, MapperPlugin.NOOP_FIELD_FILTER, Metadata.ON_NEXT_INDEX_FIND_MAPPINGS_NOOP); for (String index : concreteIndices) { MappingMetadata metadata = currentMapping.get(index); if (metadata != null) { try { @SuppressWarnings("unchecked") Map<String, Object> meta = (Map<String, Object>) metadata.sourceAsMap().get("_meta"); if (meta != null) { Integer systemIndexMappingsVersion = (Integer) meta.get(SystemIndexDescriptor.VERSION_META_KEY); if (systemIndexMappingsVersion == null) { logger.info("System index mappings version for [{}] not found, recreating", index); indicesToUpdate.add(index); continue; } if (systemIndexMappingsVersion >= minVersion) { continue; } else { logger.info( "Mappings for [{}] are outdated [{}], updating it[{}].", index, systemIndexMappingsVersion, minVersion ); indicesToUpdate.add(index); continue; } } else { logger.info("Version of mappings for [{}] not found, recreating", index); indicesToUpdate.add(index); continue; } } catch (Exception e) { logger.error(() -> "Failed to retrieve mapping version for [" + index + "], recreating", e); indicesToUpdate.add(index); continue; } } else { logger.info("No mappings found for [{}], recreating", index); indicesToUpdate.add(index); } } return indicesToUpdate.toArray(new String[indicesToUpdate.size()]); } public static void addDocMappingIfMissing( String alias, CheckedSupplier<String, IOException> mappingSupplier, Client client, ClusterState state, TimeValue masterNodeTimeout, ActionListener<Boolean> listener, int minVersion ) { IndexAbstraction indexAbstraction = state.metadata().getProject().getIndicesLookup().get(alias); if (indexAbstraction == null) { // The index has never been created yet listener.onResponse(true); return; } final var mappingCheck = new ActionRunnable<>(listener) { @Override protected void doRun() throws Exception { String[] concreteIndices = indexAbstraction.getIndices().stream().map(Index::getName).toArray(String[]::new); final String[] indicesThatRequireAnUpdate = mappingRequiresUpdate(state, concreteIndices, minVersion); if (indicesThatRequireAnUpdate.length > 0) { String mapping = mappingSupplier.get(); PutMappingRequest putMappingRequest = new PutMappingRequest(indicesThatRequireAnUpdate); putMappingRequest.source(mapping, XContentType.JSON); putMappingRequest.origin(ML_ORIGIN); putMappingRequest.masterNodeTimeout(masterNodeTimeout); executeAsyncWithOrigin( client, ML_ORIGIN, TransportPutMappingAction.TYPE, putMappingRequest, listener.delegateFailureAndWrap((delegate, response) -> { if (response.isAcknowledged()) { delegate.onResponse(true); } else { delegate.onFailure( new ElasticsearchStatusException( "Attempt to put missing mapping in indices " + Arrays.toString(indicesThatRequireAnUpdate) + " was not acknowledged", RestStatus.TOO_MANY_REQUESTS ) ); } }) ); } else { logger.trace("Mappings are up to date."); listener.onResponse(true); } } }; if (Transports.isTransportThread(Thread.currentThread())) { // TODO make it the caller's responsibility to fork to an appropriate thread before even calling this method - see #87911 client.threadPool().executor(ThreadPool.Names.MANAGEMENT).execute(mappingCheck); } else { mappingCheck.run(); } } }
ElasticsearchMappings
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StaticQualifiedUsingExpressionTest.java
{ "start": 6335, "end": 6917 }
class ____ { static Bar bar; } static void test6() { Foo foo = new Foo(); // BUG: Diagnostic contains: method baz // x = Bar.baz(); int x = Foo.bar.baz(); Bar bar = Foo.bar; // BUG: Diagnostic contains: variable bar // bar = Foo.bar; bar = foo.bar; // BUG: Diagnostic contains: variable baz // x = Bar.baz; x = Foo.bar.baz; } static
Foo
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/runtime/src/main/java/io/quarkus/rest/client/reactive/QuarkusRestClientBuilder.java
{ "start": 13388, "end": 13672 }
interface ____ * @throws IllegalStateException * if not all pre-requisites are satisfied for the builder, this exception may get thrown. For instance, * if the base URI/URL has not been set. * @throws RestClientDefinitionException if the passed-in
that
java
apache__camel
components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathBeanSuppressExceptionsTest.java
{ "start": 1035, "end": 2096 }
class ____ extends CamelTestSupport { @Test public void testFullName() throws Exception { String json = "{\"person\" : {\"firstname\" : \"foo\", \"middlename\" : \"foo2\", \"lastname\" : \"bar\"}}"; getMockEndpoint("mock:result").expectedBodiesReceived("foo foo2 bar"); template.sendBody("direct:start", json); MockEndpoint.assertIsSatisfied(context); } @Test public void testFirstAndLastName() throws Exception { String json = "{\"person\" : {\"firstname\" : \"foo\", \"lastname\" : \"bar\"}}"; getMockEndpoint("mock:result").expectedBodiesReceived("foo bar"); template.sendBody("direct:start", json); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").bean(FullNameBean.class).to("mock:result"); } }; } protected static
JsonPathBeanSuppressExceptionsTest
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/config/ConfigMappingWithProviderTest.java
{ "start": 827, "end": 1664 }
class ____ { @RegisterExtension static final QuarkusDevModeTest TEST = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addClass(MappingResource.class) .addClass(MappingFilter.class) .addClass(Mapping.class) .addAsResource(new StringAsset("mapping.hello=hello\n"), "application.properties")); @Test void configMapping() { RestAssured.when().get("/hello").then() .statusCode(200) .body(is("hello")); TEST.modifyResourceFile("application.properties", s -> "mapping.hello=Hello\n"); RestAssured.when().get("/hello").then() .statusCode(200) .body(is("Hello")); } @Path("/hello") public static
ConfigMappingWithProviderTest
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/io/RichInputOutputITCase.java
{ "start": 1708, "end": 3032 }
class ____ extends JavaProgramTestBaseJUnit4 { private String inputPath; private static ConcurrentLinkedQueue<Integer> readCalls; private static ConcurrentLinkedQueue<Integer> writeCalls; @Override protected void preSubmit() throws Exception { inputPath = createTempFile("input", "ab\n" + "cd\n" + "ef\n"); } @Override protected void testProgram() throws Exception { // test verifying the number of records read and written vs the accumulator counts readCalls = new ConcurrentLinkedQueue<Integer>(); writeCalls = new ConcurrentLinkedQueue<Integer>(); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.createInput(new TestInputFormat(new Path(inputPath))) .addSink(new OutputFormatSinkFunction<>(new TestOutputFormat())); JobExecutionResult result = env.execute(); Object a = result.getAllAccumulatorResults().get("DATA_SOURCE_ACCUMULATOR"); Object b = result.getAllAccumulatorResults().get("DATA_SINK_ACCUMULATOR"); long recordsRead = (Long) a; long recordsWritten = (Long) b; assertEquals(recordsRead, readCalls.size()); assertEquals(recordsWritten, writeCalls.size()); } private static final
RichInputOutputITCase
java
google__auto
value/src/main/java/com/google/auto/value/extension/AutoValueExtension.java
{ "start": 21089, "end": 22482 }
interface ____ a <a * href="http://developer.android.com/reference/android/os/Parcelable.html#writeToParcel(android.os.Parcel,int)">method</a> * {@code void writeToParcel(Parcel, int)}. Normally AutoValue would not know what to do with that * abstract method. But an {@code AutoValueExtension} that understands {@code Parcelable} can * provide a useful implementation and return the {@code writeToParcel} method here. That will * prevent a warning about the method from AutoValue. * * @param context the Context of the code generation for this class. */ public Set<ExecutableElement> consumeMethods(Context context) { return ImmutableSet.of(); } /** * Returns a possibly empty set of abstract methods that this Extension intends to implement. This * will prevent AutoValue from generating an implementation, in cases where it would have, and it * will also avoid complaints about abstract methods that AutoValue doesn't expect. The default * set returned by this method is empty. * * <p>Each returned method must be one of the abstract methods in {@link * Context#builderAbstractMethods()}. * * @param context the Context of the code generation for this class. */ public Set<ExecutableElement> consumeBuilderMethods(Context context) { return ImmutableSet.of(); } /** * Returns the generated source code of the
includes
java
junit-team__junit5
junit-platform-console/src/main/java/org/junit/platform/console/ConsoleLauncher.java
{ "start": 965, "end": 1779 }
class ____ { public static void main(String... args) { CommandFacade facade = newCommandFacade(CustomClassLoaderCloseStrategy.KEEP_OPEN); CommandResult<?> result = facade.run(args); System.exit(result.getExitCode()); } @API(status = INTERNAL, since = "1.0") public static CommandResult<?> run(PrintWriter out, PrintWriter err, String... args) { CommandFacade facade = newCommandFacade(CustomClassLoaderCloseStrategy.CLOSE_AFTER_CALLING_LAUNCHER); return facade.run(args, out, err); } private static CommandFacade newCommandFacade(CustomClassLoaderCloseStrategy classLoaderCleanupStrategy) { return new CommandFacade((discoveryOptions, outputOptions) -> new ConsoleTestExecutor(discoveryOptions, outputOptions, classLoaderCleanupStrategy)); } private ConsoleLauncher() { } }
ConsoleLauncher
java
elastic__elasticsearch
x-pack/plugin/security/cli/src/main/java/org/elasticsearch/xpack/security/cli/CertificateTool.java
{ "start": 5584, "end": 9682 }
class ____ that we can defer initialization until after logging has been initialized static { @SuppressWarnings("unchecked") final ConstructingObjectParser<CertificateInformation, Void> instanceParser = new ConstructingObjectParser<>( "instances", a -> new CertificateInformation( (String) a[0], (String) (a[1] == null ? a[0] : a[1]), (List<String>) a[2], (List<String>) a[3], (List<String>) a[4] ) ); instanceParser.declareString(ConstructingObjectParser.constructorArg(), new ParseField("name")); instanceParser.declareString(ConstructingObjectParser.optionalConstructorArg(), new ParseField("filename")); instanceParser.declareStringArray(ConstructingObjectParser.optionalConstructorArg(), new ParseField("ip")); instanceParser.declareStringArray(ConstructingObjectParser.optionalConstructorArg(), new ParseField("dns")); instanceParser.declareStringArray(ConstructingObjectParser.optionalConstructorArg(), new ParseField("cn")); PARSER.declareObjectArray(List::addAll, instanceParser, new ParseField("instances")); } } CertificateTool() { super(DESCRIPTION); subcommands.put("csr", new SigningRequestCommand()); subcommands.put("cert", new GenerateCertificateCommand()); subcommands.put("ca", new CertificateAuthorityCommand()); subcommands.put("http", new HttpCertificateCommand()); } @Override protected void execute(Terminal terminal, OptionSet options, ProcessInfo processInfo) throws Exception { try { super.execute(terminal, options, processInfo); } catch (OptionException e) { if (e.options().size() == 1 && e.options().contains("keep-ca-key")) { throw new UserException(ExitCodes.USAGE, """ Generating certificates without providing a CA is no longer supported. Please first generate a CA with the 'ca' sub-command and provide the ca file\s with either --ca or --ca-cert/--ca-key to generate certificates."""); } else { throw e; } } } static final String INTRO_TEXT = "This tool assists you in the generation of X.509 certificates and certificate\n" + "signing requests for use with SSL/TLS in the Elastic stack."; static final String INSTANCE_EXPLANATION = """ * An instance is any piece of the Elastic Stack that requires an SSL certificate. Depending on your configuration, Elasticsearch, Logstash, Kibana, and Beats may all require a certificate and private key. * The minimum required value for each instance is a name. This can simply be the hostname, which will be used as the Common Name of the certificate. A full distinguished name may also be used. * A filename value may be required for each instance. This is necessary when the name would result in an invalid file or directory name. The name provided here is used as the directory name (within the zip) and the prefix for the key and certificate files. The filename is required if you are prompted and the name is not displayed in the prompt. * IP addresses and DNS names are optional. Multiple values can be specified as a comma separated string. If no IP addresses or DNS names are provided, you may disable hostname verification in your SSL configuration.""".indent(4); static final String CA_EXPLANATION = """ * All certificates generated by this tool will be signed by a certificate authority (CA) unless the --self-signed command line option is specified. The tool can automatically generate a new CA for you, or you can provide your own with the --ca or --ca-cert command line options.""".indent(4); abstract static
so
java
apache__camel
components/camel-file/src/main/java/org/apache/camel/component/file/AntPathMatcherFileFilter.java
{ "start": 1181, "end": 4301 }
class ____ implements FileFilter { private static final Logger LOG = LoggerFactory.getLogger(AntPathMatcherFileFilter.class); private final AntPathMatcher matcher = new AntPathMatcher(); private String[] excludes; private String[] includes; private boolean caseSensitive = true; @Override public boolean accept(File pathname) { return acceptPathName(pathname.getPath()); } /** * Accepts the given file by the path name * * @param path the path * @return <tt>true</tt> if accepted, <tt>false</tt> if not */ public boolean acceptPathName(String path) { // must use single / as path separators path = path.replace(File.separatorChar, '/'); LOG.trace("Filtering file: {}", path); // excludes take precedence if (excludes != null) { for (String exclude : excludes) { if (matcher.match(exclude, path, caseSensitive)) { // something to exclude so we cant accept it LOG.trace("File is excluded: {}", path); return false; } } } if (includes != null) { for (String include : includes) { if (matcher.match(include, path, caseSensitive)) { // something to include so we accept it LOG.trace("File is included: {}", path); return true; } } } if (excludes != null && includes == null) { // if the user specified excludes but no includes, presumably we // should include by default return true; } // nothing to include so we can't accept it return false; } /** * @return <tt>true</tt> if case sensitive pattern matching is on, <tt>false</tt> if case sensitive pattern matching * is off. */ public boolean isCaseSensitive() { return caseSensitive; } /** * Sets Whether or not pattern matching should be case sensitive * <p/> * Is by default turned on <tt>true</tt>. * * @param caseSensitive <tt>false</tt> to disable case sensitive pattern matching */ public void setCaseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; } public String[] getExcludes() { return excludes; } public void setExcludes(String[] excludes) { this.excludes = excludes; } public String[] getIncludes() { return includes; } public void setIncludes(String[] includes) { this.includes = includes; } /** * Sets excludes using a single string where each element can be separated with comma */ public void setExcludes(String excludes) { setExcludes(excludes.split(",")); } /** * Sets includes using a single string where each element can be separated with comma */ public void setIncludes(String includes) { setIncludes(includes.split(",")); } }
AntPathMatcherFileFilter
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3ABlockOutputArray.java
{ "start": 2038, "end": 7691 }
class ____ extends AbstractS3ATestBase { private static final int BLOCK_SIZE = 256 * 1024; private static byte[] dataset; @BeforeAll public static void setupDataset() { dataset = ContractTestUtils.dataset(BLOCK_SIZE, 0, 256); } @Override protected Configuration createConfiguration() { Configuration conf = super.createConfiguration(); S3ATestUtils.disableFilesystemCaching(conf); conf.setLong(MIN_MULTIPART_THRESHOLD, MULTIPART_MIN_SIZE); conf.setInt(MULTIPART_SIZE, MULTIPART_MIN_SIZE); conf.set(FAST_UPLOAD_BUFFER, getBlockOutputBufferName()); return conf; } @Override @BeforeEach public void setup() throws Exception { super.setup(); skipIfNotEnabled(getFileSystem().getConf(), MULTIPART_UPLOADS_ENABLED, "Store has disabled multipart uploads; skipping tests"); } protected String getBlockOutputBufferName() { return FAST_UPLOAD_BUFFER_ARRAY; } @Test public void testZeroByteUpload() throws IOException { verifyUpload("0", 0); } @Test public void testRegularUpload() throws IOException { verifyUpload("regular", 1024); } @Test public void testWriteAfterStreamClose() throws Throwable { assertThrows(IOException.class, () -> { Path dest = path("testWriteAfterStreamClose"); describe(" testWriteAfterStreamClose"); FSDataOutputStream stream = getFileSystem().create(dest, true); byte[] data = ContractTestUtils.dataset(16, 'a', 26); try { stream.write(data); stream.close(); stream.write(data); } finally { IOUtils.closeStream(stream); } }); } @Test public void testBlocksClosed() throws Throwable { Path dest = path("testBlocksClosed"); describe(" testBlocksClosed"); FSDataOutputStream stream = getFileSystem().create(dest, true); BlockOutputStreamStatistics statistics = S3ATestUtils.getOutputStreamStatistics(stream); byte[] data = ContractTestUtils.dataset(16, 'a', 26); stream.write(data); LOG.info("closing output stream"); stream.close(); assertEquals(1, statistics.getBlocksAllocated(), "total allocated blocks in " + statistics); assertEquals(0, statistics.getBlocksActivelyAllocated(), "actively allocated blocks in " + statistics); LOG.info("end of test case"); } private void verifyUpload(String name, int fileSize) throws IOException { Path dest = path(name); describe(name + " upload to " + dest); ContractTestUtils.createAndVerifyFile( getFileSystem(), dest, fileSize); } /** * Create a factory for used in mark/reset tests. * @param fileSystem source FS * @return the factory */ protected S3ADataBlocks.BlockFactory createFactory(S3AFileSystem fileSystem) { return new S3ADataBlocks.ArrayBlockFactory(fileSystem.createStoreContext()); } private void markAndResetDatablock(S3ADataBlocks.BlockFactory factory) throws Exception { S3AInstrumentation instrumentation = new S3AInstrumentation(new URI("s3a://example")); BlockOutputStreamStatistics outstats = instrumentation.newOutputStreamStatistics(null); S3ADataBlocks.DataBlock block = factory.create(1, BLOCK_SIZE, outstats); block.write(dataset, 0, dataset.length); S3ADataBlocks.BlockUploadData uploadData = block.startUpload(); final UploadContentProviders.BaseContentProvider cp = uploadData.getContentProvider(); InputStream stream = cp.newStream(); assertNotNull(stream); assertEquals(0, stream.read()); stream.mark(BLOCK_SIZE); // read a lot long l = 0; while (stream.read() != -1) { // do nothing l++; } stream.reset(); assertEquals(1, stream.read()); } @Test public void testMarkReset() throws Throwable { markAndResetDatablock(createFactory(getFileSystem())); } @Test public void testAbortAfterWrite() throws Throwable { describe("Verify abort after a write does not create a file"); Path dest = path(getMethodName()); FileSystem fs = getFileSystem(); ContractTestUtils.assertHasPathCapabilities(fs, dest, ABORTABLE_STREAM); FSDataOutputStream stream = fs.create(dest, true); byte[] data = ContractTestUtils.dataset(16, 'a', 26); try { ContractTestUtils.assertCapabilities(stream, new String[]{ABORTABLE_STREAM}, null); stream.write(data); assertCompleteAbort(stream.abort()); // second attempt is harmless assertNoopAbort(stream.abort()); // the path should not exist ContractTestUtils.assertPathsDoNotExist(fs, "aborted file", dest); } finally { IOUtils.closeStream(stream); // check the path doesn't exist "after" closing stream ContractTestUtils.assertPathsDoNotExist(fs, "aborted file", dest); } // and it can be called on the stream after being closed. assertNoopAbort(stream.abort()); } /** * A stream which was abort()ed after being close()d for a * successful write will return indicating nothing happened. */ @Test public void testAbortAfterCloseIsHarmless() throws Throwable { describe("Verify abort on a closed stream is harmless " + "and that the result indicates that nothing happened"); Path dest = path(getMethodName()); FileSystem fs = getFileSystem(); byte[] data = ContractTestUtils.dataset(16, 'a', 26); try (FSDataOutputStream stream = fs.create(dest, true)) { stream.write(data); assertCompleteAbort(stream.abort()); stream.close(); assertNoopAbort(stream.abort()); } } }
ITestS3ABlockOutputArray
java
elastic__elasticsearch
distribution/archives/integ-test-zip/src/javaRestTest/java/org/elasticsearch/test/rest/NodeRestUsageIT.java
{ "start": 1209, "end": 13612 }
class ____ extends ESRestTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local().build(); @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } @SuppressWarnings("unchecked") public void testWithRestUsage() throws IOException { // First get the current usage figures String path = randomFrom("_nodes/usage", "_nodes/usage/rest_actions", "_nodes/usage/_all"); Response beforeResponse = client().performRequest(new Request("GET", path)); Map<String, Object> beforeResponseBodyMap = entityAsMap(beforeResponse); assertThat(beforeResponseBodyMap, notNullValue()); int beforeSuccessful = assertSuccess(beforeResponseBodyMap); Map<String, Object> beforeNodesMap = (Map<String, Object>) beforeResponseBodyMap.get("nodes"); assertThat(beforeNodesMap, notNullValue()); assertThat(beforeNodesMap.size(), equalTo(beforeSuccessful)); Map<String, Long> beforeCombinedRestUsage = new HashMap<>(); beforeCombinedRestUsage.put("nodes_usage_action", 0L); beforeCombinedRestUsage.put("create_index_action", 0L); beforeCombinedRestUsage.put("document_index_action", 0L); beforeCombinedRestUsage.put("search_action", 0L); beforeCombinedRestUsage.put("refresh_action", 0L); beforeCombinedRestUsage.put("cat_indices_action", 0L); beforeCombinedRestUsage.put("nodes_info_action", 0L); beforeCombinedRestUsage.put("nodes_stats_action", 0L); beforeCombinedRestUsage.put("delete_index_action", 0L); for (Map.Entry<String, Object> nodeEntry : beforeNodesMap.entrySet()) { Map<String, Object> beforeRestActionUsage = (Map<String, Object>) ((Map<String, Object>) nodeEntry.getValue()).get( "rest_actions" ); assertThat(beforeRestActionUsage, notNullValue()); for (Map.Entry<String, Object> restActionEntry : beforeRestActionUsage.entrySet()) { Long currentUsage = beforeCombinedRestUsage.get(restActionEntry.getKey()); if (currentUsage == null) { beforeCombinedRestUsage.put(restActionEntry.getKey(), ((Number) restActionEntry.getValue()).longValue()); } else { beforeCombinedRestUsage.put(restActionEntry.getKey(), currentUsage + ((Number) restActionEntry.getValue()).longValue()); } } } // Do some requests to get some rest usage stats client().performRequest(new Request("PUT", "/test")); for (int i = 0; i < 3; i++) { final Request index = new Request("POST", "/test/_doc/1"); index.setJsonEntity("{\"foo\": \"bar\"}"); client().performRequest(index); } client().performRequest(new Request("GET", "/test/_search")); final Request index4 = new Request("POST", "/test/_doc/4"); index4.setJsonEntity("{\"foo\": \"bar\"}"); client().performRequest(index4); client().performRequest(new Request("POST", "/test/_refresh")); client().performRequest(new Request("GET", "/_cat/indices")); client().performRequest(new Request("GET", "/_nodes")); client().performRequest(new Request("GET", "/test/_search")); client().performRequest(new Request("GET", "/_nodes/stats")); client().performRequest(new Request("DELETE", "/test")); Response response = client().performRequest(new Request("GET", "_nodes/usage")); Map<String, Object> responseBodyMap = entityAsMap(response); assertThat(responseBodyMap, notNullValue()); int successful = assertSuccess(responseBodyMap); Map<String, Object> nodesMap = (Map<String, Object>) responseBodyMap.get("nodes"); assertThat(nodesMap, notNullValue()); assertThat(nodesMap.size(), equalTo(successful)); Map<String, Long> combinedRestUsage = new HashMap<>(); for (Map.Entry<String, Object> nodeEntry : nodesMap.entrySet()) { Map<String, Object> restActionUsage = (Map<String, Object>) ((Map<String, Object>) nodeEntry.getValue()).get("rest_actions"); assertThat(restActionUsage, notNullValue()); for (Map.Entry<String, Object> restActionEntry : restActionUsage.entrySet()) { Long currentUsage = combinedRestUsage.get(restActionEntry.getKey()); if (currentUsage == null) { combinedRestUsage.put(restActionEntry.getKey(), ((Number) restActionEntry.getValue()).longValue()); } else { combinedRestUsage.put(restActionEntry.getKey(), currentUsage + ((Number) restActionEntry.getValue()).longValue()); } } } assertThat(combinedRestUsage.get("nodes_usage_action") - beforeCombinedRestUsage.get("nodes_usage_action"), equalTo(1L)); assertThat(combinedRestUsage.get("create_index_action") - beforeCombinedRestUsage.get("create_index_action"), equalTo(1L)); assertThat(combinedRestUsage.get("document_index_action") - beforeCombinedRestUsage.get("document_index_action"), equalTo(4L)); assertThat(combinedRestUsage.get("search_action") - beforeCombinedRestUsage.get("search_action"), equalTo(2L)); assertThat(combinedRestUsage.get("refresh_action") - beforeCombinedRestUsage.get("refresh_action"), equalTo(1L)); assertThat(combinedRestUsage.get("cat_indices_action") - beforeCombinedRestUsage.get("cat_indices_action"), equalTo(1L)); assertThat(combinedRestUsage.get("nodes_info_action") - beforeCombinedRestUsage.get("nodes_info_action"), equalTo(1L)); assertThat(combinedRestUsage.get("nodes_stats_action") - beforeCombinedRestUsage.get("nodes_stats_action"), equalTo(1L)); assertThat(combinedRestUsage.get("delete_index_action") - beforeCombinedRestUsage.get("delete_index_action"), equalTo(1L)); } public void testMetricsWithAll() throws IOException { ResponseException exception = expectThrows( ResponseException.class, () -> client().performRequest(new Request("GET", "_nodes/usage/_all,rest_actions")) ); assertNotNull(exception); assertThat(exception.getMessage(), containsString(""" "type":"illegal_argument_exception",\ "reason":"request [_nodes/usage/_all,rest_actions] contains _all and individual metrics [_all,rest_actions]\"""")); } @SuppressWarnings("unchecked") public void testAggregationUsage() throws IOException { // First get the current usage figures String path = randomFrom("_nodes/usage", "_nodes/usage/aggregations", "_nodes/usage/_all"); Response beforeResponse = client().performRequest(new Request("GET", path)); Map<String, Object> beforeResponseBodyMap = entityAsMap(beforeResponse); assertThat(beforeResponseBodyMap, notNullValue()); int beforeSuccessful = assertSuccess(beforeResponseBodyMap); Map<String, Object> beforeNodesMap = (Map<String, Object>) beforeResponseBodyMap.get("nodes"); assertThat(beforeNodesMap, notNullValue()); assertThat(beforeNodesMap.size(), equalTo(beforeSuccessful)); Map<String, Map<String, Long>> beforeCombinedAggsUsage = getTotalUsage(beforeNodesMap); // Do some requests to get some rest usage stats Request create = new Request("PUT", "/test"); create.setJsonEntity(""" { "mappings": { "properties": { "str": { "type": "keyword" }, "foo": { "type": "keyword" }, "num": { "type": "long" }, "start": { "type": "date" } } } }"""); client().performRequest(create); Request searchRequest = new Request("GET", "/test/_search"); SearchSourceBuilder searchSource = new SearchSourceBuilder().aggregation( AggregationBuilders.terms("str_terms").field("str.keyword") ).aggregation(AggregationBuilders.terms("num_terms").field("num")).aggregation(AggregationBuilders.avg("num_avg").field("num")); searchRequest.setJsonEntity(Strings.toString(searchSource)); searchRequest.setJsonEntity(Strings.toString(searchSource)); client().performRequest(searchRequest); searchRequest = new Request("GET", "/test/_search"); searchSource = new SearchSourceBuilder().aggregation(AggregationBuilders.terms("start").field("start")) .aggregation(AggregationBuilders.avg("num1").field("num")) .aggregation(AggregationBuilders.avg("num2").field("num")) .aggregation(AggregationBuilders.terms("foo").field("foo.keyword")); String r = Strings.toString(searchSource); searchRequest.setJsonEntity(Strings.toString(searchSource)); client().performRequest(searchRequest); Response response = client().performRequest(new Request("GET", "_nodes/usage")); Map<String, Object> responseBodyMap = entityAsMap(response); assertThat(responseBodyMap, notNullValue()); int successful = assertSuccess(responseBodyMap); Map<String, Object> nodesMap = (Map<String, Object>) responseBodyMap.get("nodes"); assertThat(nodesMap, notNullValue()); assertThat(nodesMap.size(), equalTo(successful)); Map<String, Map<String, Long>> afterCombinedAggsUsage = getTotalUsage(nodesMap); assertDiff(beforeCombinedAggsUsage, afterCombinedAggsUsage, "terms", "numeric", 1L); assertDiff(beforeCombinedAggsUsage, afterCombinedAggsUsage, "terms", "date", 1L); assertDiff(beforeCombinedAggsUsage, afterCombinedAggsUsage, "terms", "keyword", 2L); assertDiff(beforeCombinedAggsUsage, afterCombinedAggsUsage, "avg", "numeric", 3L); } private void assertDiff( Map<String, Map<String, Long>> before, Map<String, Map<String, Long>> after, String agg, String vst, long diff ) { Long valBefore = before.getOrDefault(agg, Collections.emptyMap()).getOrDefault(vst, 0L); Long valAfter = after.getOrDefault(agg, Collections.emptyMap()).getOrDefault(vst, 0L); assertThat(agg + "." + vst, valAfter - valBefore, equalTo(diff)); } private Map<String, Map<String, Long>> getTotalUsage(Map<String, Object> nodeUsage) { Map<String, Map<String, Long>> combined = new HashMap<>(); for (Map.Entry<String, Object> nodeEntry : nodeUsage.entrySet()) { @SuppressWarnings("unchecked") Map<String, Object> beforeAggsUsage = (Map<String, Object>) ((Map<String, Object>) nodeEntry.getValue()).get("aggregations"); assertThat(beforeAggsUsage, notNullValue()); for (Map.Entry<String, Object> aggEntry : beforeAggsUsage.entrySet()) { @SuppressWarnings("unchecked") Map<String, Object> aggMap = (Map<String, Object>) aggEntry.getValue(); Map<String, Long> combinedAggMap = combined.computeIfAbsent(aggEntry.getKey(), k -> new HashMap<>()); for (Map.Entry<String, Object> valSourceEntry : aggMap.entrySet()) { combinedAggMap.put( valSourceEntry.getKey(), combinedAggMap.getOrDefault(valSourceEntry.getKey(), 0L) + ((Number) valSourceEntry.getValue()).longValue() ); } } } return combined; } private int assertSuccess(Map<String, Object> responseBodyMap) { @SuppressWarnings("unchecked") Map<String, Object> nodesResultMap = (Map<String, Object>) responseBodyMap.get("_nodes"); assertThat(nodesResultMap, notNullValue()); Integer total = (Integer) nodesResultMap.get("total"); Integer successful = (Integer) nodesResultMap.get("successful"); Integer failed = (Integer) nodesResultMap.get("failed"); assertThat(total, greaterThan(0)); assertThat(successful, equalTo(total)); assertThat(failed, equalTo(0)); return successful; } }
NodeRestUsageIT
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/blob/NoOpTransientBlobService.java
{ "start": 1035, "end": 2382 }
enum ____ implements TransientBlobService { INSTANCE; @Override public File getFile(TransientBlobKey key) throws IOException { throw new UnsupportedOperationException(); } @Override public File getFile(JobID jobId, TransientBlobKey key) throws IOException { throw new UnsupportedOperationException(); } @Override public TransientBlobKey putTransient(byte[] value) throws IOException { throw new UnsupportedOperationException(); } @Override public TransientBlobKey putTransient(JobID jobId, byte[] value) throws IOException { throw new UnsupportedOperationException(); } @Override public TransientBlobKey putTransient(InputStream inputStream) throws IOException { throw new UnsupportedOperationException(); } @Override public TransientBlobKey putTransient(JobID jobId, InputStream inputStream) throws IOException { throw new UnsupportedOperationException(); } @Override public boolean deleteFromCache(TransientBlobKey key) { throw new UnsupportedOperationException(); } @Override public boolean deleteFromCache(JobID jobId, TransientBlobKey key) { throw new UnsupportedOperationException(); } @Override public void close() throws IOException {} }
NoOpTransientBlobService
java
spring-projects__spring-framework
spring-r2dbc/src/test/java/org/springframework/r2dbc/connection/TransactionAwareConnectionFactoryProxyTests.java
{ "start": 1562, "end": 5747 }
class ____ { ConnectionFactory connectionFactoryMock = mock(); Connection connectionMock1 = mock(); Connection connectionMock2 = mock(); Connection connectionMock3 = mock(); R2dbcTransactionManager tm; @BeforeEach @SuppressWarnings({"rawtypes", "unchecked"}) void before() { when(connectionFactoryMock.create()).thenReturn((Mono) Mono.just(connectionMock1), (Mono) Mono.just(connectionMock2), (Mono) Mono.just(connectionMock3)); tm = new R2dbcTransactionManager(connectionFactoryMock); } @Test void createShouldWrapConnection() { new TransactionAwareConnectionFactoryProxy(connectionFactoryMock).create() .as(StepVerifier::create) .consumeNextWith(connection -> assertThat(connection).isInstanceOf(Wrapped.class)) .verifyComplete(); } @Test void unwrapShouldReturnTargetConnection() { new TransactionAwareConnectionFactoryProxy(connectionFactoryMock).create() .map(Wrapped.class::cast).as(StepVerifier::create) .consumeNextWith(wrapped -> assertThat(wrapped.unwrap()).isEqualTo(connectionMock1)) .verifyComplete(); } @Test void unwrapShouldReturnTargetConnectionEvenWhenClosed() { when(connectionMock1.close()).thenReturn(Mono.empty()); new TransactionAwareConnectionFactoryProxy(connectionFactoryMock).create() .map(Connection.class::cast).flatMap( connection -> Mono.from(connection.close()).then(Mono.just(connection))).as( StepVerifier::create) .consumeNextWith(wrapped -> assertThat(((Wrapped<?>) wrapped).unwrap()).isEqualTo(connectionMock1)) .verifyComplete(); } @Test void getTargetConnectionShouldReturnTargetConnection() { new TransactionAwareConnectionFactoryProxy(connectionFactoryMock).create() .map(Wrapped.class::cast).as(StepVerifier::create) .consumeNextWith(wrapped -> assertThat(wrapped.unwrap()).isEqualTo(connectionMock1)) .verifyComplete(); } @Test void getMetadataShouldThrowsErrorEvenWhenClosed() { when(connectionMock1.close()).thenReturn(Mono.empty()); new TransactionAwareConnectionFactoryProxy(connectionFactoryMock).create() .map(Connection.class::cast).flatMap( connection -> Mono.from(connection.close()) .then(Mono.just(connection))).as(StepVerifier::create) .consumeNextWith(connection -> assertThatIllegalStateException().isThrownBy( connection::getMetadata)).verifyComplete(); } @Test void hashCodeShouldReturnProxyHash() { new TransactionAwareConnectionFactoryProxy(connectionFactoryMock).create() .map(Connection.class::cast).as(StepVerifier::create) .consumeNextWith(connection -> assertThat(connection.hashCode()).isEqualTo( System.identityHashCode(connection))).verifyComplete(); } @Test void equalsShouldCompareCorrectly() { new TransactionAwareConnectionFactoryProxy(connectionFactoryMock).create() .map(Connection.class::cast).as(StepVerifier::create) .consumeNextWith(connection -> { assertThat(connection).isEqualTo(connection); assertThat(connection).isNotEqualTo(connectionMock1); }).verifyComplete(); } @Test void shouldEmitBoundConnection() { when(connectionMock1.beginTransaction(ArgumentMatchers.any())).thenReturn(Mono.empty()); when(connectionMock1.commitTransaction()).thenReturn(Mono.empty()); when(connectionMock1.close()).thenReturn(Mono.empty()); TransactionalOperator rxtx = TransactionalOperator.create(tm); AtomicReference<Connection> transactionalConnection = new AtomicReference<>(); TransactionAwareConnectionFactoryProxy proxyCf = new TransactionAwareConnectionFactoryProxy( connectionFactoryMock); ConnectionFactoryUtils.getConnection(connectionFactoryMock) .doOnNext(transactionalConnection::set).flatMap(connection -> proxyCf.create() .doOnNext(wrappedConnection -> assertThat(((Wrapped<?>) wrappedConnection).unwrap()).isSameAs(connection))) .flatMapMany(Connection::close) .as(rxtx::transactional) .as(StepVerifier::create) .verifyComplete(); verify(connectionFactoryMock, times(1)).create(); verify(connectionMock1, times(1)).close(); verifyNoInteractions(connectionMock2); verifyNoInteractions(connectionMock3); } }
TransactionAwareConnectionFactoryProxyTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/XorPowerTest.java
{ "start": 2597, "end": 3090 }
class ____ { static final long X = 1L << 16; static final long Y = 1L << 32; static final long Z = 1L << 31; static final long TOO_BIG = 2L ^ 64; static final long P = 1000000L; } """) .doTest(); } @Test public void precedence() { BugCheckerRefactoringTestHelper.newInstance(XorPower.class, getClass()) .addInputLines( "Test.java", """
Test
java
google__dagger
javatests/dagger/functional/membersinject/MembersInjectionOrdering.java
{ "start": 1362, "end": 1449 }
class ____ extends Base { @Inject String firstToString; } @Module static
Subtype
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLists.java
{ "start": 1152, "end": 4417 }
class ____ { @Test public void testAddToEmptyArrayList() { List<String> list = Lists.newArrayList(); list.add("record1"); assertEquals(1, list.size()); assertEquals("record1", list.get(0)); } @Test public void testAddToEmptyLinkedList() { List<String> list = Lists.newLinkedList(); list.add("record1"); assertEquals(1, list.size()); assertEquals("record1", list.get(0)); } @Test public void testVarArgArrayLists() { List<String> list = Lists.newArrayList("record1", "record2", "record3"); list.add("record4"); assertEquals(4, list.size()); assertEquals("record1", list.get(0)); assertEquals("record2", list.get(1)); assertEquals("record3", list.get(2)); assertEquals("record4", list.get(3)); } @Test public void testItrArrayLists() { Set<String> set = new HashSet<>(); set.add("record1"); set.add("record2"); set.add("record3"); List<String> list = Lists.newArrayList(set); list.add("record4"); assertEquals(4, list.size()); } @Test public void testItrLinkedLists() { Set<String> set = new HashSet<>(); set.add("record1"); set.add("record2"); set.add("record3"); List<String> list = Lists.newLinkedList(set); list.add("record4"); assertEquals(4, list.size()); } @Test public void testListsPartition() { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); List<List<String>> res = Lists. partition(list, 2); assertThat(res) .describedAs("Number of partitions post partition") .hasSize(3); assertThat(res.get(0)) .describedAs("Number of elements in first partition") .hasSize(2); assertThat(res.get(2)) .describedAs("Number of elements in last partition") .hasSize(1); List<List<String>> res2 = Lists. partition(list, 1); assertThat(res2) .describedAs("Number of partitions post partition") .hasSize(5); assertThat(res2.get(0)) .describedAs("Number of elements in first partition") .hasSize(1); assertThat(res2.get(4)) .describedAs("Number of elements in last partition") .hasSize(1); List<List<String>> res3 = Lists. partition(list, 6); assertThat(res3) .describedAs("Number of partitions post partition") .hasSize(1); assertThat(res3.get(0)) .describedAs("Number of elements in first partition") .hasSize(5); } @Test public void testArrayListWithSize() { List<String> list = Lists.newArrayListWithCapacity(3); list.add("record1"); list.add("record2"); list.add("record3"); assertEquals(3, list.size()); assertEquals("record1", list.get(0)); assertEquals("record2", list.get(1)); assertEquals("record3", list.get(2)); list = Lists.newArrayListWithCapacity(3); list.add("record1"); list.add("record2"); list.add("record3"); assertEquals(3, list.size()); assertEquals("record1", list.get(0)); assertEquals("record2", list.get(1)); assertEquals("record3", list.get(2)); } }
TestLists
java
quarkusio__quarkus
integration-tests/injectmock/src/main/java/io/quarkus/it/mockbean/hello/HelloServiceImpl.java
{ "start": 84, "end": 307 }
class ____ implements HelloService { private final RecordB recB; HelloServiceImpl(RecordB recB) { this.recB = recB; } public String hello() { return recB.dataHello(); } }
HelloServiceImpl
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/FlameGraphTypeQueryParameter.java
{ "start": 982, "end": 1791 }
class ____ extends MessageQueryParameter<FlameGraphTypeQueryParameter.Type> { public static final String KEY = "type"; public FlameGraphTypeQueryParameter() { super(KEY, MessageParameterRequisiteness.OPTIONAL); } @Override public Type convertStringToValue(String value) { return Type.valueOf(value.toUpperCase()); } @Override public String convertValueToString(Type value) { return value.name().toLowerCase(); } @Override public String getDescription() { return "String value that specifies the Flame Graph type. Supported options are: \"" + Arrays.toString(Type.values()) + "\"."; } /** Flame Graph type. */ @Schema(name = "ThreadStates") public
FlameGraphTypeQueryParameter
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/bind/MethodArgumentNotValidExceptionTests.java
{ "start": 3373, "end": 3567 }
class ____ { @SuppressWarnings("unused") void handle(Person person) { } } @SuppressWarnings("unused") private record Person(@Size(max = 10) String name, @Min(25) int age) { } }
Handler
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/ConfigDataApplicationContextInitializerTests.java
{ "start": 1489, "end": 1764 }
class ____ { @Autowired private Environment environment; @Test void initializerPopulatesEnvironment() { assertThat(this.environment.getProperty("foo")).isEqualTo("bucket"); } @Configuration(proxyBeanMethods = false) static
ConfigDataApplicationContextInitializerTests
java
apache__camel
components/camel-aws/camel-aws2-kms/src/main/java/org/apache/camel/component/aws2/kms/KMS2Producer.java
{ "start": 2272, "end": 14552 }
class ____ extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(KMS2Producer.class); public static final String MISSING_KEY_ID = "Key Id must be specified"; private transient String kmsProducerToString; public KMS2Producer(Endpoint endpoint) { super(endpoint); } @Override public void process(Exchange exchange) throws Exception { switch (determineOperation(exchange)) { case listKeys: listKeys(getEndpoint().getKmsClient(), exchange); break; case createKey: createKey(getEndpoint().getKmsClient(), exchange); break; case disableKey: disableKey(getEndpoint().getKmsClient(), exchange); break; case enableKey: enableKey(getEndpoint().getKmsClient(), exchange); break; case scheduleKeyDeletion: scheduleKeyDeletion(getEndpoint().getKmsClient(), exchange); break; case describeKey: describeKey(getEndpoint().getKmsClient(), exchange); break; default: throw new IllegalArgumentException("Unsupported operation"); } } private KMS2Operations determineOperation(Exchange exchange) { KMS2Operations operation = exchange.getIn().getHeader(KMS2Constants.OPERATION, KMS2Operations.class); if (operation == null) { operation = getConfiguration().getOperation(); } if (ObjectHelper.isEmpty(operation)) { throw new IllegalArgumentException("Operation must be specified"); } return operation; } protected KMS2Configuration getConfiguration() { return getEndpoint().getConfiguration(); } @Override public String toString() { if (kmsProducerToString == null) { kmsProducerToString = "KMSProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]"; } return kmsProducerToString; } @Override public KMS2Endpoint getEndpoint() { return (KMS2Endpoint) super.getEndpoint(); } private void listKeys(KmsClient kmsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof ListKeysRequest) { ListKeysResponse result; try { result = kmsClient.listKeys((ListKeysRequest) payload); } catch (AwsServiceException ase) { LOG.trace("List Keys command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { ListKeysRequest.Builder builder = ListKeysRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(KMS2Constants.LIMIT))) { int limit = exchange.getIn().getHeader(KMS2Constants.LIMIT, Integer.class); builder.limit(limit); } ListKeysResponse result; try { result = kmsClient.listKeys(builder.build()); } catch (AwsServiceException ase) { LOG.trace("List Keys command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void createKey(KmsClient kmsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof CreateKeyRequest) { CreateKeyResponse result; try { result = kmsClient.createKey((CreateKeyRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Create Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { CreateKeyRequest.Builder builder = CreateKeyRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(KMS2Constants.DESCRIPTION))) { String description = exchange.getIn().getHeader(KMS2Constants.DESCRIPTION, String.class); builder.description(description); } CreateKeyResponse result; try { result = kmsClient.createKey(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Create Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void disableKey(KmsClient kmsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof DisableKeyRequest) { DisableKeyResponse result; try { result = kmsClient.disableKey((DisableKeyRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Disable Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { DisableKeyRequest.Builder builder = DisableKeyRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(KMS2Constants.KEY_ID))) { String keyId = exchange.getIn().getHeader(KMS2Constants.KEY_ID, String.class); builder.keyId(keyId); } else { throw new IllegalArgumentException(MISSING_KEY_ID); } DisableKeyResponse result; try { result = kmsClient.disableKey(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Disable Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void scheduleKeyDeletion(KmsClient kmsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof ScheduleKeyDeletionRequest) { ScheduleKeyDeletionResponse result; try { result = kmsClient.scheduleKeyDeletion((ScheduleKeyDeletionRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Schedule Key Deletion command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { ScheduleKeyDeletionRequest.Builder builder = ScheduleKeyDeletionRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(KMS2Constants.KEY_ID))) { String keyId = exchange.getIn().getHeader(KMS2Constants.KEY_ID, String.class); builder.keyId(keyId); } else { throw new IllegalArgumentException(MISSING_KEY_ID); } if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(KMS2Constants.PENDING_WINDOW_IN_DAYS))) { int pendingWindows = exchange.getIn().getHeader(KMS2Constants.PENDING_WINDOW_IN_DAYS, Integer.class); builder.pendingWindowInDays(pendingWindows); } ScheduleKeyDeletionResponse result; try { result = kmsClient.scheduleKeyDeletion(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Schedule Key Deletion command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void describeKey(KmsClient kmsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof DescribeKeyRequest) { DescribeKeyResponse result; try { result = kmsClient.describeKey((DescribeKeyRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Describe Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { DescribeKeyRequest.Builder builder = DescribeKeyRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(KMS2Constants.KEY_ID))) { String keyId = exchange.getIn().getHeader(KMS2Constants.KEY_ID, String.class); builder.keyId(keyId); } else { throw new IllegalArgumentException(MISSING_KEY_ID); } DescribeKeyResponse result; try { result = kmsClient.describeKey(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Describe Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } private void enableKey(KmsClient kmsClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getIn().getMandatoryBody(); if (payload instanceof EnableKeyRequest) { EnableKeyResponse result; try { result = kmsClient.enableKey((EnableKeyRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Enable Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } else { EnableKeyRequest.Builder builder = EnableKeyRequest.builder(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(KMS2Constants.KEY_ID))) { String keyId = exchange.getIn().getHeader(KMS2Constants.KEY_ID, String.class); builder.keyId(keyId); } else { throw new IllegalArgumentException(MISSING_KEY_ID); } EnableKeyResponse result; try { result = kmsClient.enableKey(builder.build()); } catch (AwsServiceException ase) { LOG.trace("Enable Key command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); message.setBody(result); } } public static Message getMessageForResponse(final Exchange exchange) { return exchange.getMessage(); } }
KMS2Producer
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/long2darrays/Long2DArrays_assertNotEmpty_Test.java
{ "start": 1014, "end": 1270 }
class ____ extends Long2DArraysBaseTest { @Test void should_delegate_to_Arrays2D() { // WHEN long2dArrays.assertNotEmpty(info, actual); // THEN verify(arrays2d).assertNotEmpty(info, failures, actual); } }
Long2DArrays_assertNotEmpty_Test
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationContext.java
{ "start": 2916, "end": 3921 }
class ____ extends AbstractBuilder<OAuth2AccessTokenAuthenticationContext, Builder> { private Builder(OAuth2AccessTokenAuthenticationToken authentication) { super(authentication); } /** * Sets the {@link OAuth2AccessTokenResponse.Builder access token response * builder}. * @param accessTokenResponse the {@link OAuth2AccessTokenResponse.Builder} * @return the {@link Builder} for further configuration */ public Builder accessTokenResponse(OAuth2AccessTokenResponse.Builder accessTokenResponse) { return put(OAuth2AccessTokenResponse.Builder.class, accessTokenResponse); } /** * Builds a new {@link OAuth2AccessTokenAuthenticationContext}. * @return the {@link OAuth2AccessTokenAuthenticationContext} */ @Override public OAuth2AccessTokenAuthenticationContext build() { Assert.notNull(get(OAuth2AccessTokenResponse.Builder.class), "accessTokenResponse cannot be null"); return new OAuth2AccessTokenAuthenticationContext(getContext()); } } }
Builder
java
quarkusio__quarkus
extensions/grpc/deployment/src/main/java/io/quarkus/grpc/deployment/GrpcServerProcessor.java
{ "start": 19453, "end": 41007 }
class ____ any of its base classes has a {@link Transaction} * annotation.</li> * <li>Else: non-blocking.</li> * </ol> */ static Set<String> gatherBlockingOrVirtualMethodNames(ClassInfo service, IndexView index, boolean virtual) { Set<String> result = new HashSet<>(); // We need to check if the service implementation extends the generated Mutiny interface // or the regular "ImplBase" class. boolean isExtendingMutinyService = false; for (DotName interfaceName : service.interfaceNames()) { ClassInfo info = index.getClassByName(interfaceName); if (info != null && info.interfaceNames().contains(MUTINY_SERVICE)) { isExtendingMutinyService = true; break; } } ClassInfo classInfo = null; var classes = classHierarchy(service, index); if (isExtendingMutinyService) { classInfo = service; } else { // Collect all gRPC methods from the *ImplBase's AsyncService interface, if present // else use ImplBase's gRPC methods ClassInfo ib = classes.get(classes.size() - 1); for (DotName interfaceName : ib.interfaceNames()) { if (interfaceName.toString().endsWith("$AsyncService")) { classInfo = index.getClassByName(interfaceName); break; } } if (classInfo == null) { classInfo = ib; } } List<MethodInfo> implBaseMethods = classInfo.methods(); for (MethodInfo implBaseMethod : implBaseMethods) { String methodName = implBaseMethod.name(); if (BLOCKING_SKIPPED_METHODS.contains(methodName)) { continue; } // Find the annotations for the current method. BlockingMode blocking = getMethodBlockingMode(classes, methodName, implBaseMethod.parameterTypes().toArray(new Type[0])); if (virtual && blocking == BlockingMode.VIRTUAL_THREAD) { result.add(methodName); } else if (!virtual && blocking.blocking) { result.add(methodName); } } log.debugf("Blocking methods for class '%s': %s", service.name(), result); return result; } @BuildStep AnnotationsTransformerBuildItem transformUserDefinedServices(CombinedIndexBuildItem combinedIndexBuildItem, CustomScopeAnnotationsBuildItem customScopes) { // User-defined services usually only declare the @GrpcService qualifier // We need to add @Singleton if needed Set<DotName> userDefinedServices = new HashSet<>(); for (AnnotationInstance annotation : combinedIndexBuildItem.getIndex().getAnnotations(GrpcDotNames.GRPC_SERVICE)) { if (annotation.target().kind() == Kind.CLASS) { userDefinedServices.add(annotation.target().asClass().name()); } } if (userDefinedServices.isEmpty()) { return null; } return new AnnotationsTransformerBuildItem( new AnnotationsTransformer() { @Override public boolean appliesTo(Kind kind) { return kind == Kind.CLASS; } @Override public int priority() { // Must run after the SpringDIProcessor annotation transformer, which has default priority 1000 return 500; } @Override public void transform(TransformationContext context) { ClassInfo clazz = context.getTarget().asClass(); if (userDefinedServices.contains(clazz.name()) && !customScopes.isScopeIn(context.getAnnotations())) { // Add @Singleton to make it a bean context.transform() .add(BuiltinScope.SINGLETON.getName()) .done(); } } }); } @BuildStep void validateBindableServices(ValidationPhaseBuildItem validationPhase, BuildProducer<ValidationPhaseBuildItem.ValidationErrorBuildItem> errors) { Type mutinyBeanType = Type.create(GrpcDotNames.MUTINY_BEAN, org.jboss.jandex.Type.Kind.CLASS); Type mutinyServiceType = Type.create(GrpcDotNames.MUTINY_SERVICE, org.jboss.jandex.Type.Kind.CLASS); Type bindableServiceType = Type.create(GrpcDotNames.BINDABLE_SERVICE, org.jboss.jandex.Type.Kind.CLASS); Predicate<Set<Type>> predicate = new Predicate<>() { @Override public boolean test(Set<Type> types) { return types.contains(bindableServiceType) || types.contains(mutinyServiceType); } }; for (BeanInfo bean : validationPhase.getContext().beans().classBeans().matchBeanTypes(predicate)) { validateBindableService(bean, mutinyBeanType, errors); } // Validate the removed beans as well - detect beans not annotated with @GrpcService for (BeanInfo bean : validationPhase.getContext().removedBeans().classBeans().matchBeanTypes(predicate)) { validateBindableService(bean, mutinyBeanType, errors); } } private void validateBindableService(BeanInfo bean, Type generatedBeanType, BuildProducer<ValidationPhaseBuildItem.ValidationErrorBuildItem> errors) { if (!bean.getTypes().contains(generatedBeanType) && bean.getQualifiers().stream().map(AnnotationInstance::name) .noneMatch(GrpcDotNames.GRPC_SERVICE::equals)) { errors.produce(new ValidationPhaseBuildItem.ValidationErrorBuildItem( new IllegalStateException( "A gRPC service bean must be annotated with @io.quarkus.grpc.GrpcService: " + bean))); } if (!bean.getScope().getDotName().equals(BuiltinScope.SINGLETON.getName())) { errors.produce(new ValidationPhaseBuildItem.ValidationErrorBuildItem( new IllegalStateException("A gRPC service bean must have the jakarta.inject.Singleton scope: " + bean))); } } @BuildStep(onlyIf = IsProduction.class) KubernetesPortBuildItem registerGrpcServiceInKubernetes(List<BindableServiceBuildItem> bindables) { if (!bindables.isEmpty()) { boolean useSeparateServer = ConfigProvider.getConfig().getOptionalValue("quarkus.grpc.server.use-separate-server", Boolean.class) .orElse(true); if (useSeparateServer) { // Only expose the named port "grpc" if the gRPC server is exposed using a separate server. return KubernetesPortBuildItem.fromRuntimeConfiguration("grpc", "quarkus.grpc.server.port", 9000, true); } } return null; } @BuildStep void registerBeans(BuildProducer<AdditionalBeanBuildItem> beans, Capabilities capabilities, List<BindableServiceBuildItem> bindables, BuildProducer<FeatureBuildItem> features) { // @GrpcService is a CDI qualifier beans.produce(new AdditionalBeanBuildItem(GrpcService.class)); if (!bindables.isEmpty() || LaunchMode.current() == LaunchMode.DEVELOPMENT) { beans.produce(AdditionalBeanBuildItem.unremovableOf(GrpcContainer.class)); // this makes GrpcRequestContextGrpcInterceptor registered as a global gRPC interceptor. // Global interceptors are invoked before any of the per-service interceptors beans.produce(AdditionalBeanBuildItem.unremovableOf(GrpcRequestContextGrpcInterceptor.class)); beans.produce(AdditionalBeanBuildItem.unremovableOf(GrpcDuplicatedContextGrpcInterceptor.class)); beans.produce(AdditionalBeanBuildItem.unremovableOf(RoutingContextGrpcInterceptor.class)); features.produce(new FeatureBuildItem(GRPC_SERVER)); if (capabilities.isPresent(Capability.SECURITY)) { beans.produce(AdditionalBeanBuildItem.unremovableOf(GrpcSecurityInterceptor.class)); beans.produce(AdditionalBeanBuildItem.unremovableOf(DefaultAuthExceptionHandlerProvider.class)); } beans.produce(AdditionalBeanBuildItem.unremovableOf(ExceptionInterceptor.class)); beans.produce(AdditionalBeanBuildItem.unremovableOf(DefaultExceptionHandlerProvider.class)); } else { log.debug("Unable to find beans exposing the `BindableService` interface - not starting the gRPC server"); } } @BuildStep void registerAdditionalInterceptors(BuildProducer<AdditionalGlobalInterceptorBuildItem> additionalInterceptors, Capabilities capabilities) { additionalInterceptors .produce(new AdditionalGlobalInterceptorBuildItem(GrpcRequestContextGrpcInterceptor.class.getName())); additionalInterceptors .produce(new AdditionalGlobalInterceptorBuildItem(GrpcDuplicatedContextGrpcInterceptor.class.getName())); if (capabilities.isPresent(Capability.SECURITY)) { additionalInterceptors .produce(new AdditionalGlobalInterceptorBuildItem(GrpcSecurityInterceptor.class.getName())); } additionalInterceptors .produce(new AdditionalGlobalInterceptorBuildItem(ExceptionInterceptor.class.getName())); } @SuppressWarnings("deprecation") @Record(ExecutionTime.RUNTIME_INIT) @BuildStep void gatherGrpcInterceptors(BeanArchiveIndexBuildItem indexBuildItem, List<AdditionalGlobalInterceptorBuildItem> additionalGlobalInterceptors, List<DelegatingGrpcBeanBuildItem> delegatingGrpcBeans, BuildProducer<SyntheticBeanBuildItem> syntheticBeans, RecorderContext recorderContext, GrpcServerRecorder recorder) { Map<String, String> delegateMap = new HashMap<>(); for (DelegatingGrpcBeanBuildItem delegatingGrpcBean : delegatingGrpcBeans) { delegateMap.put(delegatingGrpcBean.userDefinedBean.name().toString(), delegatingGrpcBean.generatedBean.name().toString()); } IndexView index = indexBuildItem.getIndex(); GrpcInterceptors interceptors = GrpcInterceptors.gatherInterceptors(index, GrpcDotNames.SERVER_INTERCEPTOR); // let's gather all the non-abstract, non-global interceptors, from these we'll filter out ones used per-service ones // the rest, if anything stays, should be logged as problematic Set<String> superfluousInterceptors = new HashSet<>(interceptors.nonGlobalInterceptors); // Remove our internal non-global interceptors superfluousInterceptors.remove(RoutingContextGrpcInterceptor.class.getName()); // Remove the metrics interceptors for (String mi : MICROMETER_INTERCEPTORS) { superfluousInterceptors.remove(mi); } List<AnnotationInstance> found = new ArrayList<>(index.getAnnotations(GrpcDotNames.REGISTER_INTERCEPTOR)); for (AnnotationInstance annotation : index.getAnnotations(GrpcDotNames.REGISTER_INTERCEPTORS)) { for (AnnotationInstance nested : annotation.value().asNestedArray()) { found.add(AnnotationInstance.create(nested.name(), annotation.target(), nested.values())); } } Map<String, Set<String>> registeredInterceptors = new HashMap<>(); for (AnnotationInstance annotation : found) { String interceptorClass = annotation.value().asString(); if (annotation.target().kind() != Kind.CLASS) { throw new IllegalStateException("Invalid target for the @RegisterInterceptor: " + annotation.target()); } String targetClass = annotation.target().asClass().name().toString(); // if the user bean is invoked by a generated bean // the interceptors defined on the user bean have to be applied to the generated bean: targetClass = delegateMap.getOrDefault(targetClass, targetClass); Set<String> registered = registeredInterceptors.computeIfAbsent(targetClass, k -> new HashSet<>()); registered.add(interceptorClass); superfluousInterceptors.remove(interceptorClass); } Set<Class<?>> globalInterceptors = new HashSet<>(); for (String interceptor : interceptors.globalInterceptors) { globalInterceptors.add(recorderContext.classProxy(interceptor)); } for (AdditionalGlobalInterceptorBuildItem globalInterceptorBuildItem : additionalGlobalInterceptors) { globalInterceptors.add(recorderContext.classProxy(globalInterceptorBuildItem.interceptorClass())); } Map<String, Set<Class<?>>> perClientInterceptors = new HashMap<>(); for (Entry<String, Set<String>> entry : registeredInterceptors.entrySet()) { Set<Class<?>> interceptorClasses = new HashSet<>(); for (String interceptorClass : entry.getValue()) { interceptorClasses.add(recorderContext.classProxy(interceptorClass)); } perClientInterceptors.put(entry.getKey(), interceptorClasses); } syntheticBeans.produce( SyntheticBeanBuildItem.configure(ServerInterceptorStorage.class) .unremovable() .runtimeValue(recorder.initServerInterceptorStorage(perClientInterceptors, globalInterceptors)) .setRuntimeInit() .done()); if (!superfluousInterceptors.isEmpty()) { log.warnf("At least one unused gRPC interceptor found: %s. If there are meant to be used globally, " + "annotate them with @GlobalInterceptor.", String.join(", ", superfluousInterceptors)); } } @BuildStep @Record(value = ExecutionTime.RUNTIME_INIT) @Consume(SyntheticBeansRuntimeInitBuildItem.class) ServiceStartBuildItem initializeServer(GrpcServerRecorder recorder, GrpcBuildTimeConfig buildTimeConfig, ShutdownContextBuildItem shutdown, List<BindableServiceBuildItem> bindables, List<RecorderBeanInitializedBuildItem> orderEnforcer, LaunchModeBuildItem launchModeBuildItem, VertxWebRouterBuildItem routerBuildItem, VertxBuildItem vertx, Capabilities capabilities, List<FilterBuildItem> filterBuildItems, ValidationPhaseBuildItem validationPhase, BeanContainerBuildItem beanContainerBuildItem) { // Build the list of blocking methods per service implementation Map<String, List<String>> blocking = new HashMap<>(); for (BindableServiceBuildItem bindable : bindables) { if (bindable.hasBlockingMethods()) { blocking.put(bindable.serviceClass.toString(), bindable.blockingMethods); } } Map<String, List<String>> virtuals = new HashMap<>(); for (BindableServiceBuildItem bindable : bindables) { if (bindable.hasVirtualMethods()) { virtuals.put(bindable.serviceClass.toString(), bindable.virtualMethods); } } if (!bindables.isEmpty() || (LaunchMode.current() == LaunchMode.DEVELOPMENT && buildTimeConfig.devMode().forceServerStart())) { //Uses mainrouter when the 'quarkus.http.root-path' is not '/' Map<Integer, Handler<RoutingContext>> securityHandlers = null; final RuntimeValue<Router> routerRuntimeValue; if (routerBuildItem.getMainRouter() != null) { routerRuntimeValue = routerBuildItem.getMainRouter(); if (capabilities.isPresent(Capability.SECURITY)) { securityHandlers = filterBuildItems .stream() .filter(filter -> filter.getPriority() == SecurityHandlerPriorities.AUTHENTICATION || filter.getPriority() == SecurityHandlerPriorities.AUTHORIZATION) .collect(Collectors.toMap(f -> f.getPriority() * -1, FilterBuildItem::getHandler)); // for the moment being, the main router doesn't have QuarkusErrorHandler, but we need to make // sure that exceptions raised during proactive authentication or HTTP authorization are handled recorder.addMainRouterErrorHandlerIfSameServer(routerRuntimeValue); } } else { routerRuntimeValue = routerBuildItem.getHttpRouter(); } Type bindableServiceType = Type.create(GrpcDotNames.BINDABLE_SERVICE, org.jboss.jandex.Type.Kind.CLASS); BeanStream bindableServiceBeanStream = validationPhase.getContext().beans().classBeans() .matchBeanTypes(new Predicate<>() { @Override public boolean test(Set<Type> types) { return types.contains(bindableServiceType); } }); recorder.initializeGrpcServer(bindableServiceBeanStream.isEmpty(), beanContainerBuildItem.getValue(), vertx.getVertx(), routerRuntimeValue, shutdown, blocking, virtuals, launchModeBuildItem.getLaunchMode(), capabilities.isPresent(Capability.SECURITY), securityHandlers); return new ServiceStartBuildItem(GRPC_SERVER); } return null; } @BuildStep(onlyIf = IsDevelopment.class) void definializeGrpcFieldsForDevMode(BuildProducer<BytecodeTransformerBuildItem> transformers) { transformers.produce(new BytecodeTransformerBuildItem("io.grpc.internal.InternalHandlerRegistry", new FieldDefinalizingVisitor("services", "methods"))); transformers.produce(new BytecodeTransformerBuildItem(ServerImpl.class.getName(), new FieldDefinalizingVisitor("interceptors"))); } @BuildStep void addHealthChecks(GrpcServerBuildTimeConfig config, List<BindableServiceBuildItem> bindables, BuildProducer<HealthBuildItem> healthBuildItems, BuildProducer<AdditionalBeanBuildItem> beans) { boolean healthEnabled = false; if (!bindables.isEmpty()) { healthEnabled = config.mpHealthEnabled(); if (config.grpcHealthEnabled()) { beans.produce(AdditionalBeanBuildItem.unremovableOf(GrpcHealthEndpoint.class)); healthEnabled = true; } healthBuildItems.produce(new HealthBuildItem("io.quarkus.grpc.runtime.health.GrpcHealthCheck", config.mpHealthEnabled())); } if (healthEnabled || LaunchMode.current() == LaunchMode.DEVELOPMENT) { beans.produce(AdditionalBeanBuildItem.unremovableOf(GrpcHealthStorage.class)); } } @BuildStep void registerSslResources(BuildProducer<NativeImageResourceBuildItem> resourceBuildItem) { Config config = ConfigProvider.getConfig(); for (String sslProperty : asList(CERTIFICATE, KEY, KEY_STORE, TRUST_STORE)) { config.getOptionalValue(sslProperty, String.class) .ifPresent(value -> ResourceRegistrationUtils.registerResourceForProperty(resourceBuildItem, value)); } } @BuildStep ExtensionSslNativeSupportBuildItem extensionSslNativeSupport() { return new ExtensionSslNativeSupportBuildItem(GRPC_SERVER); } @BuildStep BeanArchivePredicateBuildItem additionalBeanArchives() { return new BeanArchivePredicateBuildItem(new Predicate<>() { @Override public boolean test(ApplicationArchive archive) { // Every archive that contains a generated implementor of MutinyBean is considered a bean archive return !archive.getIndex().getKnownDirectImplementors(GrpcDotNames.MUTINY_BEAN).isEmpty(); } }); } @BuildStep UnremovableBeanBuildItem unremovableServerInterceptors() { return UnremovableBeanBuildItem.beanTypes(GrpcDotNames.SERVER_INTERCEPTOR); } @Consume(SyntheticBeansRuntimeInitBuildItem.class) @Record(RUNTIME_INIT) @BuildStep void initGrpcSecurityInterceptor(List<BindableServiceBuildItem> bindables, Capabilities capabilities, GrpcSecurityRecorder recorder, BeanContainerBuildItem beanContainer) { if (capabilities.isPresent(Capability.SECURITY)) { // Grpc service to blocking method Map<String, List<String>> blocking = new HashMap<>(); for (BindableServiceBuildItem bindable : bindables) { if (bindable.hasBlockingMethods()) { blocking.put(bindable.serviceClass.toString(), bindable.blockingMethods); } } if (!blocking.isEmpty()) { // provide GrpcSecurityInterceptor with blocking methods recorder.initGrpcSecurityInterceptor(blocking, beanContainer.getValue()); } } } }
or
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/id/enhanced/AbstractOptimizer.java
{ "start": 838, "end": 1101 }
class ____ is used to represent the id (e.g. {@link Long}). * * @return Value for property 'returnClass'. */ public final Class<?> getReturnClass() { return returnClass; } @Override public final int getIncrementSize() { return incrementSize; } }
which
java
apache__kafka
test-common/test-common-runtime/src/main/java/org/apache/kafka/common/test/junit/ClusterTestExtensions.java
{ "start": 2844, "end": 3678 }
class ____ use this extension should use one of the following annotations on each template method: * * <ul> * <li>{@link ClusterTest}, define a single cluster configuration</li> * <li>{@link ClusterTests}, provide multiple instances of @ClusterTest</li> * <li>{@link ClusterTemplate}, define a static method that generates cluster configurations</li> * </ul> * * Any combination of these annotations may be used on a given test template method. If no test invocations are * generated after processing the annotations, an error is thrown. * * Depending on which annotations are used, and what values are given, different {@link ClusterConfig} will be * generated. Each ClusterConfig is used to create an underlying Kafka cluster that is used for the actual test * invocation. * * For example: * * <pre> *
that
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
{ "start": 1212, "end": 5248 }
interface ____ implement // an equals() method that equates any two instances that share the // same generic type declaration and have equal type parameters." // Unfortunately, e.g. Wildcard parameter "?" doesn't equal java.lang.String, // and e.g. Set doesn't equal TreeSet, so roll our own comparison if // ParameterizedTypeImpl.equals() returns false if (typeToMock.equals(mockType)) { result = true; } else { ParameterizedType genericTypeToMock = (ParameterizedType) typeToMock; ParameterizedType genericMockType = (ParameterizedType) mockType; Type[] actualTypeArguments = genericTypeToMock.getActualTypeArguments(); Type[] actualTypeArguments2 = genericMockType.getActualTypeArguments(); if (actualTypeArguments.length == actualTypeArguments2.length) { // Recurse on type parameters, so we properly test whether e.g. Wildcard // bounds have a match result = recurseOnTypeArguments( injectMocksField, actualTypeArguments, actualTypeArguments2); } else { // the two ParameterizedTypes cannot match because they have unequal // number of type arguments result = false; } } } else { // mockType is a non-parameterized Class, i.e. a concrete class. // so walk concrete class' type hierarchy Class<?> concreteMockClass = (Class<?>) mockType; Stream<Type> mockSuperTypes = getSuperTypes(concreteMockClass); result = mockSuperTypes.anyMatch( mockSuperType -> isCompatibleTypes( typeToMock, mockSuperType, injectMocksField)); } } else if (typeToMock instanceof WildcardType) { WildcardType wildcardTypeToMock = (WildcardType) typeToMock; Type[] upperBounds = wildcardTypeToMock.getUpperBounds(); result = Arrays.stream(upperBounds) .anyMatch(t -> isCompatibleTypes(t, mockType, injectMocksField)); } else if (typeToMock instanceof Class && mockType instanceof Class) { result = ((Class<?>) typeToMock).isAssignableFrom((Class<?>) mockType); } // no need to check for GenericArrayType, as Mockito cannot mock this anyway return result; } private Stream<Type> getSuperTypes(Class<?> concreteMockClass) { Stream<Type> mockInterfaces = Arrays.stream(concreteMockClass.getGenericInterfaces()); Type genericSuperclass = concreteMockClass.getGenericSuperclass(); // for java.lang.Object, genericSuperclass is null if (genericSuperclass != null) { Stream<Type> mockSuperTypes = Stream.concat(mockInterfaces, Stream.of(genericSuperclass)); return mockSuperTypes; } else { return mockInterfaces; } } private boolean recurseOnTypeArguments( Field injectMocksField, Type[] actualTypeArguments, Type[] actualTypeArguments2) { boolean isCompatible = true; for (int i = 0; i < actualTypeArguments.length; i++) { Type actualTypeArgument = actualTypeArguments[i]; Type actualTypeArgument2 = actualTypeArguments2[i]; if (actualTypeArgument instanceof TypeVariable) { TypeVariable<?> typeVariable = (TypeVariable<?>) actualTypeArgument; // this is a TypeVariable declared by the
must
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/beans/MyMin3.java
{ "start": 885, "end": 928 }
interface ____ { MyMin3[] value(); } }
List
java
google__auto
value/src/test/java/com/google/auto/value/extension/serializable/processor/SerializableAutoValueExtensionTest.java
{ "start": 15517, "end": 16379 }
class ____ { abstract Builder setNumber(Optional<Integer> number); abstract SerializeMemoize build(); } } @Test public void serializeMemoize() { SerializeMemoize instance1 = SerializeMemoize.builder().setNumber(Optional.of(17)).build(); assertThat(instance1.methodCount).isEqualTo(0); assertThat(instance1.negate()).hasValue(-17); assertThat(instance1.methodCount).isEqualTo(1); assertThat(instance1.negate()).hasValue(-17); assertThat(instance1.methodCount).isEqualTo(1); SerializeMemoize instance2 = SerializableTester.reserialize(instance1); assertThat(instance2.methodCount).isEqualTo(0); assertThat(instance2.negate()).hasValue(-17); assertThat(instance2.methodCount).isEqualTo(1); assertThat(instance2.negate()).hasValue(-17); assertThat(instance2.methodCount).isEqualTo(1); } }
Builder
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 5135, "end": 5523 }
interface ____"); }); } @Test public void constructorInjectionWithoutAnnotation() { Source component = CompilerTests.javaSource("test.TestClass", "package test;", "", "import dagger.Component;", "import dagger.Module;", "import dagger.Provides;", "import javax.inject.Inject;", "", "final
AComponent
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedBidirectional2.java
{ "start": 1217, "end": 3595 }
class ____ extends AbstractModifiedFlagsEntityTest { private Integer ed1_id; private Integer ed2_id; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { BiRefEdEntity ed1 = new BiRefEdEntity( 1, "data_ed_1" ); BiRefEdEntity ed2 = new BiRefEdEntity( 2, "data_ed_2" ); BiRefIngEntity ing1 = new BiRefIngEntity( 3, "data_ing_1" ); BiRefIngEntity ing2 = new BiRefIngEntity( 4, "data_ing_2" ); // Revision 1 scope.inEntityManager( em -> { em.getTransaction().begin(); em.persist( ed1 ); em.persist( ed2 ); em.getTransaction().commit(); } ); // Revision 2 scope.inEntityManager( em -> { em.getTransaction().begin(); BiRefEdEntity ed1Ref = em.find( BiRefEdEntity.class, ed1.getId() ); ing1.setReference( ed1Ref ); em.persist( ing1 ); em.persist( ing2 ); em.getTransaction().commit(); } ); // Revision 3 scope.inEntityManager( em -> { em.getTransaction().begin(); BiRefEdEntity ed1Ref = em.find( BiRefEdEntity.class, ed1.getId() ); BiRefIngEntity ing1Ref = em.find( BiRefIngEntity.class, ing1.getId() ); BiRefIngEntity ing2Ref = em.find( BiRefIngEntity.class, ing2.getId() ); ing1Ref.setReference( null ); ing2Ref.setReference( ed1Ref ); em.getTransaction().commit(); } ); // Revision 4 scope.inEntityManager( em -> { em.getTransaction().begin(); BiRefEdEntity ed2Ref = em.find( BiRefEdEntity.class, ed2.getId() ); BiRefIngEntity ing1Ref = em.find( BiRefIngEntity.class, ing1.getId() ); BiRefIngEntity ing2Ref = em.find( BiRefIngEntity.class, ing2.getId() ); ing1Ref.setReference( ed2Ref ); ing2Ref.setReference( null ); em.getTransaction().commit(); } ); ed1_id = ed1.getId(); ed2_id = ed2.getId(); } @Test public void testHasChanged(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); List list = queryForPropertyHasChanged( auditReader, BiRefEdEntity.class, ed1_id, "referencing" ); assertEquals( 3, list.size() ); assertEquals( makeList( 2, 3, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, BiRefEdEntity.class, ed2_id, "referencing" ); assertEquals( 1, list.size() ); assertEquals( makeList( 4 ), extractRevisionNumbers( list ) ); } ); } }
HasChangedBidirectional2
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableTimeInterval.java
{ "start": 1405, "end": 2846 }
class ____<T> implements FlowableSubscriber<T>, Subscription { final Subscriber<? super Timed<T>> downstream; final TimeUnit unit; final Scheduler scheduler; Subscription upstream; long lastTime; TimeIntervalSubscriber(Subscriber<? super Timed<T>> actual, TimeUnit unit, Scheduler scheduler) { this.downstream = actual; this.scheduler = scheduler; this.unit = unit; } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { lastTime = scheduler.now(unit); this.upstream = s; downstream.onSubscribe(this); } } @Override public void onNext(T t) { long now = scheduler.now(unit); long last = lastTime; lastTime = now; long delta = now - last; downstream.onNext(new Timed<>(t, delta, unit)); } @Override public void onError(Throwable t) { downstream.onError(t); } @Override public void onComplete() { downstream.onComplete(); } @Override public void request(long n) { upstream.request(n); } @Override public void cancel() { upstream.cancel(); } } }
TimeIntervalSubscriber
java
apache__camel
components/camel-debezium/camel-debezium-postgres/src/generated/java/org/apache/camel/component/debezium/postgres/configuration/PostgresConnectorEmbeddedDebeziumConfiguration.java
{ "start": 56521, "end": 59212 }
interface ____ is called to determine how to lock * tables during schema snapshot. */ public void setSnapshotLockingModeCustomName( String snapshotLockingModeCustomName) { this.snapshotLockingModeCustomName = snapshotLockingModeCustomName; } public String getSnapshotLockingModeCustomName() { return snapshotLockingModeCustomName; } /** * Enables transaction metadata extraction together with event counting */ public void setProvideTransactionMetadata(boolean provideTransactionMetadata) { this.provideTransactionMetadata = provideTransactionMetadata; } public boolean isProvideTransactionMetadata() { return provideTransactionMetadata; } /** * Controls query used during the snapshot */ public void setSnapshotQueryMode(String snapshotQueryMode) { this.snapshotQueryMode = snapshotQueryMode; } public String getSnapshotQueryMode() { return snapshotQueryMode; } /** * Topic prefix that identifies and provides a namespace for the particular * database server/cluster is capturing changes. The topic prefix should be * unique across all other connectors, since it is used as a prefix for all * Kafka topic names that receive events emitted by this connector. Only * alphanumeric characters, hyphens, dots and underscores must be accepted. */ public void setTopicPrefix(String topicPrefix) { this.topicPrefix = topicPrefix; } public String getTopicPrefix() { return topicPrefix; } /** * Time to wait between retry attempts when the connector fails to connect * to a replication slot, given in milliseconds. Defaults to 10 seconds * (10,000 ms). */ public void setSlotRetryDelayMs(long slotRetryDelayMs) { this.slotRetryDelayMs = slotRetryDelayMs; } public long getSlotRetryDelayMs() { return slotRetryDelayMs; } /** * Whether the connector parse table and column's comment to metadata * object. Note: Enable this option will bring the implications on memory * usage. The number and size of ColumnImpl objects is what largely impacts * how much memory is consumed by the Debezium connectors, and adding a * String to each of them can potentially be quite heavy. The default is * 'false'. */ public void setIncludeSchemaComments(boolean includeSchemaComments) { this.includeSchemaComments = includeSchemaComments; } public boolean isIncludeSchemaComments() { return includeSchemaComments; } /** * The name of the SourceInfoStructMaker
and
java
apache__maven
impl/maven-core/src/test/java/org/apache/maven/project/RepositoryLeakageTest.java
{ "start": 1375, "end": 9574 }
class ____ extends AbstractMavenProjectTestCase { @Test @SuppressWarnings("checkstyle:MethodLength") public void testRepositoryLeakageBetweenSiblings() throws Exception { // Create a temporary directory structure for our test Path tempDir = Files.createTempDirectory("maven-repo-leakage-test"); try { // Create parent POM Path parentPom = tempDir.resolve("pom.xml"); Files.writeString(parentPom, """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>test</groupId> <artifactId>parent</artifactId> <version>1.0</version> <packaging>pom</packaging> <modules> <module>child1</module> <module>child2</module> </modules> </project> """); // Create child1 with specific repository Path child1Dir = tempDir.resolve("child1"); Files.createDirectories(child1Dir); Path child1Pom = child1Dir.resolve("pom.xml"); Files.writeString(child1Pom, """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>test</groupId> <artifactId>parent</artifactId> <version>1.0</version> </parent> <artifactId>child1</artifactId> <repositories> <repository> <id>child1-repo</id> <url>https://child1.example.com/repo</url> </repository> </repositories> </project> """); // Create child2 with different repository Path child2Dir = tempDir.resolve("child2"); Files.createDirectories(child2Dir); Path child2Pom = child2Dir.resolve("pom.xml"); Files.writeString(child2Pom, """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>test</groupId> <artifactId>parent</artifactId> <version>1.0</version> </parent> <artifactId>child2</artifactId> <repositories> <repository> <id>child2-repo</id> <url>https://child2.example.com/repo</url> </repository> </repositories> </project> """); // Create a shared ProjectBuildingRequest ProjectBuildingRequest sharedRequest = newBuildingRequest(); // Build child1 first ProjectBuildingResult result1 = projectBuilder.build(child1Pom.toFile(), sharedRequest); MavenProject child1Project = result1.getProject(); // Capture repositories after building child1 // Build child2 using the same shared request ProjectBuildingResult result2 = projectBuilder.build(child2Pom.toFile(), sharedRequest); MavenProject child2Project = result2.getProject(); // Capture repositories after building child2 List<ArtifactRepository> repositoriesAfterChild2 = List.copyOf(sharedRequest.getRemoteRepositories()); // Verify that child1 has its own repository boolean child1HasOwnRepo = child1Project.getRemoteArtifactRepositories().stream() .anyMatch(repo -> "child1-repo".equals(repo.getId())); assertTrue(child1HasOwnRepo, "Child1 should have its own repository"); // Verify that child2 has its own repository boolean child2HasOwnRepo = child2Project.getRemoteArtifactRepositories().stream() .anyMatch(repo -> "child2-repo".equals(repo.getId())); assertTrue(child2HasOwnRepo, "Child2 should have its own repository"); // Print debug information System.out.println("=== REPOSITORY LEAKAGE TEST RESULTS ==="); System.out.println( "Repositories in shared request after building child2: " + repositoriesAfterChild2.size()); repositoriesAfterChild2.forEach( repo -> System.out.println(" - " + repo.getId() + " (" + repo.getUrl() + ")")); System.out.println("Child1 project repositories:"); child1Project .getRemoteArtifactRepositories() .forEach(repo -> System.out.println(" - " + repo.getId() + " (" + repo.getUrl() + ")")); System.out.println("Child2 project repositories:"); child2Project .getRemoteArtifactRepositories() .forEach(repo -> System.out.println(" - " + repo.getId() + " (" + repo.getUrl() + ")")); System.out.println("======================================="); // Check for leakage: child2 should NOT have child1's repository boolean child2HasChild1Repo = child2Project.getRemoteArtifactRepositories().stream() .anyMatch(repo -> "child1-repo".equals(repo.getId())); assertFalse(child2HasChild1Repo, "Child2 should NOT have child1's repository (leakage detected!)"); // Check for leakage in the shared request boolean sharedRequestHasChild1Repo = repositoriesAfterChild2.stream().anyMatch(repo -> "child1-repo".equals(repo.getId())); boolean sharedRequestHasChild2Repo = repositoriesAfterChild2.stream().anyMatch(repo -> "child2-repo".equals(repo.getId())); // Print debug information /* System.out.println("Repositories after child1: " + repositoriesAfterChild1.size()); repositoriesAfterChild1.forEach(repo -> System.out.println(" - " + repo.getId() + ": " + repo.getUrl())); System.out.println("Repositories after child2: " + repositoriesAfterChild2.size()); repositoriesAfterChild2.forEach(repo -> System.out.println(" - " + repo.getId() + ": " + repo.getUrl())); */ // The shared request should not accumulate repositories from both children if (sharedRequestHasChild1Repo && sharedRequestHasChild2Repo) { fail("REPOSITORY LEAKAGE DETECTED: Shared request contains repositories from both children!"); } } finally { // Clean up deleteRecursively(tempDir.toFile()); } } private void deleteRecursively(File file) { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { deleteRecursively(child); } } } file.delete(); } }
RepositoryLeakageTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/SingleArgCreatorTest.java
{ "start": 1046, "end": 1387 }
class ____ { protected final String value; @JsonCreator(mode=JsonCreator.Mode.DELEGATING) public SingleNamedButStillDelegating(@JsonProperty("foobar") String v) { value = v; } public String getFoobar() { return "x"; } } // For [databind#557] static
SingleNamedButStillDelegating
java
hibernate__hibernate-orm
hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/postgis/PGCastingGeographyJdbcType.java
{ "start": 322, "end": 900 }
class ____ extends AbstractCastingPostGISJdbcType { // Type descriptor instance using EWKB v2 (postgis versions >= 2.2.2, see: https://trac.osgeo.org/postgis/ticket/3181) public static final PGCastingGeographyJdbcType INSTANCE_WKB_2 = new PGCastingGeographyJdbcType( Wkb.Dialect.POSTGIS_EWKB_2 ); private PGCastingGeographyJdbcType(Wkb.Dialect dialect) { super( dialect ); } @Override public int getDefaultSqlTypeCode() { return SqlTypes.GEOGRAPHY; } @Override protected String getConstructorFunction() { return "st_geogfromtext"; } }
PGCastingGeographyJdbcType
java
quarkusio__quarkus
extensions/smallrye-fault-tolerance/runtime/src/main/java/io/quarkus/smallrye/faulttolerance/runtime/config/SmallRyeFaultToleranceConfig.java
{ "start": 6189, "end": 6420 }
interface ____ { /** * Whether the {@code @Asynchronous} strategy is enabled. */ @ConfigDocDefault("true") Optional<Boolean> enabled(); }
AsynchronousConfig
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_BrowserSecure3.java
{ "start": 202, "end": 442 }
class ____ extends TestCase { public void test_0() throws Exception { String text = JSON.toJSONString("\n", SerializerFeature.BrowserSecure); Assert.assertEquals("\"\\n\"", text); } }
SerializeWriterTest_BrowserSecure3
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/tools/MarkerTool.java
{ "start": 3376, "end": 11876 }
class ____ extends S3GuardTool { private static final Logger LOG = LoggerFactory.getLogger(MarkerTool.class); /** * Name of this tool: {@value}. */ public static final String MARKERS = "markers"; /** * Purpose of this tool: {@value}. */ public static final String PURPOSE = "View and manipulate S3 directory markers"; /** * Audit sub-command: {@value}. */ public static final String OPT_AUDIT = "audit"; /** * Clean Sub-command: {@value}. */ public static final String OPT_CLEAN = "clean"; /** * Audit sub-command: {@value}. */ public static final String AUDIT = "-" + OPT_AUDIT; /** * Clean Sub-command: {@value}. */ public static final String CLEAN = "-" + OPT_CLEAN; /** * Min number of markers to find: {@value}. */ public static final String OPT_MIN = "min"; /** * Max number of markers to find: {@value}. */ public static final String OPT_MAX = "max"; /** * Name of a file to save the list of markers to: {@value}. */ public static final String OPT_OUT = "out"; /** * Limit of objects to scan: {@value}. */ public static final String OPT_LIMIT = "limit"; /** * Only consider markers found in non-authoritative paths * as failures: {@value}. */ public static final String OPT_NONAUTH = "nonauth"; /** * Error text when too few arguments are found. */ @VisibleForTesting static final String E_ARGUMENTS = "Wrong number of arguments: %d"; /** * Constant to use when there is no limit on the number of * objects listed: {@value}. * <p> * The value is 0 and not -1 because it allows for the limit to be * set on the command line {@code -limit 0}. * The command line parser rejects {@code -limit -1} as the -1 * is interpreted as the (unknown) option "-1". */ public static final int UNLIMITED_LISTING = 0; /** * Constant to use when there is no minimum number of * markers: {@value}. */ public static final int UNLIMITED_MIN_MARKERS = -1; /** * Usage string: {@value}. */ private static final String USAGE = MARKERS + " (-" + OPT_AUDIT + " | -" + OPT_CLEAN + ")" + " [-" + OPT_MIN + " <count>]" + " [-" + OPT_MAX + " <count>]" + " [-" + OPT_OUT + " <filename>]" + " [-" + OPT_LIMIT + " <limit>]" + " [-" + VERBOSE + "]" + " <PATH>\n" + "\t" + PURPOSE + "\n\n"; /** Will be overridden in run(), but during tests needs to avoid NPEs. */ private PrintStream out = System.out; /** * Verbosity flag. */ private boolean verbose; /** * Store context. */ private StoreContext storeContext; /** * Operations during the scan. */ private MarkerToolOperations operations; /** * Constructor. * @param conf configuration */ public MarkerTool(final Configuration conf) { super(conf, OPT_AUDIT, OPT_CLEAN, VERBOSE); CommandFormat format = getCommandFormat(); format.addOptionWithValue(OPT_MIN); format.addOptionWithValue(OPT_MAX); format.addOptionWithValue(OPT_LIMIT); format.addOptionWithValue(OPT_OUT); } @Override public String getUsage() { return USAGE; } @Override public String getName() { return MARKERS; } @Override public void resetBindings() { super.resetBindings(); storeContext = null; operations = null; } @Override public int run(final String[] args, final PrintStream stream) throws ExitUtil.ExitException, Exception { this.out = stream; final List<String> parsedArgs = parseArgsWithErrorReporting(args); if (parsedArgs.size() != 1) { errorln(getUsage()); println(out, "Supplied arguments: [" + String.join(", ", parsedArgs) + "]"); throw new ExitUtil.ExitException(EXIT_USAGE, String.format(E_ARGUMENTS, parsedArgs.size())); } // read arguments CommandFormat command = getCommandFormat(); verbose = command.getOpt(VERBOSE); // minimum number of markers expected int expectedMin = getOptValue(OPT_MIN, 0); // max number of markers allowed int expectedMax = getOptValue(OPT_MAX, 0); // determine the action boolean audit = command.getOpt(OPT_AUDIT); boolean clean = command.getOpt(OPT_CLEAN); if (audit == clean) { // either both are set or neither are set // this is equivalent to (not audit xor clean) errorln(getUsage()); throw new ExitUtil.ExitException(EXIT_USAGE, "Exactly one of " + AUDIT + " and " + CLEAN); } int limit = getOptValue(OPT_LIMIT, UNLIMITED_LISTING); final String dir = parsedArgs.get(0); Path path = new Path(dir); URI uri = path.toUri(); if (uri.getPath().isEmpty()) { // fix up empty URI for better CLI experience path = new Path(path, "/"); } FileSystem fs = path.getFileSystem(getConf()); ScanResult result; try { result = execute( new ScanArgsBuilder() .withSourceFS(fs) .withPath(path) .withDoPurge(clean) .withMinMarkerCount(expectedMin) .withMaxMarkerCount(expectedMax) .withLimit(limit) .build()); } catch (UnknownStoreException ex) { // bucket doesn't exist. // replace the stack trace with an error code. throw new ExitUtil.ExitException(EXIT_NOT_FOUND, ex.toString(), ex); } if (verbose) { dumpFileSystemStatistics(out); } // and finally see if the output should be saved to a file String saveFile = command.getOptValue(OPT_OUT); if (saveFile != null && !saveFile.isEmpty()) { println(out, "Saving result to %s", saveFile); try (Writer writer = new OutputStreamWriter( new FileOutputStream(saveFile), StandardCharsets.UTF_8)) { final List<String> surplus = result.getTracker() .getSurplusMarkers() .keySet() .stream() .map(p-> p.toString() + "/") .sorted() .collect(Collectors.toList()); IOUtils.writeLines(surplus, "\n", writer); } } return result.finish(); } /** * Get the value of an option, or the default if the option * is unset/empty. * @param option option key * @param defVal default * @return the value to use */ private int getOptValue(String option, int defVal) { CommandFormat command = getCommandFormat(); String value = command.getOptValue(option); if (value != null && !value.isEmpty()) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new ExitUtil.ExitException(EXIT_USAGE, String.format("Argument for %s is not a number: %s", option, value)); } } else { return defVal; } } /** * Execute the scan/purge. * * @param scanArgs@return scan+purge result. * @throws IOException failure */ @VisibleForTesting ScanResult execute(final ScanArgs scanArgs) throws IOException { S3AFileSystem fs = bindFilesystem(scanArgs.getSourceFS()); // extract the callbacks needed for the rest of the work storeContext = fs.createStoreContext(); // qualify the path Path path = scanArgs.getPath(); Path target = path.makeQualified(fs.getUri(), new Path("/")); // initial safety check: does the path exist? try { getFilesystem().getFileStatus(target); } catch (UnknownStoreException ex) { // bucket doesn't exist. // replace the stack trace with an error code. throw new ExitUtil.ExitException(EXIT_NOT_FOUND, ex.toString(), ex); } catch (FileNotFoundException ex) { throw new ExitUtil.ExitException(EXIT_NOT_FOUND, "Not found: " + target, ex); } // the default filter policy is that all entries should be deleted int minMarkerCount = scanArgs.getMinMarkerCount(); int maxMarkerCount = scanArgs.getMaxMarkerCount(); // extract the callbacks needed for the rest of the work operations = fs.createMarkerToolOperations( target.toString()); return scan(target, scanArgs.isDoPurge(), minMarkerCount, maxMarkerCount, scanArgs.getLimit() ); } /** * Result of the scan operation. */ public static final
MarkerTool
java
redisson__redisson
redisson/src/main/java/org/redisson/api/keys/MigrateArgsParams.java
{ "start": 756, "end": 3083 }
class ____ implements MigrateArgs, HostMigrateArgs, PortMigrateArgs, DatabaseMigrateArgs, TimeoutMigrateArgs, OptionalMigrateArgs { /** * keys to transfer Redis version >= 3.0.6 */ private final String[] keys; /** * destination host */ private String host; /** * destination port */ private int port; /** * destination database */ private int database; /** * maximum idle time in any moment of the communication with the destination instance in milliseconds */ private long timeout; /** * migration mode */ private MigrateMode mode = MigrateMode.MIGRATE; /** * destination username Redis version >= 6.0.0 */ private String username; /** * destination password Redis version >= 4.0.7 */ private String password; public MigrateArgsParams(String[] keys) { this.keys = keys; } @Override public PortMigrateArgs host(String host) { this.host = host; return this; } @Override public DatabaseMigrateArgs port(int port) { this.port = port; return this; } @Override public TimeoutMigrateArgs database(int database) { this.database = database; return this; } @Override public OptionalMigrateArgs timeout(long timeout) { this.timeout = timeout; return this; } @Override public OptionalMigrateArgs mode(MigrateMode mode) { this.mode = mode; return this; } @Override public OptionalMigrateArgs username(String username) { this.username = username; return this; } @Override public OptionalMigrateArgs password(String password) { this.password = password; return this; } public String[] getKeys() { return keys; } public String getHost() { return host; } public int getPort() { return port; } public int getDatabase() { return database; } public long getTimeout() { return timeout; } public MigrateMode getMode() { return mode; } public String getUsername() { return username; } public String getPassword() { return password; } }
MigrateArgsParams
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 249940, "end": 250190 }
class ____<T> { private T payload; GenericMessageTestHelper(T value) { this.payload = value; } public T getPayload() { return payload; } } // This test helper has a bound on the type variable public static
GenericMessageTestHelper
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/DownsampleStep.java
{ "start": 1387, "end": 5895 }
class ____ extends AsyncActionStep { public static final String NAME = "rollup"; private static final Logger LOGGER = LogManager.getLogger(DownsampleStep.class); private final DateHistogramInterval fixedInterval; private final TimeValue waitTimeout; private final DownsampleConfig.SamplingMethod samplingMethod; public DownsampleStep( final StepKey key, final StepKey nextStepKey, final DateHistogramInterval fixedInterval, final TimeValue waitTimeout, final DownsampleConfig.SamplingMethod samplingMethod, final Client client ) { super(key, nextStepKey, client); this.fixedInterval = fixedInterval; this.waitTimeout = waitTimeout; this.samplingMethod = samplingMethod; } @Override public boolean isRetryable() { return true; } @Override public void performAction( IndexMetadata indexMetadata, ProjectState currentState, ClusterStateObserver observer, ActionListener<Void> listener ) { LifecycleExecutionState lifecycleState = indexMetadata.getLifecycleExecutionState(); if (lifecycleState.lifecycleDate() == null) { throw new IllegalStateException("source index [" + indexMetadata.getIndex().getName() + "] is missing lifecycle date"); } final String policyName = indexMetadata.getLifecyclePolicyName(); final String indexName = indexMetadata.getIndex().getName(); final String downsampleIndexName = lifecycleState.downsampleIndexName(); IndexMetadata downsampleIndexMetadata = currentState.metadata().index(downsampleIndexName); if (downsampleIndexMetadata != null) { IndexMetadata.DownsampleTaskStatus downsampleIndexStatus = IndexMetadata.INDEX_DOWNSAMPLE_STATUS.get( downsampleIndexMetadata.getSettings() ); if (IndexMetadata.DownsampleTaskStatus.SUCCESS.equals(downsampleIndexStatus)) { // Downsample index has already been created with the generated name and its status is "success". // So we skip index downsample creation. LOGGER.info( "skipping [{}] step for index [{}] as part of policy [{}] as the downsample index [{}] already exists", DownsampleStep.NAME, indexName, policyName, downsampleIndexName ); listener.onResponse(null); return; } } performDownsampleIndex( currentState.projectId(), indexName, downsampleIndexName, listener.delegateFailureAndWrap((l, r) -> l.onResponse(r)) ); } void performDownsampleIndex(ProjectId projectId, String indexName, String downsampleIndexName, ActionListener<Void> listener) { DownsampleConfig config = new DownsampleConfig(fixedInterval, samplingMethod); DownsampleAction.Request request = new DownsampleAction.Request( TimeValue.MAX_VALUE, indexName, downsampleIndexName, waitTimeout, config ); // Currently, DownsampleAction always acknowledges action was complete when no exceptions are thrown. getClient(projectId).execute( DownsampleAction.INSTANCE, request, listener.delegateFailureAndWrap((l, response) -> l.onResponse(null)) ); } public DateHistogramInterval getFixedInterval() { return fixedInterval; } public TimeValue getWaitTimeout() { return waitTimeout; } public DownsampleConfig.SamplingMethod getSamplingMethod() { return samplingMethod; } @Override public int hashCode() { return Objects.hash(super.hashCode(), fixedInterval, waitTimeout, samplingMethod); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } DownsampleStep other = (DownsampleStep) obj; return super.equals(obj) && Objects.equals(fixedInterval, other.fixedInterval) && Objects.equals(waitTimeout, other.waitTimeout) && Objects.equals(samplingMethod, other.samplingMethod); } }
DownsampleStep
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceTransformerSupportTests.java
{ "start": 1389, "end": 4699 }
class ____ { private static final Duration TIMEOUT = Duration.ofSeconds(5); private ResourceTransformerChain chain; private TestResourceTransformerSupport transformer; @BeforeEach void setup() { VersionResourceResolver versionResolver = new VersionResourceResolver(); versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy())); PathResourceResolver pathResolver = new PathResourceResolver(); pathResolver.setAllowedLocations(new ClassPathResource("test/", getClass())); List<ResourceResolver> resolvers = new ArrayList<>(); resolvers.add(versionResolver); resolvers.add(pathResolver); ResourceResolverChain resolverChain = new DefaultResourceResolverChain(resolvers); this.chain = new DefaultResourceTransformerChain(resolverChain, Collections.emptyList()); this.transformer = new TestResourceTransformerSupport(); this.transformer.setResourceUrlProvider(createUrlProvider(resolvers)); } private ResourceUrlProvider createUrlProvider(List<ResourceResolver> resolvers) { ResourceWebHandler handler = new ResourceWebHandler(); handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass()))); handler.setResourceResolvers(resolvers); ResourceUrlProvider urlProvider = new ResourceUrlProvider(); urlProvider.registerHandlers(Collections.singletonMap("/resources/**", handler)); return urlProvider; } @Test void resolveUrlPath() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/resources/main.css")); String resourcePath = "/resources/bar.css"; Resource resource = getResource("main.css"); String actual = this.transformer.resolveUrlPath(resourcePath, exchange, resource, this.chain).block(TIMEOUT); assertThat(actual).isEqualTo("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css"); assertThat(actual).isEqualTo("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test void resolveUrlPathWithRelativePath() { Resource resource = getResource("main.css"); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); String actual = this.transformer.resolveUrlPath("bar.css", exchange, resource, this.chain).block(TIMEOUT); assertThat(actual).isEqualTo("bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test void resolveUrlPathWithRelativePathInParentDirectory() { Resource resource = getResource("images/image.png"); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); String actual = this.transformer.resolveUrlPath("../bar.css", exchange, resource, this.chain).block(TIMEOUT); assertThat(actual).isEqualTo("../bar-11e16cf79faee7ac698c805cf28248d2.css"); } @Test void toAbsolutePath() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/resources/main.css")); String absolute = this.transformer.toAbsolutePath("img/image.png", exchange); assertThat(absolute).isEqualTo("/resources/img/image.png"); absolute = this.transformer.toAbsolutePath("/img/image.png", exchange); assertThat(absolute).isEqualTo("/img/image.png"); } private Resource getResource(String filePath) { return new ClassPathResource("test/" + filePath, getClass()); } private static
ResourceTransformerSupportTests
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/PushImageUpdateEventTests.java
{ "start": 1050, "end": 1854 }
class ____ extends ProgressUpdateEventTests<PushImageUpdateEvent> { @Test void getIdReturnsId() { PushImageUpdateEvent event = createEvent(); assertThat(event.getId()).isEqualTo("id"); } @Test void getErrorReturnsErrorDetail() { PushImageUpdateEvent event = new PushImageUpdateEvent("id", "status", new ProgressDetail(null, null), "progress", new PushImageUpdateEvent.ErrorDetail("test message")); ErrorDetail errorDetail = event.getErrorDetail(); assertThat(errorDetail).isNotNull(); assertThat(errorDetail.getMessage()).isEqualTo("test message"); } @Override protected PushImageUpdateEvent createEvent(String status, ProgressDetail progressDetail, String progress) { return new PushImageUpdateEvent("id", status, progressDetail, progress, null); } }
PushImageUpdateEventTests
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/core/Observer.java
{ "start": 5091, "end": 6609 }
interface ____<@NonNull T> { /** * Provides the {@link Observer} with the means of cancelling (disposing) the * connection (channel) with the {@link Observable} in both * synchronous (from within {@link #onNext(Object)}) and asynchronous manner. * @param d the {@link Disposable} instance whose {@link Disposable#dispose()} can * be called anytime to cancel the connection * @since 2.0 */ void onSubscribe(@NonNull Disposable d); /** * Provides the {@link Observer} with a new item to observe. * <p> * The {@link Observable} may call this method 0 or more times. * <p> * The {@code Observable} will not call this method again after it calls either {@link #onComplete} or * {@link #onError}. * * @param t * the item emitted by the Observable */ void onNext(@NonNull T t); /** * Notifies the {@link Observer} that the {@link Observable} has experienced an error condition. * <p> * If the {@code Observable} calls this method, it will not thereafter call {@link #onNext} or * {@link #onComplete}. * * @param e * the exception encountered by the Observable */ void onError(@NonNull Throwable e); /** * Notifies the {@link Observer} that the {@link Observable} has finished sending push-based notifications. * <p> * The {@code Observable} will not call this method if it calls {@link #onError}. */ void onComplete(); }
Observer
java
quarkusio__quarkus
integration-tests/gradle/src/main/resources/test-resources-vs-main-resources/src/main/java/org/acme/TestOnlyResource.java
{ "start": 261, "end": 455 }
class ____ { @ConfigProperty(name = "test-only") String testOnly; @GET @Produces(MediaType.TEXT_PLAIN) public String hello() { return testOnly; } }
TestOnlyResource
java
grpc__grpc-java
binder/src/androidTest/java/io/grpc/binder/internal/BinderClientTransportTest.java
{ "start": 25914, "end": 26357 }
class ____ extends SecurityPolicy { private final BlockingQueue<Status> results = new LinkedBlockingQueue<>(); public void provideNextCheckAuthorizationResult(Status status) { results.add(status); } @Override public Status checkAuthorization(int uid) { try { return results.take(); } catch (InterruptedException e) { return Status.fromThrowable(e); } } } }
BlockingSecurityPolicy
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-common/spi-deployment/src/main/java/io/quarkus/resteasy/reactive/spi/DynamicFeatureBuildItem.java
{ "start": 172, "end": 750 }
class ____ extends MultiBuildItem implements CheckBean { private final String className; private final boolean registerAsBean; public DynamicFeatureBuildItem(String className) { this(className, true); } public DynamicFeatureBuildItem(String className, boolean registerAsBean) { this.className = className; this.registerAsBean = registerAsBean; } public String getClassName() { return className; } @Override public boolean isRegisterAsBean() { return registerAsBean; } }
DynamicFeatureBuildItem
java
quarkusio__quarkus
independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/quarkus/QuarkusCodestartGenerationTest.java
{ "start": 1271, "end": 6443 }
class ____ { private static final Path testDirPath = Paths.get("target/quarkus-codestart-gen-test"); @BeforeAll static void setUp() throws Throwable { SnapshotTesting.deleteTestDirectory(testDirPath.toFile()); } private Map<String, Object> getGenerationTestInputData() { return QuarkusCodestartTesting.getMockedTestInputData(Collections.emptyMap()); } @Test void generateDefault(TestInfo testInfo) throws Throwable { final QuarkusCodestartProjectInput input = newInputBuilder() .noCode() .noDockerfiles() .noBuildToolWrapper() .addData(getGenerationTestInputData()) .addBoms(QuarkusCodestartTesting.getPlatformBoms()) .build(); final Path projectDir = testDirPath.resolve("default"); getCatalog().createProject(input).generate(projectDir); checkMaven(projectDir); checkReadme(projectDir); assertThat(projectDir.resolve(".mvnw")).doesNotExist(); assertThat(projectDir.resolve(".dockerignore")).doesNotExist(); assertThatMatchSnapshot(testInfo, projectDir, "pom.xml"); assertThatMatchSnapshot(testInfo, projectDir, "README.md"); assertThat(projectDir.resolve("src/main/java")).exists().isEmptyDirectory(); } private static QuarkusCodestartProjectInputBuilder newInputBuilder() { return QuarkusCodestartProjectInput.builder().defaultCodestart(FakeExtensionCatalog.getDefaultCodestart()); } @Test void generateRESTEasyJavaCustom(TestInfo testInfo) throws Throwable { final QuarkusCodestartProjectInput input = newInputBuilder() .addData(getGenerationTestInputData()) .addExtension(ArtifactKey.fromString("io.quarkus:quarkus-resteasy")) .putData(PROJECT_PACKAGE_NAME.key(), "com.andy") .putData(RESTEASY_CODESTART_RESOURCE_CLASS_NAME.key(), "BonjourResource") .putData(RESTEASY_CODESTART_RESOURCE_PATH.key(), "/bonjour") .build(); final Path projectDir = testDirPath.resolve("resteasy-java-custom"); getCatalog().createProject(input).generate(projectDir); checkMaven(projectDir); checkReadme(projectDir); checkDockerfiles(projectDir, BuildTool.MAVEN); checkConfigProperties(projectDir); assertThatMatchSnapshot(testInfo, projectDir, "src/main/java/com/andy/BonjourResource.java"); assertThatMatchSnapshot(testInfo, projectDir, "src/test/java/com/andy/BonjourResourceIT.java"); } @Test void generateMavenWithCustomDep(TestInfo testInfo) throws Throwable { final QuarkusCodestartProjectInput input = newInputBuilder() .addData(getGenerationTestInputData()) .addBoms(QuarkusCodestartTesting.getPlatformBoms()) .addExtension(ArtifactCoords.fromString("io.quarkus:quarkus-resteasy:1.8")) .addExtension(ArtifactCoords.fromString("commons-io:commons-io:2.5")) .build(); final Path projectDir = testDirPath.resolve("maven-custom-dep"); getCatalog().createProject(input).generate(projectDir); checkMaven(projectDir); assertThatMatchSnapshot(testInfo, projectDir, "pom.xml") .satisfies(checkContains("<dependency>\n" + " <groupId>io.quarkus</groupId>\n" + " <artifactId>quarkus-resteasy</artifactId>\n" + " <version>1.8</version>\n" + " </dependency>")) .satisfies(checkContains("<dependency>\n" + " <groupId>io.quarkus</groupId>\n" + " <artifactId>quarkus-resteasy</artifactId>\n" + " <version>1.8</version>\n" + " </dependency>")); } @Test void generateRESTEasyKotlinCustom(TestInfo testInfo) throws Throwable { final QuarkusCodestartProjectInput input = newInputBuilder() .addData(getGenerationTestInputData()) .addExtension(ArtifactKey.fromString("io.quarkus:quarkus-resteasy")) .addExtension(ArtifactKey.fromString("io.quarkus:quarkus-kotlin")) .putData(PROJECT_PACKAGE_NAME.key(), "com.andy") .putData(RESTEASY_CODESTART_RESOURCE_CLASS_NAME.key(), "BonjourResource") .putData(RESTEASY_CODESTART_RESOURCE_PATH.key(), "/bonjour") .build(); final Path projectDir = testDirPath.resolve("resteasy-kotlin-custom"); getCatalog().createProject(input).generate(projectDir); checkMaven(projectDir); checkReadme(projectDir); checkDockerfiles(projectDir, BuildTool.MAVEN); checkConfigProperties(projectDir); assertThatMatchSnapshot(testInfo, projectDir, "src/main/kotlin/com/andy/BonjourResource.kt") .satisfies(checkContains("package com.andy")) .satisfies(checkContains("
QuarkusCodestartGenerationTest
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/cdi/bcextensions/CustomNormalScopeTest.java
{ "start": 5312, "end": 5818 }
class ____ implements SyntheticBeanCreator<CommandContextController> { @Override public CommandContextController create(Instance<Object> lookup, Parameters params) { BeanContainer beanContainer = lookup.select(BeanContainer.class).get(); CommandContext ctx = (CommandContext) beanContainer.getContexts(CommandScoped.class).iterator().next(); return new CommandContextController(ctx, beanContainer); } } static
CommandContextControllerCreator
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerSourceTaskTest.java
{ "start": 6376, "end": 41132 }
class ____ { public static final String POLL_TIMEOUT_MSG = "Timeout waiting for poll"; private static final String TOPIC = "topic"; private static final Map<String, Object> PARTITION = Map.of("key", "partition".getBytes()); private static final Map<String, Object> OFFSET = Map.of("key", 12); // Connect-format data private static final Schema KEY_SCHEMA = Schema.INT32_SCHEMA; private static final Integer KEY = -1; private static final Schema RECORD_SCHEMA = Schema.INT64_SCHEMA; private static final Long RECORD = 12L; // Serialized data. The actual format of this data doesn't matter -- we just want to see that the right version // is used in the right place. private static final byte[] SERIALIZED_KEY = "converted-key".getBytes(); private static final byte[] SERIALIZED_RECORD = "converted-record".getBytes(); private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final ConnectorTaskId taskId = new ConnectorTaskId("job", 0); private WorkerConfig config; private SourceConnectorConfig sourceConfig; private Plugins plugins; private MockConnectMetrics metrics; @Mock private SourceTask sourceTask; @Mock private Converter keyConverter; @Mock private Converter valueConverter; @Mock private HeaderConverter headerConverter; @Mock private TransformationChain<SourceRecord, SourceRecord> transformationChain; @Mock private KafkaProducer<byte[], byte[]> producer; @Mock private TopicAdmin admin; @Mock private CloseableOffsetStorageReader offsetReader; @Mock private OffsetStorageWriter offsetWriter; @Mock private ConnectorOffsetBackingStore offsetStore; @Mock private ClusterConfigState clusterConfigState; private WorkerSourceTask workerTask; @Mock private TaskStatus.Listener statusListener; @Mock private StatusBackingStore statusBackingStore; @Mock private ErrorHandlingMetrics errorHandlingMetrics; private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSourceTask.class.getName()); } private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); private static final List<SourceRecord> RECORDS = List.of( new SourceRecord(PARTITION, OFFSET, "topic", null, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD) ); public void setup(boolean enableTopicCreation) { Map<String, String> workerProps = workerProps(enableTopicCreation); plugins = new Plugins(workerProps); config = new StandaloneConfig(workerProps); sourceConfig = new SourceConnectorConfig(plugins, sourceConnectorPropsWithGroups(TOPIC), true); metrics = new MockConnectMetrics(); } private Map<String, String> workerProps(boolean enableTopicCreation) { Map<String, String> props = new HashMap<>(); props.put("key.converter", "org.apache.kafka.connect.json.JsonConverter"); props.put("value.converter", "org.apache.kafka.connect.json.JsonConverter"); props.put("offset.storage.file.filename", "/tmp/connect.offsets"); props.put(TOPIC_CREATION_ENABLE_CONFIG, String.valueOf(enableTopicCreation)); props.put(WorkerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); return props; } private Map<String, String> sourceConnectorPropsWithGroups(String topic) { // setup up props for the source connector Map<String, String> props = new HashMap<>(); props.put("name", "foo-connector"); props.put(CONNECTOR_CLASS_CONFIG, TestableSourceConnector.class.getSimpleName()); props.put(TASKS_MAX_CONFIG, String.valueOf(1)); props.put(TOPIC_CONFIG, topic); props.put(KEY_CONVERTER_CLASS_CONFIG, StringConverter.class.getName()); props.put(VALUE_CONVERTER_CLASS_CONFIG, StringConverter.class.getName()); props.put(TOPIC_CREATION_GROUPS_CONFIG, String.join(",", "foo", "bar")); props.put(DEFAULT_TOPIC_CREATION_PREFIX + REPLICATION_FACTOR_CONFIG, String.valueOf(1)); props.put(DEFAULT_TOPIC_CREATION_PREFIX + PARTITIONS_CONFIG, String.valueOf(1)); props.put(SourceConnectorConfig.TOPIC_CREATION_PREFIX + "foo" + "." + INCLUDE_REGEX_CONFIG, topic); props.put(SourceConnectorConfig.TOPIC_CREATION_PREFIX + "bar" + "." + INCLUDE_REGEX_CONFIG, ".*"); props.put(SourceConnectorConfig.TOPIC_CREATION_PREFIX + "bar" + "." + EXCLUDE_REGEX_CONFIG, topic); return props; } @AfterEach public void tearDown() { if (metrics != null) metrics.stop(); verifyNoMoreInteractions(statusListener); } private void createWorkerTask() { createWorkerTask(TargetState.STARTED, RetryWithToleranceOperatorTest.noneOperator()); } private void createWorkerTaskWithErrorToleration() { createWorkerTask(TargetState.STARTED, RetryWithToleranceOperatorTest.allOperator()); } private void createWorkerTask(TargetState initialState) { createWorkerTask(initialState, RetryWithToleranceOperatorTest.noneOperator()); } private void createWorkerTask(TargetState initialState, RetryWithToleranceOperator<SourceRecord> retryWithToleranceOperator) { createWorkerTask(initialState, keyConverter, valueConverter, headerConverter, retryWithToleranceOperator); } private void createWorkerTask(TargetState initialState, Converter keyConverter, Converter valueConverter, HeaderConverter headerConverter, RetryWithToleranceOperator<SourceRecord> retryWithToleranceOperator) { Plugin<Converter> keyConverterPlugin = metrics.wrap(keyConverter, taskId, true); Plugin<Converter> valueConverterPlugin = metrics.wrap(valueConverter, taskId, false); Plugin<HeaderConverter> headerConverterPlugin = metrics.wrap(headerConverter, taskId); workerTask = new WorkerSourceTask(taskId, sourceTask, statusListener, initialState, keyConverterPlugin, valueConverterPlugin, errorHandlingMetrics, headerConverterPlugin, transformationChain, producer, admin, TopicCreationGroup.configuredGroups(sourceConfig), offsetReader, offsetWriter, offsetStore, config, clusterConfigState, metrics, plugins.delegatingLoader(), Time.SYSTEM, retryWithToleranceOperator, statusBackingStore, Runnable::run, List::of, null, TestPlugins.noOpLoaderSwap()); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testStartPaused(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); final CountDownLatch pauseLatch = new CountDownLatch(1); createWorkerTask(TargetState.PAUSED); doAnswer(invocation -> { pauseLatch.countDown(); return null; }).when(statusListener).onPause(taskId); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); assertTrue(pauseLatch.await(5, TimeUnit.SECONDS)); workerTask.stop(); assertTrue(workerTask.awaitStop(1000)); taskFuture.get(); verify(statusListener).onPause(taskId); verify(statusListener).onShutdown(taskId); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testPause(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); createWorkerTask(); AtomicInteger count = new AtomicInteger(0); CountDownLatch pollLatch = expectPolls(10, count); // In this test, we don't flush, so nothing goes any further than the offset writer expectTopicCreation(TOPIC); expectOffsetFlush(); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); workerTask.transitionTo(TargetState.PAUSED); int priorCount = count.get(); Thread.sleep(100); // since the transition is observed asynchronously, the count could be off by one loop iteration assertTrue(count.get() - priorCount <= 1); workerTask.stop(); assertTrue(workerTask.awaitStop(1000)); taskFuture.get(); verifyCleanStartup(); verifyTaskGetTopic(count.get()); verifyOffsetFlush(true); verifyTopicCreation(TOPIC); verify(statusListener).onPause(taskId); verify(statusListener).onShutdown(taskId); verify(sourceTask).stop(); verify(offsetWriter).offset(PARTITION, OFFSET); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testPollsInBackground(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); createWorkerTask(); final CountDownLatch pollLatch = expectPolls(10); expectTopicCreation(TOPIC); expectOffsetFlush(); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); workerTask.stop(); assertTrue(workerTask.awaitStop(1000)); taskFuture.get(); assertPollMetrics(10); verifyCleanStartup(); verifyOffsetFlush(true); verify(offsetWriter).offset(PARTITION, OFFSET); verify(statusListener).onShutdown(taskId); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testFailureInPoll(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); createWorkerTask(); final CountDownLatch pollLatch = new CountDownLatch(1); final RuntimeException exception = new RuntimeException(); when(sourceTask.poll()).thenAnswer(invocation -> { pollLatch.countDown(); throw exception; }); expectEmptyOffsetFlush(); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); //Failure in poll should trigger automatic stop of the task assertTrue(workerTask.awaitStop(1000)); taskFuture.get(); assertPollMetrics(0); verifyCleanStartup(); verify(statusListener).onFailure(taskId, exception); verify(sourceTask).stop(); assertShouldSkipCommit(); verifyOffsetFlush(true); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testFailureInPollAfterCancel(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); createWorkerTask(); final CountDownLatch pollLatch = new CountDownLatch(1); final CountDownLatch workerCancelLatch = new CountDownLatch(1); final RuntimeException exception = new RuntimeException(); when(sourceTask.poll()).thenAnswer(invocation -> { pollLatch.countDown(); ConcurrencyUtils.awaitLatch(workerCancelLatch, "Timeout waiting for main test thread to cancel task."); throw exception; }); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); workerTask.cancel(); workerCancelLatch.countDown(); assertTrue(workerTask.awaitStop(1000)); taskFuture.get(); assertPollMetrics(0); verifyCleanStartup(); verify(offsetReader, atLeastOnce()).close(); verify(producer).close(Duration.ZERO); verify(sourceTask).stop(); verify(admin).close(any(Duration.class)); verify(transformationChain).close(); verify(offsetStore).stop(); try { verify(headerConverter).close(); } catch (IOException e) { throw new RuntimeException(e); } } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testFailureInPollAfterStop(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); createWorkerTask(); final CountDownLatch pollLatch = new CountDownLatch(1); final CountDownLatch workerStopLatch = new CountDownLatch(1); final RuntimeException exception = new RuntimeException(); when(sourceTask.poll()).thenAnswer(invocation -> { pollLatch.countDown(); ConcurrencyUtils.awaitLatch(workerStopLatch, "Timeout waiting for main test thread to stop task"); throw exception; }); expectOffsetFlush(); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); workerTask.stop(); workerStopLatch.countDown(); assertTrue(workerTask.awaitStop(1000)); assertShouldSkipCommit(); taskFuture.get(); assertPollMetrics(0); verifyCleanStartup(); verify(statusListener).onShutdown(taskId); verify(sourceTask).stop(); verifyOffsetFlush(true); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testPollReturnsNoRecords(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); // Test that the task handles an empty list of records createWorkerTask(); // We'll wait for some data, then trigger a flush final CountDownLatch pollLatch = expectEmptyPolls(new AtomicInteger()); expectEmptyOffsetFlush(); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); assertTrue(workerTask.commitOffsets()); verify(offsetWriter).beginFlush(anyLong(), any(TimeUnit.class)); workerTask.stop(); assertTrue(workerTask.awaitStop(1000)); verify(offsetWriter, times(2)).beginFlush(anyLong(), any(TimeUnit.class)); verifyNoMoreInteractions(offsetWriter); taskFuture.get(); assertPollMetrics(0); verifyCleanStartup(); verify(sourceTask).stop(); verify(statusListener).onShutdown(taskId); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testCommit(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); // Test that the task commits properly when prompted createWorkerTask(); // We'll wait for some data, then trigger a flush final CountDownLatch pollLatch = expectPolls(1); expectTopicCreation(TOPIC); expectBeginFlush(List.of(true, false).iterator()::next); expectOffsetFlush(true, true); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); assertTrue(workerTask.commitOffsets()); workerTask.stop(); assertTrue(workerTask.awaitStop(1000)); taskFuture.get(); assertPollMetrics(1); verifyCleanStartup(); verifyTopicCreation(TOPIC); verify(offsetWriter, times(2)).beginFlush(anyLong(), any(TimeUnit.class)); verify(offsetWriter, atLeastOnce()).offset(PARTITION, OFFSET); verify(sourceTask).stop(); verify(statusListener).onShutdown(taskId); verifyOffsetFlush(true, 2); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testCommitFailure(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); // Test that the task commits properly when prompted createWorkerTask(); // We'll wait for some data, then trigger a flush final CountDownLatch pollLatch = expectPolls(1); expectBeginFlush(); expectOffsetFlush(true, false); expectTopicCreation(TOPIC); workerTask.initialize(TASK_CONFIG); Future<?> taskFuture = executor.submit(workerTask); ConcurrencyUtils.awaitLatch(pollLatch, POLL_TIMEOUT_MSG); assertTrue(workerTask.commitOffsets()); workerTask.stop(); assertTrue(workerTask.awaitStop(1000)); taskFuture.get(); assertPollMetrics(1); verifyCleanStartup(); verify(sourceTask).stop(); verify(offsetWriter, atLeastOnce()).offset(PARTITION, OFFSET); verify(statusListener).onShutdown(taskId); verifyOffsetFlush(true); // First call to doFlush() succeeded verifyOffsetFlush(false); // Second call threw a TimeoutException verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testSendRecordsRetries(boolean enableTopicCreation) { setup(enableTopicCreation); createWorkerTask(); // Differentiate only by Kafka partition, so we can reuse conversion expectations SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, "topic", 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, "topic", 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record3 = new SourceRecord(PARTITION, OFFSET, "topic", 3, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectTopicCreation(TOPIC); expectPreliminaryCalls(); expectTaskGetTopic(); when(producer.send(any(ProducerRecord.class), any(Callback.class))) // First round .thenAnswer(producerSendAnswer(true)) // Any Producer retriable exception should work here .thenThrow(new org.apache.kafka.common.errors.TimeoutException("retriable sync failure")) // Second round .thenAnswer(producerSendAnswer(true)) .thenAnswer(producerSendAnswer(true)); // Try to send 3, make first pass, second fail. Should save last two workerTask.toSend = List.of(record1, record2, record3); workerTask.sendRecords(); assertEquals(List.of(record2, record3), workerTask.toSend); // Next they all succeed workerTask.sendRecords(); assertNull(workerTask.toSend); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testSendRecordsProducerCallbackFail(boolean enableTopicCreation) { setup(enableTopicCreation); createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, "topic", 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, "topic", 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectTopicCreation(TOPIC); expectSendRecordProducerCallbackFail(); workerTask.toSend = List.of(record1, record2); assertThrows(ConnectException.class, () -> workerTask.sendRecords()); verify(transformationChain, times(2)).apply(any(), any(SourceRecord.class)); verify(keyConverter, times(2)).fromConnectData(anyString(), any(Headers.class), eq(KEY_SCHEMA), eq(KEY)); verify(valueConverter, times(2)).fromConnectData(anyString(), any(Headers.class), eq(RECORD_SCHEMA), eq(RECORD)); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testSendRecordsProducerSendFailsImmediately(boolean enableTopicCreation) { setup(enableTopicCreation); createWorkerTask(); SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectPreliminaryCalls(); expectTopicCreation(TOPIC); when(producer.send(any(ProducerRecord.class), any(Callback.class))) .thenThrow(new KafkaException("Producer closed while send in progress", new InvalidTopicException(TOPIC))); workerTask.toSend = List.of(record1, record2); assertThrows(ConnectException.class, () -> workerTask.sendRecords()); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testSendRecordsTaskCommitRecordFail(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); createWorkerTask(); // Differentiate only by Kafka partition, so we can reuse conversion expectations SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, "topic", 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, OFFSET, "topic", 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record3 = new SourceRecord(PARTITION, OFFSET, "topic", 3, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectTopicCreation(TOPIC); expectSendRecord(); // Source task commit record failure will not cause the task to abort doNothing() .doThrow(new RuntimeException("Error committing record in source task")) .doNothing() .when(sourceTask).commitRecord(any(SourceRecord.class), any(RecordMetadata.class)); workerTask.toSend = List.of(record1, record2, record3); workerTask.sendRecords(); assertNull(workerTask.toSend); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testSourceTaskIgnoresProducerException(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); createWorkerTaskWithErrorToleration(); expectTopicCreation(TOPIC); //Use different offsets for each record, so we can verify all were committed final Map<String, Object> offset2 = Map.of("key", 13); // send two records // record 1 will succeed // record 2 will invoke the producer's failure callback, but ignore the exception via retryOperator // and no ConnectException will be thrown SourceRecord record1 = new SourceRecord(PARTITION, OFFSET, TOPIC, 1, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); SourceRecord record2 = new SourceRecord(PARTITION, offset2, TOPIC, 2, KEY_SCHEMA, KEY, RECORD_SCHEMA, RECORD); expectOffsetFlush(); expectPreliminaryCalls(); when(producer.send(any(ProducerRecord.class), any(Callback.class))) .thenAnswer(producerSendAnswer(true)) .thenAnswer(producerSendAnswer(false)); //Send records and then commit offsets and verify both were committed and no exception workerTask.toSend = List.of(record1, record2); workerTask.sendRecords(); workerTask.updateCommittableOffsets(); workerTask.commitOffsets(); //As of KAFKA-14079 all offsets should be committed, even for failed records (if ignored) //Only the last offset will be passed to the method as everything up to that point is committed //Before KAFKA-14079 offset 12 would have been passed and not 13 as it would have been unacked verify(offsetWriter).offset(PARTITION, offset2); verify(sourceTask).commitRecord(any(SourceRecord.class), isNull()); //Double check to make sure all submitted records were cleared assertEquals(0, workerTask.submittedRecords.records.size()); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testSlowTaskStart(boolean enableTopicCreation) throws Exception { setup(enableTopicCreation); final CountDownLatch startupLatch = new CountDownLatch(1); final CountDownLatch finishStartupLatch = new CountDownLatch(1); createWorkerTask(); doAnswer((Answer<Object>) invocation -> { startupLatch.countDown(); ConcurrencyUtils.awaitLatch(finishStartupLatch, "Timeout waiting for main test thread to allow task startup to complete"); return null; }).when(sourceTask).start(TASK_PROPS); expectOffsetFlush(); workerTask.initialize(TASK_CONFIG); Future<?> workerTaskFuture = executor.submit(workerTask); // Stopping immediately while the other thread has work to do should result in no polling, no offset commits, // exiting the work thread immediately, and the stop() method will be invoked in the background thread since it // cannot be invoked immediately in the thread trying to stop the task. ConcurrencyUtils.awaitLatch(startupLatch, "Timeout waiting for task to begin startup"); workerTask.stop(); finishStartupLatch.countDown(); assertTrue(workerTask.awaitStop(1000)); workerTaskFuture.get(); verify(offsetStore).start(); verify(sourceTask).initialize(any(SourceTaskContext.class)); verify(sourceTask).start(TASK_PROPS); verify(statusListener).onStartup(taskId); verify(statusListener).onShutdown(taskId); verify(sourceTask).stop(); verifyClose(); } @ParameterizedTest @ValueSource(booleans = {true, false}) public void testCancel(boolean enableTopicCreation) { setup(enableTopicCreation); createWorkerTask(); workerTask.cancel(); verify(offsetReader).close(); verify(producer).close(Duration.ZERO); } private TopicAdmin.TopicCreationResponse createdTopic(String topic) { Set<String> created = Set.of(topic); Set<String> existing = Set.of(); return new TopicAdmin.TopicCreationResponse(created, existing); } private void expectPreliminaryCalls() { expectConvertHeadersAndKeyValue(TOPIC, emptyHeaders()); expectApplyTransformationChain(); } private CountDownLatch expectEmptyPolls(final AtomicInteger count) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); // Note that we stub these to allow any number of calls because the thread will continue to // run. The count passed in + latch returned just makes sure we get *at least* that number of // calls when(sourceTask.poll()).thenAnswer((Answer<List<SourceRecord>>) invocation -> { count.incrementAndGet(); latch.countDown(); Thread.sleep(10); return List.of(); }); return latch; } private CountDownLatch expectPolls(int minimum, final AtomicInteger count) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(minimum); // Note that we stub these to allow any number of calls because the thread will continue to // run. The count passed in + latch returned just makes sure we get *at least* that number of // calls doAnswer((Answer<List<SourceRecord>>) invocation -> { count.incrementAndGet(); latch.countDown(); Thread.sleep(10); return RECORDS; }).when(sourceTask).poll(); // Fallout of the poll() call expectSendRecord(); return latch; } private CountDownLatch expectPolls(int count) throws InterruptedException { return expectPolls(count, new AtomicInteger()); } private void expectSendRecord() { expectSendRecordTaskCommitRecordSucceed(); } private void expectSendRecordProducerCallbackFail() { expectSendRecord(TOPIC, false, emptyHeaders()); } private void expectSendRecordTaskCommitRecordSucceed() { expectSendRecord(TOPIC, true, emptyHeaders()); } private void expectSendRecord(String topic, boolean sendSuccess, Headers headers) { expectConvertHeadersAndKeyValue(topic, headers); expectApplyTransformationChain(); if (sendSuccess) { // 2. As a result of a successful producer send callback, we'll notify the source task of the record commit expectTaskGetTopic(); } doAnswer(producerSendAnswer(sendSuccess)) .when(producer).send(any(ProducerRecord.class), any(Callback.class)); } private Answer<Future<RecordMetadata>> producerSendAnswer(boolean sendSuccess) { return invocation -> { Callback cb = invocation.getArgument(1); if (sendSuccess) { cb.onCompletion(new RecordMetadata(new TopicPartition("foo", 0), 0, 0, 0L, 0, 0), null); } else { cb.onCompletion(null, new TopicAuthorizationException("foo")); } return null; }; } private void expectConvertHeadersAndKeyValue(String topic, Headers headers) { if (headers.iterator().hasNext()) { when(headerConverter.fromConnectHeader(anyString(), anyString(), eq(Schema.STRING_SCHEMA), anyString())) .thenAnswer((Answer<byte[]>) invocation -> { String headerValue = invocation.getArgument(3, String.class); return headerValue.getBytes(StandardCharsets.UTF_8); }); } when(keyConverter.fromConnectData(eq(topic), any(Headers.class), eq(KEY_SCHEMA), eq(KEY))) .thenReturn(SERIALIZED_KEY); when(valueConverter.fromConnectData(eq(topic), any(Headers.class), eq(RECORD_SCHEMA), eq(RECORD))) .thenReturn(SERIALIZED_RECORD); } private void expectApplyTransformationChain() { when(transformationChain.apply(any(), any(SourceRecord.class))) .thenAnswer(AdditionalAnswers.returnsSecondArg()); } private void expectTaskGetTopic() { when(statusBackingStore.getTopic(anyString(), anyString())).thenAnswer((Answer<TopicStatus>) invocation -> { String connector = invocation.getArgument(0, String.class); String topic = invocation.getArgument(1, String.class); return new TopicStatus(topic, new ConnectorTaskId(connector, 0), Time.SYSTEM.milliseconds()); }); } private void verifyTaskGetTopic(int times) { ArgumentCaptor<String> connectorCapture = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> topicCapture = ArgumentCaptor.forClass(String.class); verify(statusBackingStore, times(times)).getTopic(connectorCapture.capture(), topicCapture.capture()); assertEquals("job", connectorCapture.getValue()); assertEquals(TOPIC, topicCapture.getValue()); } private void expectBeginFlush() throws Exception { expectBeginFlush(() -> true); } private void expectBeginFlush(Supplier<Boolean> resultSupplier) throws Exception { when(offsetWriter.beginFlush(anyLong(), any(TimeUnit.class))).thenAnswer(ignored -> resultSupplier.get()); } private void expectOffsetFlush() throws Exception { expectBeginFlush(); expectOffsetFlush(true); } @SuppressWarnings("unchecked") private void expectOffsetFlush(Boolean... succeedList) throws Exception { Future<Void> flushFuture = mock(Future.class); when(offsetWriter.doFlush(any(org.apache.kafka.connect.util.Callback.class))).thenReturn(flushFuture); LinkedList<Boolean> succeedQueue = new LinkedList<>(List.of(succeedList)); doAnswer(invocationOnMock -> { boolean succeed = succeedQueue.pop(); if (succeed) { return null; } else { throw new TimeoutException(); } }).when(flushFuture).get(anyLong(), any(TimeUnit.class)); } private void expectEmptyOffsetFlush() throws Exception { expectBeginFlush(() -> false); } private void verifyOffsetFlush(boolean succeed) throws Exception { verifyOffsetFlush(succeed, 1); } private void verifyOffsetFlush(boolean succeed, int times) throws Exception { // Should throw for failure if (succeed) { verify(sourceTask, atLeast(times)).commit(); } else { verify(offsetWriter, atLeast(times)).cancelFlush(); } } private void assertPollMetrics(int minimumPollCountExpected) { MetricGroup sourceTaskGroup = workerTask.sourceTaskMetricsGroup().metricGroup(); MetricGroup taskGroup = workerTask.taskMetricsGroup().metricGroup(); double pollRate = metrics.currentMetricValueAsDouble(sourceTaskGroup, "source-record-poll-rate"); double pollTotal = metrics.currentMetricValueAsDouble(sourceTaskGroup, "source-record-poll-total"); if (minimumPollCountExpected > 0) { assertEquals(RECORDS.size(), metrics.currentMetricValueAsDouble(taskGroup, "batch-size-max"), 0.000001d); assertEquals(RECORDS.size(), metrics.currentMetricValueAsDouble(taskGroup, "batch-size-avg"), 0.000001d); assertTrue(pollRate > 0.0d); } else { assertEquals(0.0d, pollRate, 0.0); } assertTrue(pollTotal >= minimumPollCountExpected); double writeRate = metrics.currentMetricValueAsDouble(sourceTaskGroup, "source-record-write-rate"); double writeTotal = metrics.currentMetricValueAsDouble(sourceTaskGroup, "source-record-write-total"); if (minimumPollCountExpected > 0) { assertTrue(writeRate > 0.0d); } else { assertEquals(0.0d, writeRate, 0.0); } assertTrue(writeTotal >= minimumPollCountExpected); double pollBatchTimeMax = metrics.currentMetricValueAsDouble(sourceTaskGroup, "poll-batch-max-time-ms"); double pollBatchTimeAvg = metrics.currentMetricValueAsDouble(sourceTaskGroup, "poll-batch-avg-time-ms"); if (minimumPollCountExpected > 0) { assertTrue(pollBatchTimeMax >= 0.0d); } assertTrue(Double.isNaN(pollBatchTimeAvg) || pollBatchTimeAvg > 0.0d); double activeCount = metrics.currentMetricValueAsDouble(sourceTaskGroup, "source-record-active-count"); double activeCountMax = metrics.currentMetricValueAsDouble(sourceTaskGroup, "source-record-active-count-max"); assertEquals(0, activeCount, 0.000001d); if (minimumPollCountExpected > 0) { assertEquals(RECORDS.size(), activeCountMax, 0.000001d); } } private RecordHeaders emptyHeaders() { return new RecordHeaders(); } private abstract static
WorkerSourceTaskTest
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java
{ "start": 3370, "end": 3912 }
class ____ method. * * <p>A transaction aspect is serializable if its {@code TransactionManager} and * {@code TransactionAttributeSource} are serializable. * * @author Rod Johnson * @author Juergen Hoeller * @author Stéphane Nicoll * @author Sam Brannen * @author Mark Paluch * @author Sebastien Deleuze * @author Enric Sala * @since 1.1 * @see PlatformTransactionManager * @see ReactiveTransactionManager * @see #setTransactionManager * @see #setTransactionAttributes * @see #setTransactionAttributeSource */ public abstract
or
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StaticQualifiedUsingExpressionTest.java
{ "start": 11291, "end": 11651 }
class ____ { void f(I i) { System.err.println(I.CONST); i.id(); System.err.println(I.CONST); } } """) .doTest(); } @Test public void superAccess() { refactoringHelper .addInputLines( "I.java", """
Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AbstractAsynchronousOperationHandlersTest.java
{ "start": 13265, "end": 15177 }
class ____ extends TriggerHandler<RestfulGateway, EmptyRequestBody, EmptyMessageParameters> { protected TestingTriggerHandler( GatewayRetriever<? extends RestfulGateway> leaderRetriever, Duration timeout, Map<String, String> responseHeaders, MessageHeaders<EmptyRequestBody, TriggerResponse, EmptyMessageParameters> messageHeaders) { super(leaderRetriever, timeout, responseHeaders, messageHeaders); } private BiFunction< HandlerRequest<EmptyRequestBody>, RestfulGateway, CompletableFuture<Acknowledge>> gatewayCallback = (handlerRequest, restfulGateway) -> { throw new UnsupportedOperationException(); }; public void setGatewayCallback( BiFunction< HandlerRequest<EmptyRequestBody>, RestfulGateway, CompletableFuture<Acknowledge>> callback) { this.gatewayCallback = callback; } @Override protected CompletableFuture<Acknowledge> triggerOperation( HandlerRequest<EmptyRequestBody> request, RestfulGateway gateway) throws RestHandlerException { return gatewayCallback.apply(request, gateway); } @Override protected TestOperationKey createOperationKey( HandlerRequest<EmptyRequestBody> request) { return new TestOperationKey(new TriggerId()); } }
TestingTriggerHandler
java
quarkusio__quarkus
integration-tests/openapi/src/main/java/io/quarkus/it/openapi/jaxrs/BooleanResource.java
{ "start": 460, "end": 3039 }
class ____ { @GET @Path("/justBoolean") public Boolean justBoolean() { return Boolean.TRUE; } @POST @Path("/justBoolean") public Boolean justBoolean(Boolean body) { return body; } @GET @Path("/justBool") public boolean justBool() { return true; } @POST @Path("/justBool") public boolean justBool(boolean body) { return body; } @GET @Path("/restResponseBoolean") public RestResponse<Boolean> restResponseBoolean() { return RestResponse.ok(Boolean.TRUE); } @POST @Path("/restResponseBoolean") public RestResponse<Boolean> restResponseBoolean(Boolean body) { return RestResponse.ok(body); } @GET @Path("/optionalBoolean") public Optional<Boolean> optionalBoolean() { return Optional.of(Boolean.TRUE); } @POST @Path("/optionalBoolean") public Optional<Boolean> optionalBoolean(Optional<Boolean> body) { return body; } @GET @Path("/uniBoolean") public Uni<Boolean> uniBoolean() { return Uni.createFrom().item(Boolean.TRUE); } @GET @Path("/completionStageBoolean") public CompletionStage<Boolean> completionStageBoolean() { return CompletableFuture.completedStage(Boolean.TRUE); } @GET @Path("/completedFutureBoolean") public CompletableFuture<Boolean> completedFutureBoolean() { return CompletableFuture.completedFuture(Boolean.TRUE); } @GET @Path("/listBoolean") public List<Boolean> listBoolean() { return Arrays.asList(new Boolean[] { Boolean.TRUE }); } @POST @Path("/listBoolean") public List<Boolean> listBoolean(List<Boolean> body) { return body; } @GET @Path("/arrayBoolean") public Boolean[] arrayBoolean() { return new Boolean[] { Boolean.TRUE }; } @POST @Path("/arrayBoolean") public Boolean[] arrayBoolean(Boolean[] body) { return body; } @GET @Path("/arrayBool") public boolean[] arrayBool() { return new boolean[] { true }; } @POST @Path("/arrayBool") public boolean[] arrayBool(boolean[] body) { return body; } @GET @Path("/mapBoolean") public Map<Boolean, Boolean> mapBoolean() { Map<Boolean, Boolean> m = new HashMap<>(); m.put(true, true); return m; } @POST @Path("/mapBoolean") public Map<Boolean, Boolean> mapBoolean(Map<Boolean, Boolean> body) { return body; } }
BooleanResource
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/parallel/ResourceLocksProvider.java
{ "start": 4204, "end": 4567 }
class ____ by * {@code testMethod.getDeclaringClass()} &mdash; for example, when a test * method is inherited from a superclass. * * @param enclosingInstanceTypes the runtime types of the enclosing * instances for the test class, ordered from outermost to innermost, * excluding {@code testClass}; never {@code null} * @param testClass the test
returned
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NonApiType.java
{ "start": 12332, "end": 12401 }
enum ____ { PARAMETER, RETURN_TYPE, ANY }
ApiElementType
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2SelectTest_23.java
{ "start": 1037, "end": 2773 }
class ____ extends DB2Test { public void test_0() throws Exception { String sql = "select current date,current timestamp from dual"; DB2StatementParser parser = new DB2StatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); System.out.println(SQLUtils.toDB2String(stmt)); assertEquals(1, statementList.size()); DB2SchemaStatVisitor visitor = new DB2SchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertFalse(visitor.getTables().containsKey(new TableStat.Name("dual"))); // assertTrue(visitor.getColumns().contains(new Column("DSN8B10.EMP", "WORKDEPT"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "first_name"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "full_name"))); assertEquals("SELECT CURRENT DATE, CURRENT TIMESTAMP\n" + "FROM dual", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2)); assertEquals("select CURRENT DATE, CURRENT TIMESTAMP\n" + "from dual", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } }
DB2SelectTest_23
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/orca/OrcaPerRequestUtilTest.java
{ "start": 4508, "end": 9024 }
class ____ implements ArgumentMatcher<MetricReport> { private MetricReport original; public MetricsReportMatcher(MetricReport report) { this.original = report; } @Override public boolean matches(MetricReport argument) { return reportEqual(original, argument); } } static boolean reportEqual(MetricReport a, MetricReport b) { return a.getCpuUtilization() == b.getCpuUtilization() && a.getApplicationUtilization() == b.getApplicationUtilization() && a.getMemoryUtilization() == b.getMemoryUtilization() && a.getQps() == b.getQps() && a.getEps() == b.getEps() && Objects.equal(a.getRequestCostMetrics(), b.getRequestCostMetrics()) && Objects.equal(a.getUtilizationMetrics(), b.getUtilizationMetrics()) && Objects.equal(a.getNamedMetrics(), b.getNamedMetrics()); } /** * Tests parent-child load balance policies' listeners both receive per-request ORCA reports upon * call trailer arrives and ORCA report deserialization happens only once. */ @Test public void twoLevelPoliciesTypicalWorkflow() { ClientStreamTracer.Factory parentFactory = mock(ClientStreamTracer.Factory.class, delegatesTo( OrcaPerRequestUtil.getInstance().newOrcaClientStreamTracerFactory(orcaListener1))); ClientStreamTracer.Factory childFactory = OrcaPerRequestUtil.getInstance() .newOrcaClientStreamTracerFactory(parentFactory, orcaListener2); // Child factory will augment the StreamInfo and pass it to the parent factory. ClientStreamTracer childTracer = childFactory.newClientStreamTracer(STREAM_INFO, new Metadata()); ArgumentCaptor<ClientStreamTracer.StreamInfo> streamInfoCaptor = ArgumentCaptor.forClass(ClientStreamTracer.StreamInfo.class); verify(parentFactory).newClientStreamTracer(streamInfoCaptor.capture(), any(Metadata.class)); ClientStreamTracer.StreamInfo parentStreamInfo = streamInfoCaptor.getValue(); assertThat(parentStreamInfo).isNotEqualTo(STREAM_INFO); // When the trailer does not contain ORCA report, no listener callback will be invoked. Metadata trailer = new Metadata(); childTracer.inboundTrailers(trailer); verifyNoMoreInteractions(orcaListener1); verifyNoMoreInteractions(orcaListener2); // When the trailer contains an ORCA report, callbacks for both listeners will be invoked. // Both listener will receive the same ORCA report instance, which means deserialization // happens only once. trailer.put( OrcaReportingTracerFactory.ORCA_ENDPOINT_LOAD_METRICS_KEY, OrcaLoadReport.getDefaultInstance()); childTracer.inboundTrailers(trailer); ArgumentCaptor<MetricReport> parentReportCap = ArgumentCaptor.forClass(MetricReport.class); ArgumentCaptor<MetricReport> childReportCap = ArgumentCaptor.forClass(MetricReport.class); verify(orcaListener1).onLoadReport(parentReportCap.capture()); verify(orcaListener2).onLoadReport(childReportCap.capture()); assertThat(reportEqual(parentReportCap.getValue(), OrcaPerRequestUtil.fromOrcaLoadReport(OrcaLoadReport.getDefaultInstance()))).isTrue(); assertThat(childReportCap.getValue()).isSameInstanceAs(parentReportCap.getValue()); } /** * Tests the case when parent policy creates its own {@link ClientStreamTracer.Factory}, ORCA * reports are only forwarded to the parent's listener. */ @Test public void onlyParentPolicyReceivesReportsIfCreatesOwnTracer() { ClientStreamTracer.Factory parentFactory = OrcaPerRequestUtil.getInstance().newOrcaClientStreamTracerFactory(orcaListener1); ClientStreamTracer.Factory childFactory = mock(ClientStreamTracer.Factory.class, delegatesTo(OrcaPerRequestUtil.getInstance() .newOrcaClientStreamTracerFactory(parentFactory, orcaListener2))); ClientStreamTracer parentTracer = parentFactory.newClientStreamTracer(STREAM_INFO, new Metadata()); Metadata trailer = new Metadata(); OrcaLoadReport report = OrcaLoadReport.getDefaultInstance(); trailer.put( OrcaReportingTracerFactory.ORCA_ENDPOINT_LOAD_METRICS_KEY, report); parentTracer.inboundTrailers(trailer); verify(orcaListener1).onLoadReport( argThat(new MetricsReportMatcher(OrcaPerRequestUtil.fromOrcaLoadReport(report)))); verifyNoInteractions(childFactory); verifyNoInteractions(orcaListener2); } }
MetricsReportMatcher