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/generator/ApplicationContextAotGeneratorRuntimeHintsTests.java
{ "start": 2052, "end": 5213 }
class ____ { @Test void generateApplicationContextWithSimpleBean() { GenericApplicationContext context = new AnnotationConfigApplicationContext(); context.registerBeanDefinition("test", new RootBeanDefinition(SimpleComponent.class)); compile(context, (hints, invocations) -> assertThat(invocations).match(hints)); } @Test void generateApplicationContextWithAutowiring() { GenericApplicationContext context = new AnnotationConfigApplicationContext(); context.registerBeanDefinition("autowiredComponent", new RootBeanDefinition(AutowiredComponent.class)); context.registerBeanDefinition("number", BeanDefinitionBuilder.rootBeanDefinition( Integer.class, "valueOf").addConstructorArgValue("42").getBeanDefinition()); compile(context, (hints, invocations) -> assertThat(invocations).match(hints)); } @Test void generateApplicationContextWithInitDestroyMethods() { GenericApplicationContext context = new AnnotationConfigApplicationContext(); context.registerBeanDefinition("initDestroyComponent", new RootBeanDefinition(InitDestroyComponent.class)); compile(context, (hints, invocations) -> assertThat(invocations).match(hints)); } @Test void generateApplicationContextWithMultipleInitDestroyMethods() { GenericApplicationContext context = new AnnotationConfigApplicationContext(); RootBeanDefinition beanDefinition = new RootBeanDefinition(InitDestroyComponent.class); beanDefinition.setInitMethodName("customInit"); beanDefinition.setDestroyMethodName("customDestroy"); context.registerBeanDefinition("initDestroyComponent", beanDefinition); compile(context, (hints, invocations) -> assertThat(invocations).match(hints)); } @Test void generateApplicationContextWithInheritedDestroyMethods() { GenericApplicationContext context = new AnnotationConfigApplicationContext(); RootBeanDefinition beanDefinition = new RootBeanDefinition(InheritedDestroy.class); context.registerBeanDefinition("initDestroyComponent", beanDefinition); compile(context, (hints, invocations) -> assertThat(invocations).match(hints)); } @SuppressWarnings({"rawtypes", "unchecked"}) private void compile(GenericApplicationContext applicationContext, BiConsumer<RuntimeHints, RuntimeHintsInvocations> initializationResult) { ApplicationContextAotGenerator generator = new ApplicationContextAotGenerator(); TestGenerationContext generationContext = new TestGenerationContext(); generator.processAheadOfTime(applicationContext, generationContext); generationContext.writeGeneratedContent(); TestCompiler.forSystem().with(generationContext).compile(compiled -> { ApplicationContextInitializer instance = compiled.getInstance(ApplicationContextInitializer.class); GenericApplicationContext freshContext = new GenericApplicationContext(); RuntimeHintsInvocations recordedInvocations = org.springframework.aot.test.agent.RuntimeHintsRecorder.record(() -> { instance.initialize(freshContext); freshContext.refresh(); freshContext.close(); }); initializationResult.accept(generationContext.getRuntimeHints(), recordedInvocations); }); } public
ApplicationContextAotGeneratorRuntimeHintsTests
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/BadAnnotationImplementation.java
{ "start": 2575, "end": 3009 }
class ____ extends BugChecker implements ClassTreeMatcher { private static final Matcher<ClassTree> CLASS_TREE_MATCHER = allOf(anyOf(kindIs(CLASS), kindIs(ENUM)), isSubtypeOf(ANNOTATION_TYPE)); @Override public Description matchClass(ClassTree classTree, VisitorState state) { if (!CLASS_TREE_MATCHER.matches(classTree, state)) { return Description.NO_MATCH; } // If this is an
BadAnnotationImplementation
java
apache__camel
components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowProducer.java
{ "start": 2343, "end": 11274 }
class ____ extends DefaultAsyncProducer { private static final Logger LOG = LoggerFactory.getLogger(UndertowProducer.class); private UndertowClient client; private final UndertowEndpoint endpoint; private final OptionMap options; private DefaultByteBufferPool pool; private XnioSsl ssl; private XnioWorker worker; private CamelWebSocketHandler webSocketHandler; public UndertowProducer(final UndertowEndpoint endpoint, final OptionMap options) { super(endpoint); this.endpoint = endpoint; this.options = options; } @Override public UndertowEndpoint getEndpoint() { return endpoint; } boolean isSendToAll(Message in) { // header may be null; have to be careful here (and fallback to use sendToAll option configured from endpoint) Boolean value = in.getHeader(UndertowConstants.SEND_TO_ALL, endpoint.getSendToAll(), Boolean.class); return value != null && value; } @Override public boolean process(final Exchange camelExchange, final AsyncCallback callback) { if (endpoint.isWebSocket()) { return processWebSocket(camelExchange, callback); } /* not a WebSocket */ final URI uri; final HttpString method; try { final String exchangeUri = UndertowHelper.createURL(camelExchange, getEndpoint()); uri = UndertowHelper.createURI(camelExchange, exchangeUri, getEndpoint()); method = UndertowHelper.createMethod(camelExchange, endpoint, camelExchange.getIn().getBody() != null); } catch (final URISyntaxException e) { camelExchange.setException(e); callback.done(true); return true; } final String pathAndQuery = URISupport.pathAndQueryOf(uri); final UndertowHttpBinding undertowHttpBinding = endpoint.getUndertowHttpBinding(); final CookieHandler cookieHandler = endpoint.getCookieHandler(); final Map<String, List<String>> cookieHeaders; if (cookieHandler != null) { try { cookieHeaders = cookieHandler.loadCookies(camelExchange, uri); } catch (final IOException e) { camelExchange.setException(e); callback.done(true); return true; } } else { cookieHeaders = Collections.emptyMap(); } final ClientRequest request = new ClientRequest(); request.setMethod(method); request.setPath(pathAndQuery); final HeaderMap requestHeaders = request.getRequestHeaders(); // Set the Host header final Message message = camelExchange.getIn(); final String host = message.getHeader(UndertowConstants.HOST_STRING, String.class); if (endpoint.isPreserveHostHeader()) { requestHeaders.put(Headers.HOST, Optional.ofNullable(host).orElseGet(uri::getAuthority)); } else { requestHeaders.put(Headers.HOST, uri.getAuthority()); } cookieHeaders.forEach((key, values) -> { requestHeaders.putAll(HttpString.tryFromString(key), values); }); final Object body = undertowHttpBinding.toHttpRequest(request, camelExchange.getIn()); final UndertowClientCallback clientCallback; final boolean streaming = getEndpoint().isUseStreaming(); if (streaming && body instanceof InputStream) { // For streaming, make it chunked encoding instead of specifying content length requestHeaders.put(Headers.TRANSFER_ENCODING, "chunked"); clientCallback = new UndertowStreamingClientCallback( camelExchange, callback, getEndpoint(), request, (InputStream) body); } else { final TypeConverter tc = endpoint.getCamelContext().getTypeConverter(); final ByteBuffer bodyAsByte = tc.tryConvertTo(ByteBuffer.class, body); // As tryConvertTo is used to convert the body, we should do null check // or the call bodyAsByte.remaining() may throw an NPE if (body != null && bodyAsByte != null) { requestHeaders.put(Headers.CONTENT_LENGTH, bodyAsByte.remaining()); } if (streaming) { // response may receive streaming clientCallback = new UndertowStreamingClientCallback( camelExchange, callback, getEndpoint(), request, bodyAsByte); } else { clientCallback = new UndertowClientCallback( camelExchange, callback, getEndpoint(), request, bodyAsByte); } } if (LOG.isDebugEnabled()) { LOG.debug("Executing http {} method: {}", method, pathAndQuery); } // when connect succeeds or fails UndertowClientCallback will // get notified on a I/O thread run by Xnio worker. The writing // of request and reading of response is performed also in the // callback client.connect(clientCallback, uri, worker, ssl, pool, options); // the call above will proceed on Xnio I/O thread we will // notify the exchange asynchronously when the HTTP exchange // ends with success or failure from UndertowClientCallback return false; } private boolean processWebSocket(final Exchange camelExchange, final AsyncCallback camelCallback) { final Message in = camelExchange.getIn(); try { Object message = in.getBody(); if (!(message instanceof String || message instanceof byte[] || message instanceof Reader || message instanceof InputStream)) { message = in.getBody(String.class); } if (message != null) { final int timeout = endpoint.getSendTimeout(); if (isSendToAll(in)) { return webSocketHandler.send(peer -> true, message, timeout, camelExchange, camelCallback); } final List<String> connectionKeys = in.getHeader(UndertowConstants.CONNECTION_KEY_LIST, List.class); if (connectionKeys != null) { return webSocketHandler.send( peer -> connectionKeys.contains(peer.getAttribute(UndertowConstants.CONNECTION_KEY)), message, timeout, camelExchange, camelCallback); } final String connectionKey = in.getHeader(UndertowConstants.CONNECTION_KEY, String.class); if (connectionKey != null) { return webSocketHandler.send( peer -> connectionKey.equals(peer.getAttribute(UndertowConstants.CONNECTION_KEY)), message, timeout, camelExchange, camelCallback); } throw new IllegalStateException( String.format("Cannot process message which has none of the headers %s, %s or %s set: %s", UndertowConstants.SEND_TO_ALL, UndertowConstants.CONNECTION_KEY_LIST, UndertowConstants.CONNECTION_KEY, in)); } else { /* nothing to do for a null body */ camelCallback.done(true); return true; } } catch (Exception e) { camelExchange.setException(e); camelCallback.done(true); return true; } } @Override protected void doStart() throws Exception { super.doStart(); // as in Undertow tests pool = new DefaultByteBufferPool(true, 17 * 1024); final Xnio xnio = Xnio.getInstance(); worker = xnio.createWorker(options); final SSLContext sslContext = getEndpoint().getSslContext(); if (sslContext != null) { ssl = new UndertowXnioSsl(xnio, options, sslContext); } client = UndertowClient.getInstance(); if (endpoint.isWebSocket()) { this.webSocketHandler = (CamelWebSocketHandler) endpoint.getComponent().registerEndpoint(null, endpoint.getHttpHandlerRegistrationInfo(), endpoint.getSslContext(), new CamelWebSocketHandler()); } LOG.debug("Created worker: {} with options: {}", worker, options); } @Override protected void doStop() throws Exception { super.doStop(); if (endpoint.isWebSocket()) { endpoint.getComponent().unregisterEndpoint(null, endpoint.getHttpHandlerRegistrationInfo(), endpoint.getSslContext()); } if (worker != null && !worker.isShutdown()) { LOG.debug("Shutting down worker: {}", worker); worker.shutdown(); } } }
UndertowProducer
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java
{ "start": 9263, "end": 9607 }
class ____ implements AnotherAnnotationTestBean { private String bar; @Override public void foo() { } @Override public String getBar() { return this.bar; } @Override public void setBar(String bar) { this.bar = bar; } @Override public int getCacheEntries() { return 0; } } }
PackagePrivateAnnotationTestBean
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/factories/c/BarFactory.java
{ "start": 356, "end": 501 }
class ____ { @ObjectFactory public Bar4 createBar4(Foo4 foo4) { return new Bar4( foo4.getProp().toUpperCase() ); } }
BarFactory
java
quarkusio__quarkus
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/BlockingNonBlockingTest.java
{ "start": 871, "end": 1968 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(BlockingHealthCheck.class, Routes.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")); @Test void testRegisterHealthOnBlockingThreadStep1() { // initial startup health blocking call on worker thread given() .when().get("/start-health") .then().statusCode(200); try { RestAssured.defaultParser = Parser.JSON; // repeat the call a few times since the block isn't always logged for (int i = 0; i < 3; i++) { RestAssured.when().get("/q/health").then() .body("status", is("UP"), "checks.status", contains("UP"), "checks.name", contains("blocking")); } } finally { RestAssured.reset(); } } @Liveness static final
BlockingNonBlockingTest
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/matchers/VerificationAndStubbingUsingMatchersTest.java
{ "start": 463, "end": 2560 }
class ____ extends TestBase { private IMethods one; private IMethods two; private IMethods three; @Before public void setUp() { one = mock(IMethods.class); two = mock(IMethods.class); three = mock(IMethods.class); } @Test public void shouldStubUsingMatchers() { when(one.simpleMethod(2)).thenReturn("2"); when(two.simpleMethod(anyString())).thenReturn("any"); when(three.simpleMethod(startsWith("test"))).thenThrow(new RuntimeException()); assertEquals(null, one.simpleMethod(1)); assertEquals("2", one.simpleMethod(2)); assertEquals("any", two.simpleMethod("two")); assertEquals("any", two.simpleMethod("two again")); assertEquals(null, three.simpleMethod("three")); assertEquals(null, three.simpleMethod("three again")); try { three.simpleMethod("test three again"); fail(); } catch (RuntimeException e) { } } @Test public void shouldVerifyUsingMatchers() { doThrow(new RuntimeException()).when(one).oneArg(true); when(three.varargsObject(5, "first arg", "second arg")).thenReturn("stubbed"); try { one.oneArg(true); fail(); } catch (RuntimeException e) { } one.simpleMethod(100); two.simpleMethod("test Mockito"); three.varargsObject(10, "first arg", "second arg"); assertEquals("stubbed", three.varargsObject(5, "first arg", "second arg")); verify(one).oneArg(eq(true)); verify(one).simpleMethod(anyInt()); verify(two).simpleMethod(startsWith("test")); verify(three).varargsObject(5, "first arg", "second arg"); verify(three).varargsObject(eq(10), eq("first arg"), startsWith("second")); verifyNoMoreInteractions(one, two, three); try { verify(three).varargsObject(eq(10), eq("first arg"), startsWith("third")); fail(); } catch (WantedButNotInvoked e) { } } }
VerificationAndStubbingUsingMatchersTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/embeddable/JoinedSubclassWithEmbeddableTest.java
{ "start": 2194, "end": 2992 }
class ____ implements Serializable { @Id @GeneratedValue private Long id; private String name; @Embedded private Contact contact; @ManyToOne @JoinColumn(name = "alert_contact") private Person alertContact; @OneToMany @JoinColumn(name = "alert_contact") private Set<Person> alerteeContacts = new HashSet<>(); @ManyToMany @OrderColumn(name = "list_idx") @JoinTable(name = "person_list") private List<Person> personList = new ArrayList<>(); @ManyToMany @CollectionTable(name = "person_map") @MapKeyColumn(name = "person_key", length = 20) private Map<String, Person> personMap = new HashMap<>(); public Person() { } public Person(String name) { this.name = name; } } @Entity(name = "Employee") @Table(name = "employees") public static
Person
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/processor/DefaultVersionInformation.java
{ "start": 7807, "end": 9618 }
class ____ moduleNameSeparator = resource.getFile().indexOf( '/', 1 ); if ( moduleNameSeparator > 1 ) { return resource.getFile().substring( 1, moduleNameSeparator ); } return resource.toExternalForm(); } private static URL createManifestUrl(String classFileName, URL resource) throws MalformedURLException { String classUrlString = resource.toExternalForm(); String baseFileUrl = classUrlString.substring( 0, classUrlString.length() - classFileName.length() ); return new URL( baseFileUrl + "META-INF/MANIFEST.MF" ); } private static String asClassFileName(String className) { return className.replace( '.', '/' ) + ".class"; } private static String extractJarFileName(String file) { int excl = file.indexOf( '!' ); if ( excl > 0 ) { String fullFileName = file.substring( 0, excl ); // it's an URL, so it's not the system path separator char: int lastPathSep = fullFileName.lastIndexOf( '/' ); if ( lastPathSep > 0 && lastPathSep < fullFileName.length() ) { return fullFileName.substring( lastPathSep + 1 ); } } return file; } private static String initMapStructVersion() { String classFileName = asClassFileName( DefaultVersionInformation.class.getName() ); URL resource = DefaultVersionInformation.class.getClassLoader().getResource( classFileName ); Manifest manifest = openManifest( classFileName, resource ); if ( null != manifest ) { String version = manifest.getMainAttributes().getValue( "Implementation-Version" ); if ( version != null ) { return version; } } return ""; } }
int
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/refresh/MergeAndRefreshTest.java
{ "start": 1162, "end": 1806 }
class ____ { @Test public void testRefresh(SessionFactoryScope scope) { Long phaseId = 1L; scope.inTransaction( session -> { PhaseDescription description = new PhaseDescription("phase 1"); Phase phase = new Phase( phaseId, description ); session.persist( phase ); } ); Phase phase = scope.fromTransaction( session -> session.find( Phase.class, phaseId ) ); scope.inTransaction( session -> { Phase merged = session.merge( phase ); session.refresh( merged ); } ); } @Entity(name = "Phase") @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public static
MergeAndRefreshTest
java
apache__flink
flink-datastream/src/test/java/org/apache/flink/datastream/impl/common/ValueTypeDescriptorTest.java
{ "start": 1690, "end": 3712 }
class ____ { @ParameterizedTest @MethodSource("valueTypeDescriptors") <T> void testValueTypeDescriptor(TypeDescriptor<T> typeDescriptor, String expectedString) throws ReflectiveOperationException { assertThat(TypeDescriptors.value(typeDescriptor).toString()).isEqualTo(expectedString); } static Object[][] valueTypeDescriptors() { return new Object[][] { { (TypeDescriptor<BooleanValue>) () -> BooleanValue.class, "ValueTypeDescriptorImpl [valueTypeInfo=ValueType<BooleanValue>]" }, { (TypeDescriptor<IntValue>) () -> IntValue.class, "ValueTypeDescriptorImpl [valueTypeInfo=ValueType<IntValue>]" }, { (TypeDescriptor<LongValue>) () -> LongValue.class, "ValueTypeDescriptorImpl [valueTypeInfo=ValueType<LongValue>]" }, { (TypeDescriptor<ShortValue>) () -> ShortValue.class, "ValueTypeDescriptorImpl [valueTypeInfo=ValueType<ShortValue>]" }, { (TypeDescriptor<FloatValue>) () -> FloatValue.class, "ValueTypeDescriptorImpl [valueTypeInfo=ValueType<FloatValue>]" }, { (TypeDescriptor<CharValue>) () -> CharValue.class, "ValueTypeDescriptorImpl [valueTypeInfo=ValueType<CharValue>]" }, { (TypeDescriptor<DoubleValue>) () -> DoubleValue.class, "ValueTypeDescriptorImpl [valueTypeInfo=ValueType<DoubleValue>]" }, }; } @Test void testValueTypeDescriptorNonValue() { assertThatThrownBy( () -> TypeDescriptors.value((TypeDescriptor<Double>) () -> Double.class) .toString()) .isInstanceOf(InvocationTargetException.class); } }
ValueTypeDescriptorTest
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableThrottleFirstTest.java
{ "start": 1309, "end": 11461 }
class ____ extends RxJavaTest { private TestScheduler scheduler; private Scheduler.Worker innerScheduler; private Subscriber<String> subscriber; @Before public void before() { scheduler = new TestScheduler(); innerScheduler = scheduler.createWorker(); subscriber = TestHelper.mockSubscriber(); } @Test public void throttlingWithDropCallbackCrashes() throws Throwable { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); publishNext(subscriber, 100, "one"); // publish as it's first publishNext(subscriber, 300, "two"); // skip as it's last within the first 400 publishNext(subscriber, 900, "three"); // publish publishNext(subscriber, 905, "four"); // skip publishCompleted(subscriber, 1000); // Should be published as soon as the timeout expires. } }); Action whenDisposed = mock(Action.class); Flowable<String> sampled = source .doOnCancel(whenDisposed) .throttleFirst(400, TimeUnit.MILLISECONDS, scheduler, e -> { if ("two".equals(e)) { throw new TestException("forced"); } }); sampled.subscribe(subscriber); InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); inOrder.verify(subscriber, times(1)).onNext("one"); inOrder.verify(subscriber, times(1)).onError(any(TestException.class)); inOrder.verify(subscriber, times(0)).onNext("two"); inOrder.verify(subscriber, times(0)).onNext("three"); inOrder.verify(subscriber, times(0)).onNext("four"); inOrder.verify(subscriber, times(0)).onComplete(); inOrder.verifyNoMoreInteractions(); verify(whenDisposed).run(); } @Test public void throttlingWithDropCallback() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); publishNext(subscriber, 100, "one"); // publish as it's first publishNext(subscriber, 300, "two"); // skip as it's last within the first 400 publishNext(subscriber, 900, "three"); // publish publishNext(subscriber, 905, "four"); // skip publishCompleted(subscriber, 1000); // Should be published as soon as the timeout expires. } }); Observer<Object> dropCallbackObserver = TestHelper.mockObserver(); Flowable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler, dropCallbackObserver::onNext); sampled.subscribe(subscriber); InOrder inOrder = inOrder(subscriber); InOrder dropCallbackOrder = inOrder(dropCallbackObserver); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); inOrder.verify(subscriber, times(1)).onNext("one"); inOrder.verify(subscriber, times(0)).onNext("two"); dropCallbackOrder.verify(dropCallbackObserver, times(1)).onNext("two"); inOrder.verify(subscriber, times(1)).onNext("three"); inOrder.verify(subscriber, times(0)).onNext("four"); dropCallbackOrder.verify(dropCallbackObserver, times(1)).onNext("four"); inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); dropCallbackOrder.verifyNoMoreInteractions(); } @Test public void throttlingWithCompleted() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); publishNext(subscriber, 100, "one"); // publish as it's first publishNext(subscriber, 300, "two"); // skip as it's last within the first 400 publishNext(subscriber, 900, "three"); // publish publishNext(subscriber, 905, "four"); // skip publishCompleted(subscriber, 1000); // Should be published as soon as the timeout expires. } }); Flowable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler); sampled.subscribe(subscriber); InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); inOrder.verify(subscriber, times(1)).onNext("one"); inOrder.verify(subscriber, times(0)).onNext("two"); inOrder.verify(subscriber, times(1)).onNext("three"); inOrder.verify(subscriber, times(0)).onNext("four"); inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void throttlingWithError() { Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); Exception error = new TestException(); publishNext(subscriber, 100, "one"); // Should be published since it is first publishNext(subscriber, 200, "two"); // Should be skipped since onError will arrive before the timeout expires publishError(subscriber, 300, error); // Should be published as soon as the timeout expires. } }); Flowable<String> sampled = source.throttleFirst(400, TimeUnit.MILLISECONDS, scheduler); sampled.subscribe(subscriber); InOrder inOrder = inOrder(subscriber); scheduler.advanceTimeTo(400, TimeUnit.MILLISECONDS); inOrder.verify(subscriber).onNext("one"); inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); } private <T> void publishCompleted(final Subscriber<T> subscriber, long delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } private <T> void publishError(final Subscriber<T> subscriber, long delay, final Exception error) { innerScheduler.schedule(new Runnable() { @Override public void run() { subscriber.onError(error); } }, delay, TimeUnit.MILLISECONDS); } private <T> void publishNext(final Subscriber<T> subscriber, long delay, final T value) { innerScheduler.schedule(new Runnable() { @Override public void run() { subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } @Test public void throttle() { Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); TestScheduler s = new TestScheduler(); PublishProcessor<Integer> o = PublishProcessor.create(); o.throttleFirst(500, TimeUnit.MILLISECONDS, s).subscribe(subscriber); // send events with simulated time increments s.advanceTimeTo(0, TimeUnit.MILLISECONDS); o.onNext(1); // deliver o.onNext(2); // skip s.advanceTimeTo(501, TimeUnit.MILLISECONDS); o.onNext(3); // deliver s.advanceTimeTo(600, TimeUnit.MILLISECONDS); o.onNext(4); // skip s.advanceTimeTo(700, TimeUnit.MILLISECONDS); o.onNext(5); // skip o.onNext(6); // skip s.advanceTimeTo(1001, TimeUnit.MILLISECONDS); o.onNext(7); // deliver s.advanceTimeTo(1501, TimeUnit.MILLISECONDS); o.onComplete(); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber).onNext(1); inOrder.verify(subscriber).onNext(3); inOrder.verify(subscriber).onNext(7); inOrder.verify(subscriber).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void throttleFirstDefaultScheduler() { Flowable.just(1).throttleFirst(100, TimeUnit.MILLISECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1); } @Test public void dispose() { TestHelper.checkDisposed(Flowable.just(1).throttleFirst(1, TimeUnit.DAYS)); } @Test public void badSource() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); subscriber.onNext(1); subscriber.onNext(2); subscriber.onComplete(); subscriber.onNext(3); subscriber.onError(new TestException()); subscriber.onComplete(); } } .throttleFirst(1, TimeUnit.DAYS) .test() .assertResult(1); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void backpressureNoRequest() { Flowable.range(1, 3) .throttleFirst(1, TimeUnit.MINUTES) .test(0L) .assertFailure(MissingBackpressureException.class); } @Test public void badRequest() { TestHelper.assertBadRequestReported(Flowable.never().throttleFirst(1, TimeUnit.MINUTES)); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(f -> f.throttleFirst(1, TimeUnit.MINUTES)); } }
FlowableThrottleFirstTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/blockhash/BlockHashRandomizedTests.java
{ "start": 16464, "end": 17284 }
class ____ implements Comparator<List<?>> { @Override public int compare(List<?> lhs, List<?> rhs) { for (int i = 0; i < lhs.size(); i++) { @SuppressWarnings("unchecked") Comparable<Object> l = (Comparable<Object>) lhs.get(i); Object r = rhs.get(i); if (l == null) { if (r == null) { continue; } else { return 1; } } if (r == null) { return -1; } int cmp = l.compareTo(r); if (cmp != 0) { return cmp; } } return 0; } } private static
KeyComparator
java
apache__maven
compat/maven-model/src/main/java/org/apache/maven/model/merge/ModelMerger.java
{ "start": 93228, "end": 93487 }
class ____ implements KeyComputer<Dependency> { @Override public Object key(Dependency dependency) { return getDependencyKey(dependency); } } /** * KeyComputer for License */ private
DependencyKeyComputer
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/inlineme/Inliner.java
{ "start": 3970, "end": 21655 }
class ____ extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher, MemberReferenceTreeMatcher { public static final String FINDING_TAG = "JavaInlineMe"; static final String PREFIX_FLAG = "InlineMe:Prefix"; static final String SKIP_COMMENTS_FLAG = "InlineMe:SkipInliningsWithComments"; private static final Splitter PACKAGE_SPLITTER = Splitter.on('.'); private static final String CHECK_FIX_COMPILES = "InlineMe:CheckFixCompiles"; private static final String INLINE_ME = "InlineMe"; private static final String VALIDATION_DISABLED = "InlineMeValidationDisabled"; private final ImmutableSet<String> apiPrefixes; private final boolean skipCallsitesWithComments; private final boolean checkFixCompiles; @Inject Inliner(ErrorProneFlags flags) { this.apiPrefixes = flags.getSetOrEmpty(PREFIX_FLAG); this.skipCallsitesWithComments = flags.getBoolean(SKIP_COMMENTS_FLAG).orElse(true); this.checkFixCompiles = flags.getBoolean(CHECK_FIX_COMPILES).orElse(false); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } String receiverString = "new " + state.getSourceForNode(tree.getIdentifier()); return match(tree, symbol, tree.getArguments(), receiverString, null, state); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } String receiverString = ""; ExpressionTree receiver = getReceiver(tree); if (receiver != null) { receiverString = state.getSourceForNode(receiver); } ExpressionTree methodSelectTree = tree.getMethodSelect(); if (methodSelectTree != null) { String methodSelect = state.getSourceForNode(methodSelectTree); if (methodSelect.equals("super")) { receiverString = methodSelect; } // TODO(kak): Can we omit the `this` case? The getReceiver() call above handles `this` if (methodSelect.equals("this")) { receiverString = methodSelect; } } return match(tree, symbol, tree.getArguments(), receiverString, receiver, state); } @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { MethodSymbol symbol = getSymbol(tree); if (symbol.isStatic()) { // TODO: b/165938605 - handle static member references return Description.NO_MATCH; } if (!hasDirectAnnotationWithSimpleName(symbol, INLINE_ME)) { return Description.NO_MATCH; } Optional<InlineMeData> inlineMeMaybe = InlineMeData.createFromSymbol(symbol); if (inlineMeMaybe.isEmpty()) { return Description.NO_MATCH; } InlineMeData inlineMe = inlineMeMaybe.get(); if (!inlineMe.imports().isEmpty() || !inlineMe.staticImports().isEmpty()) { // TODO: b/165938605 - handle imports return Description.NO_MATCH; } Api api = Api.create(symbol, state); if (!matchesApiPrefixes(api)) { return Description.NO_MATCH; } if (skipCallsitesWithComments && stringContainsComments(state.getSourceForNode(tree), state.context)) { return Description.NO_MATCH; } JavacParser parser = newParser(inlineMe.replacement(), state); if (!(parser.parseExpression() instanceof MethodInvocationTree mit && mit.getArguments().isEmpty() && getReceiver(mit) instanceof IdentifierTree it && it.getName().contentEquals("this"))) { return Description.NO_MATCH; } String identifier = ((MemberSelectTree) mit.getMethodSelect()).getIdentifier().toString(); SuggestedFix fix = SuggestedFix.replace( state.getEndPosition(tree.getQualifierExpression()), state.getEndPosition(tree), "::" + identifier); return maybeCheckFixCompiles(tree, state, fix, api); } private Description match( ExpressionTree tree, MethodSymbol symbol, List<? extends ExpressionTree> callingVars, String receiverString, ExpressionTree receiver, VisitorState state) { Optional<InlineMeData> inlineMe = InlineMeData.createFromSymbol(symbol); if (inlineMe.isEmpty()) { return Description.NO_MATCH; } Api api = Api.create(symbol, state); if (!matchesApiPrefixes(api)) { return Description.NO_MATCH; } if (skipCallsitesWithComments && stringContainsComments(state.getSourceForNode(tree), state.context)) { return Description.NO_MATCH; } ImmutableList<String> varNames = symbol.getParameters().stream() .map(varSymbol -> varSymbol.getSimpleName().toString()) .collect(toImmutableList()); ImmutableList<String> callingVarStrings; boolean varargsWithEmptyArguments = false; if (symbol.isVarArgs()) { // If we're calling a varargs method, its inlining *should* have the varargs parameter in a // reasonable position. If there are 0 arguments, we'll need to do more surgery if (callingVars.size() == varNames.size() - 1) { varargsWithEmptyArguments = true; callingVarStrings = callingVars.stream().map(state::getSourceForNode).collect(toImmutableList()); } else { List<? extends ExpressionTree> nonvarargs = callingVars.subList(0, varNames.size() - 1); String varargsJoined = callingVars.subList(varNames.size() - 1, callingVars.size()).stream() .map(state::getSourceForNode) .collect(joining(", ")); callingVarStrings = ImmutableList.<String>builderWithExpectedSize(varNames.size()) .addAll(nonvarargs.stream().map(state::getSourceForNode).collect(toImmutableList())) .add(varargsJoined) .build(); } } else { callingVarStrings = callingVars.stream().map(state::getSourceForNode).collect(toImmutableList()); } String replacement = inlineMe.get().replacement(); JavacParser parser = newParser(replacement, state); ExpressionTree replacementExpression = parser.parseExpression(); SuggestedFix.Builder replacementFixes = SuggestedFix.builder(); SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); for (String newImport : inlineMe.get().imports()) { String typeName = Iterables.getLast(PACKAGE_SPLITTER.split(newImport)); String qualifiedTypeName = SuggestedFixes.qualifyType(state, fixBuilder, newImport); visitIdentifiers( replacementExpression, (node, unused) -> { if (node.getName().contentEquals(typeName)) { replacementFixes.replace(node, qualifiedTypeName); } }); } for (String newStaticImport : inlineMe.get().staticImports()) { fixBuilder.addStaticImport(newStaticImport); } int replacementStart = getStartPosition(tree); int replacementEnd = state.getEndPosition(tree); // Special case replacements starting with "this." so the receiver portion is not included in // the replacement. This avoids overlapping replacement regions for fluent chains. boolean removedThisPrefix = replacement.startsWith("this.") && receiver != null; if (removedThisPrefix) { replacementFixes.replace(0, "this".length(), ""); replacementStart = state.getEndPosition(receiver); } if (Strings.isNullOrEmpty(receiverString)) { visitIdentifiers( replacementExpression, (node, unused) -> { if (node.getName().contentEquals("this")) { replacementFixes.replace( getStartPosition(node), parser.getEndPos((JCTree) node) + 1, ""); } }); } else { if (replacement.equals("this")) { // e.g.: foo.b() -> foo Tree parent = state.getPath().getParentPath().getLeaf(); // If the receiver is a side-effect-free expression and the whole expression is standalone, // the receiver likely can't stand on its own (e.g.: "foo;" is not a valid statement while // "foo.noOpMethod();" is). if (parent instanceof ExpressionStatementTree && !hasSideEffect(receiver)) { return describe(parent, SuggestedFix.delete(parent), api); } } visitIdentifiers( replacementExpression, (node, unused) -> { if ((!removedThisPrefix || getStartPosition(node) != 0) && node.getName().contentEquals("this")) { replacementFixes.replace( getStartPosition(node), parser.getEndPos((JCTree) node), receiverString); } }); } for (int i = 0; i < varNames.size(); i++) { String varName = varNames.get(i); // If the parameter names are missing (b/365094947), don't perform the inlining. if (InlinabilityResult.matchesArgN(varName)) { return Description.NO_MATCH; } // Ex: foo(int a, int... others) -> this.bar(a, others) // If caller passes 0 args in the varargs position, we want to remove the preceding comma to // make this.bar(a) (as opposed to "this.bar(a, )" boolean terminalVarargsReplacement = varargsWithEmptyArguments && i == varNames.size() - 1; String replacementResult = terminalVarargsReplacement ? "" : callingVarStrings.get(i); boolean mayRequireParens = i < callingVars.size() && requiresParentheses(callingVars.get(i), state); visitIdentifiers( replacementExpression, (node, path) -> { if (!node.getName().contentEquals(varName)) { return; } // Substituting into a method invocation never requires parens. boolean outerNeverRequiresParens = path.size() < 2 || getArguments(path.get(path.size() - 2)).contains(node); if (terminalVarargsReplacement) { var calledMethodArguments = getArguments(path.get(path.size() - 2)); replacementFixes.replace( calledMethodArguments.indexOf(node) == 0 ? getStartPosition(node) : parser.getEndPos( (JCTree) calledMethodArguments.get(calledMethodArguments.indexOf(node) - 1)), parser.getEndPos((JCTree) node), replacementResult); } else { replacementFixes.replace( node, !outerNeverRequiresParens && mayRequireParens ? "(" + replacementResult + ")" : replacementResult); } }); } String fixedReplacement = AppliedFix.applyReplacements(replacement, asEndPosTable(parser), replacementFixes.build()); fixBuilder.replace( replacementStart, replacementEnd, inliningRequiresParentheses(state.getPath(), replacementExpression) ? format("(%s)", fixedReplacement) : fixedReplacement); return maybeCheckFixCompiles(tree, state, fixBuilder.build(), api); } private static JavacParser newParser(String replacement, VisitorState state) { return ParserFactory.instance(state.context) .newParser( replacement, /* keepDocComments= */ true, /* keepEndPos= */ true, /* keepLineMap= */ true); } private static List<? extends ExpressionTree> getArguments(Tree tree) { return switch (tree) { case MethodInvocationTree mit -> mit.getArguments(); case NewClassTree nct -> nct.getArguments(); default -> ImmutableList.of(); }; } /** * Checks whether an expression requires parentheses when substituting in. * * <p>{@code treePath} is the original path including the old tree at the tip; {@code replacement} * is the proposed replacement tree. * * <p>This was originally from {@link com.google.errorprone.util.ASTHelpers#requiresParentheses} * but is heavily specialised for this use case. */ private static boolean inliningRequiresParentheses( TreePath treePath, ExpressionTree replacement) { var originalExpression = treePath.getLeaf(); var parent = treePath.getParentPath().getLeaf(); Optional<OperatorPrecedence> replacementPrecedence = OperatorPrecedence.optionallyFrom(replacement.getKind()); Optional<OperatorPrecedence> parentPrecedence = OperatorPrecedence.optionallyFrom(parent.getKind()); if (replacementPrecedence.isPresent() && parentPrecedence.isPresent()) { return parentPrecedence.get().isHigher(replacementPrecedence.get()); } // There are some locations, based on the parent path, where we never want to parenthesise. // This list is likely not exhaustive. switch (parent.getKind()) { case RETURN, EXPRESSION_STATEMENT -> { return false; } case VARIABLE -> { if (Objects.equals(((VariableTree) parent).getInitializer(), originalExpression)) { return false; } } case ASSIGNMENT -> { if (((AssignmentTree) parent).getExpression().equals(originalExpression)) { return false; } } case METHOD_INVOCATION, NEW_CLASS -> { if (getArguments(parent).contains(originalExpression)) { return false; } } default -> { // continue below } } switch (replacement.getKind()) { case IDENTIFIER, MEMBER_SELECT, METHOD_INVOCATION, ARRAY_ACCESS, PARENTHESIZED, NEW_CLASS, MEMBER_REFERENCE -> { return false; } default -> { // continue below } } if (replacement instanceof UnaryTree) { return parent instanceof MemberSelectTree; } return true; } private Description maybeCheckFixCompiles( ExpressionTree tree, VisitorState state, SuggestedFix fix, Api api) { if (checkFixCompiles && fix.getImportsToAdd().isEmpty()) { // If there are no new imports being added (then there are no new dependencies). Therefore, we // can verify that the fix compiles (if CHECK_FIX_COMPILES is enabled). return SuggestedFixes.compilesWithFix(fix, state) ? describe(tree, fix, api) : Description.NO_MATCH; } return describe(tree, fix, api); } private static void visitIdentifiers( Tree tree, BiConsumer<IdentifierTree, List<Tree>> identifierConsumer) { new TreeScanner<Void, Void>() { // It'd be nice to use a TreePathScanner, but we don't have CompilationUnit-rooted AST. private final List<Tree> path = new ArrayList<>(); @Override public Void scan(Tree tree, Void unused) { if (tree != null) { path.add(tree); super.scan(tree, null); path.remove(path.size() - 1); } return null; } @Override public Void visitIdentifier(IdentifierTree node, Void unused) { identifierConsumer.accept(node, path); return super.visitIdentifier(node, null); } }.scan(tree, null); } private static ImmutableList<String> getStrings(Attribute.Compound attribute, String name) { return getValue(attribute, name) .map(MoreAnnotations::asStrings) .orElse(Stream.empty()) .collect(toImmutableList()); } private Description describe(Tree tree, SuggestedFix fix, Api api) { return buildDescription(tree).setMessage(api.message()).addFix(fix).build(); } private record Api( String className, String methodName, String packageName, boolean isConstructor, boolean isDeprecated, String extraMessage) { private static final Splitter CLASS_NAME_SPLITTER = Splitter.on('.'); static Api create(MethodSymbol method, VisitorState state) { String extraMessage = ""; if (hasDirectAnnotationWithSimpleName(method, VALIDATION_DISABLED)) { Attribute.Compound inlineMeValidationDisabled = method.getRawAttributes().stream() .filter(a -> a.type.tsym.getSimpleName().contentEquals(VALIDATION_DISABLED)) .collect(onlyElement()); String reason = Iterables.getOnlyElement(getStrings(inlineMeValidationDisabled, "value")); extraMessage = " NOTE: this is an unvalidated inlining! Reasoning: " + reason; } return new Api( method.owner.getQualifiedName().toString(), method.getSimpleName().toString(), enclosingPackage(method).toString(), method.isConstructor(), hasAnnotation(method, "java.lang.Deprecated", state), extraMessage); } final String message() { return "Migrate (via inlining) away from " + (isDeprecated() ? "deprecated " : "") + shortName() + "." + extraMessage(); } /** Returns {@code FullyQualifiedClassName#methodName}. */ final String methodId() { return format("%s#%s", className(), methodName()); } /** * Returns a short, human readable description of this API in markdown format (e.g., {@code * `ClassName.methodName()`}). */ final String shortName() { String humanReadableClassName = className().replaceFirst(packageName() + ".", ""); return format("`%s.%s()`", humanReadableClassName, methodName()); } /** Returns the simple
Inliner
java
elastic__elasticsearch
modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RestRankEvalAction.java
{ "start": 2553, "end": 4501 }
class ____ extends BaseRestHandler { public static final String ENDPOINT = "_rank_eval"; private Predicate<NodeFeature> clusterSupportsFeature; public RestRankEvalAction(Predicate<NodeFeature> clusterSupportsFeature) { this.clusterSupportsFeature = clusterSupportsFeature; } @Override public List<Route> routes() { return List.of( new Route(GET, "/" + ENDPOINT), new Route(POST, "/" + ENDPOINT), new Route(GET, "/{index}/" + ENDPOINT), new Route(POST, "/{index}/" + ENDPOINT) ); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { RankEvalRequest rankEvalRequest = new RankEvalRequest(); try (XContentParser parser = request.contentOrSourceParamParser()) { parseRankEvalRequest(rankEvalRequest, request, parser, clusterSupportsFeature); } return channel -> client.executeLocally( RankEvalPlugin.ACTION, rankEvalRequest, new RestToXContentListener<RankEvalResponse>(channel) ); } private static void parseRankEvalRequest( RankEvalRequest rankEvalRequest, RestRequest request, XContentParser parser, Predicate<NodeFeature> clusterSupportsFeature ) { rankEvalRequest.indices(Strings.splitStringByCommaToArray(request.param("index"))); rankEvalRequest.indicesOptions(IndicesOptions.fromRequest(request, rankEvalRequest.indicesOptions())); if (request.hasParam("search_type")) { rankEvalRequest.searchType(SearchType.fromString(request.param("search_type"))); } RankEvalSpec spec = RankEvalSpec.parse(parser, clusterSupportsFeature); rankEvalRequest.setRankEvalSpec(spec); } @Override public String getName() { return "rank_eval_action"; } }
RestRankEvalAction
java
grpc__grpc-java
core/src/test/java/io/grpc/internal/AbstractClientStreamTest.java
{ "start": 20978, "end": 23226 }
class ____ extends AbstractClientStream { private final TransportState state; private final Sink sink; public BaseAbstractClientStream( WritableBufferAllocator allocator, StatsTraceContext statsTraceCtx, TransportTracer transportTracer) { this( allocator, new BaseTransportState(statsTraceCtx, transportTracer), new BaseSink(), statsTraceCtx, transportTracer); } public BaseAbstractClientStream( WritableBufferAllocator allocator, TransportState state, Sink sink, StatsTraceContext statsTraceCtx, TransportTracer transportTracer) { this(allocator, state, sink, statsTraceCtx, transportTracer, false); } public BaseAbstractClientStream( WritableBufferAllocator allocator, TransportState state, Sink sink, StatsTraceContext statsTraceCtx, TransportTracer transportTracer, boolean useGet) { this(allocator, state, sink, statsTraceCtx, transportTracer, CallOptions.DEFAULT, useGet); } public BaseAbstractClientStream( WritableBufferAllocator allocator, TransportState state, Sink sink, StatsTraceContext statsTraceCtx, TransportTracer transportTracer, CallOptions callOptions, boolean useGet) { super(allocator, statsTraceCtx, transportTracer, new Metadata(), callOptions, useGet); this.state = state; this.sink = sink; if (callOptions.getOnReadyThreshold() != null) { this.transportState().setOnReadyThreshold(callOptions.getOnReadyThreshold()); } } @Override protected Sink abstractClientStreamSink() { return sink; } @Override public TransportState transportState() { return state; } @Override public void setAuthority(String authority) {} @Override public void setMaxInboundMessageSize(int maxSize) {} @Override public void setMaxOutboundMessageSize(int maxSize) {} @Override public Attributes getAttributes() { return Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, SERVER_ADDR).build(); } } private static
BaseAbstractClientStream
java
google__dagger
javatests/dagger/grpc/functional/server/CoffeeServerWithUnscopedService.java
{ "start": 1123, "end": 1289 }
class ____ extends CoffeeServer<CoffeeServerWithUnscopedService> implements FriendlyBaristaServiceDefinition { @Component.Builder
CoffeeServerWithUnscopedService
java
greenrobot__EventBus
EventBusTest/src/org/greenrobot/eventbus/indexed/EventBusCancelEventDeliveryTestWithIndex.java
{ "start": 786, "end": 986 }
class ____ extends EventBusCancelEventDeliveryTest { @Before public void overwriteEventBus() throws Exception { eventBus = Indexed.build(); } }
EventBusCancelEventDeliveryTestWithIndex
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/uniqueconstraint/UniqueConstraintNameTest.java
{ "start": 1006, "end": 1377 }
class ____ { @Test void test(SessionFactoryScope scope) { scope.getSessionFactory(); } @Entity @Table(name = "my_entity", uniqueConstraints = @UniqueConstraint( name = "my_other_entity_id_unique", columnNames = "my_other_entity_id" ), indexes = @Index(name = "some_long_index", columnList = "some_long")) static
UniqueConstraintNameTest
java
mockito__mockito
mockito-core/src/main/java/org/mockito/session/MockitoSessionBuilder.java
{ "start": 394, "end": 562 }
interface ____ {@code MockitoSession} objects. * See the documentation and examples in Javadoc for {@link MockitoSession}. * * @since 2.7.0 */ @NotExtensible public
for
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/InflightRepository.java
{ "start": 1133, "end": 6533 }
interface ____ { /** * The exchange being inflight */ Exchange getExchange(); /** * The duration in millis the exchange has been inflight */ long getDuration(); /** * The elapsed time in millis processing the exchange at the current node */ long getElapsed(); /** * The id of the node from the route where the exchange currently is being processed * <p/> * Is <tt>null</tt> if message history is disabled. */ String getNodeId(); /** * The id of the route where the exchange originates (started) */ String getFromRouteId(); /** * Whether the endpoint is remote where the exchange originates (started) */ boolean isFromRemoteEndpoint(); /** * The id of the route where the exchange currently is being processed * <p/> * Is <tt>null</tt> if message history is disabled. */ String getAtRouteId(); } /** * Adds the exchange to the inflight registry to the total counter * * @param exchange the exchange */ void add(Exchange exchange); /** * Removes the exchange from the inflight registry to the total counter * * @param exchange the exchange */ void remove(Exchange exchange); /** * Adds the exchange to the inflight registry associated to the given route * * @param exchange the exchange * @param routeId the id of the route */ void add(Exchange exchange, String routeId); /** * Removes the exchange from the inflight registry removing association to the given route * * @param exchange the exchange * @param routeId the id of the route */ void remove(Exchange exchange, String routeId); /** * Current size of inflight exchanges. * <p/> * Will return 0 if there are no inflight exchanges. * * @return number of exchanges currently in flight. */ int size(); /** * Adds the route from the in flight registry. * <p/> * Is used for initializing up resources * * @param routeId the id of the route */ void addRoute(String routeId); /** * Removes the route from the in flight registry. * <p/> * Is used for cleaning up resources to avoid leaking. * * @param routeId the id of the route */ void removeRoute(String routeId); /** * Current size of inflight exchanges which are from the given route. * <p/> * Will return 0 if there are no inflight exchanges. * * @param routeId the id of the route * @return number of exchanges currently in flight. */ int size(String routeId); /** * Whether the inflight repository should allow browsing each inflight exchange. * * This is by default disabled as there is a very slight performance overhead when enabled. */ boolean isInflightBrowseEnabled(); /** * Whether the inflight repository should allow browsing each inflight exchange. * * This is by default disabled as there is a very slight performance overhead when enabled. * * @param inflightBrowseEnabled whether browsing is enabled */ void setInflightBrowseEnabled(boolean inflightBrowseEnabled); /** * A <i>read-only</i> browser of the {@link InflightExchange}s that are currently inflight. */ Collection<InflightExchange> browse(); /** * A <i>read-only</i> browser of the {@link InflightExchange}s that are currently inflight that started from the * given route. * * @param fromRouteId the route id, or <tt>null</tt> for all routes. */ Collection<InflightExchange> browse(String fromRouteId); /** * A <i>read-only</i> browser of the {@link InflightExchange}s that are currently inflight. * * @param limit maximum number of entries to return * @param sortByLongestDuration to sort by the longest duration. Set to <tt>true</tt> to include the exchanges that * has been inflight the longest time, set to <tt>false</tt> to sort by exchange id */ Collection<InflightExchange> browse(int limit, boolean sortByLongestDuration); /** * A <i>read-only</i> browser of the {@link InflightExchange}s that are currently inflight that started from the * given route. * * @param fromRouteId the route id, or <tt>null</tt> for all routes. * @param limit maximum number of entries to return * @param sortByLongestDuration to sort by the longest duration. Set to <tt>true</tt> to include the exchanges that * has been inflight the longest time, set to <tt>false</tt> to sort by exchange id */ Collection<InflightExchange> browse(String fromRouteId, int limit, boolean sortByLongestDuration); /** * Gets the oldest {@link InflightExchange} that are currently inflight that started from the given route. * * @param fromRouteId the route id, or <tt>null</tt> for all routes. * @return the oldest, or <tt>null</tt> if none inflight */ InflightExchange oldest(String fromRouteId); }
InflightExchange
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/EmbeddableInheritanceHierarchyOrderTest.java
{ "start": 4423, "end": 4773 }
class ____ extends Animal { private String mother; public Mammal() { } public Mammal(int age, String name, String mother) { super( age, name ); this.mother = mother; } public String getMother() { return mother; } public void setMother(String mother) { this.mother = mother; } } @Entity(name = "Owner") static
Mammal
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDematerializeTest.java
{ "start": 1029, "end": 4079 }
class ____ extends RxJavaTest { @Test public void success() { Maybe.just(Notification.createOnNext(1)) .dematerialize(Functions.<Notification<Integer>>identity()) .test() .assertResult(1); } @Test public void empty() { Maybe.just(Notification.<Integer>createOnComplete()) .dematerialize(Functions.<Notification<Integer>>identity()) .test() .assertResult(); } @Test public void emptySource() throws Throwable { @SuppressWarnings("unchecked") Function<Notification<Integer>, Notification<Integer>> function = mock(Function.class); Maybe.<Notification<Integer>>empty() .dematerialize(function) .test() .assertResult(); verify(function, never()).apply(any()); } @Test public void error() { Maybe.<Notification<Integer>>error(new TestException()) .dematerialize(Functions.<Notification<Integer>>identity()) .test() .assertFailure(TestException.class); } @Test public void errorNotification() { Maybe.just(Notification.<Integer>createOnError(new TestException())) .dematerialize(Functions.<Notification<Integer>>identity()) .test() .assertFailure(TestException.class); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Object>, MaybeSource<Object>>() { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public MaybeSource<Object> apply(Maybe<Object> v) throws Exception { return v.dematerialize((Function)Functions.identity()); } }); } @Test public void dispose() { TestHelper.checkDisposed(MaybeSubject.<Notification<Integer>>create().dematerialize(Functions.<Notification<Integer>>identity())); } @Test public void selectorCrash() { Maybe.just(Notification.createOnNext(1)) .dematerialize(new Function<Notification<Integer>, Notification<Integer>>() { @Override public Notification<Integer> apply(Notification<Integer> v) throws Exception { throw new TestException(); } }) .test() .assertFailure(TestException.class); } @Test public void selectorNull() { Maybe.just(Notification.createOnNext(1)) .dematerialize(Functions.justFunction((Notification<Integer>)null)) .test() .assertFailure(NullPointerException.class); } @Test public void selectorDifferentType() { Maybe.just(Notification.createOnNext(1)) .dematerialize(new Function<Notification<Integer>, Notification<String>>() { @Override public Notification<String> apply(Notification<Integer> v) throws Exception { return Notification.createOnNext("Value-" + 1); } }) .test() .assertResult("Value-1"); } }
MaybeDematerializeTest
java
hibernate__hibernate-orm
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/HANALegacySqlAstTranslator.java
{ "start": 2097, "end": 11180 }
class ____<T extends JdbcOperation> extends AbstractSqlAstTranslator<T> { private boolean inLateral; public HANALegacySqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) { super( sessionFactory, statement ); } @Override public void visitBinaryArithmeticExpression(BinaryArithmeticExpression arithmeticExpression) { if ( isIntegerDivisionEmulationRequired( arithmeticExpression ) ) { appendSql( "cast(" ); visitArithmeticOperand( arithmeticExpression.getLeftHandOperand() ); appendSql( arithmeticExpression.getOperator().getOperatorSqlTextString() ); visitArithmeticOperand( arithmeticExpression.getRightHandOperand() ); appendSql( " as int)" ); } else { super.visitBinaryArithmeticExpression( arithmeticExpression ); } } @Override protected void visitArithmeticOperand(Expression expression) { render( expression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER ); } private boolean isHanaCloud() { return ( (HANALegacyDialect) getDialect() ).isCloud(); } @Override protected void visitInsertStatementOnly(InsertSelectStatement statement) { if ( statement.getConflictClause() == null || statement.getConflictClause().isDoNothing() ) { // Render plain insert statement and possibly run into unique constraint violation super.visitInsertStatementOnly( statement ); } else { visitInsertStatementEmulateMerge( statement ); } } @Override protected void visitUpdateStatementOnly(UpdateStatement statement) { // HANA Cloud does not support the FROM clause in UPDATE statements if ( isHanaCloud() && hasNonTrivialFromClause( statement.getFromClause() ) ) { visitUpdateStatementEmulateMerge( statement ); } else { super.visitUpdateStatementOnly( statement ); } } @Override protected void renderUpdateClause(UpdateStatement updateStatement) { // HANA Cloud does not support the FROM clause in UPDATE statements if ( isHanaCloud() ) { super.renderUpdateClause( updateStatement ); } else { appendSql( "update" ); final Stack<Clause> clauseStack = getClauseStack(); try { clauseStack.push( Clause.UPDATE ); renderTableReferenceIdentificationVariable( updateStatement.getTargetTable() ); } finally { clauseStack.pop(); } } } @Override protected void renderFromClauseAfterUpdateSet(UpdateStatement statement) { // HANA Cloud does not support the FROM clause in UPDATE statements if ( !isHanaCloud() ) { if ( statement.getFromClause().getRoots().isEmpty() ) { appendSql( " from " ); renderDmlTargetTableExpression( statement.getTargetTable() ); } else { visitFromClause( statement.getFromClause() ); } } } @Override protected void renderDmlTargetTableExpression(NamedTableReference tableReference) { super.renderDmlTargetTableExpression( tableReference ); if ( getClauseStack().getCurrent() != Clause.INSERT ) { renderTableReferenceIdentificationVariable( tableReference ); } } @Override protected void visitConflictClause(ConflictClause conflictClause) { if ( conflictClause != null ) { if ( conflictClause.isDoUpdate() && conflictClause.getConstraintName() != null ) { throw new IllegalQueryOperationException( "Insert conflict 'do update' clause with constraint name is not supported" ); } } } protected boolean shouldEmulateFetchClause(QueryPart queryPart) { // HANA only supports the LIMIT + OFFSET syntax but also window functions // Check if current query part is already row numbering to avoid infinite recursion return useOffsetFetchClause( queryPart ) && getQueryPartForRowNumbering() != queryPart && !isRowsOnlyFetchClauseType( queryPart ); } @Override protected boolean isCorrelated(CteStatement cteStatement) { // Report false here, because apparently HANA does not need the "lateral" keyword to correlate a from clause subquery in a subquery return false; } @Override public void visitQueryGroup(QueryGroup queryGroup) { if ( shouldEmulateFetchClause( queryGroup ) ) { emulateFetchOffsetWithWindowFunctions( queryGroup, true ); } else { super.visitQueryGroup( queryGroup ); } } @Override public void visitQuerySpec(QuerySpec querySpec) { if ( shouldEmulateFetchClause( querySpec ) ) { emulateFetchOffsetWithWindowFunctions( querySpec, true ); } else { super.visitQuerySpec( querySpec ); } } @Override public void visitQueryPartTableReference(QueryPartTableReference tableReference) { if ( tableReference.isLateral() && !inLateral ) { inLateral = true; emulateQueryPartTableReferenceColumnAliasing( tableReference ); inLateral = false; } else { emulateQueryPartTableReferenceColumnAliasing( tableReference ); } } @Override protected void renderDerivedTableReference(DerivedTableReference tableReference) { if ( tableReference instanceof FunctionTableReference && tableReference.isLateral() ) { // No need for a lateral keyword for functions tableReference.accept( this ); } else { super.renderDerivedTableReference( tableReference ); } } @Override public void renderNamedSetReturningFunction(String functionName, List<? extends SqlAstNode> sqlAstArguments, AnonymousTupleTableGroupProducer tupleType, String tableIdentifierVariable, SqlAstNodeRenderingMode argumentRenderingMode) { final ModelPart ordinalitySubPart = tupleType.findSubPart( CollectionPart.Nature.INDEX.getName(), null ); if ( ordinalitySubPart != null ) { appendSql( "(select t.*, row_number() over() " ); appendSql( ordinalitySubPart.asBasicValuedModelPart().getSelectionExpression() ); appendSql( " from " ); renderSimpleNamedFunction( functionName, sqlAstArguments, argumentRenderingMode ); append( " t)" ); } else { super.renderNamedSetReturningFunction( functionName, sqlAstArguments, tupleType, tableIdentifierVariable, argumentRenderingMode ); } } @Override protected SqlAstNodeRenderingMode getParameterRenderingMode() { // HANA does not support parameters in lateral subqueries for some reason, so inline all the parameters in this case return inLateral ? SqlAstNodeRenderingMode.INLINE_ALL_PARAMETERS : super.getParameterRenderingMode(); } @Override public void visitOffsetFetchClause(QueryPart queryPart) { if ( !isRowNumberingCurrentQueryPart() ) { renderLimitOffsetClause( queryPart ); } } @Override protected void renderComparison(Expression lhs, ComparisonOperator operator, Expression rhs) { // In SAP HANA, LOBs are not "comparable", so we have to use a like predicate for comparison final boolean isLob = isLob( lhs.getExpressionType() ); if ( operator == ComparisonOperator.DISTINCT_FROM || operator == ComparisonOperator.NOT_DISTINCT_FROM ) { if ( isLob ) { switch ( operator ) { case DISTINCT_FROM: appendSql( "case when " ); lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); appendSql( " or " ); lhs.accept( this ); appendSql( " is null and " ); rhs.accept( this ); appendSql( " is null then 0 else 1 end=1" ); return; case NOT_DISTINCT_FROM: appendSql( "case when " ); lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); appendSql( " or " ); lhs.accept( this ); appendSql( " is null and " ); rhs.accept( this ); appendSql( " is null then 0 else 1 end=0" ); return; default: // Fall through break; } } // HANA does not support plain parameters in the select clause of the intersect emulation withParameterRenderingMode( SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER, () -> renderComparisonEmulateIntersect( lhs, operator, rhs ) ); } else { if ( isLob ) { switch ( operator ) { case EQUAL: lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); return; case NOT_EQUAL: lhs.accept( this ); appendSql( " not like " ); rhs.accept( this ); return; default: // Fall through break; } } renderComparisonStandard( lhs, operator, rhs ); } } @Override protected void renderPartitionItem(Expression expression) { if ( expression instanceof Literal ) { appendSql( "grouping sets (())" ); } else if ( expression instanceof Summarization ) { throw new UnsupportedOperationException( "Summarization is not supported by DBMS" ); } else { expression.accept( this ); } } @Override protected void renderInsertIntoNoColumns(TableInsertStandard tableInsert) { throw new MappingException( String.format( "The INSERT statement for table [%s] contains no column, and this is not supported by [%s]", tableInsert.getMutatingTable().getTableId(), getDialect() ) ); } @Override protected void visitValuesList(List<Values> valuesList) { visitValuesListEmulateSelectUnion( valuesList ); } @Override public void visitValuesTableReference(ValuesTableReference tableReference) { emulateValuesTableReferenceColumnAliasing( tableReference ); } }
HANALegacySqlAstTranslator
java
quarkusio__quarkus
integration-tests/main/src/main/java/io/quarkus/it/rest/ApplicationFooProvider.java
{ "start": 482, "end": 1094 }
class ____ implements MessageBodyWriter<String> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return mediaType.equals(new MediaType("application", "foo")); } @Override public void writeTo(String s, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write((s + "-foo").getBytes(StandardCharsets.UTF_8)); } }
ApplicationFooProvider
java
apache__flink
flink-rpc/flink-rpc-akka/src/main/java/org/apache/flink/runtime/rpc/pekko/RobustActorSystem.java
{ "start": 4396, "end": 5882 }
class ____ implements Thread.UncaughtExceptionHandler { private final AtomicBoolean shutdownComplete = new AtomicBoolean(); private final Thread.UncaughtExceptionHandler uncaughtExceptionHandler; public PostShutdownClassLoadingErrorFilter( Thread.UncaughtExceptionHandler uncaughtExceptionHandler) { this.uncaughtExceptionHandler = uncaughtExceptionHandler; } public void notifyShutdownComplete() { shutdownComplete.set(true); } @Override public void uncaughtException(Thread t, Throwable e) { if (shutdownComplete.get() && (e instanceof NoClassDefFoundError || e instanceof ClassNotFoundException)) { // ignore classloading errors after the actor system terminated // some parts of the pekko shutdown procedure are not tied to the actor // system termination future, and can occasionally fail if the rpc // classloader has been closed. return; } uncaughtExceptionHandler.uncaughtException(t, e); } } private static <T> Optional<T> toJavaOptional(Option<T> option) { return Optional.ofNullable(option.getOrElse(() -> null)); } private static <T> Option<T> toScalaOption(Optional<T> option) { return option.map(Option::apply).orElse(Option.empty()); } }
PostShutdownClassLoadingErrorFilter
java
apache__camel
components/camel-docker/src/test/java/org/apache/camel/component/docker/headers/CreateImageCmdHeaderTest.java
{ "start": 1395, "end": 2267 }
class ____ extends BaseDockerHeaderTest<CreateImageCmd> { @Mock private CreateImageCmd mockObject; @Mock private InputStream inputStream; @Test void createImageHeaderTest() { String repository = "docker/empty"; Map<String, Object> headers = getDefaultParameters(); headers.put(DockerConstants.DOCKER_REPOSITORY, repository); template.sendBodyAndHeaders("direct:in", inputStream, headers); Mockito.verify(dockerClient, Mockito.times(1)).createImageCmd(eq(repository), any(InputStream.class)); } @Override protected void setupMocks() { Mockito.when(dockerClient.createImageCmd(anyString(), any(InputStream.class))).thenReturn(mockObject); } @Override protected DockerOperation getOperation() { return DockerOperation.CREATE_IMAGE; } }
CreateImageCmdHeaderTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/dirty/DynamicUpdateTest.java
{ "start": 3055, "end": 3798 }
class ____ { @Id private Long id; private String description; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) private Payment payment; public StuffToPay() { } public StuffToPay(Long id) { this.id = id; } public void confirmPayment() { payment.confirmPayment( LocalDate.now() ); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Payment getPayment() { return payment; } public void setPayment(Payment payment) { this.payment = payment; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } }
StuffToPay
java
apache__maven
compat/maven-model/src/main/java/org/apache/maven/model/io/xpp3/MavenXpp3ReaderEx.java
{ "start": 2403, "end": 2832 }
interface ____ { /** * Interpolate the value read from the xpp3 document * * @param source the source value * @param fieldName a description of the field being interpolated. The implementation may use this to * log stuff * @return the interpolated value */ String transform(String source, String fieldName); } }
ContentTransformer
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractStickyAssignor.java
{ "start": 21892, "end": 26278 }
class ____ { private final Map<String, String> consumerRacks; private final Map<TopicPartition, Set<String>> partitionRacks; private final Map<TopicPartition, Integer> numConsumersByPartition; public RackInfo(List<PartitionInfo> partitionInfos, Map<String, Subscription> subscriptions) { List<Subscription> consumers = new ArrayList<>(subscriptions.values()); Map<String, List<String>> consumersByRack = new HashMap<>(); subscriptions.forEach((memberId, subscription) -> subscription.rackId().filter(r -> !r.isEmpty()).ifPresent(rackId -> put(consumersByRack, rackId, memberId))); Map<String, List<TopicPartition>> partitionsByRack; Map<TopicPartition, Set<String>> partitionRacks; if (consumersByRack.isEmpty()) { partitionsByRack = Collections.emptyMap(); partitionRacks = Collections.emptyMap(); } else { partitionRacks = new HashMap<>(partitionInfos.size()); partitionsByRack = new HashMap<>(); partitionInfos.forEach(p -> { TopicPartition tp = new TopicPartition(p.topic(), p.partition()); Set<String> racks = new HashSet<>(p.replicas().length); partitionRacks.put(tp, racks); Arrays.stream(p.replicas()) .map(Node::rack) .filter(Objects::nonNull) .distinct() .forEach(rackId -> { put(partitionsByRack, rackId, tp); racks.add(rackId); }); }); } if (useRackAwareAssignment(consumersByRack.keySet(), partitionsByRack.keySet(), partitionRacks)) { this.consumerRacks = new HashMap<>(consumers.size()); consumersByRack.forEach((rack, rackConsumers) -> rackConsumers.forEach(c -> consumerRacks.put(c, rack))); this.partitionRacks = partitionRacks; } else { this.consumerRacks = Collections.emptyMap(); this.partitionRacks = Collections.emptyMap(); } numConsumersByPartition = partitionRacks.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().stream() .map(r -> consumersByRack.getOrDefault(r, Collections.emptyList()).size()) .reduce(0, Integer::sum))); } private boolean racksMismatch(String consumer, TopicPartition tp) { String consumerRack = consumerRacks.get(consumer); Set<String> replicaRacks = partitionRacks.get(tp); return consumerRack != null && (replicaRacks == null || !replicaRacks.contains(consumerRack)); } private List<TopicPartition> sortPartitionsByRackConsumers(List<TopicPartition> partitions) { if (numConsumersByPartition.isEmpty()) return partitions; // Return a sorted linked list of partitions to enable fast updates during rack-aware assignment List<TopicPartition> sortedPartitions = new LinkedList<>(partitions); sortedPartitions.sort(Comparator.comparing(tp -> numConsumersByPartition.getOrDefault(tp, 0))); return sortedPartitions; } private int nextRackConsumer(TopicPartition tp, List<String> consumerList, int firstIndex) { Set<String> racks = partitionRacks.get(tp); if (racks == null || racks.isEmpty()) return -1; for (int i = 0; i < consumerList.size(); i++) { int index = (firstIndex + i) % consumerList.size(); String consumer = consumerList.get(index); String consumerRack = consumerRacks.get(consumer); if (consumerRack != null && racks.contains(consumerRack)) return index; } return -1; } @Override public String toString() { return "RackInfo(" + "consumerRacks=" + consumerRacks + ", partitionRacks=" + partitionRacks + ")"; } } private abstract
RackInfo
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/FirstBytesRefByTimestampAggregatorFunctionSupplier.java
{ "start": 663, "end": 1760 }
class ____ implements AggregatorFunctionSupplier { public FirstBytesRefByTimestampAggregatorFunctionSupplier() { } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return FirstBytesRefByTimestampAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return FirstBytesRefByTimestampGroupingAggregatorFunction.intermediateStateDesc(); } @Override public FirstBytesRefByTimestampAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { return FirstBytesRefByTimestampAggregatorFunction.create(driverContext, channels); } @Override public FirstBytesRefByTimestampGroupingAggregatorFunction groupingAggregator( DriverContext driverContext, List<Integer> channels) { return FirstBytesRefByTimestampGroupingAggregatorFunction.create(channels, driverContext); } @Override public String describe() { return FirstBytesRefByTimestampAggregator.describe(); } }
FirstBytesRefByTimestampAggregatorFunctionSupplier
java
grpc__grpc-java
core/src/test/java/io/grpc/internal/PickFirstLeafLoadBalancerTest.java
{ "start": 148399, "end": 149902 }
class ____ extends LoadBalancer.Helper { private final List<Subchannel> subchannels; public MockHelperImpl(List<? extends Subchannel> subchannels) { this.subchannels = new ArrayList<Subchannel>(subchannels); } @Override public ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority) { return null; } @Override public String getAuthority() { return null; } @Override public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) { // ignore } @Override public SynchronizationContext getSynchronizationContext() { return syncContext; } @Override public ScheduledExecutorService getScheduledExecutorService() { return fakeClock.getScheduledExecutorService(); } @Override public void refreshNameResolution() { // noop } @Override public Subchannel createSubchannel(CreateSubchannelArgs args) { for (int i = 0; i < subchannels.size(); i++) { Subchannel subchannel = subchannels.get(i); List<EquivalentAddressGroup> addrs = subchannel.getAllAddresses(); verify(subchannel, atLeast(1)).getAllAddresses(); // ignore the interaction if (!args.getAddresses().equals(addrs)) { continue; } subchannels.remove(i); return subchannel; } throw new IllegalArgumentException("Unexpected addresses: " + args.getAddresses()); } } }
MockHelperImpl
java
elastic__elasticsearch
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/checkpoint/CheckpointClient.java
{ "start": 1244, "end": 3630 }
interface ____ { /** * Execute {@link GetIndexAction}. */ void getIndex(GetIndexRequest request, ActionListener<GetIndexResponse> listener); /** * Execute {@link IndicesStatsAction}. */ void getIndicesStats(IndicesStatsRequest request, ActionListener<IndicesStatsResponse> listener); /** * Execute {@link GetCheckpointAction}. */ void getCheckpoint(GetCheckpointAction.Request request, ActionListener<GetCheckpointAction.Response> listener); /** * Construct a {@link CheckpointClient} which executes its requests on the local cluster. */ static CheckpointClient local(ElasticsearchClient client) { return new CheckpointClient() { @Override public void getIndex(GetIndexRequest request, ActionListener<GetIndexResponse> listener) { client.execute(GetIndexAction.INSTANCE, request, listener); } @Override public void getIndicesStats(IndicesStatsRequest request, ActionListener<IndicesStatsResponse> listener) { client.execute(IndicesStatsAction.INSTANCE, request, listener); } @Override public void getCheckpoint(GetCheckpointAction.Request request, ActionListener<GetCheckpointAction.Response> listener) { client.execute(GetCheckpointAction.INSTANCE, request, listener); } }; } /** * Construct a {@link CheckpointClient} which executes its requests on a remote cluster. */ static CheckpointClient remote(RemoteClusterClient client) { return new CheckpointClient() { @Override public void getIndex(GetIndexRequest request, ActionListener<GetIndexResponse> listener) { client.execute(GetIndexAction.REMOTE_TYPE, request, listener); } @Override public void getIndicesStats(IndicesStatsRequest request, ActionListener<IndicesStatsResponse> listener) { client.execute(IndicesStatsAction.REMOTE_TYPE, request, listener); } @Override public void getCheckpoint(GetCheckpointAction.Request request, ActionListener<GetCheckpointAction.Response> listener) { client.execute(GetCheckpointAction.REMOTE_TYPE, request, listener); } }; } }
CheckpointClient
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/kotlin/Issue1547.java
{ "start": 246, "end": 636 }
class ____ extends TestCase { public void test_user() throws Exception { ExtClassLoader classLoader = new ExtClassLoader(); Class clazz = classLoader.loadClass("Head"); Object head = JSON.parseObject("{\"msg\":\"mmm\",\"code\":\"ccc\"}", clazz); assertEquals("{\"code\":\"ccc\",\"msg\":\"mmm\"}", JSON.toJSONString(head)); } public static
Issue1547
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_filteredOn_notIn_Test.java
{ "start": 1105, "end": 4267 }
class ____ extends ObjectArrayAssert_filtered_baseTest { @Test void should_apply_notIn_filter() { assertThat(employees).filteredOn("age", notIn(800, 10)).containsOnly(luke); assertThat(employees).filteredOn("age", notIn(800)).containsOnly(luke, noname); } @Test void should_filter_object_array_under_test_on_property_not_backed_by_a_field_values() { assertThat(employees).filteredOn("adult", notIn(false)).containsOnly(yoda, obiwan, luke); assertThat(employees).filteredOn("adult", notIn(true)).containsOnly(noname); assertThat(employees).filteredOn("adult", notIn(true, false)).isEmpty(); } @Test void should_filter_object_array_under_test_on_public_field_values() { assertThat(employees).filteredOn("id", notIn(2L, 3L, 4L)).containsOnly(yoda); } @Test void should_filter_object_array_under_test_on_private_field_values() { assertThat(employees).filteredOn("city", notIn("Paris")).containsOnly(yoda, obiwan, luke, noname); assertThat(employees).filteredOn("city", notIn("New York")).isEmpty(); assertThat(employees).filteredOn("city", notIn("New York", "Paris")).isEmpty(); } @Test void should_fail_if_filter_is_on_private_field_and_reading_private_field_is_disabled() { setAllowExtractingPrivateFields(false); try { assertThatExceptionOfType(IntrospectionError.class).isThrownBy(() -> { assertThat(employees).filteredOn("city", notIn("New York")).isEmpty(); }); } finally { setAllowExtractingPrivateFields(true); } } @Test void should_filter_object_array_under_test_on_nested_property_values() { assertThat(employees).filteredOn("name.first", notIn("Luke")).containsOnly(yoda, obiwan, noname); } @Test void should_filter_object_array_under_test_on_nested_mixed_property_and_field_values() { assertThat(employees).filteredOn("name.last", notIn("Skywalker")).containsOnly(yoda, obiwan, noname); assertThat(employees).filteredOn("name.last", notIn("Skywalker", null)).isEmpty(); assertThat(employees).filteredOn("name.last", notIn("Vader")).containsOnly(yoda, obiwan, noname, luke); } @Test void should_fail_if_given_property_or_field_name_is_null() { assertThatIllegalArgumentException().isThrownBy(() -> assertThat(employees).filteredOn((String) null, notIn(800))) .withMessage("The property/field name to filter on should not be null or empty"); } @Test void should_fail_if_given_property_or_field_name_is_empty() { assertThatIllegalArgumentException().isThrownBy(() -> assertThat(employees).filteredOn("", notIn(800))) .withMessage("The property/field name to filter on should not be null or empty"); } @Test void should_fail_if_on_of_the_object_array_element_does_not_have_given_property_or_field() { assertThatExceptionOfType(IntrospectionError.class).isThrownBy(() -> assertThat(employees).filteredOn("secret", notIn("???"))) .withMessageContaining("Can't find any field or property with name 'secret'"); } }
ObjectArrayAssert_filteredOn_notIn_Test
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/LambdaTestUtils.java
{ "start": 38245, "end": 38675 }
class ____ implements Callable<Void> { private final VoidCallable callback; public VoidCaller(VoidCallable callback) { this.callback = callback; } @Override public Void call() throws Exception { callback.call(); return null; } } /** * A lambda-invoker for doAs use; invokes the callable provided * in the constructor. * @param <T> return type. */ public static
VoidCaller
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
{ "start": 7665, "end": 8461 }
class ____ retrieve the attribute for * @return all transaction attribute associated with this class, or {@code null} if none */ protected abstract @Nullable TransactionAttribute findTransactionAttribute(Class<?> clazz); /** * Subclasses need to implement this to return the transaction attribute for the * given method, if any. * @param method the method to retrieve the attribute for * @return all transaction attribute associated with this method, or {@code null} if none */ protected abstract @Nullable TransactionAttribute findTransactionAttribute(Method method); /** * Should only public methods be allowed to have transactional semantics? * <p>The default implementation returns {@code false}. */ protected boolean allowPublicMethodsOnly() { return false; } }
to
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/wiring/ConnectorAttachmentMutinyEmitterTest.java
{ "start": 2089, "end": 2348 }
class ____ { @Channel("my-source") MutinyEmitter<Integer> emitter; public void generate() { for (int i = 0; i < 5; i++) { emitter.send(i).subscribeAsCompletionStage(); } } } }
MySource
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/internal/ManagedTypeHelper.java
{ "start": 9284, "end": 14030 }
interface ____<T> { void accept(SelfDirtinessTracker tracker, T optionalParam); } /** * Cast the object to PersistentAttributeInterceptable * (using this is highly preferrable over a direct cast) * @param entity the entity to cast * @return the same instance after casting * @throws ClassCastException if it's not of the right type */ public static PersistentAttributeInterceptable asPersistentAttributeInterceptable(final Object entity) { Objects.requireNonNull( entity ); if ( entity instanceof PrimeAmongSecondarySupertypes t ) { final PersistentAttributeInterceptable e = t.asPersistentAttributeInterceptable(); if ( e != null ) { return e; } } throw new ClassCastException( "Object of type '" + entity.getClass() + "' can't be cast to PersistentAttributeInterceptable" ); } public static PersistentAttributeInterceptable asPersistentAttributeInterceptableOrNull(final Object entity) { if ( entity instanceof PrimeAmongSecondarySupertypes t ) { return t.asPersistentAttributeInterceptable(); } return null; } /** * Cast the object to HibernateProxy * (using this is highly preferrable over a direct cast) * @param entity the entity to cast * @return the same instance after casting * @throws ClassCastException if it's not of the right type */ public static HibernateProxy asHibernateProxy(final Object entity) { Objects.requireNonNull( entity ); if ( entity instanceof PrimeAmongSecondarySupertypes t ) { final HibernateProxy e = t.asHibernateProxy(); if ( e != null ) { return e; } } throw new ClassCastException( "Object of type '" + entity.getClass() + "' can't be cast to HibernateProxy" ); } /** * Cast the object to ManagedEntity * (using this is highly preferrable over a direct cast) * @param entity the entity to cast * @return the same instance after casting * @throws ClassCastException if it's not of the right type */ public static ManagedEntity asManagedEntity(final Object entity) { Objects.requireNonNull( entity ); if ( entity instanceof PrimeAmongSecondarySupertypes t ) { final ManagedEntity e = t.asManagedEntity(); if ( e != null ) { return e; } } throw new ClassCastException( "Object of type '" + entity.getClass() + "' can't be cast to ManagedEntity" ); } /** * Cast the object to CompositeTracker * (using this is highly preferrable over a direct cast) * @param entity the entity to cast * @return the same instance after casting * @throws ClassCastException if it's not of the right type */ public static CompositeTracker asCompositeTracker(final Object entity) { Objects.requireNonNull( entity ); if ( entity instanceof PrimeAmongSecondarySupertypes t ) { final CompositeTracker e = t.asCompositeTracker(); if ( e != null ) { return e; } } throw new ClassCastException( "Object of type '" + entity.getClass() + "' can't be cast to CompositeTracker" ); } /** * Cast the object to CompositeOwner * (using this is highly preferrable over a direct cast) * @param entity the entity to cast * @return the same instance after casting * @throws ClassCastException if it's not of the right type */ public static CompositeOwner asCompositeOwner(final Object entity) { Objects.requireNonNull( entity ); if ( entity instanceof PrimeAmongSecondarySupertypes t ) { final CompositeOwner e = t.asCompositeOwner(); if ( e != null ) { return e; } } throw new ClassCastException( "Object of type '" + entity.getClass() + "' can't be cast to CompositeOwner" ); } /** * Cast the object to SelfDirtinessTracker * (using this is highly preferrable over a direct cast) * @param entity the entity to cast * @return the same instance after casting * @throws ClassCastException if it's not of the right type */ public static SelfDirtinessTracker asSelfDirtinessTracker(final Object entity) { Objects.requireNonNull( entity ); if ( entity instanceof PrimeAmongSecondarySupertypes t ) { final SelfDirtinessTracker e = t.asSelfDirtinessTracker(); if ( e != null ) { return e; } } throw new ClassCastException( "Object of type '" + entity.getClass() + "' can't be cast to SelfDirtinessTracker" ); } /** * Cast the object to an HibernateProxy, or return null in case it is not an instance of HibernateProxy * @param entity the entity to cast * @return the same instance after casting or null if it is not an instance of HibernateProxy */ public static HibernateProxy asHibernateProxyOrNull(final Object entity) { return entity instanceof PrimeAmongSecondarySupertypes ? ( (PrimeAmongSecondarySupertypes) entity ).asHibernateProxy() : null; } private static final
SelfDirtinessTrackerAction
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/jwt/JwkSetLoader.java
{ "start": 16135, "end": 16875 }
class ____ implements FileChangesListener { final FileWatcher fileWatcher; boolean changed = false; FileChangeWatcher(Path path) { this.fileWatcher = new PrivilegedFileWatcher(path); this.fileWatcher.addListener(this); } boolean changedSinceLastCall() throws IOException { fileWatcher.checkAndNotify(); // may call onFileInit, onFileChanged boolean c = changed; changed = false; return c; } @Override public void onFileChanged(Path file) { changed = true; } @Override public void onFileInit(Path file) { changed = true; } } }
FileChangeWatcher
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/RedundantEditLogInputStream.java
{ "start": 10103, "end": 10515 }
class ____ extends IOException { private static final long serialVersionUID = 1L; PrematureEOFException(String msg) { super(msg); } } @Override public void setMaxOpSize(int maxOpSize) { for (EditLogInputStream elis : streams) { elis.setMaxOpSize(maxOpSize); } } @Override public boolean isLocalLog() { return streams[curIdx].isLocalLog(); } }
PrematureEOFException
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/graph/ReactiveTransactionalGraphCommands.java
{ "start": 697, "end": 3643 }
interface ____<K> extends ReactiveTransactionalRedisCommands { /** * Execute the command <a href="https://redis.io/commands/graph.delete">GRAPH.DELETE</a>. * Summary: Completely removes the graph and all of its entities. * Group: graph * * @param key the key, must not be {@code null} * @return A {@code Uni} emitting {@code null} when the command has been enqueued successfully in the transaction, * a failure otherwise. In the case of failure, the transaction is discarded. */ Uni<Void> graphDelete(K key); /** * Execute the command <a href="https://redis.io/commands/graph.delete">GRAPH.EXPLAIN</a>. * Summary: Constructs a query execution plan but does not run it. Inspect this execution plan to better understand * how your query will get executed. * Group: graph * <p> * * @param key the key, must not be {@code null} * @param query the query, must not be {@code null} * @return A {@code Uni} emitting {@code null} when the command has been enqueued successfully in the transaction, * a failure otherwise. In the case of failure, the transaction is discarded. */ Uni<Void> graphExplain(K key, String query); /** * Execute the command <a href="https://redis.io/commands/graph.list">GRAPH.LIST</a>. * Summary: Lists all graph keys in the keyspace. * Group: graph * <p> * * @return A {@code Uni} emitting {@code null} when the command has been enqueued successfully in the transaction, * a failure otherwise. In the case of failure, the transaction is discarded. */ Uni<Void> graphList(); /** * Execute the command <a href="https://redis.io/commands/graph.delete">GRAPH.QUERY</a>. * Summary: Executes the given query against a specified graph. * Group: graph * <p> * * @param key the key, must not be {@code null} * @param query the query, must not be {@code null} * @return A {@code Uni} emitting {@code null} when the command has been enqueued successfully in the transaction, * a failure otherwise. In the case of failure, the transaction is discarded. */ Uni<Void> graphQuery(K key, String query); /** * Execute the command <a href="https://redis.io/commands/graph.delete">GRAPH.QUERY</a>. * Summary: Executes the given query against a specified graph. * Group: graph * <p> * * @param key the key, must not be {@code null} * @param query the query, must not be {@code null} * @param timeout a timeout, must not be {@code null} * @return A {@code Uni} emitting {@code null} when the command has been enqueued successfully in the transaction, * a failure otherwise. In the case of failure, the transaction is discarded. */ Uni<Void> graphQuery(K key, String query, Duration timeout); }
ReactiveTransactionalGraphCommands
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLIfStatement.java
{ "start": 810, "end": 3270 }
class ____ extends SQLStatementImpl implements SQLReplaceable { private SQLExpr condition; private List<SQLStatement> statements = new ArrayList<SQLStatement>(); private List<ElseIf> elseIfList = new ArrayList<ElseIf>(); private Else elseItem; public SQLIfStatement clone() { SQLIfStatement x = new SQLIfStatement(); for (SQLStatement stmt : statements) { SQLStatement stmt2 = stmt.clone(); stmt2.setParent(x); x.statements.add(stmt2); } for (ElseIf o : elseIfList) { ElseIf o2 = o.clone(); o2.setParent(x); x.elseIfList.add(o2); } if (elseItem != null) { x.setElseItem(elseItem.clone()); } return x; } @Override public void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { if (condition != null) { condition.accept(visitor); } for (int i = 0; i < statements.size(); i++) { statements.get(i) .accept(visitor); } for (int i = 0; i < elseIfList.size(); i++) { elseIfList.get(i) .accept(visitor); } if (elseItem != null) { elseItem.accept(visitor); } } visitor.endVisit(this); } public SQLExpr getCondition() { return condition; } public void setCondition(SQLExpr condition) { if (condition != null) { condition.setParent(this); } this.condition = condition; } public List<SQLStatement> getStatements() { return statements; } public void addStatement(SQLStatement statement) { if (statement != null) { statement.setParent(this); } this.statements.add(statement); } public List<ElseIf> getElseIfList() { return elseIfList; } public Else getElseItem() { return elseItem; } public void setElseItem(Else elseItem) { if (elseItem != null) { elseItem.setParent(this); } this.elseItem = elseItem; } @Override public boolean replace(SQLExpr expr, SQLExpr target) { if (condition == expr) { setCondition(target); return true; } return false; } public static
SQLIfStatement
java
netty__netty
testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketSslEchoTest.java
{ "start": 3919, "end": 4116 }
enum ____ { NONE, // no renegotiation CLIENT_INITIATED, // renegotiation from client SERVER_INITIATED, // renegotiation from server } protected static
RenegotiationType
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecLegacyTableSourceScan.java
{ "start": 3059, "end": 8558 }
class ____ extends ExecNodeBase<RowData> implements MultipleTransformationTranslator<RowData> { protected final TableSource<?> tableSource; protected final List<String> qualifiedName; public CommonExecLegacyTableSourceScan( int id, ExecNodeContext context, ReadableConfig persistedConfig, TableSource<?> tableSource, List<String> qualifiedName, RowType outputType, String description) { super(id, context, persistedConfig, Collections.emptyList(), outputType, description); this.tableSource = tableSource; this.qualifiedName = qualifiedName; } @SuppressWarnings("unchecked") @Override protected Transformation<RowData> translateToPlanInternal( PlannerBase planner, ExecNodeConfig config) { final Transformation<?> sourceTransform; final StreamExecutionEnvironment env = planner.getExecEnv(); if (tableSource instanceof InputFormatTableSource) { InputFormatTableSource<Object> inputFormat = (InputFormatTableSource<Object>) tableSource; TypeInformation<Object> typeInfo = (TypeInformation<Object>) fromDataTypeToTypeInfo(inputFormat.getProducedDataType()); InputFormat<Object, ?> format = inputFormat.getInputFormat(); sourceTransform = createInput(env, format, typeInfo); } else if (tableSource instanceof StreamTableSource) { sourceTransform = ((StreamTableSource<?>) tableSource).getDataStream(env).getTransformation(); } else { throw new UnsupportedOperationException( tableSource.getClass().getSimpleName() + " is unsupported."); } final TypeInformation<?> inputType = sourceTransform.getOutputType(); final DataType producedDataType = tableSource.getProducedDataType(); // check that declared and actual type of table source DataStream are identical if (!inputType.equals(TypeInfoDataTypeConverter.fromDataTypeToTypeInfo(producedDataType))) { throw new TableException( String.format( "TableSource of type %s " + "returned a DataStream of data type %s that does not match with the " + "data type %s declared by the TableSource.getProducedDataType() method. " + "Please validate the implementation of the TableSource.", tableSource.getClass().getCanonicalName(), inputType, producedDataType)); } final RowType outputType = (RowType) getOutputType(); // get expression to extract rowtime attribute final Optional<RexNode> rowtimeExpression = JavaScalaConversionUtil.toJava( TableSourceUtil.getRowtimeAttributeDescriptor( tableSource, outputType)) .map( desc -> TableSourceUtil.getRowtimeExtractionExpression( desc.getTimestampExtractor(), producedDataType, planner.createRelBuilder(), getNameRemapping())); return createConversionTransformationIfNeeded( planner.getExecEnv(), config, planner.getFlinkContext().getClassLoader(), sourceTransform, rowtimeExpression.orElse(null)); } protected abstract <IN> Transformation<IN> createInput( StreamExecutionEnvironment env, InputFormat<IN, ? extends InputSplit> inputFormat, TypeInformation<IN> typeInfo); protected abstract Transformation<RowData> createConversionTransformationIfNeeded( StreamExecutionEnvironment streamExecEnv, ExecNodeConfig config, ClassLoader classLoader, Transformation<?> sourceTransform, @Nullable RexNode rowtimeExpression); protected boolean needInternalConversion(int[] fieldIndexes) { return ScanUtil.hasTimeAttributeField(fieldIndexes) || ScanUtil.needsConversion(tableSource.getProducedDataType()); } protected int[] computeIndexMapping(boolean isStreaming) { RowType outputType = (RowType) getOutputType(); TableSchema tableSchema = TableSchema.fromResolvedSchema( DataTypeUtils.expandCompositeTypeToSchema(DataTypes.of(outputType)), DefaultSqlFactory.INSTANCE); return TypeMappingUtils.computePhysicalIndicesOrTimeAttributeMarkers( tableSource, tableSchema.getTableColumns(), isStreaming, getNameRemapping()); } private Function<String, String> getNameRemapping() { if (tableSource instanceof DefinedFieldMapping) { Map<String, String> mapping = ((DefinedFieldMapping) tableSource).getFieldMapping(); if (mapping != null) { return mapping::get; } } return Function.identity(); } }
CommonExecLegacyTableSourceScan
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
{ "start": 85279, "end": 85547 }
class ____ implements Converter<String, Person> { @Override public Person convert(String source) { String[] content = StringUtils.split(source, " "); assertThat(content).isNotNull(); return new Person(content[0], content[1]); } } static
PersonConverter
java
apache__kafka
tools/src/main/java/org/apache/kafka/tools/VerifiableShareConsumer.java
{ "start": 8896, "end": 16660 }
class ____ extends ShareConsumerEvent { private final ConsumerRecord<String, String> record; public RecordData(ConsumerRecord<String, String> record) { this.record = record; } @Override public String name() { return "record_data"; } @JsonProperty public String topic() { return record.topic(); } @JsonProperty public int partition() { return record.partition(); } @JsonProperty public String key() { return record.key(); } @JsonProperty public String value() { return record.value(); } @JsonProperty public long offset() { return record.offset(); } } public VerifiableShareConsumer(KafkaShareConsumer<String, String> consumer, Admin adminClient, PrintStream out, Integer maxMessages, String topic, AcknowledgementMode acknowledgementMode, String offsetResetStrategy, String groupId, Boolean verbose) { this.out = out; this.consumer = consumer; this.adminClient = adminClient; this.topic = topic; this.acknowledgementMode = acknowledgementMode; this.offsetResetStrategy = offsetResetStrategy; this.verbose = verbose; this.maxMessages = maxMessages; this.groupId = groupId; addKafkaSerializerModule(); } private void addKafkaSerializerModule() { SimpleModule kafka = new SimpleModule(); kafka.addSerializer(TopicPartition.class, new JsonSerializer<>() { @Override public void serialize(TopicPartition tp, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeObjectField("topic", tp.topic()); gen.writeObjectField("partition", tp.partition()); gen.writeEndObject(); } }); mapper.registerModule(kafka); } private void onRecordsReceived(ConsumerRecords<String, String> records) { List<RecordSetSummary> summaries = new ArrayList<>(); for (TopicPartition tp : records.partitions()) { List<ConsumerRecord<String, String>> partitionRecords = records.records(tp); if (partitionRecords.isEmpty()) continue; TreeSet<Long> partitionOffsets = new TreeSet<>(); for (ConsumerRecord<String, String> record : partitionRecords) { partitionOffsets.add(record.offset()); } summaries.add(new RecordSetSummary(tp.topic(), tp.partition(), partitionOffsets)); if (this.verbose) { for (ConsumerRecord<String, String> record : partitionRecords) { printJson(new RecordData(record)); } } } printJson(new RecordsConsumed(records.count(), summaries)); } @Override public void onComplete(Map<TopicIdPartition, Set<Long>> offsetsMap, Exception exception) { List<AcknowledgedData> acknowledgedOffsets = new ArrayList<>(); int totalAcknowledged = 0; for (Map.Entry<TopicIdPartition, Set<Long>> offsetEntry : offsetsMap.entrySet()) { TopicIdPartition tp = offsetEntry.getKey(); acknowledgedOffsets.add(new AcknowledgedData(tp.topic(), tp.partition(), offsetEntry.getValue())); totalAcknowledged += offsetEntry.getValue().size(); } boolean success = true; String error = null; if (exception != null) { success = false; error = exception.getMessage(); } printJson(new OffsetsAcknowledged(totalAcknowledged, acknowledgedOffsets, error, success)); if (success) { this.totalAcknowledged += totalAcknowledged; } } public void run() { try { printJson(new StartupComplete()); if (!Objects.equals(offsetResetStrategy, "")) { ShareGroupAutoOffsetResetStrategy offsetResetStrategy = ShareGroupAutoOffsetResetStrategy.fromString(this.offsetResetStrategy); ConfigResource configResource = new ConfigResource(ConfigResource.Type.GROUP, groupId); Map<ConfigResource, Collection<AlterConfigOp>> alterEntries = new HashMap<>(); alterEntries.put(configResource, List.of(new AlterConfigOp(new ConfigEntry( GroupConfig.SHARE_AUTO_OFFSET_RESET_CONFIG, offsetResetStrategy.type().toString()), AlterConfigOp.OpType.SET))); AlterConfigsOptions alterOptions = new AlterConfigsOptions(); // Setting the share group auto offset reset strategy adminClient.incrementalAlterConfigs(alterEntries, alterOptions) .all() .get(60, TimeUnit.SECONDS); printJson(new OffsetResetStrategySet(offsetResetStrategy.type().toString())); } consumer.subscribe(Set.of(this.topic)); consumer.setAcknowledgementCommitCallback(this); while (!(maxMessages >= 0 && totalAcknowledged >= maxMessages)) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(5000)); if (!records.isEmpty()) { onRecordsReceived(records); if (acknowledgementMode == AcknowledgementMode.ASYNC) { consumer.commitAsync(); } else if (acknowledgementMode == AcknowledgementMode.SYNC) { Map<TopicIdPartition, Optional<KafkaException>> result = consumer.commitSync(); for (Map.Entry<TopicIdPartition, Optional<KafkaException>> resultEntry : result.entrySet()) { if (resultEntry.getValue().isPresent()) { log.error("Failed to commit offset synchronously for topic partition: {}", resultEntry.getKey()); } } } } } } catch (WakeupException e) { // ignore, we are closing log.trace("Caught WakeupException because share consumer is shutdown, ignore and terminate.", e); } catch (Throwable t) { // Log the error, so it goes to the service log and not stdout log.error("Error during processing, terminating share consumer process: ", t); } finally { consumer.close(); printJson(new ShutdownComplete()); shutdownLatch.countDown(); } } public void close() { boolean interrupted = false; try { consumer.wakeup(); while (true) { try { shutdownLatch.await(); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) Thread.currentThread().interrupt(); } } protected synchronized void printJson(Object data) { try { out.println(mapper.writeValueAsString(data)); } catch (JsonProcessingException e) { out.println("Bad data can't be written as json: " + e.getMessage()); } } public
RecordData
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/jdbc/SqlGroup.java
{ "start": 1790, "end": 1831 }
interface ____ { Sql[] value(); }
SqlGroup
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/DynamicRouterTest.java
{ "start": 1087, "end": 3226 }
class ____ extends ContextTestSupport { private static int invoked; private static final List<String> bodies = new ArrayList<>(); @Test public void testDynamicRouter() throws Exception { getMockEndpoint("mock:a").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:b").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:c").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); assertEquals(5, invoked); assertEquals(5, bodies.size()); assertEquals("Hello World", bodies.get(0)); assertEquals("Hello World", bodies.get(1)); assertEquals("Hello World", bodies.get(2)); assertEquals("Bye World", bodies.get(3)); assertEquals("Bye World", bodies.get(4)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // START SNIPPET: e1 from("direct:start") // use a bean as the dynamic router .dynamicRouter(method(DynamicRouterTest.class, "slip")); // END SNIPPET: e1 from("direct:foo").transform(constant("Bye World")); } }; } // START SNIPPET: e2 /** * Use this method to compute dynamic where we should route next. * * @param body the message body * @return endpoints to go, or <tt>null</tt> to indicate the end */ public String slip(String body) { bodies.add(body); invoked++; if (invoked == 1) { return "mock:a"; } else if (invoked == 2) { return "mock:b,mock:c"; } else if (invoked == 3) { return "direct:foo"; } else if (invoked == 4) { return "mock:result"; } // no more so return null return null; } // END SNIPPET: e2 }
DynamicRouterTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/GetLabelsToNodesRequestPBImpl.java
{ "start": 1259, "end": 3509 }
class ____ extends GetLabelsToNodesRequest { Set<String> nodeLabels = null; GetLabelsToNodesRequestProto proto = GetLabelsToNodesRequestProto.getDefaultInstance(); GetLabelsToNodesRequestProto.Builder builder = null; boolean viaProto = false; public GetLabelsToNodesRequestPBImpl() { builder = GetLabelsToNodesRequestProto.newBuilder(); } public GetLabelsToNodesRequestPBImpl(GetLabelsToNodesRequestProto proto) { this.proto = proto; viaProto = true; } public GetLabelsToNodesRequestProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void mergeLocalToProto() { if (viaProto) maybeInitBuilder(); mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void mergeLocalToBuilder() { if (nodeLabels != null && !nodeLabels.isEmpty()) { builder.clearNodeLabels(); builder.addAllNodeLabels(nodeLabels); } } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = GetLabelsToNodesRequestProto.newBuilder(proto); } viaProto = false; } private void initNodeLabels() { if (this.nodeLabels != null) { return; } GetLabelsToNodesRequestProtoOrBuilder p = viaProto ? proto : builder; List<String> nodeLabelsList = p.getNodeLabelsList(); this.nodeLabels = new HashSet<String>(); this.nodeLabels.addAll(nodeLabelsList); } @Override public Set<String> getNodeLabels() { initNodeLabels(); return this.nodeLabels; } @Override public void setNodeLabels(Set<String> nodeLabels) { maybeInitBuilder(); if (nodeLabels == null) builder.clearNodeLabels(); this.nodeLabels = nodeLabels; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } }
GetLabelsToNodesRequestPBImpl
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/ECAdmin.java
{ "start": 12990, "end": 15165 }
class ____ implements AdminHelper.Command { @Override public String getName() { return "-unsetPolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -path <path>]\n"; } @Override public String getLongUsage() { TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<path>", "The path of the directory " + "from which the erasure coding policy will be unset."); return getShortUsage() + "\n" + "Unset the erasure coding policy for a directory.\n\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String path = StringUtils.popOptionWithArgument("-path", args); if (path == null) { System.err.println("Please specify a path.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final Path p = new Path(path); final DistributedFileSystem dfs = AdminHelper.getDFS(p.toUri(), conf); try { dfs.unsetErasureCodingPolicy(p); System.out.println("Unset erasure coding policy from " + path); RemoteIterator<FileStatus> dirIt = dfs.listStatusIterator(p); if (dirIt.hasNext()) { System.out.println("Warning: unsetting erasure coding policy on a " + "non-empty directory will not automatically convert existing" + " files to replicated data."); } } catch (NoECPolicySetException e) { System.err.println(AdminHelper.prettifyException(e)); System.err.println("Use '-setPolicy -path <PATH> -replicate' to enforce" + " default replication policy irrespective of EC policy" + " defined on parent."); return 2; } catch (Exception e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to list the set of supported erasure coding codecs and coders. */ private static
UnsetECPolicyCommand
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/main/java/io/github/resilience4j/ratelimiter/autoconfigure/RateLimiterAutoConfiguration.java
{ "start": 2022, "end": 2131 }
class ____ { @Configuration @ConditionalOnClass( Endpoint.class) static
RateLimiterAutoConfiguration
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableGroupJoin.java
{ "start": 1265, "end": 2776 }
class ____<TLeft, TRight, TLeftEnd, TRightEnd, R> extends AbstractFlowableWithUpstream<TLeft, R> { final Publisher<? extends TRight> other; final Function<? super TLeft, ? extends Publisher<TLeftEnd>> leftEnd; final Function<? super TRight, ? extends Publisher<TRightEnd>> rightEnd; final BiFunction<? super TLeft, ? super Flowable<TRight>, ? extends R> resultSelector; public FlowableGroupJoin( Flowable<TLeft> source, Publisher<? extends TRight> other, Function<? super TLeft, ? extends Publisher<TLeftEnd>> leftEnd, Function<? super TRight, ? extends Publisher<TRightEnd>> rightEnd, BiFunction<? super TLeft, ? super Flowable<TRight>, ? extends R> resultSelector) { super(source); this.other = other; this.leftEnd = leftEnd; this.rightEnd = rightEnd; this.resultSelector = resultSelector; } @Override protected void subscribeActual(Subscriber<? super R> s) { GroupJoinSubscription<TLeft, TRight, TLeftEnd, TRightEnd, R> parent = new GroupJoinSubscription<>(s, leftEnd, rightEnd, resultSelector); s.onSubscribe(parent); LeftRightSubscriber left = new LeftRightSubscriber(parent, true); parent.disposables.add(left); LeftRightSubscriber right = new LeftRightSubscriber(parent, false); parent.disposables.add(right); source.subscribe(left); other.subscribe(right); }
FlowableGroupJoin
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/SQLExpr.java
{ "start": 683, "end": 858 }
interface ____ extends SQLObject, Cloneable { SQLExpr clone(); SQLDataType computeDataType(); List<SQLObject> getChildren(); SQLCommentHint getHint(); }
SQLExpr
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/requestcontext/RequestContextActivatedByListTest.java
{ "start": 1345, "end": 1572 }
class ____ { @All List<RequestScopedBean> list; @OnTextMessage String process(String message) { return "pong:" + Arc.container().requestContext().isActive(); } } }
Endpoint
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java
{ "start": 21148, "end": 21328 }
class ____ loaded * @param <T> type of instance to return * @return new instance of the requested class * @throws NoClassDefFoundError if the provided
being
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/QueryParameterAttribute.java
{ "start": 1660, "end": 2452 }
class ____ implements ExchangeAttributeBuilder { @Override public String name() { return "Query Parameter"; } @Override public ExchangeAttribute build(final String token) { if (token.startsWith("%{q,") && token.endsWith("}")) { final String qp = token.substring(4, token.length() - 1); return new QueryParameterAttribute(qp, false); } if (token.startsWith("%{<q,") && token.endsWith("}")) { final String qp = token.substring(5, token.length() - 1); return new QueryParameterAttribute(qp, true); } return null; } @Override public int priority() { return 0; } } }
Builder
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRule.java
{ "start": 8011, "end": 8083 }
class ____ { boolean foundMatch = false; } } }
State
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/di/MojoExecutionScope.java
{ "start": 1256, "end": 3888 }
class ____ { private final Map<Key<?>, Supplier<?>> seeded = new HashMap<>(); private final Map<Key<?>, Object> provided = new HashMap<>(); public <T> void seed(Class<T> clazz, Supplier<T> value) { seeded.put(Key.of(clazz), value); } public Collection<Object> provided() { return provided.values(); } } private final ThreadLocal<LinkedList<ScopeState>> values = new ThreadLocal<>(); public MojoExecutionScope() {} public static <T> Supplier<T> seededKeySupplier(Class<? extends T> clazz) { return () -> { throw new IllegalStateException( "No instance of " + clazz.getName() + " is bound to the mojo execution scope."); }; } public void enter() { LinkedList<ScopeState> stack = values.get(); if (stack == null) { stack = new LinkedList<>(); values.set(stack); } stack.addFirst(new ScopeState()); } protected ScopeState getScopeState() { LinkedList<ScopeState> stack = values.get(); if (stack == null || stack.isEmpty()) { throw new IllegalStateException(); } return stack.getFirst(); } public void exit() { final LinkedList<ScopeState> stack = values.get(); if (stack == null || stack.isEmpty()) { throw new IllegalStateException(); } stack.removeFirst(); if (stack.isEmpty()) { values.remove(); } } public <T> void seed(Class<T> clazz, Supplier<T> value) { getScopeState().seed(clazz, value); } public <T> void seed(Class<T> clazz, final T value) { seed(clazz, (Supplier<T>) () -> value); } @SuppressWarnings("unchecked") @Nonnull @Override public <T> Supplier<T> scope(@Nonnull Key<T> key, @Nonnull Supplier<T> unscoped) { return () -> { LinkedList<ScopeState> stack = values.get(); if (stack == null || stack.isEmpty()) { throw new DIException("Cannot access " + key + " outside of a scoping block"); } ScopeState state = stack.getFirst(); Supplier<?> seeded = state.seeded.get(key); if (seeded != null) { return (T) seeded.get(); } T provided = (T) state.provided.get(key); if (provided == null && unscoped != null) { provided = unscoped.get(); state.provided.put(key, provided); } return provided; }; } }
ScopeState
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/AbstractAbstractFutureTest.java
{ "start": 9626, "end": 10016 }
class ____ extends RuntimeException {} Runnable bad = new Runnable() { @Override public void run() { throw new BadRunnableException(); } }; future.set(1); future.addListener(bad, directExecutor()); // BadRunnableException must not propagate. } public void testMisbehavingListenerLaterDone() {
BadRunnableException
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-rest/src/main/java/smoketest/data/rest/domain/City.java
{ "start": 941, "end": 2053 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", initialValue = 23) @GeneratedValue(generator = "city_generator") private @Nullable Long id; @Column(nullable = false) @SuppressWarnings("NullAway.Init") private String name; @Column(nullable = false) @SuppressWarnings("NullAway.Init") private String state; @Column(nullable = false) @SuppressWarnings("NullAway.Init") private String country; @Column(nullable = false) @SuppressWarnings("NullAway.Init") private String map; protected City() { } public City(String name, String country, String state, String map) { this.name = name; this.country = country; this.state = state; this.map = map; } public String getName() { return this.name; } public String getState() { return this.state; } public String getCountry() { return this.country; } public String getMap() { return this.map; } @Override public String toString() { return getName() + "," + getState() + "," + getCountry(); } }
City
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/config/ConfigFilterTest3.java
{ "start": 418, "end": 3012 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setFilters("config"); } protected void tearDown() throws Exception { JdbcUtils.close(dataSource); } public void test_0() throws Exception { String password = "abcdefg1234"; String[] keys = ConfigTools.genKeyPair(1024); File file = File.createTempFile("MyTest", Long.toString(System.nanoTime())); Properties properties = new Properties(); properties.put(DruidDataSourceFactory.PROP_URL, "jdbc:mock:xx0"); properties.put(DruidDataSourceFactory.PROP_USERNAME, "sa"); properties.put(DruidDataSourceFactory.PROP_PASSWORD, ConfigTools.encrypt(keys[0], password)); properties.put(ConfigFilter.CONFIG_DECRYPT, "true"); properties.store(new FileOutputStream(file), ""); dataSource.getConnectProperties().put(ConfigFilter.CONFIG_KEY, keys[1]); dataSource.getConnectProperties().put(ConfigFilter.CONFIG_FILE, "file://" + file.getAbsolutePath()); dataSource.init(); assertEquals("jdbc:mock:xx0", dataSource.getUrl()); assertEquals("sa", dataSource.getUsername()); assertEquals(password, dataSource.getPassword()); } public void test_sys_property() throws Exception { String password = "abcdefg1234"; String[] keys = ConfigTools.genKeyPair(1024); File file = File.createTempFile("MyTest", Long.toString(System.nanoTime())); Properties properties = new Properties(); properties.put(DruidDataSourceFactory.PROP_URL, "jdbc:mock:xx0"); properties.put(DruidDataSourceFactory.PROP_USERNAME, "sa"); properties.put(DruidDataSourceFactory.PROP_PASSWORD, ConfigTools.encrypt(keys[0], password)); properties.put(ConfigFilter.CONFIG_DECRYPT, "true"); properties.store(new FileOutputStream(file), ""); System.getProperties().put(ConfigFilter.SYS_PROP_CONFIG_KEY, keys[1]); System.getProperties().put(ConfigFilter.SYS_PROP_CONFIG_FILE, "file://" + file.getAbsolutePath()); try { dataSource.init(); assertEquals("jdbc:mock:xx0", dataSource.getUrl()); assertEquals("sa", dataSource.getUsername()); assertEquals(password, dataSource.getPassword()); } finally { System.clearProperty(ConfigFilter.SYS_PROP_CONFIG_KEY); System.clearProperty(ConfigFilter.SYS_PROP_CONFIG_FILE); } } }
ConfigFilterTest3
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/parser/EqlBaseListener.java
{ "start": 244, "end": 19549 }
interface ____ extends ParseTreeListener { /** * Enter a parse tree produced by {@link EqlBaseParser#singleStatement}. * @param ctx the parse tree */ void enterSingleStatement(EqlBaseParser.SingleStatementContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#singleStatement}. * @param ctx the parse tree */ void exitSingleStatement(EqlBaseParser.SingleStatementContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#singleExpression}. * @param ctx the parse tree */ void enterSingleExpression(EqlBaseParser.SingleExpressionContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#singleExpression}. * @param ctx the parse tree */ void exitSingleExpression(EqlBaseParser.SingleExpressionContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#statement}. * @param ctx the parse tree */ void enterStatement(EqlBaseParser.StatementContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#statement}. * @param ctx the parse tree */ void exitStatement(EqlBaseParser.StatementContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#query}. * @param ctx the parse tree */ void enterQuery(EqlBaseParser.QueryContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#query}. * @param ctx the parse tree */ void exitQuery(EqlBaseParser.QueryContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#sequenceParams}. * @param ctx the parse tree */ void enterSequenceParams(EqlBaseParser.SequenceParamsContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#sequenceParams}. * @param ctx the parse tree */ void exitSequenceParams(EqlBaseParser.SequenceParamsContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#sequence}. * @param ctx the parse tree */ void enterSequence(EqlBaseParser.SequenceContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#sequence}. * @param ctx the parse tree */ void exitSequence(EqlBaseParser.SequenceContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#sample}. * @param ctx the parse tree */ void enterSample(EqlBaseParser.SampleContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#sample}. * @param ctx the parse tree */ void exitSample(EqlBaseParser.SampleContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#join}. * @param ctx the parse tree */ void enterJoin(EqlBaseParser.JoinContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#join}. * @param ctx the parse tree */ void exitJoin(EqlBaseParser.JoinContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#pipe}. * @param ctx the parse tree */ void enterPipe(EqlBaseParser.PipeContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#pipe}. * @param ctx the parse tree */ void exitPipe(EqlBaseParser.PipeContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#joinKeys}. * @param ctx the parse tree */ void enterJoinKeys(EqlBaseParser.JoinKeysContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#joinKeys}. * @param ctx the parse tree */ void exitJoinKeys(EqlBaseParser.JoinKeysContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#joinTerm}. * @param ctx the parse tree */ void enterJoinTerm(EqlBaseParser.JoinTermContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#joinTerm}. * @param ctx the parse tree */ void exitJoinTerm(EqlBaseParser.JoinTermContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#sequenceTerm}. * @param ctx the parse tree */ void enterSequenceTerm(EqlBaseParser.SequenceTermContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#sequenceTerm}. * @param ctx the parse tree */ void exitSequenceTerm(EqlBaseParser.SequenceTermContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#subquery}. * @param ctx the parse tree */ void enterSubquery(EqlBaseParser.SubqueryContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#subquery}. * @param ctx the parse tree */ void exitSubquery(EqlBaseParser.SubqueryContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#eventQuery}. * @param ctx the parse tree */ void enterEventQuery(EqlBaseParser.EventQueryContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#eventQuery}. * @param ctx the parse tree */ void exitEventQuery(EqlBaseParser.EventQueryContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#eventFilter}. * @param ctx the parse tree */ void enterEventFilter(EqlBaseParser.EventFilterContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#eventFilter}. * @param ctx the parse tree */ void exitEventFilter(EqlBaseParser.EventFilterContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#expression}. * @param ctx the parse tree */ void enterExpression(EqlBaseParser.ExpressionContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#expression}. * @param ctx the parse tree */ void exitExpression(EqlBaseParser.ExpressionContext ctx); /** * Enter a parse tree produced by the {@code logicalNot} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterLogicalNot(EqlBaseParser.LogicalNotContext ctx); /** * Exit a parse tree produced by the {@code logicalNot} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitLogicalNot(EqlBaseParser.LogicalNotContext ctx); /** * Enter a parse tree produced by the {@code booleanDefault} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterBooleanDefault(EqlBaseParser.BooleanDefaultContext ctx); /** * Exit a parse tree produced by the {@code booleanDefault} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitBooleanDefault(EqlBaseParser.BooleanDefaultContext ctx); /** * Enter a parse tree produced by the {@code processCheck} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterProcessCheck(EqlBaseParser.ProcessCheckContext ctx); /** * Exit a parse tree produced by the {@code processCheck} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitProcessCheck(EqlBaseParser.ProcessCheckContext ctx); /** * Enter a parse tree produced by the {@code logicalBinary} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterLogicalBinary(EqlBaseParser.LogicalBinaryContext ctx); /** * Exit a parse tree produced by the {@code logicalBinary} * labeled alternative in {@link EqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitLogicalBinary(EqlBaseParser.LogicalBinaryContext ctx); /** * Enter a parse tree produced by the {@code valueExpressionDefault} * labeled alternative in {@link EqlBaseParser#valueExpression}. * @param ctx the parse tree */ void enterValueExpressionDefault(EqlBaseParser.ValueExpressionDefaultContext ctx); /** * Exit a parse tree produced by the {@code valueExpressionDefault} * labeled alternative in {@link EqlBaseParser#valueExpression}. * @param ctx the parse tree */ void exitValueExpressionDefault(EqlBaseParser.ValueExpressionDefaultContext ctx); /** * Enter a parse tree produced by the {@code comparison} * labeled alternative in {@link EqlBaseParser#valueExpression}. * @param ctx the parse tree */ void enterComparison(EqlBaseParser.ComparisonContext ctx); /** * Exit a parse tree produced by the {@code comparison} * labeled alternative in {@link EqlBaseParser#valueExpression}. * @param ctx the parse tree */ void exitComparison(EqlBaseParser.ComparisonContext ctx); /** * Enter a parse tree produced by the {@code operatorExpressionDefault} * labeled alternative in {@link EqlBaseParser#operatorExpression}. * @param ctx the parse tree */ void enterOperatorExpressionDefault(EqlBaseParser.OperatorExpressionDefaultContext ctx); /** * Exit a parse tree produced by the {@code operatorExpressionDefault} * labeled alternative in {@link EqlBaseParser#operatorExpression}. * @param ctx the parse tree */ void exitOperatorExpressionDefault(EqlBaseParser.OperatorExpressionDefaultContext ctx); /** * Enter a parse tree produced by the {@code arithmeticBinary} * labeled alternative in {@link EqlBaseParser#operatorExpression}. * @param ctx the parse tree */ void enterArithmeticBinary(EqlBaseParser.ArithmeticBinaryContext ctx); /** * Exit a parse tree produced by the {@code arithmeticBinary} * labeled alternative in {@link EqlBaseParser#operatorExpression}. * @param ctx the parse tree */ void exitArithmeticBinary(EqlBaseParser.ArithmeticBinaryContext ctx); /** * Enter a parse tree produced by the {@code arithmeticUnary} * labeled alternative in {@link EqlBaseParser#operatorExpression}. * @param ctx the parse tree */ void enterArithmeticUnary(EqlBaseParser.ArithmeticUnaryContext ctx); /** * Exit a parse tree produced by the {@code arithmeticUnary} * labeled alternative in {@link EqlBaseParser#operatorExpression}. * @param ctx the parse tree */ void exitArithmeticUnary(EqlBaseParser.ArithmeticUnaryContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#predicate}. * @param ctx the parse tree */ void enterPredicate(EqlBaseParser.PredicateContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#predicate}. * @param ctx the parse tree */ void exitPredicate(EqlBaseParser.PredicateContext ctx); /** * Enter a parse tree produced by the {@code constantDefault} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterConstantDefault(EqlBaseParser.ConstantDefaultContext ctx); /** * Exit a parse tree produced by the {@code constantDefault} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitConstantDefault(EqlBaseParser.ConstantDefaultContext ctx); /** * Enter a parse tree produced by the {@code function} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterFunction(EqlBaseParser.FunctionContext ctx); /** * Exit a parse tree produced by the {@code function} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitFunction(EqlBaseParser.FunctionContext ctx); /** * Enter a parse tree produced by the {@code dereference} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterDereference(EqlBaseParser.DereferenceContext ctx); /** * Exit a parse tree produced by the {@code dereference} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitDereference(EqlBaseParser.DereferenceContext ctx); /** * Enter a parse tree produced by the {@code parenthesizedExpression} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterParenthesizedExpression(EqlBaseParser.ParenthesizedExpressionContext ctx); /** * Exit a parse tree produced by the {@code parenthesizedExpression} * labeled alternative in {@link EqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitParenthesizedExpression(EqlBaseParser.ParenthesizedExpressionContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#functionExpression}. * @param ctx the parse tree */ void enterFunctionExpression(EqlBaseParser.FunctionExpressionContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#functionExpression}. * @param ctx the parse tree */ void exitFunctionExpression(EqlBaseParser.FunctionExpressionContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#functionName}. * @param ctx the parse tree */ void enterFunctionName(EqlBaseParser.FunctionNameContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#functionName}. * @param ctx the parse tree */ void exitFunctionName(EqlBaseParser.FunctionNameContext ctx); /** * Enter a parse tree produced by the {@code nullLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void enterNullLiteral(EqlBaseParser.NullLiteralContext ctx); /** * Exit a parse tree produced by the {@code nullLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void exitNullLiteral(EqlBaseParser.NullLiteralContext ctx); /** * Enter a parse tree produced by the {@code numericLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void enterNumericLiteral(EqlBaseParser.NumericLiteralContext ctx); /** * Exit a parse tree produced by the {@code numericLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void exitNumericLiteral(EqlBaseParser.NumericLiteralContext ctx); /** * Enter a parse tree produced by the {@code booleanLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void enterBooleanLiteral(EqlBaseParser.BooleanLiteralContext ctx); /** * Exit a parse tree produced by the {@code booleanLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void exitBooleanLiteral(EqlBaseParser.BooleanLiteralContext ctx); /** * Enter a parse tree produced by the {@code stringLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void enterStringLiteral(EqlBaseParser.StringLiteralContext ctx); /** * Exit a parse tree produced by the {@code stringLiteral} * labeled alternative in {@link EqlBaseParser#constant}. * @param ctx the parse tree */ void exitStringLiteral(EqlBaseParser.StringLiteralContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#comparisonOperator}. * @param ctx the parse tree */ void enterComparisonOperator(EqlBaseParser.ComparisonOperatorContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#comparisonOperator}. * @param ctx the parse tree */ void exitComparisonOperator(EqlBaseParser.ComparisonOperatorContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#booleanValue}. * @param ctx the parse tree */ void enterBooleanValue(EqlBaseParser.BooleanValueContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#booleanValue}. * @param ctx the parse tree */ void exitBooleanValue(EqlBaseParser.BooleanValueContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#qualifiedName}. * @param ctx the parse tree */ void enterQualifiedName(EqlBaseParser.QualifiedNameContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#qualifiedName}. * @param ctx the parse tree */ void exitQualifiedName(EqlBaseParser.QualifiedNameContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#identifier}. * @param ctx the parse tree */ void enterIdentifier(EqlBaseParser.IdentifierContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#identifier}. * @param ctx the parse tree */ void exitIdentifier(EqlBaseParser.IdentifierContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#timeUnit}. * @param ctx the parse tree */ void enterTimeUnit(EqlBaseParser.TimeUnitContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#timeUnit}. * @param ctx the parse tree */ void exitTimeUnit(EqlBaseParser.TimeUnitContext ctx); /** * Enter a parse tree produced by the {@code decimalLiteral} * labeled alternative in {@link EqlBaseParser#number}. * @param ctx the parse tree */ void enterDecimalLiteral(EqlBaseParser.DecimalLiteralContext ctx); /** * Exit a parse tree produced by the {@code decimalLiteral} * labeled alternative in {@link EqlBaseParser#number}. * @param ctx the parse tree */ void exitDecimalLiteral(EqlBaseParser.DecimalLiteralContext ctx); /** * Enter a parse tree produced by the {@code integerLiteral} * labeled alternative in {@link EqlBaseParser#number}. * @param ctx the parse tree */ void enterIntegerLiteral(EqlBaseParser.IntegerLiteralContext ctx); /** * Exit a parse tree produced by the {@code integerLiteral} * labeled alternative in {@link EqlBaseParser#number}. * @param ctx the parse tree */ void exitIntegerLiteral(EqlBaseParser.IntegerLiteralContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#string}. * @param ctx the parse tree */ void enterString(EqlBaseParser.StringContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#string}. * @param ctx the parse tree */ void exitString(EqlBaseParser.StringContext ctx); /** * Enter a parse tree produced by {@link EqlBaseParser#eventValue}. * @param ctx the parse tree */ void enterEventValue(EqlBaseParser.EventValueContext ctx); /** * Exit a parse tree produced by {@link EqlBaseParser#eventValue}. * @param ctx the parse tree */ void exitEventValue(EqlBaseParser.EventValueContext ctx); }
EqlBaseListener
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/orca/OrcaPerRequestUtilTest.java
{ "start": 1833, "end": 4508 }
class ____ { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); private static final ClientStreamTracer.StreamInfo STREAM_INFO = ClientStreamTracer.StreamInfo.newBuilder().build(); @Mock private OrcaPerRequestReportListener orcaListener1; @Mock private OrcaPerRequestReportListener orcaListener2; /** * Tests a single load balance policy's listener receive per-request ORCA reports upon call * trailer arrives. */ @Test public void singlePolicyTypicalWorkflow() { // Use a mocked noop stream tracer factory as the original stream tracer factory. ClientStreamTracer.Factory fakeDelegateFactory = mock(ClientStreamTracer.Factory.class); ClientStreamTracer fakeTracer = mock(ClientStreamTracer.class); doNothing().when(fakeTracer).inboundTrailers(any(Metadata.class)); when(fakeDelegateFactory.newClientStreamTracer( any(ClientStreamTracer.StreamInfo.class), any(Metadata.class))) .thenReturn(fakeTracer); // The OrcaReportingTracerFactory will augment the StreamInfo passed to its // newClientStreamTracer method. The augmented StreamInfo's CallOptions will contain // a OrcaReportBroker, in which has the registered listener. ClientStreamTracer.Factory factory = OrcaPerRequestUtil.getInstance() .newOrcaClientStreamTracerFactory(fakeDelegateFactory, orcaListener1); ClientStreamTracer tracer = factory.newClientStreamTracer(STREAM_INFO, new Metadata()); ArgumentCaptor<ClientStreamTracer.StreamInfo> streamInfoCaptor = ArgumentCaptor.forClass(ClientStreamTracer.StreamInfo.class); verify(fakeDelegateFactory) .newClientStreamTracer(streamInfoCaptor.capture(), any(Metadata.class)); ClientStreamTracer.StreamInfo capturedInfo = streamInfoCaptor.getValue(); assertThat(capturedInfo).isNotEqualTo(STREAM_INFO); // When the trailer does not contain ORCA report, listener callback will not be invoked. Metadata trailer = new Metadata(); tracer.inboundTrailers(trailer); verifyNoMoreInteractions(orcaListener1); // When the trailer contains an ORCA report, listener callback will be invoked. trailer.put( OrcaReportingTracerFactory.ORCA_ENDPOINT_LOAD_METRICS_KEY, OrcaLoadReport.getDefaultInstance()); tracer.inboundTrailers(trailer); ArgumentCaptor<MetricReport> reportCaptor = ArgumentCaptor.forClass(MetricReport.class); verify(orcaListener1).onLoadReport(reportCaptor.capture()); assertThat(reportEqual(reportCaptor.getValue(), OrcaPerRequestUtil.fromOrcaLoadReport(OrcaLoadReport.getDefaultInstance()))).isTrue(); } static final
OrcaPerRequestUtilTest
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/mock/http/client/reactive/MockClientHttpResponse.java
{ "start": 1683, "end": 4216 }
class ____ implements ClientHttpResponse { private final HttpStatusCode statusCode; private final HttpHeaders headers = new HttpHeaders(); private final MultiValueMap<String, ResponseCookie> cookies = new LinkedMultiValueMap<>(); private Flux<DataBuffer> body = Flux.empty(); public MockClientHttpResponse(int status) { this(HttpStatusCode.valueOf(status)); } public MockClientHttpResponse(HttpStatusCode status) { Assert.notNull(status, "HttpStatusCode must not be null"); this.statusCode = status; } @Override public HttpStatusCode getStatusCode() { return this.statusCode; } @Override public HttpHeaders getHeaders() { if (!getCookies().isEmpty() && this.headers.get(HttpHeaders.SET_COOKIE) == null) { getCookies().values().stream().flatMap(Collection::stream) .forEach(cookie -> this.headers.add(HttpHeaders.SET_COOKIE, cookie.toString())); } return this.headers; } @Override public MultiValueMap<String, ResponseCookie> getCookies() { return this.cookies; } public void setBody(Publisher<DataBuffer> body) { this.body = Flux.from(body); } public void setBody(String body) { setBody(body, StandardCharsets.UTF_8); } public void setBody(String body, Charset charset) { DataBuffer buffer = toDataBuffer(body, charset); this.body = Flux.just(buffer); } private DataBuffer toDataBuffer(String body, Charset charset) { byte[] bytes = body.getBytes(charset); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); return DefaultDataBufferFactory.sharedInstance.wrap(byteBuffer); } @Override public Flux<DataBuffer> getBody() { return this.body; } /** * Return the response body aggregated and converted to a String using the * charset of the Content-Type response or otherwise as "UTF-8". */ public Mono<String> getBodyAsString() { return DataBufferUtils.join(getBody()) .map(buffer -> { String s = buffer.toString(getCharset()); DataBufferUtils.release(buffer); return s; }) .defaultIfEmpty(""); } private Charset getCharset() { Charset charset = null; MediaType contentType = getHeaders().getContentType(); if (contentType != null) { charset = contentType.getCharset(); } return (charset != null ? charset : StandardCharsets.UTF_8); } @Override public String toString() { if (this.statusCode instanceof HttpStatus status) { return status.name() + "(" + this.statusCode + ")" + this.headers; } else { return "Status (" + this.statusCode + ")" + this.headers; } } }
MockClientHttpResponse
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/MaxLongGroupingAggregatorFunction.java
{ "start": 1172, "end": 12837 }
class ____ implements GroupingAggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("max", ElementType.LONG), new IntermediateStateDesc("seen", ElementType.BOOLEAN) ); private final LongArrayState state; private final List<Integer> channels; private final DriverContext driverContext; public MaxLongGroupingAggregatorFunction(List<Integer> channels, LongArrayState state, DriverContext driverContext) { this.channels = channels; this.state = state; this.driverContext = driverContext; } public static MaxLongGroupingAggregatorFunction create(List<Integer> channels, DriverContext driverContext) { return new MaxLongGroupingAggregatorFunction(channels, new LongArrayState(driverContext.bigArrays(), MaxLongAggregator.init()), driverContext); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public GroupingAggregatorFunction.AddInput prepareProcessRawInputPage(SeenGroupIds seenGroupIds, Page page) { LongBlock vBlock = page.getBlock(channels.get(0)); LongVector vVector = vBlock.asVector(); if (vVector == null) { maybeEnableGroupIdTracking(seenGroupIds, vBlock); return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, vBlock); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, vBlock); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, vBlock); } @Override public void close() { } }; } return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, vVector); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, vVector); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, vVector); } @Override public void close() { } }; } private void addRawInput(int positionOffset, IntArrayBlock groups, LongBlock vBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; if (vBlock.isNull(valuesPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int vStart = vBlock.getFirstValueIndex(valuesPosition); int vEnd = vStart + vBlock.getValueCount(valuesPosition); for (int vOffset = vStart; vOffset < vEnd; vOffset++) { long vValue = vBlock.getLong(vOffset); state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), vValue)); } } } } private void addRawInput(int positionOffset, IntArrayBlock groups, LongVector vVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); long vValue = vVector.getLong(valuesPosition); state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), vValue)); } } } @Override public void addIntermediateInput(int positionOffset, IntArrayBlock groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block maxUncast = page.getBlock(channels.get(0)); if (maxUncast.areAllValuesNull()) { return; } LongVector max = ((LongBlock) maxUncast).asVector(); Block seenUncast = page.getBlock(channels.get(1)); if (seenUncast.areAllValuesNull()) { return; } BooleanVector seen = ((BooleanBlock) seenUncast).asVector(); assert max.getPositionCount() == seen.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valuesPosition = groupPosition + positionOffset; if (seen.getBoolean(valuesPosition)) { state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), max.getLong(valuesPosition))); } } } } private void addRawInput(int positionOffset, IntBigArrayBlock groups, LongBlock vBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; if (vBlock.isNull(valuesPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int vStart = vBlock.getFirstValueIndex(valuesPosition); int vEnd = vStart + vBlock.getValueCount(valuesPosition); for (int vOffset = vStart; vOffset < vEnd; vOffset++) { long vValue = vBlock.getLong(vOffset); state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), vValue)); } } } } private void addRawInput(int positionOffset, IntBigArrayBlock groups, LongVector vVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); long vValue = vVector.getLong(valuesPosition); state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), vValue)); } } } @Override public void addIntermediateInput(int positionOffset, IntBigArrayBlock groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block maxUncast = page.getBlock(channels.get(0)); if (maxUncast.areAllValuesNull()) { return; } LongVector max = ((LongBlock) maxUncast).asVector(); Block seenUncast = page.getBlock(channels.get(1)); if (seenUncast.areAllValuesNull()) { return; } BooleanVector seen = ((BooleanBlock) seenUncast).asVector(); assert max.getPositionCount() == seen.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valuesPosition = groupPosition + positionOffset; if (seen.getBoolean(valuesPosition)) { state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), max.getLong(valuesPosition))); } } } } private void addRawInput(int positionOffset, IntVector groups, LongBlock vBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int valuesPosition = groupPosition + positionOffset; if (vBlock.isNull(valuesPosition)) { continue; } int groupId = groups.getInt(groupPosition); int vStart = vBlock.getFirstValueIndex(valuesPosition); int vEnd = vStart + vBlock.getValueCount(valuesPosition); for (int vOffset = vStart; vOffset < vEnd; vOffset++) { long vValue = vBlock.getLong(vOffset); state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), vValue)); } } } private void addRawInput(int positionOffset, IntVector groups, LongVector vVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int valuesPosition = groupPosition + positionOffset; int groupId = groups.getInt(groupPosition); long vValue = vVector.getLong(valuesPosition); state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), vValue)); } } @Override public void addIntermediateInput(int positionOffset, IntVector groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block maxUncast = page.getBlock(channels.get(0)); if (maxUncast.areAllValuesNull()) { return; } LongVector max = ((LongBlock) maxUncast).asVector(); Block seenUncast = page.getBlock(channels.get(1)); if (seenUncast.areAllValuesNull()) { return; } BooleanVector seen = ((BooleanBlock) seenUncast).asVector(); assert max.getPositionCount() == seen.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int groupId = groups.getInt(groupPosition); int valuesPosition = groupPosition + positionOffset; if (seen.getBoolean(valuesPosition)) { state.set(groupId, MaxLongAggregator.combine(state.getOrDefault(groupId), max.getLong(valuesPosition))); } } } private void maybeEnableGroupIdTracking(SeenGroupIds seenGroupIds, LongBlock vBlock) { if (vBlock.mayHaveNulls()) { state.enableGroupIdTracking(seenGroupIds); } } @Override public void selectedMayContainUnseenGroups(SeenGroupIds seenGroupIds) { state.enableGroupIdTracking(seenGroupIds); } @Override public void evaluateIntermediate(Block[] blocks, int offset, IntVector selected) { state.toIntermediate(blocks, offset, selected, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, IntVector selected, GroupingAggregatorEvaluationContext ctx) { blocks[offset] = state.toValuesBlock(selected, ctx.driverContext()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
MaxLongGroupingAggregatorFunction
java
quarkusio__quarkus
extensions/spring-data-jpa/deployment/src/main/java/io/quarkus/spring/data/deployment/DotNames.java
{ "start": 1988, "end": 10711 }
class ____ { public static final DotName SPRING_DATA_REPOSITORY = DotName .createSimple(Repository.class.getName()); public static final DotName SPRING_DATA_CRUD_REPOSITORY = DotName .createSimple(CrudRepository.class.getName()); public static final DotName SPRING_DATA_LIST_CRUD_REPOSITORY = DotName .createSimple(ListCrudRepository.class.getName()); public static final DotName SPRING_DATA_PAGING_REPOSITORY = DotName .createSimple(PagingAndSortingRepository.class.getName()); public static final DotName SPRING_DATA_LIST_PAGING_REPOSITORY = DotName .createSimple(ListPagingAndSortingRepository.class.getName()); public static final DotName SPRING_DATA_JPA_REPOSITORY = DotName .createSimple(JpaRepository.class.getName()); public static final DotName SPRING_DATA_REPOSITORY_DEFINITION = DotName .createSimple(RepositoryDefinition.class.getName()); public static final Set<DotName> SUPPORTED_REPOSITORIES = new HashSet<>(Arrays.asList( SPRING_DATA_JPA_REPOSITORY, SPRING_DATA_PAGING_REPOSITORY, SPRING_DATA_LIST_PAGING_REPOSITORY, SPRING_DATA_CRUD_REPOSITORY, SPRING_DATA_LIST_CRUD_REPOSITORY, SPRING_DATA_REPOSITORY)); public static final DotName SPRING_DATA_NO_REPOSITORY_BEAN = DotName .createSimple(NoRepositoryBean.class.getName()); public static final DotName SPRING_DATA_PAGEABLE = DotName .createSimple(Pageable.class.getName()); public static final DotName SPRING_DATA_PAGE_REQUEST = DotName .createSimple(PageRequest.class.getName()); public static final DotName SPRING_DATA_SORT = DotName .createSimple(Sort.class.getName()); public static final DotName SPRING_DATA_PAGE = DotName .createSimple(Page.class.getName()); public static final DotName SPRING_DATA_SLICE = DotName .createSimple(Slice.class.getName()); public static final DotName SPRING_DATA_QUERY = DotName .createSimple(Query.class.getName()); public static final DotName SPRING_DATA_PARAM = DotName .createSimple(Param.class.getName()); public static final DotName SPRING_DATA_MODIFYING = DotName .createSimple(Modifying.class.getName()); public static final DotName SPRING_DATA_PERSISTABLE = DotName .createSimple(Persistable.class.getName()); public static final DotName JPA_ID = DotName.createSimple(Id.class.getName()); public static final DotName JPA_EMBEDDED_ID = DotName.createSimple(EmbeddedId.class.getName()); public static final DotName VERSION = DotName.createSimple(Version.class.getName()); public static final DotName JPA_INHERITANCE = DotName.createSimple(Inheritance.class.getName()); public static final DotName JPA_MAPPED_SUPERCLASS = DotName.createSimple(MappedSuperclass.class.getName()); public static final DotName JPA_ENTITY = DotName.createSimple(Entity.class.getName());; public static final DotName JPA_NAMED_QUERY = DotName.createSimple(NamedQuery.class.getName()); public static final DotName JPA_NAMED_QUERIES = DotName.createSimple(NamedQueries.class.getName()); public static final DotName JPA_TRANSIENT = DotName.createSimple(Transient.class.getName()); public static final DotName VOID = DotName.createSimple(void.class.getName()); public static final DotName LONG = DotName.createSimple(Long.class.getName()); public static final DotName PRIMITIVE_LONG = DotName.createSimple(long.class.getName()); public static final DotName INTEGER = DotName.createSimple(Integer.class.getName()); public static final DotName PRIMITIVE_INTEGER = DotName.createSimple(int.class.getName()); public static final DotName SHORT = DotName.createSimple(Short.class.getName()); public static final DotName PRIMITIVE_SHORT = DotName.createSimple(short.class.getName()); public static final DotName CHARACTER = DotName.createSimple(Character.class.getName()); public static final DotName PRIMITIVE_CHAR = DotName.createSimple(char.class.getName()); public static final DotName BYTE = DotName.createSimple(Byte.class.getName()); public static final DotName PRIMITIVE_BYTE = DotName.createSimple(byte.class.getName()); public static final DotName DOUBLE = DotName.createSimple(Double.class.getName()); public static final DotName PRIMITIVE_DOUBLE = DotName.createSimple(double.class.getName()); public static final DotName FLOAT = DotName.createSimple(Float.class.getName()); public static final DotName PRIMITIVE_FLOAT = DotName.createSimple(float.class.getName()); public static final DotName BOOLEAN = DotName.createSimple(Boolean.class.getName()); public static final DotName PRIMITIVE_BOOLEAN = DotName.createSimple(boolean.class.getName()); public static final DotName BIG_INTEGER = DotName.createSimple(BigInteger.class.getName()); public static final DotName BIG_DECIMAL = DotName.createSimple(BigDecimal.class.getName()); public static final DotName STRING = DotName.createSimple(String.class.getName()); public static final DotName ITERATOR = DotName.createSimple(Iterator.class.getName()); public static final DotName COLLECTION = DotName.createSimple(Collection.class.getName()); public static final DotName LIST = DotName.createSimple(List.class.getName()); public static final DotName SET = DotName.createSimple(Set.class.getName()); public static final DotName STREAM = DotName.createSimple(Stream.class.getName()); public static final DotName OPTIONAL = DotName.createSimple(Optional.class.getName()); public static final DotName OBJECT = DotName.createSimple(Object.class.getName()); public static final DotName LOCALE = DotName.createSimple(Locale.class.getName()); public static final DotName TIMEZONE = DotName.createSimple(TimeZone.class.getName()); public static final DotName URL = DotName.createSimple(java.net.URL.class.getName()); public static final DotName CLASS = DotName.createSimple(Class.class.getName()); public static final DotName UUID = DotName.createSimple(java.util.UUID.class.getName()); public static final DotName BLOB = DotName.createSimple(java.sql.Blob.class.getName()); public static final DotName CLOB = DotName.createSimple(java.sql.Clob.class.getName()); public static final DotName NCLOB = DotName.createSimple(java.sql.NClob.class.getName()); // temporal types public static final DotName UTIL_DATE = DotName.createSimple(java.util.Date.class.getName()); public static final DotName CALENDAR = DotName.createSimple(Calendar.class.getName()); // java.sql public static final DotName SQL_DATE = DotName.createSimple(java.sql.Date.class.getName()); public static final DotName SQL_TIME = DotName.createSimple(java.sql.Time.class.getName()); public static final DotName SQL_TIMESTAMP = DotName.createSimple(java.sql.Timestamp.class.getName()); // java.time public static final DotName LOCAL_DATE = DotName.createSimple(LocalDate.class.getName()); public static final DotName LOCAL_TIME = DotName.createSimple(LocalTime.class.getName()); public static final DotName LOCAL_DATETIME = DotName.createSimple(LocalDateTime.class.getName()); public static final DotName OFFSET_TIME = DotName.createSimple(OffsetTime.class.getName()); public static final DotName OFFSET_DATETIME = DotName.createSimple(OffsetDateTime.class.getName()); public static final DotName DURATION = DotName.createSimple(Duration.class.getName()); public static final DotName INSTANT = DotName.createSimple(Instant.class.getName()); public static final DotName ZONED_DATETIME = DotName.createSimple(ZonedDateTime.class.getName()); // https://docs.hibernate.org/stable/orm/userguide/html_single/#basic // Should be in sync with org.hibernate.type.BasicTypeRegistry public static final Set<DotName> HIBERNATE_PROVIDED_BASIC_TYPES = new HashSet<>(Arrays.asList( STRING, CLASS, BOOLEAN, PRIMITIVE_BOOLEAN, INTEGER, PRIMITIVE_INTEGER, LONG, PRIMITIVE_LONG, SHORT, PRIMITIVE_SHORT, BYTE, PRIMITIVE_BYTE, CHARACTER, PRIMITIVE_CHAR, DOUBLE, PRIMITIVE_DOUBLE, FLOAT, PRIMITIVE_FLOAT, BIG_INTEGER, BIG_DECIMAL, UTIL_DATE, CALENDAR, SQL_DATE, SQL_TIME, SQL_TIMESTAMP, LOCAL_DATE, LOCAL_TIME, LOCAL_DATETIME, OFFSET_TIME, OFFSET_DATETIME, DURATION, INSTANT, ZONED_DATETIME, TIMEZONE, LOCALE, URL, UUID, BLOB, CLOB, NCLOB)); private DotNames() { } }
DotNames
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/spi/PropertyData.java
{ "start": 415, "end": 830 }
interface ____ { /** * @return default member access (whether field or property) * @throws MappingException No getter or field found or wrong JavaBean spec usage */ AccessType getDefaultAccess(); /** * @return property name * @throws MappingException No getter or field found or wrong JavaBean spec usage */ String getPropertyName() throws MappingException; /** * Returns the returned
PropertyData
java
google__dagger
javatests/dagger/internal/codegen/XTypesStripTypeNameTest.java
{ "start": 2538, "end": 2833 }
interface ____ {}", "}"), /* strippedTypeName = */ "Foo<Bar<Baz>, Bar<Baz>>"); } @Test public void multipleParametersSameArgument() { assertStrippedWildcardTypeNameEquals( /* source = */ CompilerTests.javaSource( "Subject", "
Baz
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/IterableAssertBaseTest.java
{ "start": 915, "end": 1487 }
class ____ extends BaseTestTemplate<ConcreteIterableAssert<Object>, Iterable<Object>> { protected Iterables iterables; @Override protected ConcreteIterableAssert<Object> create_assertions() { return new ConcreteIterableAssert<>(emptyList()); } @Override protected void inject_internal_objects() { super.inject_internal_objects(); iterables = mock(Iterables.class); assertions.iterables = iterables; } protected Iterables getIterables(ConcreteIterableAssert<Object> assertions) { return assertions.iterables; } }
IterableAssertBaseTest
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/metrics/MetricsFactory.java
{ "start": 339, "end": 778 }
interface ____ { /** A well-known string for MicroProfile metrics provided by the SmallRye Metrics quarkus extension */ final String MP_METRICS = "smallrye-metrics"; /** A well-known string for Micrometer metrics provided by the Micrometer Metrics quarkus extension */ final String MICROMETER = "micrometer"; /** Registry type or scope. This may not be used by all metrics extensions. */ public static
MetricsFactory
java
apache__camel
tooling/openapi-rest-dsl-generator/src/main/java/org/apache/camel/generator/openapi/RestDslSourceCodeGenerator.java
{ "start": 1640, "end": 9267 }
class ____<T> extends RestDslGenerator<RestDslSourceCodeGenerator<T>> { static final String DEFAULT_CLASS_NAME = "RestDslRoute"; static final String DEFAULT_PACKAGE_NAME = "rest.dsl.generated"; private static final String DEFAULT_INDENT = " "; private Function<OpenAPI, String> classNameGenerator = RestDslSourceCodeGenerator::generateClassName; private Instant generated = Instant.now(); private String indent = DEFAULT_INDENT; private Function<OpenAPI, String> packageNameGenerator = RestDslSourceCodeGenerator::generatePackageName; private boolean sourceCodeTimestamps; RestDslSourceCodeGenerator(final OpenAPI document) { super(document); } public abstract void generate(T destination) throws IOException; public RestDslSourceCodeGenerator<T> withClassName(final String className) { notEmpty(className, "className"); this.classNameGenerator = s -> className; return this; } public RestDslSourceCodeGenerator<T> withIndent(final String indent) { this.indent = ObjectHelper.notNull(indent, "indent"); return this; } public RestDslSourceCodeGenerator<T> withoutSourceCodeTimestamps() { sourceCodeTimestamps = false; return this; } public RestDslSourceCodeGenerator<T> withPackageName(final String packageName) { notEmpty(packageName, "packageName"); this.packageNameGenerator = s -> packageName; return this; } public RestDslSourceCodeGenerator<T> withSourceCodeTimestamps() { sourceCodeTimestamps = true; return this; } MethodSpec generateConfigureMethod(final OpenAPI document) { final MethodSpec.Builder configure = MethodSpec.methodBuilder("configure").addModifiers(Modifier.PUBLIC) .returns(void.class).addJavadoc("Defines Apache Camel routes using REST DSL fluent API.\n"); final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(configure); boolean restConfig = restComponent != null || restContextPath != null || clientRequestValidation; if (restConfig) { configure.addCode("\n"); configure.addCode("restConfiguration()"); if (ObjectHelper.isNotEmpty(restComponent)) { configure.addCode(".component(\"" + restComponent + "\")"); } if (ObjectHelper.isNotEmpty(restContextPath)) { configure.addCode(".contextPath(\"" + restContextPath + "\")"); } if (ObjectHelper.isNotEmpty(apiContextPath)) { configure.addCode(".apiContextPath(\"" + apiContextPath + "\")"); } if (clientRequestValidation) { configure.addCode(".clientRequestValidation(true)"); } configure.addCode(";\n"); } final String basePath = RestDslGenerator.determineBasePathFrom(this.basePath, document); for (String name : document.getPaths().keySet()) { PathItem s = document.getPaths().get(name); // there must be at least one verb if (s.getGet() != null || s.getDelete() != null || s.getHead() != null || s.getOptions() != null || s.getPut() != null || s.getPatch() != null || s.getPost() != null) { // there must be at least one operation accepted by the filter (otherwise we generate empty rest methods) boolean anyAccepted = filter == null || ofNullable(s.getGet(), s.getDelete(), s.getHead(), s.getOptions(), s.getPut(), s.getPatch(), s.getPost()) .stream().anyMatch(o -> filter.accept(o.getOperationId())); if (anyAccepted) { // create new rest statement per path to avoid a giant chained single method PathVisitor<MethodSpec> restDslStatement = new PathVisitor<>(basePath, emitter, filter, destinationGenerator(), dtoPackageName); restDslStatement.visit(document, name, s); emitter.endEmit(); } } } return emitter.result(); } Instant generated() { return generated; } JavaFile generateSourceCode() { final MethodSpec methodSpec = generateConfigureMethod(document); final String classNameToUse = classNameGenerator.apply(document); final AnnotationSpec.Builder generatedAnnotation = AnnotationSpec.builder(Generated.class).addMember("value", "$S", getClass().getName()); if (sourceCodeTimestamps) { generatedAnnotation.addMember("date", "$S", generated()); } final TypeSpec.Builder builder = TypeSpec.classBuilder(classNameToUse).superclass(RouteBuilder.class) .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addMethod(methodSpec) .addAnnotation(generatedAnnotation.build()) .addJavadoc("Generated from OpenApi specification by Camel REST DSL generator.\n"); if (springComponent) { final AnnotationSpec.Builder springAnnotation = AnnotationSpec.builder(ClassName.bestGuess("org.springframework.stereotype.Component")); builder.addAnnotation(springAnnotation.build()); } final TypeSpec generatedRouteBuilder = builder.build(); final String packageNameToUse = packageNameGenerator.apply(document); return JavaFile.builder(packageNameToUse, generatedRouteBuilder).indent(indent).build(); } RestDslSourceCodeGenerator<T> withGeneratedTime(final Instant generated) { this.generated = generated; return this; } static String generateClassName(final OpenAPI document) { final Info info = document.getInfo(); if (info == null) { return DEFAULT_CLASS_NAME; } final String title = info.getTitle(); if (title == null) { return DEFAULT_CLASS_NAME; } final String className = title.chars().filter(Character::isJavaIdentifierPart).filter(c -> c < 'z').boxed() .collect(Collector.of(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append, StringBuilder::toString)); if (className.isEmpty() || !Character.isJavaIdentifierStart(className.charAt(0))) { return DEFAULT_CLASS_NAME; } return className; } static String generatePackageName(final OpenAPI document) { final String host = RestDslGenerator.determineHostFrom(document); if (ObjectHelper.isNotEmpty(host)) { final StringBuilder packageName = new StringBuilder(); final String hostWithoutPort = host.replaceFirst(":.*", ""); if ("localhost".equalsIgnoreCase(hostWithoutPort)) { return DEFAULT_PACKAGE_NAME; } final String[] parts = hostWithoutPort.split("\\."); for (int i = parts.length - 1; i >= 0; i--) { packageName.append(parts[i]); if (i != 0) { packageName.append('.'); } } return packageName.toString(); } return DEFAULT_PACKAGE_NAME; } private static <T> List<T> ofNullable(T... t) { List<T> list = new ArrayList<>(); for (T o : t) { if (o != null) { list.add(o); } } return list; } }
RestDslSourceCodeGenerator
java
mapstruct__mapstruct
integrationtest/src/test/resources/java8Test/src/main/java/org/mapstruct/itest/java8/Target.java
{ "start": 191, "end": 576 }
class ____ { private String givenName; private String surname; public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } }
Target
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/request/target/PreloadTargetTest.java
{ "start": 795, "end": 3108 }
class ____ { @Mock private RequestManager requestManager; @Before public void setUp() { MockitoAnnotations.initMocks(this); shadowOf(Looper.getMainLooper()).pause(); } @Test public void testCallsSizeReadyWithGivenDimensions() { int width = 1234; int height = 456; PreloadTarget<Object> target = PreloadTarget.obtain(requestManager, width, height); SizeReadyCallback cb = mock(SizeReadyCallback.class); target.getSize(cb); verify(cb).onSizeReady(eq(width), eq(height)); } // This isn't really supposed to happen, but just to double check... @Test public void onResourceReady_withNullRequest_doesNotClearTarget() { PreloadTarget<Object> target = PreloadTarget.obtain(requestManager, 100, 100); target.setRequest(null); callOnResourceReadyAndRunUiRunnables(target); verify(requestManager, never()).clear(target); } @Test public void onResourceReady_withNotYetCompleteRequest_doesNotClearTarget() { Request request = mock(Request.class); when(request.isComplete()).thenReturn(false); PreloadTarget<Object> target = PreloadTarget.obtain(requestManager, 100, 100); target.setRequest(request); callOnResourceReadyAndRunUiRunnables(target); verify(requestManager, never()).clear(target); } @Test public void onResourceReady_withCompleteRequest_postsToClearTarget() { Request request = mock(Request.class); when(request.isComplete()).thenReturn(true); PreloadTarget<Object> target = PreloadTarget.obtain(requestManager, 100, 100); target.setRequest(request); callOnResourceReadyAndRunUiRunnables(target); verify(requestManager).clear(target); } @Test public void onResourceReady_withCompleteRequest_doesNotImmediatelyClearTarget() { Request request = mock(Request.class); when(request.isComplete()).thenReturn(true); PreloadTarget<Object> target = PreloadTarget.obtain(requestManager, 100, 100); target.setRequest(request); target.onResourceReady(new Object(), /* transition= */ null); verify(requestManager, never()).clear(target); } private void callOnResourceReadyAndRunUiRunnables(Target<Object> target) { target.onResourceReady(new Object(), /* transition= */ null); shadowOf(Looper.getMainLooper()).idle(); } }
PreloadTargetTest
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/ReadOnlySessionStore.java
{ "start": 1149, "end": 22230 }
interface ____<K, AGG> { /** * Fetch any sessions with the matching key and the sessions end is &ge; earliestSessionEndTime * and the sessions start is &le; latestSessionStartTime iterating from earliest to latest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param key the key to return sessions for * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration starts. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration ends. * @return iterator of sessions with the matching key and aggregated values, from earliest to * latest session time. * @throws NullPointerException If null is used for key. */ default KeyValueIterator<Windowed<K>, AGG> findSessions(final K key, final long earliestSessionEndTime, final long latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Fetch any sessions with the matching key and the sessions end is &ge; earliestSessionEndTime * and the sessions start is &le; latestSessionStartTime iterating from earliest to latest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param key the key to return sessions for * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration starts. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration ends. * @return iterator of sessions with the matching key and aggregated values, from earliest to * latest session time. * @throws NullPointerException If null is used for key. */ default KeyValueIterator<Windowed<K>, AGG> findSessions(final K key, final Instant earliestSessionEndTime, final Instant latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Fetch any sessions with the matching key and the sessions end is &ge; earliestSessionEndTime * and the sessions start is &le; latestSessionStartTime iterating from latest to earliest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param key the key to return sessions for * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration ends. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration starts. * @return backward iterator of sessions with the matching key and aggregated values, from * latest to earliest session time. * @throws NullPointerException If null is used for key. */ default KeyValueIterator<Windowed<K>, AGG> backwardFindSessions(final K key, final long earliestSessionEndTime, final long latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Fetch any sessions with the matching key and the sessions end is &ge; earliestSessionEndTime * and the sessions start is &le; latestSessionStartTime iterating from latest to earliest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param key the key to return sessions for * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration ends. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration starts. * @return backward iterator of sessions with the matching key and aggregated values, from * latest to earliest session time. * @throws NullPointerException If null is used for key. */ default KeyValueIterator<Windowed<K>, AGG> backwardFindSessions(final K key, final Instant earliestSessionEndTime, final Instant latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Fetch any sessions in the given range of keys and the sessions end is &ge; * earliestSessionEndTime and the sessions start is &le; latestSessionStartTime iterating from * earliest to latest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param keyFrom The first key that could be in the range * A null value indicates a starting position from the first element in the store. * @param keyTo The last key that could be in the range * A null value indicates that the range ends with the last element in the store. * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration starts. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration ends. * @return iterator of sessions with the matching keys and aggregated values, from earliest to * latest session time. */ default KeyValueIterator<Windowed<K>, AGG> findSessions(final K keyFrom, final K keyTo, final long earliestSessionEndTime, final long latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Fetch any sessions in the given range of keys and the sessions end is &ge; * earliestSessionEndTime and the sessions start is &le; latestSessionStartTime iterating from * earliest to latest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param keyFrom The first key that could be in the range * A null value indicates a starting position from the first element in the store. * @param keyTo The last key that could be in the range * A null value indicates that the range ends with the last element in the store. * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration starts. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration ends. * @return iterator of sessions with the matching keys and aggregated values, from earliest to * latest session time. */ default KeyValueIterator<Windowed<K>, AGG> findSessions(final K keyFrom, final K keyTo, final Instant earliestSessionEndTime, final Instant latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Fetch any sessions in the given range of keys and the sessions end is &ge; * earliestSessionEndTime and the sessions start is &le; latestSessionStartTime iterating from * latest to earliest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param keyFrom The first key that could be in the range * A null value indicates a starting position from the first element in the store. * @param keyTo The last key that could be in the range * A null value indicates that the range ends with the last element in the store. * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration ends. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration starts. * @return backward iterator of sessions with the matching keys and aggregated values, from * latest to earliest session time. */ default KeyValueIterator<Windowed<K>, AGG> backwardFindSessions(final K keyFrom, final K keyTo, final long earliestSessionEndTime, final long latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Fetch any sessions in the given range of keys and the sessions end is &ge; * earliestSessionEndTime and the sessions start is &le; latestSessionStartTime iterating from * latest to earliest. * I.e., earliestSessionEndTime is the lower bound of the search interval and latestSessionStartTime * is the upper bound of the search interval, and the method returns all sessions that overlap * with the search interval. * Thus, if a session ends before earliestSessionEndTime, or starts after latestSessionStartTime * it won't be contained in the result: * <pre>{@code * earliestSessionEndTime: ESET * latestSessionStartTime: LSST * * [ESET............LSST] * [not-included] [included] [included] [included] [not-included] * }</pre> * <p> * This iterator must be closed after use. * * @param keyFrom The first key that could be in the range * A null value indicates a starting position from the first element in the store. * @param keyTo The last key that could be in the range * A null value indicates that the range ends with the last element in the store. * @param earliestSessionEndTime the end timestamp of the earliest session to search for, where * iteration ends. * @param latestSessionStartTime the end timestamp of the latest session to search for, where * iteration starts. * @return backward iterator of sessions with the matching keys and aggregated values, from * latest to earliest session time. */ default KeyValueIterator<Windowed<K>, AGG> backwardFindSessions(final K keyFrom, final K keyTo, final Instant earliestSessionEndTime, final Instant latestSessionStartTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Get the value of key from a single session. * * @param key the key to fetch * @param sessionStartTime start timestamp of the session * @param sessionEndTime end timestamp of the session * @return The value or {@code null} if no session with the exact start and end timestamp exists * for the given key * @throws NullPointerException If {@code null} is used for any key. */ default AGG fetchSession(final K key, final long sessionStartTime, final long sessionEndTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Get the value of key from a single session. * * @param key the key to fetch * @param sessionStartTime start timestamp of the session * @param sessionEndTime end timestamp of the session * @return The value or {@code null} if no session with the exact start and end timestamp exists * for the given key * @throws NullPointerException If {@code null} is used for any key. */ default AGG fetchSession(final K key, final Instant sessionStartTime, final Instant sessionEndTime) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Retrieve all aggregated sessions for the provided key. This iterator must be closed after * use. * <p> * For each key, the iterator guarantees ordering of sessions, starting from the oldest/earliest * available session to the newest/latest session. * * @param key record key to find aggregated session values for * @return KeyValueIterator containing all sessions for the provided key, from oldest to newest * session. * @throws NullPointerException If null is used for key. */ KeyValueIterator<Windowed<K>, AGG> fetch(final K key); /** * Retrieve all aggregated sessions for the provided key. This iterator must be closed after * use. * <p> * For each key, the iterator guarantees ordering of sessions, starting from the newest/latest * available session to the oldest/earliest session. * * @param key record key to find aggregated session values for * @return backward KeyValueIterator containing all sessions for the provided key, from newest * to oldest session. * @throws NullPointerException If null is used for key. */ default KeyValueIterator<Windowed<K>, AGG> backwardFetch(final K key) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } /** * Retrieve all aggregated sessions for the given range of keys. This iterator must be closed * after use. * <p> * For each key, the iterator guarantees ordering of sessions, starting from the oldest/earliest * available session to the newest/latest session. * * @param keyFrom first key in the range to find aggregated session values for * A null value indicates a starting position from the first element in the store. * @param keyTo last key in the range to find aggregated session values for * A null value indicates that the range ends with the last element in the store. * @return KeyValueIterator containing all sessions for the provided key, from oldest to newest * session. */ KeyValueIterator<Windowed<K>, AGG> fetch(final K keyFrom, final K keyTo); /** * Retrieve all aggregated sessions for the given range of keys. This iterator must be closed * after use. * <p> * For each key, the iterator guarantees ordering of sessions, starting from the newest/latest * available session to the oldest/earliest session. * * @param keyFrom first key in the range to find aggregated session values for * A null value indicates a starting position from the first element in the store. * @param keyTo last key in the range to find aggregated session values for * A null value indicates that the range ends with the last element in the store. * @return backward KeyValueIterator containing all sessions for the provided key, from newest * to oldest session. */ default KeyValueIterator<Windowed<K>, AGG> backwardFetch(final K keyFrom, final K keyTo) { throw new UnsupportedOperationException( "This API is not supported by this implementation of ReadOnlySessionStore."); } }
ReadOnlySessionStore
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/serialization/ByteArraySchemaTest.java
{ "start": 985, "end": 1318 }
class ____ { @Test void testSimpleSerialisation() throws IOException { final byte[] testBytes = "hello world".getBytes(); assertThat(new ByteArraySchema().serialize(testBytes)).isEqualTo(testBytes); assertThat(new ByteArraySchema().deserialize(testBytes)).isEqualTo(testBytes); } }
ByteArraySchemaTest
java
junit-team__junit5
junit-vintage-engine/src/testFixtures/java/org/junit/vintage/engine/samples/junit4/PlainJUnit4TestCaseWithSingleInheritedTestWhichFails.java
{ "start": 395, "end": 510 }
class ____ extends PlainJUnit4TestCaseWithSingleTestWhichFails { }
PlainJUnit4TestCaseWithSingleInheritedTestWhichFails
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/support/http/RestUtilTest.java
{ "start": 927, "end": 3358 }
class ____ { @Test public void testRestUtil() { Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType(null, null)); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType(null, "*/*")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "*/*")); Assertions.assertFalse(RestUtil.isValidOrAcceptedContentType("application/json", "application/xml")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "application/json,application/xml")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "application/json, application/xml")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "application/xml,application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "application/xml, application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "application/xml,application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json", "application/xml, application/json")); Assertions.assertFalse(RestUtil.isValidOrAcceptedContentType("application/xml", "application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/xml", "application/json,application/xml")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/xml", "application/json, application/xml")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/xml", "application/xml,application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/xml", "application/xml, application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/xml", "application/xml,application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/xml", "application/xml, application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json,application/xml", "application/json")); Assertions.assertTrue(RestUtil.isValidOrAcceptedContentType("application/json,application/xml", "application/xml")); } }
RestUtilTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/tableperclass/TablePerClassInheritanceWithConcreteRootTest.java
{ "start": 7309, "end": 7647 }
class ____ extends Person { private String name; public Customer() { } public Customer(Integer id, String name) { super( id ); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity(name = "DomesticCustomer") public static
Customer
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/interceptor/InterceptorAndNonPublicDecoratorTest.java
{ "start": 817, "end": 1586 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(Converter.class, ToUpperCaseConverter.class, TrimConverterDecorator.class, LoggingInterceptor.class, Logging.class); @Test public void testInterceptionAndDecoration() { LoggingInterceptor.LOG.set(null); ToUpperCaseConverter converter = Arc.container().instance(ToUpperCaseConverter.class).get(); assertEquals("HOLA!", converter.convert(" holA!")); assertEquals("HOLA!", LoggingInterceptor.LOG.get()); assertEquals(" HOLA!", converter.convertNoDelegation(" holA!")); assertEquals(" HOLA!", LoggingInterceptor.LOG.get()); } @Priority(1) @Decorator static
InterceptorAndNonPublicDecoratorTest
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFlatMapBiSelector.java
{ "start": 2016, "end": 3790 }
class ____<T, U, R> implements MaybeObserver<T>, Disposable { final Function<? super T, ? extends MaybeSource<? extends U>> mapper; final InnerObserver<T, U, R> inner; FlatMapBiMainObserver(MaybeObserver<? super R> actual, Function<? super T, ? extends MaybeSource<? extends U>> mapper, BiFunction<? super T, ? super U, ? extends R> resultSelector) { this.inner = new InnerObserver<>(actual, resultSelector); this.mapper = mapper; } @Override public void dispose() { DisposableHelper.dispose(inner); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(inner.get()); } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.setOnce(inner, d)) { inner.downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { MaybeSource<? extends U> next; try { next = Objects.requireNonNull(mapper.apply(value), "The mapper returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); inner.downstream.onError(ex); return; } if (DisposableHelper.replace(inner, null)) { inner.value = value; next.subscribe(inner); } } @Override public void onError(Throwable e) { inner.downstream.onError(e); } @Override public void onComplete() { inner.downstream.onComplete(); } static final
FlatMapBiMainObserver
java
lettuce-io__lettuce-core
src/test/jmh/io/lettuce/core/codec/StringCodecBenchmark.java
{ "start": 461, "end": 1545 }
class ____ { @Benchmark public void encodeUtf8Unpooled(Input input) { input.blackhole.consume(input.utf8Codec.encodeKey(input.teststring)); } @Benchmark public void encodeUtf8ToBuf(Input input) { input.byteBuf.clear(); input.utf8Codec.encode(input.teststring, input.byteBuf); } @Benchmark public void encodeUtf8PlainStringToBuf(Input input) { input.byteBuf.clear(); input.utf8Codec.encode(input.teststringPlain, input.byteBuf); } @Benchmark public void encodeAsciiToBuf(Input input) { input.byteBuf.clear(); input.asciiCodec.encode(input.teststringPlain, input.byteBuf); } @Benchmark public void encodeIsoToBuf(Input input) { input.byteBuf.clear(); input.isoCodec.encode(input.teststringPlain, input.byteBuf); } @Benchmark public void decodeUtf8Unpooled(Input input) { input.input.rewind(); input.blackhole.consume(input.utf8Codec.decodeKey(input.input)); } @State(Scope.Thread) public static
StringCodecBenchmark
java
google__dagger
javatests/dagger/functional/multibindings/ByteKey.java
{ "start": 698, "end": 736 }
interface ____ { byte value(); }
ByteKey
java
apache__camel
components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/KameletConsumer.java
{ "start": 1112, "end": 2842 }
class ____ extends DefaultConsumer implements ShutdownAware, Suspendable { private final InflightRepository inflight; private final KameletComponent component; private final String key; public KameletConsumer(KameletEndpoint endpoint, Processor processor, String key) { super(endpoint, processor); this.component = endpoint.getComponent(); this.key = key; this.inflight = endpoint.getCamelContext().getInflightRepository(); } @Override public KameletEndpoint getEndpoint() { return (KameletEndpoint) super.getEndpoint(); } @Override protected void doStart() throws Exception { super.doStart(); component.addConsumer(key, this); } @Override protected void doStop() throws Exception { component.removeConsumer(key, this); super.doStop(); } @Override protected void doSuspend() throws Exception { component.removeConsumer(key, this); } @Override protected void doResume() throws Exception { // resume by using the start logic component.addConsumer(key, this); } @Override public boolean deferShutdown(ShutdownRunningTask shutdownRunningTask) { // deny stopping on shutdown as we want kamelet consumers to run in // case some other queues depend on this consumer to run, so it can // complete its exchanges return true; } @Override public int getPendingExchangesSize() { // capture the inflight counter from the route return inflight.size(getRouteId()); } @Override public void prepareShutdown(boolean suspendOnly, boolean forced) { // noop } }
KameletConsumer
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/source/defaultExpressions/java/ErroneousDefaultExpressionConstantMapper.java
{ "start": 435, "end": 764 }
interface ____ { @Mappings({ @Mapping(target = "sourceId", constant = "3", defaultExpression = "java( UUID.randomUUID().toString() )"), @Mapping(target = "sourceDate", source = "date", defaultExpression = "java( new Date())") }) Target sourceToTarget(Source s); }
ErroneousDefaultExpressionConstantMapper
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/CompositeRequestConditionTests.java
{ "start": 1189, "end": 5115 }
class ____ { private ParamsRequestCondition param1; private ParamsRequestCondition param2; private ParamsRequestCondition param3; private HeadersRequestCondition header1; private HeadersRequestCondition header2; private HeadersRequestCondition header3; @BeforeEach void setup() { this.param1 = new ParamsRequestCondition("param1"); this.param2 = new ParamsRequestCondition("param2"); this.param3 = this.param1.combine(this.param2); this.header1 = new HeadersRequestCondition("header1"); this.header2 = new HeadersRequestCondition("header2"); this.header3 = this.header1.combine(this.header2); } @Test void combine() { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1, this.header1); CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param2, this.header2); CompositeRequestCondition cond3 = new CompositeRequestCondition(this.param3, this.header3); assertThat(cond1.combine(cond2)).isEqualTo(cond3); } @Test void combineEmpty() { CompositeRequestCondition empty = new CompositeRequestCondition(); CompositeRequestCondition notEmpty = new CompositeRequestCondition(this.param1); assertThat(empty.combine(empty)).isSameAs(empty); assertThat(notEmpty.combine(empty)).isSameAs(notEmpty); assertThat(empty.combine(notEmpty)).isSameAs(notEmpty); } @Test void combineDifferentLength() { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1); assertThatIllegalArgumentException().isThrownBy(() -> cond1.combine(cond2)); } @Test void match() { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); request.setParameter("param1", "paramValue1"); request.addHeader("header1", "headerValue1"); RequestCondition<?> getPostCond = new RequestMethodsRequestCondition(RequestMethod.GET, RequestMethod.POST); RequestCondition<?> getCond = new RequestMethodsRequestCondition(RequestMethod.GET); CompositeRequestCondition condition = new CompositeRequestCondition(this.param1, getPostCond); CompositeRequestCondition matchingCondition = new CompositeRequestCondition(this.param1, getCond); assertThat(condition.getMatchingCondition(request)).isEqualTo(matchingCondition); } @Test void noMatch() { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); CompositeRequestCondition cond = new CompositeRequestCondition(this.param1); assertThat(cond.getMatchingCondition(request)).isNull(); } @Test void matchEmpty() { CompositeRequestCondition empty = new CompositeRequestCondition(); assertThat(empty.getMatchingCondition(new MockHttpServletRequest())).isSameAs(empty); } @Test void compare() { HttpServletRequest request = new MockHttpServletRequest(); CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond3 = new CompositeRequestCondition(this.param3); assertThat(cond1.compareTo(cond3, request)).isEqualTo(1); assertThat(cond3.compareTo(cond1, request)).isEqualTo(-1); } @Test void compareEmpty() { HttpServletRequest request = new MockHttpServletRequest(); CompositeRequestCondition empty = new CompositeRequestCondition(); CompositeRequestCondition notEmpty = new CompositeRequestCondition(this.param1); assertThat(empty.compareTo(empty, request)).isEqualTo(0); assertThat(notEmpty.compareTo(empty, request)).isEqualTo(-1); assertThat(empty.compareTo(notEmpty, request)).isEqualTo(1); } @Test void compareDifferentLength() { CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1); CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1); assertThatIllegalArgumentException().isThrownBy(() -> cond1.compareTo(cond2, new MockHttpServletRequest())); } }
CompositeRequestConditionTests
java
apache__camel
components/camel-huawei/camel-huaweicloud-frs/src/generated/java/org/apache/camel/component/huaweicloud/frs/FaceRecognitionEndpointUriFactory.java
{ "start": 525, "end": 3167 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":operation"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(24); props.add("accessKey"); props.add("actionTimes"); props.add("actions"); props.add("anotherImageBase64"); props.add("anotherImageFilePath"); props.add("anotherImageUrl"); props.add("endpoint"); props.add("ignoreSslVerification"); props.add("imageBase64"); props.add("imageFilePath"); props.add("imageUrl"); props.add("lazyStartProducer"); props.add("operation"); props.add("projectId"); props.add("proxyHost"); props.add("proxyPassword"); props.add("proxyPort"); props.add("proxyUser"); props.add("region"); props.add("secretKey"); props.add("serviceKeys"); props.add("videoBase64"); props.add("videoFilePath"); props.add("videoUrl"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(5); secretProps.add("accessKey"); secretProps.add("proxyPassword"); secretProps.add("proxyUser"); secretProps.add("secretKey"); secretProps.add("serviceKeys"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "hwcloud-frs".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "operation", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
FaceRecognitionEndpointUriFactory
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanContextCustomizerEqualityTests.java
{ "start": 3586, "end": 3685 }
class ____ { @MockitoSpyBean("serviceBean") private String serviceToMock; } static
Case5ByName
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java
{ "start": 2073, "end": 8308 }
class ____ { @Test public void testNormalOperation() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); // filter.init(null); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result != null).isTrue(); assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test public void testConstructorInjectionOfAuthenticationManager() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "dokdo"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter( createAuthenticationManager()); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result).isNotNull(); } @Test public void testNullPasswordHandledGracefully() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull(); } @Test public void testNullUsernameHandledGracefully() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull(); } @Test public void testUsingDifferentParameterNamesWorksAsExpected() { UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); filter.setUsernameParameter("x"); filter.setPasswordParameter("y"); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter("x", "rod"); request.addParameter("y", "koala"); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result).isNotNull(); assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test public void testSpacesAreTrimmedCorrectlyFromUsername() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, " rod "); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result.getName()).isEqualTo("rod"); } @Test public void testFailedAuthenticationThrowsException() { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/"); request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); filter.setAuthenticationManager(am); assertThatExceptionOfType(AuthenticationException.class) .isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse())); } @Test public void testSecurityContextHolderStrategyUsed() throws Exception { MockHttpServletRequest request = post("/login") .param(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod") .param(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala") .build(); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAuthenticationManager(createAuthenticationManager()); SecurityContextHolderStrategy strategy = spy(SecurityContextHolder.getContextHolderStrategy()); filter.setSecurityContextHolderStrategy(strategy); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class); verify(strategy).setContext(captor.capture()); assertThat(captor.getValue().getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class); } /** * SEC-571 */ @Test public void noSessionIsCreatedIfAllowSessionCreationIsFalse() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("POST"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); filter.setAllowSessionCreation(false); filter.setAuthenticationManager(createAuthenticationManager()); filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(request.getSession(false)).isNull(); } private AuthenticationManager createAuthenticationManager() { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))) .willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]); return am; } }
UsernamePasswordAuthenticationFilterTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeRemoveTest.java
{ "start": 388, "end": 1002 }
class ____ { @Test public void removeTest(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Person person = new Person(); person.setId( 1L ); person.setName( "John Doe" ); Phone phone = new Phone(); phone.setId( 1L ); phone.setNumber( "123-456-7890" ); person.addPhone( phone ); entityManager.persist( person ); } ); scope.inTransaction( entityManager -> { //tag::pc-cascade-remove-example[] Person person = entityManager.find( Person.class, 1L ); entityManager.remove( person ); //end::pc-cascade-remove-example[] } ); } }
CascadeRemoveTest
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/metrics/StoreMetricsManager.java
{ "start": 1287, "end": 1415 }
interface ____ a unified way to access metrics functionality * regardless of the underlying message store type. */ public
provides
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/fielddata/AbstractNumericDocValues.java
{ "start": 895, "end": 1261 }
class ____ extends NumericDocValues { @Override public int nextDoc() { throw new UnsupportedOperationException(); } @Override public int advance(int target) { throw new UnsupportedOperationException(); } @Override public long cost() { throw new UnsupportedOperationException(); } }
AbstractNumericDocValues
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronEvery2DirectTest.java
{ "start": 1511, "end": 3433 }
class ____ { private static final String CONFIG = "log4j-rolling-cron-every2-direct.xml"; private static final String DIR = "target/rolling-cron-every2Direct"; private static final int LOOP_COUNT = 100; private final LoggerContextRule loggerContextRule = LoggerContextRule.createShutdownTimeoutLoggerContextRule(CONFIG); @Rule public RuleChain chain = loggerContextRule.withCleanFoldersRule(DIR); @Test public void testAppender() throws Exception { // TODO Is there a better way to test than putting the thread to sleep all over the place? final Logger logger = loggerContextRule.getLogger(); final long end = System.currentTimeMillis() + 5000; final Random rand = new SecureRandom(); rand.setSeed(end); int count = 1; do { logger.debug("Log Message {}", count++); Thread.sleep(10 * rand.nextInt(100)); } while (System.currentTimeMillis() < end); final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final int MAX_TRIES = 20; final Matcher<File[]> hasGzippedFile = hasItemInArray(that(hasName(that(endsWith(".gz"))))); boolean succeeded = false; for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); if (hasGzippedFile.matches(files)) { succeeded = true; break; } logger.debug("Sleeping #" + i); Thread.sleep(100); // Allow time for rollover to complete } if (!succeeded) { final File[] files = dir.listFiles(); for (final File dirFile : files) { logger.error("Found file: " + dirFile.getPath()); } fail("No compressed files found"); } } }
RollingAppenderCronEvery2DirectTest
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/Suspendable.java
{ "start": 1232, "end": 1368 }
class ____ a * {@link SuspendableService} but the actual implementation may not have special logic for suspend. Therefore this * marker
is
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java
{ "start": 1755, "end": 3315 }
class ____ { private TestRestTemplate testRestTemplate; @Autowired private ApplicationContext applicationContext; @BeforeEach void setUp() { RestTemplateBuilder builder = new RestTemplateBuilder(); LocalTestWebServer localTestWebServer = LocalTestWebServer.obtain(this.applicationContext); builder = builder.uriTemplateHandler(localTestWebServer.uriBuilderFactory()); this.testRestTemplate = new TestRestTemplate(builder); } @Test void endpointShouldReturnUnauthorized() { ResponseEntity<?> entity = this.testRestTemplate.getForEntity("/actuator/env", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void preflightRequestToEndpointShouldReturnOk() throws Exception { RequestEntity<?> envRequest = RequestEntity.options(new URI("/actuator/env")) .header("Origin", "http://localhost:8080") .header("Access-Control-Request-Method", "GET") .build(); ResponseEntity<?> exchange = this.testRestTemplate.exchange(envRequest, Map.class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { RequestEntity<?> entity = RequestEntity.options(new URI("/actuator/env")) .header("Origin", "http://localhost:9095") .header("Access-Control-Request-Method", "GET") .build(); ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, byte[].class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } }
CorsSampleActuatorApplicationTests
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/llama/embeddings/LlamaEmbeddingsServiceSettings.java
{ "start": 2179, "end": 2285 }
class ____ the configuration settings required to use Llama for generating embeddings. */ public
encapsulates
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/assignment/TrainedModelAssignmentMetadata.java
{ "start": 1554, "end": 8236 }
class ____ implements Metadata.ProjectCustom { private static final TrainedModelAssignmentMetadata EMPTY = new TrainedModelAssignmentMetadata(Collections.emptyMap()); public static final String DEPRECATED_NAME = "trained_model_allocation"; public static final String NAME = "trained_model_assignment"; private final Map<String, TrainedModelAssignment> deploymentRoutingEntries; private final String writeableName; public static TrainedModelAssignmentMetadata fromXContent(XContentParser parser) throws IOException { return new TrainedModelAssignmentMetadata(parser.map(LinkedHashMap::new, TrainedModelAssignment::fromXContent)); } public static TrainedModelAssignmentMetadata fromStream(StreamInput input) throws IOException { return new TrainedModelAssignmentMetadata(input, NAME); } public static TrainedModelAssignmentMetadata fromStreamOld(StreamInput input) throws IOException { return new TrainedModelAssignmentMetadata(input, DEPRECATED_NAME); } public static NamedDiff<Metadata.ProjectCustom> readDiffFrom(StreamInput in) throws IOException { return new TrainedModelAssignmentMetadata.TrainedModeAssignmentDiff(in); } public static NamedDiff<Metadata.ProjectCustom> readDiffFromOld(StreamInput in) throws IOException { return new TrainedModelAssignmentMetadata.TrainedModeAssignmentDiff(in, DEPRECATED_NAME); } public static Builder builder(ClusterState clusterState) { return Builder.fromMetadata(fromState(clusterState)); } @Deprecated(forRemoval = true) public static TrainedModelAssignmentMetadata fromState(ClusterState clusterState) { TrainedModelAssignmentMetadata trainedModelAssignmentMetadata = clusterState.metadata().getSingleProjectCustom(NAME); if (trainedModelAssignmentMetadata == null) { trainedModelAssignmentMetadata = clusterState.metadata().getSingleProjectCustom(DEPRECATED_NAME); } return trainedModelAssignmentMetadata == null ? EMPTY : trainedModelAssignmentMetadata; } public static TrainedModelAssignmentMetadata fromMetadata(ProjectMetadata projectMetadata) { TrainedModelAssignmentMetadata trainedModelAssignmentMetadata = projectMetadata.custom(NAME); if (trainedModelAssignmentMetadata == null) { trainedModelAssignmentMetadata = projectMetadata.custom(DEPRECATED_NAME); } return trainedModelAssignmentMetadata == null ? EMPTY : trainedModelAssignmentMetadata; } public static List<TrainedModelAssignment> assignmentsForModelId(ClusterState clusterState, String modelId) { return TrainedModelAssignmentMetadata.fromState(clusterState) .allAssignments() .values() .stream() .filter(assignment -> modelId.equals(assignment.getModelId())) .collect(Collectors.toList()); } public static Optional<TrainedModelAssignment> assignmentForDeploymentId(ClusterState clusterState, String deploymentId) { return Optional.ofNullable(TrainedModelAssignmentMetadata.fromState(clusterState)) .map(metadata -> metadata.getDeploymentAssignment(deploymentId)); } public TrainedModelAssignmentMetadata(Map<String, TrainedModelAssignment> modelRoutingEntries) { this(modelRoutingEntries, NAME); } private TrainedModelAssignmentMetadata(Map<String, TrainedModelAssignment> modelRoutingEntries, String writeableName) { this.deploymentRoutingEntries = ExceptionsHelper.requireNonNull(modelRoutingEntries, NAME); this.writeableName = writeableName; } private TrainedModelAssignmentMetadata(StreamInput in, String writeableName) throws IOException { this.deploymentRoutingEntries = in.readOrderedMap(StreamInput::readString, TrainedModelAssignment::new); this.writeableName = writeableName; } public TrainedModelAssignment getDeploymentAssignment(String deploymentId) { return deploymentRoutingEntries.get(deploymentId); } public boolean isAssigned(String deploymentId) { return deploymentRoutingEntries.containsKey(deploymentId); } public boolean modelIsDeployed(String modelId) { return deploymentRoutingEntries.values().stream().anyMatch(assignment -> modelId.equals(assignment.getModelId())); } public List<TrainedModelAssignment> getDeploymentsUsingModel(String modelId) { return deploymentRoutingEntries.values() .stream() .filter(assignment -> modelId.equals(assignment.getModelId())) .collect(Collectors.toList()); } public Map<String, TrainedModelAssignment> allAssignments() { return Collections.unmodifiableMap(deploymentRoutingEntries); } @Override public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params ignored) { return Iterators.map( deploymentRoutingEntries.entrySet().iterator(), entry -> (builder, params) -> entry.getValue().toXContent(builder.field(entry.getKey()), params) ); } @Override public Diff<Metadata.ProjectCustom> diff(Metadata.ProjectCustom previousState) { return new TrainedModeAssignmentDiff((TrainedModelAssignmentMetadata) previousState, this); } @Override public EnumSet<Metadata.XContentContext> context() { return ALL_CONTEXTS; } @Override public String getWriteableName() { return writeableName; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.minimumCompatible(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeMap(deploymentRoutingEntries, StreamOutput::writeWriteable); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrainedModelAssignmentMetadata that = (TrainedModelAssignmentMetadata) o; return Objects.equals(deploymentRoutingEntries, that.deploymentRoutingEntries); } @Override public int hashCode() { return Objects.hash(deploymentRoutingEntries); } @Override public String toString() { return Strings.toString(this); } public boolean hasOutdatedAssignments() { return deploymentRoutingEntries.values().stream().anyMatch(TrainedModelAssignment::hasOutdatedRoutingEntries); } public boolean hasDeployment(String deploymentId) { return deploymentRoutingEntries.containsKey(deploymentId); } public static
TrainedModelAssignmentMetadata
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/UnresolvedId.java
{ "start": 147, "end": 272 }
class ____ {@link UnresolvedForwardReference}, to contain information about unresolved ids. * * @author pgelinas */ public
for
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/ReactiveBackpressurePropagationUnitTests.java
{ "start": 6493, "end": 6794 }
class ____ { static byte[] arrayHeader(int count) { return String.format("*%d\r\n", count).getBytes(); } static byte[] bulkString(String string) { return String.format("$%d\r\n%s\r\n", string.getBytes().length, string).getBytes(); } } }
RESP