language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/producer/JettyRestProducerGetUriParameterTest.java
{ "start": 1135, "end": 2342 }
class ____ extends BaseJettyTest { @Test public void testJettyProducerGet() { String out = fluentTemplate.withHeader("id", "123").to("direct:start").request(String.class); assertEquals("123;Donald Duck", out); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // configure to use localhost with the given port restConfiguration().component("jetty").producerComponent("http").host("localhost").port(getPort()); from("direct:start").to("rest:get:users/basic?id={id}"); // use the rest DSL to define the rest services rest("/users/").get("basic/?id={id}").to("direct:basic"); from("direct:basic").to("mock:input").process(new Processor() { public void process(Exchange exchange) { String id = exchange.getIn().getHeader("id", String.class); exchange.getMessage().setBody(id + ";Donald Duck"); } }); } }; } }
JettyRestProducerGetUriParameterTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/exc/TestExceptionHandlingWithDefaultDeserialization.java
{ "start": 437, "end": 583 }
class ____ { private Bar bar; public Foo() { } public Bar getBar() { return bar; } } static
Foo
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFlattenIterableTest.java
{ "start": 1587, "end": 32716 }
class ____ extends RxJavaTest { @Test public void normal0() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.range(1, 2) .reduce(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer a, Integer b) { return Math.max(a, b); } }) .toFlowable() .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return Arrays.asList(v, v + 1); } }) .subscribe(ts); ts.assertValues(2, 3) .assertNoErrors() .assertComplete(); } final Function<Integer, Iterable<Integer>> mapper = new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return Arrays.asList(v, v + 1); } }; @Test public void normal() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.range(1, 5).concatMapIterable(mapper) .subscribe(ts); ts.assertValues(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); ts.assertNoErrors(); ts.assertComplete(); } @Test public void normalViaFlatMap() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.range(1, 5).flatMapIterable(mapper) .subscribe(ts); ts.assertValues(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); ts.assertNoErrors(); ts.assertComplete(); } @Test public void normalBackpressured() { TestSubscriber<Integer> ts = new TestSubscriber<>(0); Flowable.range(1, 5).concatMapIterable(mapper) .subscribe(ts); ts.assertNoValues(); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(1); ts.assertValue(1); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(2); ts.assertValues(1, 2, 2); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(7); ts.assertValues(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); ts.assertNoErrors(); ts.assertComplete(); } @Test public void longRunning() { TestSubscriber<Integer> ts = new TestSubscriber<>(); int n = 1000 * 1000; Flowable.range(1, n).concatMapIterable(mapper) .subscribe(ts); ts.assertValueCount(n * 2); ts.assertNoErrors(); ts.assertComplete(); } @Test public void asIntermediate() { TestSubscriber<Integer> ts = new TestSubscriber<>(); int n = 1000 * 1000; Flowable.range(1, n).concatMapIterable(mapper).concatMap(new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer v) { return Flowable.just(v); } }) .subscribe(ts); ts.assertValueCount(n * 2); ts.assertNoErrors(); ts.assertComplete(); } @Test public void just() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.just(1).concatMapIterable(mapper) .subscribe(ts); ts.assertValues(1, 2); ts.assertNoErrors(); ts.assertComplete(); } @Test public void justHidden() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.just(1).hide().concatMapIterable(mapper) .subscribe(ts); ts.assertValues(1, 2); ts.assertNoErrors(); ts.assertComplete(); } @Test public void empty() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.<Integer>empty().concatMapIterable(mapper) .subscribe(ts); ts.assertNoValues(); ts.assertNoErrors(); ts.assertComplete(); } @Test public void error() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.<Integer>just(1).concatWith(Flowable.<Integer>error(new TestException())) .concatMapIterable(mapper) .subscribe(ts); ts.assertValues(1, 2); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void iteratorHasNextThrowsImmediately() { TestSubscriber<Integer> ts = new TestSubscriber<>(); final Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { throw new TestException(); } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; Flowable.range(1, 2) .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return it; } }) .subscribe(ts); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void iteratorHasNextThrowsImmediatelyJust() { TestSubscriber<Integer> ts = new TestSubscriber<>(); final Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { throw new TestException(); } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; Flowable.just(1) .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return it; } }) .subscribe(ts); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void iteratorHasNextThrowsSecondCall() { TestSubscriber<Integer> ts = new TestSubscriber<>(); final Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int count; @Override public boolean hasNext() { if (++count >= 2) { throw new TestException(); } return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; Flowable.range(1, 2) .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return it; } }) .subscribe(ts); ts.assertValue(1); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void iteratorNextThrows() { TestSubscriber<Integer> ts = new TestSubscriber<>(); final Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { throw new TestException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; Flowable.range(1, 2) .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return it; } }) .subscribe(ts); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); } @Test public void iteratorNextThrowsAndUnsubscribes() { TestSubscriber<Integer> ts = new TestSubscriber<>(); final Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { throw new TestException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; PublishProcessor<Integer> pp = PublishProcessor.create(); pp .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return it; } }) .subscribe(ts); pp.onNext(1); ts.assertNoValues(); ts.assertError(TestException.class); ts.assertNotComplete(); Assert.assertFalse("PublishProcessor has Subscribers?!", pp.hasSubscribers()); } @Test public void mixture() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.range(0, 1000) .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return (v % 2) == 0 ? Collections.singleton(1) : Collections.<Integer>emptySet(); } }) .subscribe(ts); ts.assertValueCount(500); ts.assertNoErrors(); ts.assertComplete(); } @Test public void emptyInnerThenSingleBackpressured() { TestSubscriber<Integer> ts = new TestSubscriber<>(1); Flowable.range(1, 2) .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return v == 2 ? Collections.singleton(1) : Collections.<Integer>emptySet(); } }) .subscribe(ts); ts.assertValue(1); ts.assertNoErrors(); ts.assertComplete(); } @Test public void manyEmptyInnerThenSingleBackpressured() { TestSubscriber<Integer> ts = new TestSubscriber<>(1); Flowable.range(1, 1000) .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return v == 1000 ? Collections.singleton(1) : Collections.<Integer>emptySet(); } }) .subscribe(ts); ts.assertValue(1); ts.assertNoErrors(); ts.assertComplete(); } @Test public void hasNextIsNotCalledAfterChildUnsubscribedOnNext() { TestSubscriber<Integer> ts = new TestSubscriber<>(); final AtomicInteger counter = new AtomicInteger(); final Iterable<Integer> it = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { counter.getAndIncrement(); return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; PublishProcessor<Integer> pp = PublishProcessor.create(); pp .concatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return it; } }) .take(1) .subscribe(ts); pp.onNext(1); ts.assertValue(1); ts.assertNoErrors(); ts.assertComplete(); Assert.assertFalse("PublishProcessor has Subscribers?!", pp.hasSubscribers()); Assert.assertEquals(1, counter.get()); } @Test public void normalPrefetchViaFlatMap() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.range(1, 5).flatMapIterable(mapper, 2) .subscribe(ts); ts.assertValues(1, 2, 2, 3, 3, 4, 4, 5, 5, 6); ts.assertNoErrors(); ts.assertComplete(); } @Test public void withResultSelectorMaxConcurrent() { TestSubscriber<Integer> ts = TestSubscriber.create(); Flowable.range(1, 5) .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return Collections.singletonList(1); } }, new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer a, Integer b) { return a * 10 + b; } }, 2) .subscribe(ts) ; ts.assertValues(11, 21, 31, 41, 51); ts.assertNoErrors(); ts.assertComplete(); } @Test public void flatMapIterablePrefetch() { Flowable.just(1, 2) .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer t) throws Exception { return Arrays.asList(t * 10); } }, 1) .test() .assertResult(10, 20); } @Test public void dispose() { TestHelper.checkDisposed(PublishProcessor.create().flatMapIterable(new Function<Object, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Object v) throws Exception { return Arrays.asList(10, 20); } })); } @Test public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override public Object apply(Flowable<Integer> f) throws Exception { return f.flatMapIterable(new Function<Object, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Object v) throws Exception { return Arrays.asList(10, 20); } }); } }, false, 1, 1, 10, 20); } @Test public void callableThrows() { Flowable.fromCallable(new Callable<Object>() { @Override public Object call() throws Exception { throw new TestException(); } }) .flatMapIterable(Functions.justFunction(Arrays.asList(1, 2, 3))) .test() .assertFailure(TestException.class); } @Test public void fusionMethods() { Flowable.just(1, 2) .flatMapIterable(Functions.justFunction(Arrays.asList(1, 2, 3))) .subscribe(new FlowableSubscriber<Integer>() { @Override public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription<Integer> qs = (QueueSubscription<Integer>)s; assertEquals(QueueFuseable.SYNC, qs.requestFusion(QueueFuseable.ANY)); try { assertFalse("Source reports being empty!", qs.isEmpty()); assertEquals(1, qs.poll().intValue()); assertFalse("Source reports being empty!", qs.isEmpty()); assertEquals(2, qs.poll().intValue()); assertFalse("Source reports being empty!", qs.isEmpty()); qs.clear(); assertTrue("Source reports not empty!", qs.isEmpty()); assertNull(qs.poll()); } catch (Throwable ex) { throw ExceptionHelper.wrapOrThrow(ex); } } @Override public void onNext(Integer t) { } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); } @Test public void smallPrefetch() { Flowable.just(1, 2, 3) .flatMapIterable(Functions.justFunction(Arrays.asList(1, 2, 3)), 1) .test() .assertResult(1, 2, 3, 1, 2, 3, 1, 2, 3); } @Test public void smallPrefetch2() { Flowable.just(1, 2, 3).hide() .flatMapIterable(Functions.justFunction(Collections.emptyList()), 1) .test() .assertResult(); } @Test public void mixedInnerSource() { TestSubscriberEx<Integer> ts = new TestSubscriberEx<Integer>().setInitialFusionMode(QueueFuseable.ANY); Flowable.just(1, 2, 3) .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) throws Exception { if ((v & 1) == 0) { return Collections.emptyList(); } return Arrays.asList(1, 2); } }) .subscribe(ts); ts.assertFusionMode(QueueFuseable.SYNC) .assertResult(1, 2, 1, 2); } @Test public void mixedInnerSource2() { TestSubscriberEx<Integer> ts = new TestSubscriberEx<Integer>().setInitialFusionMode(QueueFuseable.ANY); Flowable.just(1, 2, 3) .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) throws Exception { if ((v & 1) == 1) { return Collections.emptyList(); } return Arrays.asList(1, 2); } }) .subscribe(ts); ts.assertFusionMode(QueueFuseable.SYNC) .assertResult(1, 2); } @Test public void fusionRejected() { TestSubscriberEx<Integer> ts = new TestSubscriberEx<Integer>().setInitialFusionMode(QueueFuseable.ANY); Flowable.just(1, 2, 3).hide() .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) throws Exception { return Arrays.asList(1, 2); } }) .subscribe(ts); ts.assertFusionMode(QueueFuseable.NONE) .assertResult(1, 2, 1, 2, 1, 2); } @Test public void fusedIsEmptyWithEmptySource() { Flowable.just(1, 2, 3) .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) throws Exception { if ((v & 1) == 0) { return Collections.emptyList(); } return Arrays.asList(v); } }) .subscribe(new FlowableSubscriber<Integer>() { @Override public void onSubscribe(Subscription s) { @SuppressWarnings("unchecked") QueueSubscription<Integer> qs = (QueueSubscription<Integer>)s; assertEquals(QueueFuseable.SYNC, qs.requestFusion(QueueFuseable.ANY)); try { assertFalse("Source reports being empty!", qs.isEmpty()); assertEquals(1, qs.poll().intValue()); assertFalse("Source reports being empty!", qs.isEmpty()); assertEquals(3, qs.poll().intValue()); assertTrue("Source reports being non-empty!", qs.isEmpty()); } catch (Throwable ex) { throw ExceptionHelper.wrapOrThrow(ex); } } @Override public void onNext(Integer t) { } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); } @Test public void fusedSourceCrash() { Flowable.range(1, 3) .map(new Function<Integer, Object>() { @Override public Object apply(Integer v) throws Exception { throw new TestException(); } }) .flatMapIterable(Functions.justFunction(Collections.emptyList()), 1) .test() .assertFailure(TestException.class); } @Test public void take() { Flowable.range(1, 3) .flatMapIterable(Functions.justFunction(Arrays.asList(1)), 1) .take(1) .test() .assertResult(1); } @Test public void overflowSource() { new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> s) { s.onSubscribe(new BooleanSubscription()); s.onNext(1); s.onNext(2); s.onNext(3); } } .flatMapIterable(Functions.justFunction(Arrays.asList(1)), 1) .test(0L) .assertFailure(QueueOverflowException.class); } @Test public void oneByOne() { Flowable.range(1, 3).hide() .flatMapIterable(Functions.justFunction(Arrays.asList(1)), 1) .rebatchRequests(1) .test() .assertResult(1, 1, 1); } @Test public void cancelAfterHasNext() { final TestSubscriber<Integer> ts = new TestSubscriber<>(); Flowable.range(1, 3).hide() .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) throws Exception { return new Iterable<Integer>() { int count; @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { if (++count == 2) { ts.cancel(); ts.onComplete(); } return true; } @Override public Integer next() { return 1; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } }) .subscribe(ts); ts.assertResult(1); } @Test public void doubleShare() { Iterable<Integer> it = Flowable.range(1, 300).blockingIterable(); Flowable.just(it, it) .flatMapIterable(Functions.<Iterable<Integer>>identity()) .share() .share() .count() .test() .assertResult(600L); } @Test public void multiShare() { Iterable<Integer> it = Flowable.range(1, 300).blockingIterable(); for (int i = 0; i < 5; i++) { Flowable<Integer> f = Flowable.just(it, it) .flatMapIterable(Functions.<Iterable<Integer>>identity()); for (int j = 0; j < i; j++) { f = f.share(); } f .count() .test() .withTag("Share: " + i) .assertResult(600L); } } @Test public void multiShareHidden() { Iterable<Integer> it = Flowable.range(1, 300).blockingIterable(); for (int i = 0; i < 5; i++) { Flowable<Integer> f = Flowable.just(it, it) .flatMapIterable(Functions.<Iterable<Integer>>identity()) .hide(); for (int j = 0; j < i; j++) { f = f.share(); } f .count() .test() .withTag("Share: " + i) .assertResult(600L); } } @Test public void failingInnerCancelsSource() { final AtomicInteger counter = new AtomicInteger(); Flowable.range(1, 5) .doOnNext(new Consumer<Integer>() { @Override public void accept(Integer v) throws Exception { counter.getAndIncrement(); } }) .flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) throws Exception { return new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { throw new TestException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } }) .test() .assertFailure(TestException.class); assertEquals(1, counter.get()); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<Object> f) throws Exception { return f.flatMapIterable(Functions.justFunction(Collections.emptyList())); } }); } @Test public void upstreamFusionRejected() { TestSubscriber<Integer> ts = new TestSubscriber<>(); FlattenIterableSubscriber<Integer, Integer> f = new FlattenIterableSubscriber<>(ts, Functions.justFunction(Collections.<Integer>emptyList()), 128); final AtomicLong requested = new AtomicLong(); f.onSubscribe(new QueueSubscription<Integer>() { @Override public int requestFusion(int mode) { return 0; } @Override public boolean offer(Integer value) { return false; } @Override public boolean offer(Integer v1, Integer v2) { return false; } @Override public Integer poll() throws Exception { return null; } @Override public boolean isEmpty() { return false; } @Override public void clear() { } @Override public void request(long n) { requested.set(n); } @Override public void cancel() { } }); assertEquals(128, requested.get()); assertNotNull(f.queue); ts.assertEmpty(); } @Test public void onErrorLate() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(); FlattenIterableSubscriber<Integer, Integer> f = new FlattenIterableSubscriber<>(ts, Functions.justFunction(Collections.<Integer>emptyList()), 128); f.onSubscribe(new BooleanSubscription()); f.onError(new TestException("first")); ts.assertFailureAndMessage(TestException.class, "first"); assertTrue(errors.isEmpty()); f.done = false; f.onError(new TestException("second")); TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); } finally { RxJavaPlugins.reset(); } } @Test public void badRequest() { TestHelper.assertBadRequestReported(Flowable.never().flatMapIterable(Functions.justFunction(Collections.emptyList()))); } @Test public void fusedCurrentIteratorEmpty() throws Throwable { TestSubscriber<Integer> ts = new TestSubscriber<>(0); FlattenIterableSubscriber<Integer, Integer> f = new FlattenIterableSubscriber<>(ts, Functions.justFunction(Arrays.<Integer>asList(1, 2)), 128); f.onSubscribe(new BooleanSubscription()); f.onNext(1); assertFalse(f.isEmpty()); assertEquals(1, f.poll().intValue()); assertFalse(f.isEmpty()); assertEquals(2, f.poll().intValue()); assertTrue(f.isEmpty()); } @Test public void fusionRequestedState() throws Exception { TestSubscriber<Integer> ts = new TestSubscriber<>(0); FlattenIterableSubscriber<Integer, Integer> f = new FlattenIterableSubscriber<>(ts, Functions.justFunction(Arrays.<Integer>asList(1, 2)), 128); f.onSubscribe(new BooleanSubscription()); f.fusionMode = QueueFuseable.NONE; assertEquals(QueueFuseable.NONE, f.requestFusion(QueueFuseable.SYNC)); assertEquals(QueueFuseable.NONE, f.requestFusion(QueueFuseable.ASYNC)); f.fusionMode = QueueFuseable.SYNC; assertEquals(QueueFuseable.SYNC, f.requestFusion(QueueFuseable.SYNC)); assertEquals(QueueFuseable.NONE, f.requestFusion(QueueFuseable.ASYNC)); } }
FlowableFlattenIterableTest
java
google__guava
android/guava/src/com/google/common/primitives/Ints.java
{ "start": 26033, "end": 32081 }
class ____ extends AbstractList<Integer> implements RandomAccess, Serializable { final int[] array; final int start; final int end; IntArrayAsList(int[] array) { this(array, 0, array.length); } IntArrayAsList(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Integer get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override /* * This is an override that is not directly visible to callers, so NewApi will catch calls to * Collection.spliterator() where necessary. */ @IgnoreJRERequirement public Spliterator.OfInt spliterator() { return Spliterators.spliterator(array, start, end, 0); } @Override public boolean contains(@Nullable Object target) { // Overridden to prevent a ton of boxing return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; } @Override public int indexOf(@Nullable Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.indexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@Nullable Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.lastIndexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Integer set(int index, Integer element) { checkElementIndex(index, size()); int oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Integer> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new IntArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof IntArrayAsList) { IntArrayAsList that = (IntArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Integer.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } int[] toIntArray() { return Arrays.copyOfRange(array, start, end); } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'} * (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, * and returns {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link * Integer#parseInt(String)} accepts them. * * @param string the string representation of an integer value * @return the integer value represented by {@code string}, or {@code null} if {@code string} has * a length of zero or cannot be parsed as an integer value * @throws NullPointerException if {@code string} is {@code null} * @since 11.0 */ public static @Nullable Integer tryParse(String string) { return tryParse(string, 10); } /** * Parses the specified string as a signed integer value using the specified radix. The ASCII * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, * and returns {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link * Integer#parseInt(String)} accepts them. * * @param string the string representation of an integer value * @param radix the radix to use when parsing * @return the integer value represented by {@code string} using {@code radix}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as an integer value * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix > * Character.MAX_RADIX} * @throws NullPointerException if {@code string} is {@code null} * @since 19.0 */ public static @Nullable Integer tryParse(String string, int radix) { Long result = Longs.tryParse(string, radix); if (result == null || result.longValue() != result.intValue()) { return null; } else { return result.intValue(); } } }
IntArrayAsList
java
netty__netty
example/src/main/java/io/netty/example/http/helloworld/HttpHelloWorldServerInitializer.java
{ "start": 1098, "end": 1756 }
class ____ extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; public HttpHelloWorldServerInitializer(SslContext sslCtx) { this.sslCtx = sslCtx; } @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } p.addLast(new HttpServerCodec()); p.addLast(new HttpContentCompressor((CompressionOptions[]) null)); p.addLast(new HttpServerExpectContinueHandler()); p.addLast(new HttpHelloWorldServerHandler()); } }
HttpHelloWorldServerInitializer
java
google__guava
android/guava-testlib/test/com/google/common/collect/testing/features/FeatureEnumTest.java
{ "start": 1230, "end": 3516 }
class ____ extends TestCase { private static void assertGoodTesterAnnotation(Class<? extends Annotation> annotationClass) { assertWithMessage( rootLocaleFormat("%s must be annotated with @TesterAnnotation.", annotationClass)) .that(annotationClass.getAnnotation(TesterAnnotation.class)) .isNotNull(); Retention retentionPolicy = annotationClass.getAnnotation(Retention.class); assertWithMessage(rootLocaleFormat("%s must have a @Retention annotation.", annotationClass)) .that(retentionPolicy) .isNotNull(); assertEquals( rootLocaleFormat("%s must have RUNTIME RetentionPolicy.", annotationClass), RetentionPolicy.RUNTIME, retentionPolicy.value()); assertWithMessage(rootLocaleFormat("%s must be inherited.", annotationClass)) .that(annotationClass.getAnnotation(Inherited.class)) .isNotNull(); for (String propertyName : new String[] {"value", "absent"}) { Method method = null; try { method = annotationClass.getMethod(propertyName); } catch (NoSuchMethodException e) { throw new AssertionError("Annotation is missing required method", e); } Class<?> returnType = method.getReturnType(); assertTrue( rootLocaleFormat("%s.%s() must return an array.", annotationClass, propertyName), returnType.isArray()); assertSame( rootLocaleFormat( "%s.%s() must return an array of %s.", annotationClass, propertyName, annotationClass.getDeclaringClass()), annotationClass.getDeclaringClass(), returnType.getComponentType()); } } // This is public so that tests for Feature enums we haven't yet imagined // can reuse it. public static <E extends Enum<?> & Feature<?>> void assertGoodFeatureEnum( Class<E> featureEnumClass) { Class<?>[] classes = featureEnumClass.getDeclaredClasses(); for (Class<?> containedClass : classes) { if (containedClass.getSimpleName().equals("Require")) { if (containedClass.isAnnotation()) { assertGoodTesterAnnotation(asAnnotation(containedClass)); } else { fail( rootLocaleFormat( "Feature enum %s contains a
FeatureEnumTest
java
apache__flink
flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/state/rocksdb/RocksDBIncrementalCheckpointUtilsTest.java
{ "start": 1817, "end": 9311 }
class ____ extends TestLogger { @Rule public final TemporaryFolder tmp = new TemporaryFolder(); @Test public void testClipDBWithKeyGroupRange() throws Exception { testClipDBWithKeyGroupRangeHelper(new KeyGroupRange(0, 1), new KeyGroupRange(0, 2), 1); testClipDBWithKeyGroupRangeHelper(new KeyGroupRange(0, 1), new KeyGroupRange(0, 1), 1); testClipDBWithKeyGroupRangeHelper(new KeyGroupRange(0, 1), new KeyGroupRange(1, 2), 1); testClipDBWithKeyGroupRangeHelper(new KeyGroupRange(0, 1), new KeyGroupRange(2, 4), 1); testClipDBWithKeyGroupRangeHelper(new KeyGroupRange(4, 5), new KeyGroupRange(2, 7), 1); testClipDBWithKeyGroupRangeHelper( new KeyGroupRange(Byte.MAX_VALUE - 15, Byte.MAX_VALUE), new KeyGroupRange(Byte.MAX_VALUE - 10, Byte.MAX_VALUE), 1); testClipDBWithKeyGroupRangeHelper( new KeyGroupRange(Short.MAX_VALUE - 15, Short.MAX_VALUE), new KeyGroupRange(Short.MAX_VALUE - 10, Short.MAX_VALUE), 2); testClipDBWithKeyGroupRangeHelper( new KeyGroupRange(Byte.MAX_VALUE - 15, Byte.MAX_VALUE - 1), new KeyGroupRange(Byte.MAX_VALUE - 10, Byte.MAX_VALUE), 1); testClipDBWithKeyGroupRangeHelper( new KeyGroupRange(Short.MAX_VALUE - 15, Short.MAX_VALUE - 1), new KeyGroupRange(Short.MAX_VALUE - 10, Short.MAX_VALUE), 2); } @Test public void testChooseTheBestStateHandleForInitial() { List<KeyedStateHandle> keyedStateHandles = new ArrayList<>(3); KeyedStateHandle keyedStateHandle1 = mock(KeyedStateHandle.class); when(keyedStateHandle1.getKeyGroupRange()).thenReturn(new KeyGroupRange(0, 3)); keyedStateHandles.add(keyedStateHandle1); KeyedStateHandle keyedStateHandle2 = mock(KeyedStateHandle.class); when(keyedStateHandle2.getKeyGroupRange()).thenReturn(new KeyGroupRange(4, 7)); keyedStateHandles.add(keyedStateHandle2); KeyedStateHandle keyedStateHandle3 = mock(KeyedStateHandle.class); when(keyedStateHandle3.getKeyGroupRange()).thenReturn(new KeyGroupRange(8, 12)); keyedStateHandles.add(keyedStateHandle3); // this should choose keyedStateHandle2, because keyedStateHandle2's key-group range // satisfies the overlap fraction demand. Assert.assertEquals( keyedStateHandle2, RocksDBIncrementalCheckpointUtils.chooseTheBestStateHandleForInitial( keyedStateHandles, new KeyGroupRange(3, 6), RESTORE_OVERLAP_FRACTION_THRESHOLD.defaultValue())); // both keyedStateHandle2 & keyedStateHandle3's key-group range satisfies the overlap // fraction, but keyedStateHandle3's key group range is better. Assert.assertEquals( keyedStateHandle3, RocksDBIncrementalCheckpointUtils.chooseTheBestStateHandleForInitial( keyedStateHandles, new KeyGroupRange(5, 12), RESTORE_OVERLAP_FRACTION_THRESHOLD.defaultValue())); // The intersect key group number of keyedStateHandle2 & keyedStateHandle3's with [4, 11] // are 4. But the over fraction of keyedStateHandle2 is better. Assert.assertEquals( keyedStateHandle2, RocksDBIncrementalCheckpointUtils.chooseTheBestStateHandleForInitial( keyedStateHandles, new KeyGroupRange(4, 11), RESTORE_OVERLAP_FRACTION_THRESHOLD.defaultValue())); // both keyedStateHandle2 & keyedStateHandle3's key-group range are covered by [3, 12], // but this should choose the keyedStateHandle3, because keyedStateHandle3's key-group is // bigger than keyedStateHandle2. Assert.assertEquals( keyedStateHandle3, RocksDBIncrementalCheckpointUtils.chooseTheBestStateHandleForInitial( keyedStateHandles, new KeyGroupRange(3, 12), RESTORE_OVERLAP_FRACTION_THRESHOLD.defaultValue())); } private void testClipDBWithKeyGroupRangeHelper( KeyGroupRange targetGroupRange, KeyGroupRange currentGroupRange, int keyGroupPrefixBytes) throws RocksDBException, IOException { try (RocksDB rocksDB = RocksDB.open(tmp.newFolder().getAbsolutePath()); ColumnFamilyHandle columnFamilyHandle = rocksDB.createColumnFamily(new ColumnFamilyDescriptor("test".getBytes()))) { int currentGroupRangeStart = currentGroupRange.getStartKeyGroup(); int currentGroupRangeEnd = currentGroupRange.getEndKeyGroup(); DataOutputSerializer outputView = new DataOutputSerializer(32); for (int i = currentGroupRangeStart; i <= currentGroupRangeEnd; ++i) { for (int j = 0; j < 100; ++j) { outputView.clear(); CompositeKeySerializationUtils.writeKeyGroup( i, keyGroupPrefixBytes, outputView); CompositeKeySerializationUtils.writeKey( j, IntSerializer.INSTANCE, outputView, false); rocksDB.put( columnFamilyHandle, outputView.getCopyOfBuffer(), String.valueOf(j).getBytes()); } } for (int i = currentGroupRangeStart; i <= currentGroupRangeEnd; ++i) { for (int j = 0; j < 100; ++j) { outputView.clear(); CompositeKeySerializationUtils.writeKeyGroup( i, keyGroupPrefixBytes, outputView); CompositeKeySerializationUtils.writeKey( j, IntSerializer.INSTANCE, outputView, false); byte[] value = rocksDB.get(columnFamilyHandle, outputView.getCopyOfBuffer()); Assert.assertEquals(String.valueOf(j), new String(value)); } } RocksDBIncrementalCheckpointUtils.clipDBWithKeyGroupRange( rocksDB, Collections.singletonList(columnFamilyHandle), targetGroupRange, currentGroupRange, keyGroupPrefixBytes, true); for (int i = currentGroupRangeStart; i <= currentGroupRangeEnd; ++i) { for (int j = 0; j < 100; ++j) { outputView.clear(); CompositeKeySerializationUtils.writeKeyGroup( i, keyGroupPrefixBytes, outputView); CompositeKeySerializationUtils.writeKey( j, IntSerializer.INSTANCE, outputView, false); byte[] value = rocksDB.get(columnFamilyHandle, outputView.getCopyOfBuffer()); if (targetGroupRange.contains(i)) { Assert.assertEquals(String.valueOf(j), new String(value)); } else { Assert.assertNull(value); } } } } } }
RocksDBIncrementalCheckpointUtilsTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/BytesRefSortScript.java
{ "start": 570, "end": 1043 }
class ____ extends AbstractSortScript { public static final String[] PARAMETERS = {}; public static final ScriptContext<Factory> CONTEXT = new ScriptContext<>("bytesref_sort", Factory.class); public BytesRefSortScript(Map<String, Object> params, DocReader docReader) { super(params, docReader); } public abstract Object execute(); /** * A factory to construct {@link BytesRefSortScript} instances. */ public
BytesRefSortScript
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/oncrpc/security/TestRpcAuthInfo.java
{ "start": 1177, "end": 1749 }
class ____ { @Test public void testAuthFlavor() { assertEquals(AuthFlavor.AUTH_NONE, AuthFlavor.fromValue(0)); assertEquals(AuthFlavor.AUTH_SYS, AuthFlavor.fromValue(1)); assertEquals(AuthFlavor.AUTH_SHORT, AuthFlavor.fromValue(2)); assertEquals(AuthFlavor.AUTH_DH, AuthFlavor.fromValue(3)); assertEquals(AuthFlavor.RPCSEC_GSS, AuthFlavor.fromValue(6)); } @Test public void testInvalidAuthFlavor() { assertThrows(IllegalArgumentException.class, ()-> assertEquals(AuthFlavor.AUTH_NONE, AuthFlavor.fromValue(4))); } }
TestRpcAuthInfo
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/ai/remote/request/AbstractAgentRequest.java
{ "start": 841, "end": 1404 }
class ____ extends Request { private String namespaceId; private String agentName; @Override public String getModule() { return Constants.AI.AI_MODULE; } public String getNamespaceId() { return namespaceId; } public void setNamespaceId(String namespaceId) { this.namespaceId = namespaceId; } public String getAgentName() { return agentName; } public void setAgentName(String agentName) { this.agentName = agentName; } }
AbstractAgentRequest
java
apache__camel
components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/AvailablePhoneNumberCountryEndpointConfiguration.java
{ "start": 1260, "end": 2033 }
class ____ extends TwilioConfiguration { @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "fetcher"), @ApiMethod(methodName = "reader")}) private String pathAccountSid; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "fetcher")}) private String pathCountryCode; public String getPathAccountSid() { return pathAccountSid; } public void setPathAccountSid(String pathAccountSid) { this.pathAccountSid = pathAccountSid; } public String getPathCountryCode() { return pathCountryCode; } public void setPathCountryCode(String pathCountryCode) { this.pathCountryCode = pathCountryCode; } }
AvailablePhoneNumberCountryEndpointConfiguration
java
apache__flink
flink-test-utils-parent/flink-table-filesystem-test-utils/src/main/java/org/apache/flink/table/file/testutils/catalog/TestFileSystemCatalogFactory.java
{ "start": 1413, "end": 2930 }
class ____ implements CatalogFactory { public static final ConfigOption<String> PATH = ConfigOptions.key("path") .stringType() .noDefaultValue() .withDescription( "Catalog base DFS path, used for inferring the sink table path. " + "The default strategy for a table path is: ${catalog.path}/${db_name}/${table_name}"); public static final ConfigOption<String> DEFAULT_DATABASE = ConfigOptions.key(CommonCatalogOptions.DEFAULT_DATABASE_KEY) .stringType() .defaultValue("default"); @Override public String factoryIdentifier() { return IDENTIFIER; } @Override public Catalog createCatalog(Context context) { final FactoryUtil.CatalogFactoryHelper helper = FactoryUtil.createCatalogFactoryHelper(this, context); helper.validate(); return new TestFileSystemCatalog( helper.getOptions().get(PATH), context.getName(), helper.getOptions().get(DEFAULT_DATABASE)); } @Override public Set<ConfigOption<?>> requiredOptions() { Set<ConfigOption<?>> set = new HashSet<>(); set.add(PATH); set.add(DEFAULT_DATABASE); return set; } @Override public Set<ConfigOption<?>> optionalOptions() { return Collections.emptySet(); } }
TestFileSystemCatalogFactory
java
elastic__elasticsearch
plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextFieldMapper.java
{ "start": 11817, "end": 12065 }
class ____ * instances created per search request and field being highlighted. This allows us to * keep state about the annotations being processed and pass them into token streams * being highlighted. */ public static final
has
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentInjectionTest.java
{ "start": 8208, "end": 8433 }
class ____ extends PreferenceActivity {}") .addSourceLines( "MyPrefActivity.java", """ // BUG: Diagnostic contains: does not implement isValidFragment
MyAbstractPrefActivity
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleStatementImpl.java
{ "start": 934, "end": 1336 }
class ____ extends SQLStatementImpl implements OracleStatement { public OracleStatementImpl() { super(DbType.oracle); } protected void accept0(SQLASTVisitor visitor) { accept0((OracleASTVisitor) visitor); } public abstract void accept0(OracleASTVisitor visitor); public String toString() { return SQLUtils.toOracleString(this); } }
OracleStatementImpl
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java
{ "start": 1057, "end": 2000 }
class ____ { private final Object source = new Object(); @Test @SuppressWarnings("NullAway") // Test null check void changeSetMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false)) .withMessageContaining("'changeSet' must not be null"); } @Test void getChangeSet() { Set<ChangedFiles> changeSet = new LinkedHashSet<>(); ClassPathChangedEvent event = new ClassPathChangedEvent(this.source, changeSet, false); assertThat(event.getChangeSet()).isSameAs(changeSet); } @Test void getRestartRequired() { Set<ChangedFiles> changeSet = new LinkedHashSet<>(); ClassPathChangedEvent event; event = new ClassPathChangedEvent(this.source, changeSet, false); assertThat(event.isRestartRequired()).isFalse(); event = new ClassPathChangedEvent(this.source, changeSet, true); assertThat(event.isRestartRequired()).isTrue(); } }
ClassPathChangedEventTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/allocation/IndexBalanceConstraintSettings.java
{ "start": 747, "end": 2209 }
class ____ { private static final String SETTING_PREFIX = "cluster.routing.allocation.index_balance_decider."; public static final Setting<Boolean> INDEX_BALANCE_DECIDER_ENABLED_SETTING = Setting.boolSetting( SETTING_PREFIX + "enabled", false, Setting.Property.Dynamic, Setting.Property.NodeScope ); /** * This setting permits nodes to host more than ideally balanced number of index shards. * Maximum tolerated index shard count = ideal + skew_tolerance * i.e. ideal = 4 shards, skew_tolerance = 1 * maximum tolerated index shards = 4 + 1 = 5. */ public static final Setting<Integer> INDEX_BALANCE_DECIDER_EXCESS_SHARDS = Setting.intSetting( SETTING_PREFIX + "excess_shards", 0, 0, Setting.Property.Dynamic, Setting.Property.NodeScope ); private volatile boolean deciderEnabled; private volatile int excessShards; public IndexBalanceConstraintSettings(ClusterSettings clusterSettings) { clusterSettings.initializeAndWatch(INDEX_BALANCE_DECIDER_ENABLED_SETTING, enabled -> this.deciderEnabled = enabled); clusterSettings.initializeAndWatch(INDEX_BALANCE_DECIDER_EXCESS_SHARDS, value -> this.excessShards = value); } public boolean isDeciderEnabled() { return this.deciderEnabled; } public int getExcessShards() { return this.excessShards; } }
IndexBalanceConstraintSettings
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/instrument/classloading/tomcat/TomcatLoadTimeWeaver.java
{ "start": 1782, "end": 2019 }
class ____}. * @see org.springframework.util.ClassUtils#getDefaultClassLoader() */ public TomcatLoadTimeWeaver() { this(ClassUtils.getDefaultClassLoader()); } /** * Create a new instance of the {@link TomcatLoadTimeWeaver}
loader
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/SecondarySort.java
{ "start": 5232, "end": 6003 }
class ____ extends Mapper<LongWritable, Text, IntPair, IntWritable> { private final IntPair key = new IntPair(); private final IntWritable value = new IntWritable(); @Override public void map(LongWritable inKey, Text inValue, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(inValue.toString()); int left = 0; int right = 0; if (itr.hasMoreTokens()) { left = Integer.parseInt(itr.nextToken()); if (itr.hasMoreTokens()) { right = Integer.parseInt(itr.nextToken()); } key.set(left, right); value.set(right); context.write(key, value); } } } /** * A reducer
MapClass
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/results/jdbc/spi/JdbcValuesMapping.java
{ "start": 650, "end": 1240 }
interface ____ { /** * The JDBC selection descriptors. Used to read ResultSet values and build * the "JDBC values array" */ List<SqlSelection> getSqlSelections(); int getRowSize(); /** * Mapping from value index to cache index. */ int[] getValueIndexesToCacheIndexes(); /** * The size of the row for caching. */ int getRowToCacheSize(); List<DomainResult<?>> getDomainResults(); JdbcValuesMappingResolution resolveAssemblers(SessionFactoryImplementor sessionFactory); LockMode determineDefaultLockMode(String alias, LockMode defaultLockMode); }
JdbcValuesMapping
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java
{ "start": 3008, "end": 5568 }
class ____<T> { private final TreeMap<Long, Invoker<T>> virtualInvokers; private final int replicaNumber; private final int identityHashCode; private final int[] argumentIndex; ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) { this.virtualInvokers = new TreeMap<>(); this.identityHashCode = identityHashCode; URL url = invokers.get(0).getUrl(); this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160); String[] index = COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0")); argumentIndex = new int[index.length]; for (int i = 0; i < index.length; i++) { argumentIndex[i] = Integer.parseInt(index[i]); } for (Invoker<T> invoker : invokers) { String address = invoker.getUrl().getAddress(); for (int i = 0; i < replicaNumber / 4; i++) { byte[] digest = Bytes.getMD5(address + i); for (int h = 0; h < 4; h++) { long m = hash(digest, h); virtualInvokers.put(m, invoker); } } } } public Invoker<T> select(Invocation invocation) { String key = toKey(RpcUtils.getArguments(invocation)); byte[] digest = Bytes.getMD5(key); return selectForKey(hash(digest, 0)); } private String toKey(Object[] args) { StringBuilder buf = new StringBuilder(); for (int i : argumentIndex) { if (i >= 0 && args != null && i < args.length) { buf.append(args[i]); } } return buf.toString(); } private Invoker<T> selectForKey(long hash) { Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash); if (entry == null) { entry = virtualInvokers.firstEntry(); } return entry.getValue(); } private long hash(byte[] digest, int number) { return (((long) (digest[3 + number * 4] & 0xFF) << 24) | ((long) (digest[2 + number * 4] & 0xFF) << 16) | ((long) (digest[1 + number * 4] & 0xFF) << 8) | (digest[number * 4] & 0xFF)) & 0xFFFFFFFFL; } } }
ConsistentHashSelector
java
redisson__redisson
redisson/src/main/java/org/redisson/executor/RedissonCompletionService.java
{ "start": 975, "end": 1144 }
class ____ lightweight enough to be suitable for transient use * when processing groups of tasks. * * @author Nikita Koksharov * * @param <V> value type */ public
is
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/DefaultApplicationContextFactory.java
{ "start": 1386, "end": 3490 }
class ____ implements ApplicationContextFactory { // Method reference is not detected with correct nullability @SuppressWarnings("NullAway") @Override public @Nullable Class<? extends ConfigurableEnvironment> getEnvironmentType( @Nullable WebApplicationType webApplicationType) { return getFromSpringFactories(webApplicationType, ApplicationContextFactory::getEnvironmentType, null); } // Method reference is not detected with correct nullability @SuppressWarnings("NullAway") @Override public @Nullable ConfigurableEnvironment createEnvironment(@Nullable WebApplicationType webApplicationType) { return getFromSpringFactories(webApplicationType, ApplicationContextFactory::createEnvironment, null); } // Method reference is not detected with correct nullability @SuppressWarnings("NullAway") @Override public ConfigurableApplicationContext create(@Nullable WebApplicationType webApplicationType) { try { return getFromSpringFactories(webApplicationType, ApplicationContextFactory::create, this::createDefaultApplicationContext); } catch (Exception ex) { throw new IllegalStateException("Unable create a default ApplicationContext instance, " + "you may need a custom ApplicationContextFactory", ex); } } private ConfigurableApplicationContext createDefaultApplicationContext() { if (!AotDetector.useGeneratedArtifacts()) { return new AnnotationConfigApplicationContext(); } return new GenericApplicationContext(); } @Contract("_, _, !null -> !null") private <T> @Nullable T getFromSpringFactories(@Nullable WebApplicationType webApplicationType, BiFunction<ApplicationContextFactory, @Nullable WebApplicationType, @Nullable T> action, @Nullable Supplier<T> defaultResult) { for (ApplicationContextFactory candidate : SpringFactoriesLoader.loadFactories(ApplicationContextFactory.class, getClass().getClassLoader())) { T result = action.apply(candidate, webApplicationType); if (result != null) { return result; } } return (defaultResult != null) ? defaultResult.get() : null; } }
DefaultApplicationContextFactory
java
google__guava
android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
{ "start": 10543, "end": 10681 }
class ____ method public Comparator<? super E> comparator() { return q.comparator(); } @CanIgnoreReturnValue // pushed down from
to
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ser/jackson/JsonValueSerializer.java
{ "start": 16443, "end": 16651 }
class ____ need to re-route type serialization so that we can * override Object to use for type id (logical type) even when asking serialization * of something else (delegate type) */ static
we
java
google__guice
extensions/assistedinject/src/com/google/inject/assistedinject/FactoryProvider.java
{ "start": 2438, "end": 2840 }
class ____ an {@literal @}{@link Inject}-annotated * constructor. In addition to injector-supplied parameters, the constructor should have parameters * that match each of the factory method's parameters. Each factory-supplied parameter requires an * {@literal @}{@link Assisted} annotation. This serves to document that the parameter is not bound * by your application's modules. * * <pre>public
with
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/RobotFrameworkEndpointBuilderFactory.java
{ "start": 57915, "end": 88268 }
interface ____ extends EndpointProducerBuilder { default AdvancedRobotFrameworkEndpointProducerBuilder advanced() { return (AdvancedRobotFrameworkEndpointProducerBuilder) this; } /** * Sets whether the context map should allow access to all details. By * default only the message body and headers can be accessed. This * option can be enabled for full access to the current Exchange and * CamelContext. Doing so impose a potential security risk as this opens * access to the full power of CamelContext API. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param allowContextMapAll the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder allowContextMapAll(boolean allowContextMapAll) { doSetProperty("allowContextMapAll", allowContextMapAll); return this; } /** * Sets whether the context map should allow access to all details. By * default only the message body and headers can be accessed. This * option can be enabled for full access to the current Exchange and * CamelContext. Doing so impose a potential security risk as this opens * access to the full power of CamelContext API. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param allowContextMapAll the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder allowContextMapAll(String allowContextMapAll) { doSetProperty("allowContextMapAll", allowContextMapAll); return this; } /** * Whether to allow to use resource template from header or not (default * false). Enabling this allows to specify dynamic templates via message * header. However this can be seen as a potential security * vulnerability if the header is coming from a malicious user, so use * this with care. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param allowTemplateFromHeader the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder allowTemplateFromHeader(boolean allowTemplateFromHeader) { doSetProperty("allowTemplateFromHeader", allowTemplateFromHeader); return this; } /** * Whether to allow to use resource template from header or not (default * false). Enabling this allows to specify dynamic templates via message * header. However this can be seen as a potential security * vulnerability if the header is coming from a malicious user, so use * this with care. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param allowTemplateFromHeader the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder allowTemplateFromHeader(String allowTemplateFromHeader) { doSetProperty("allowTemplateFromHeader", allowTemplateFromHeader); return this; } /** * A text String to read more arguments from. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param argumentFiles the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder argumentFiles(String argumentFiles) { doSetProperty("argumentFiles", argumentFiles); return this; } /** * Creates combined statistics based on tags. Use the format tags:title * List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param combinedTagStats the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder combinedTagStats(String combinedTagStats) { doSetProperty("combinedTagStats", combinedTagStats); return this; } /** * Tests that have the given tags are considered critical. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param criticalTags the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder criticalTags(String criticalTags) { doSetProperty("criticalTags", criticalTags); return this; } /** * A debug String that is written during execution. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param debugFile the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder debugFile(String debugFile) { doSetProperty("debugFile", debugFile); return this; } /** * Sets the documentation of the top-level tests suites. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param document the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder document(String document) { doSetProperty("document", document); return this; } /** * Sets dryrun mode on use. In the dry run mode tests are run without * executing keywords originating from test libraries. Useful for * validating test data syntax. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param dryrun the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder dryrun(boolean dryrun) { doSetProperty("dryrun", dryrun); return this; } /** * Sets dryrun mode on use. In the dry run mode tests are run without * executing keywords originating from test libraries. Useful for * validating test data syntax. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param dryrun the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder dryrun(String dryrun) { doSetProperty("dryrun", dryrun); return this; } /** * Selects the tests cases by tags. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param excludes the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder excludes(String excludes) { doSetProperty("excludes", excludes); return this; } /** * Sets robot to stop execution immediately if a critical test fails. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param exitOnFailure the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder exitOnFailure(boolean exitOnFailure) { doSetProperty("exitOnFailure", exitOnFailure); return this; } /** * Sets robot to stop execution immediately if a critical test fails. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param exitOnFailure the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder exitOnFailure(String exitOnFailure) { doSetProperty("exitOnFailure", exitOnFailure); return this; } /** * Selects the tests cases by tags. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param includes the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder includes(String includes) { doSetProperty("includes", includes); return this; } /** * Sets a single listener for monitoring tests execution. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param listener the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder listener(String listener) { doSetProperty("listener", listener); return this; } /** * Sets multiple listeners for monitoring tests execution. Use the * format ListenerWithArgs:arg1:arg2 or simply ListenerWithoutArgs List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param listeners the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder listeners(String listeners) { doSetProperty("listeners", listeners); return this; } /** * Sets the path to the generated log String. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param log the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder log(String log) { doSetProperty("log", log); return this; } /** * Sets the threshold level for logging. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param logLevel the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder logLevel(String logLevel) { doSetProperty("logLevel", logLevel); return this; } /** * Sets a title for the generated tests log. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param logTitle the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder logTitle(String logTitle) { doSetProperty("logTitle", logTitle); return this; } /** * Sets free metadata for the top level tests suites. comma seperated * list of string resulting as List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param metadata the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder metadata(String metadata) { doSetProperty("metadata", metadata); return this; } /** * Using ANSI colors in console. Normally colors work in unixes but not * in Windows. Default is 'on'. 'on' - use colors in unixes but not in * Windows 'off' - never use colors 'force' - always use colors (also in * Windows). * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param monitorColors the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder monitorColors(String monitorColors) { doSetProperty("monitorColors", monitorColors); return this; } /** * Width of the monitor output. Default is 78. * * The option is a: <code>java.lang.String</code> type. * * Default: 78 * Group: common * * @param monitorWidth the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder monitorWidth(String monitorWidth) { doSetProperty("monitorWidth", monitorWidth); return this; } /** * Sets the name of the top-level tests suites. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param name the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder name(String name) { doSetProperty("name", name); return this; } /** * Tests that have the given tags are not critical. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param nonCriticalTags the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder nonCriticalTags(String nonCriticalTags) { doSetProperty("nonCriticalTags", nonCriticalTags); return this; } /** * If true, sets the return code to zero regardless of failures in test * cases. Error codes are returned normally. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param noStatusReturnCode the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder noStatusReturnCode(boolean noStatusReturnCode) { doSetProperty("noStatusReturnCode", noStatusReturnCode); return this; } /** * If true, sets the return code to zero regardless of failures in test * cases. Error codes are returned normally. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param noStatusReturnCode the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder noStatusReturnCode(String noStatusReturnCode) { doSetProperty("noStatusReturnCode", noStatusReturnCode); return this; } /** * Sets the path to the generated output String. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param output the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder output(String output) { doSetProperty("output", output); return this; } /** * Configures where generated reports are to be placed. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param outputDirectory the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder outputDirectory(String outputDirectory) { doSetProperty("outputDirectory", outputDirectory); return this; } /** * Sets the test execution order to be randomized. Valid values are all, * suite, and test. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param randomize the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder randomize(String randomize) { doSetProperty("randomize", randomize); return this; } /** * Sets the path to the generated report String. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param report the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder report(String report) { doSetProperty("report", report); return this; } /** * Sets background colors for the generated report and summary. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param reportBackground the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder reportBackground(String reportBackground) { doSetProperty("reportBackground", reportBackground); return this; } /** * Sets a title for the generated tests report. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param reportTitle the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder reportTitle(String reportTitle) { doSetProperty("reportTitle", reportTitle); return this; } /** * Executes tests also if the top level test suite is empty. Useful e.g. * with --include/--exclude when it is not an error that no test matches * the condition. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param runEmptySuite the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder runEmptySuite(boolean runEmptySuite) { doSetProperty("runEmptySuite", runEmptySuite); return this; } /** * Executes tests also if the top level test suite is empty. Useful e.g. * with --include/--exclude when it is not an error that no test matches * the condition. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param runEmptySuite the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder runEmptySuite(String runEmptySuite) { doSetProperty("runEmptySuite", runEmptySuite); return this; } /** * Re-run failed tests, based on output.xml String. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param runFailed the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder runFailed(String runFailed) { doSetProperty("runFailed", runFailed); return this; } /** * Sets the execution mode for this tests run. Note that this setting * has been deprecated in Robot Framework 2.8. Use separate dryryn, * skipTeardownOnExit, exitOnFailure, and randomize settings instead. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param runMode the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder runMode(String runMode) { doSetProperty("runMode", runMode); return this; } /** * Sets whether the teardowns are skipped if the test execution is * prematurely stopped. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param skipTeardownOnExit the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder skipTeardownOnExit(boolean skipTeardownOnExit) { doSetProperty("skipTeardownOnExit", skipTeardownOnExit); return this; } /** * Sets whether the teardowns are skipped if the test execution is * prematurely stopped. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param skipTeardownOnExit the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder skipTeardownOnExit(String skipTeardownOnExit) { doSetProperty("skipTeardownOnExit", skipTeardownOnExit); return this; } /** * Splits output and log files. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param splitOutputs the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder splitOutputs(String splitOutputs) { doSetProperty("splitOutputs", splitOutputs); return this; } /** * Selects the tests suites by name. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param suites the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder suites(String suites) { doSetProperty("suites", suites); return this; } /** * Defines how many levels to show in the Statistics by Suite table in * outputs. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param suiteStatLevel the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder suiteStatLevel(String suiteStatLevel) { doSetProperty("suiteStatLevel", suiteStatLevel); return this; } /** * Sets a title for the generated summary report. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param summaryTitle the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder summaryTitle(String summaryTitle) { doSetProperty("summaryTitle", summaryTitle); return this; } /** * Adds documentation to the specified tags. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param tagDocs the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder tagDocs(String tagDocs) { doSetProperty("tagDocs", tagDocs); return this; } /** * Sets the tags(s) to all executed tests cases. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param tags the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder tags(String tags) { doSetProperty("tags", tags); return this; } /** * Excludes these tags from the Statistics by Tag and Test Details by * Tag tables in outputs. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param tagStatExcludes the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder tagStatExcludes(String tagStatExcludes) { doSetProperty("tagStatExcludes", tagStatExcludes); return this; } /** * Includes only these tags in the Statistics by Tag and Test Details by * Tag tables in outputs. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param tagStatIncludes the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder tagStatIncludes(String tagStatIncludes) { doSetProperty("tagStatIncludes", tagStatIncludes); return this; } /** * Adds external links to the Statistics by Tag table in outputs. Use * the format pattern:link:title List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param tagStatLinks the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder tagStatLinks(String tagStatLinks) { doSetProperty("tagStatLinks", tagStatLinks); return this; } /** * Selects the tests cases by name. List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param tests the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder tests(String tests) { doSetProperty("tests", tests); return this; } /** * Adds a timestamp to all output files. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param timestampOutputs the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder timestampOutputs(boolean timestampOutputs) { doSetProperty("timestampOutputs", timestampOutputs); return this; } /** * Adds a timestamp to all output files. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param timestampOutputs the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder timestampOutputs(String timestampOutputs) { doSetProperty("timestampOutputs", timestampOutputs); return this; } /** * Sets variables using variables files. Use the format path:args List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param variableFiles the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder variableFiles(String variableFiles) { doSetProperty("variableFiles", variableFiles); return this; } /** * Sets individual variables. Use the format name:value List. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param variables the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder variables(String variables) { doSetProperty("variables", variables); return this; } /** * Show a warning when an invalid String is skipped. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param warnOnSkippedFiles the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder warnOnSkippedFiles(boolean warnOnSkippedFiles) { doSetProperty("warnOnSkippedFiles", warnOnSkippedFiles); return this; } /** * Show a warning when an invalid String is skipped. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param warnOnSkippedFiles the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder warnOnSkippedFiles(String warnOnSkippedFiles) { doSetProperty("warnOnSkippedFiles", warnOnSkippedFiles); return this; } /** * Sets the path to the generated XUnit compatible result String, * relative to outputDirectory. The String is in xml format. By default, * the String name is derived from the testCasesDirectory parameter, * replacing blanks in the directory name by underscores. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param xunitFile the value to set * @return the dsl builder */ default RobotFrameworkEndpointProducerBuilder xunitFile(String xunitFile) { doSetProperty("xunitFile", xunitFile); return this; } } /** * Advanced builder for endpoint producers for the Robot Framework component. */ public
RobotFrameworkEndpointProducerBuilder
java
apache__camel
components/camel-google/camel-google-mail/src/generated/java/org/apache/camel/component/google/mail/GoogleMailComponentConfigurer.java
{ "start": 738, "end": 7754 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("ApplicationName", java.lang.String.class); map.put("ClientId", java.lang.String.class); map.put("Configuration", org.apache.camel.component.google.mail.GoogleMailConfiguration.class); map.put("Delegate", java.lang.String.class); map.put("Scopes", java.lang.String.class); map.put("BridgeErrorHandler", boolean.class); map.put("LazyStartProducer", boolean.class); map.put("AutowiredEnabled", boolean.class); map.put("ClientFactory", org.apache.camel.component.google.mail.GoogleMailClientFactory.class); map.put("AccessToken", java.lang.String.class); map.put("ClientSecret", java.lang.String.class); map.put("RefreshToken", java.lang.String.class); map.put("ServiceAccountKey", java.lang.String.class); ALL_OPTIONS = map; } private org.apache.camel.component.google.mail.GoogleMailConfiguration getOrCreateConfiguration(GoogleMailComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.google.mail.GoogleMailConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { GoogleMailComponent target = (GoogleMailComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": getOrCreateConfiguration(target).setAccessToken(property(camelContext, java.lang.String.class, value)); return true; case "applicationname": case "applicationName": getOrCreateConfiguration(target).setApplicationName(property(camelContext, java.lang.String.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "clientfactory": case "clientFactory": target.setClientFactory(property(camelContext, org.apache.camel.component.google.mail.GoogleMailClientFactory.class, value)); return true; case "clientid": case "clientId": getOrCreateConfiguration(target).setClientId(property(camelContext, java.lang.String.class, value)); return true; case "clientsecret": case "clientSecret": getOrCreateConfiguration(target).setClientSecret(property(camelContext, java.lang.String.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.google.mail.GoogleMailConfiguration.class, value)); return true; case "delegate": getOrCreateConfiguration(target).setDelegate(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "refreshtoken": case "refreshToken": getOrCreateConfiguration(target).setRefreshToken(property(camelContext, java.lang.String.class, value)); return true; case "scopes": getOrCreateConfiguration(target).setScopes(property(camelContext, java.lang.String.class, value)); return true; case "serviceaccountkey": case "serviceAccountKey": getOrCreateConfiguration(target).setServiceAccountKey(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return java.lang.String.class; case "applicationname": case "applicationName": return java.lang.String.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "clientfactory": case "clientFactory": return org.apache.camel.component.google.mail.GoogleMailClientFactory.class; case "clientid": case "clientId": return java.lang.String.class; case "clientsecret": case "clientSecret": return java.lang.String.class; case "configuration": return org.apache.camel.component.google.mail.GoogleMailConfiguration.class; case "delegate": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "refreshtoken": case "refreshToken": return java.lang.String.class; case "scopes": return java.lang.String.class; case "serviceaccountkey": case "serviceAccountKey": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { GoogleMailComponent target = (GoogleMailComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return getOrCreateConfiguration(target).getAccessToken(); case "applicationname": case "applicationName": return getOrCreateConfiguration(target).getApplicationName(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "clientfactory": case "clientFactory": return target.getClientFactory(); case "clientid": case "clientId": return getOrCreateConfiguration(target).getClientId(); case "clientsecret": case "clientSecret": return getOrCreateConfiguration(target).getClientSecret(); case "configuration": return target.getConfiguration(); case "delegate": return getOrCreateConfiguration(target).getDelegate(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "refreshtoken": case "refreshToken": return getOrCreateConfiguration(target).getRefreshToken(); case "scopes": return getOrCreateConfiguration(target).getScopes(); case "serviceaccountkey": case "serviceAccountKey": return getOrCreateConfiguration(target).getServiceAccountKey(); default: return null; } } }
GoogleMailComponentConfigurer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/OrderColumnListIndexHHH18771ListInitializerTest.java
{ "start": 3213, "end": 3536 }
class ____ { @Id private Long id; @ManyToOne private Person person; public Phone() { } public Phone(Long id) { this.id = id; } public Long getId() { return id; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } } }
Phone
java
google__dagger
javatests/dagger/internal/codegen/MapRequestRepresentationWithGuavaTest.java
{ "start": 12398, "end": 12940 }
interface ____ {", " Map<Integer, Integer> intMap();", " Set<Integer> intSet();", " TestSubcomponent testSubcomponent();", "}"); Source subcomponent = CompilerTests.javaSource( "test.TestSubcomponent", "package test;", "", "import dagger.Subcomponent;", "import java.util.Map;", "import java.util.Set;", "", "@Subcomponent(modules = SubcomponentModule.class)", "
TestComponent
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/filter/ProblemHandlerTest.java
{ "start": 1873, "end": 2309 }
class ____ extends DeserializationProblemHandler { protected final Object value; public WeirdStringHandler(Object v0) { value = v0; } @Override public Object handleWeirdStringValue(DeserializationContext ctxt, Class<?> targetType, String v, String failureMsg) { return value; } } static
WeirdStringHandler
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/HwcloudObsComponentBuilderFactory.java
{ "start": 6946, "end": 8100 }
class ____ extends AbstractComponentBuilder<OBSComponent> implements HwcloudObsComponentBuilder { @Override protected OBSComponent buildConcreteComponent() { return new OBSComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "bridgeErrorHandler": ((OBSComponent) component).setBridgeErrorHandler((boolean) value); return true; case "lazyStartProducer": ((OBSComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((OBSComponent) component).setAutowiredEnabled((boolean) value); return true; case "healthCheckConsumerEnabled": ((OBSComponent) component).setHealthCheckConsumerEnabled((boolean) value); return true; case "healthCheckProducerEnabled": ((OBSComponent) component).setHealthCheckProducerEnabled((boolean) value); return true; default: return false; } } } }
HwcloudObsComponentBuilderImpl
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/date/DateExtract.java
{ "start": 2049, "end": 9503 }
class ____ extends EsqlConfigurationFunction { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( Expression.class, "DateExtract", DateExtract::new ); private ChronoField chronoField; @FunctionInfo( returnType = "long", description = "Extracts parts of a date, like year, month, day, hour.", examples = { @Example(file = "date", tag = "dateExtract"), @Example( file = "date", tag = "docsDateExtractBusinessHours", description = "Find all events that occurred outside of business hours (before 9 AM or after 5PM), on any given date:" ) } ) public DateExtract( Source source, // Need to replace the commas in the description here with semi-colon as there’s a bug in the CSV parser // used in the CSVTests and fixing it is not trivial @Param(name = "datePart", type = { "keyword", "text" }, description = """ Part of the date to extract.\n Can be: `aligned_day_of_week_in_month`, `aligned_day_of_week_in_year`, `aligned_week_of_month`, `aligned_week_of_year`, `ampm_of_day`, `clock_hour_of_ampm`, `clock_hour_of_day`, `day_of_month`, `day_of_week`, `day_of_year`, `epoch_day`, `era`, `hour_of_ampm`, `hour_of_day`, `instant_seconds`, `micro_of_day`, `micro_of_second`, `milli_of_day`, `milli_of_second`, `minute_of_day`, `minute_of_hour`, `month_of_year`, `nano_of_day`, `nano_of_second`, `offset_seconds`, `proleptic_month`, `second_of_day`, `second_of_minute`, `year`, or `year_of_era`. Refer to {javadoc8}/java/time/temporal/ChronoField.html[java.time.temporal.ChronoField] for a description of these values.\n If `null`, the function returns `null`.""") Expression chronoFieldExp, @Param( name = "date", type = { "date", "date_nanos" }, description = "Date expression. If `null`, the function returns `null`." ) Expression field, Configuration configuration ) { super(source, List.of(chronoFieldExp, field), configuration); } private DateExtract(StreamInput in) throws IOException { this( Source.readFrom((PlanStreamInput) in), in.readNamedWriteable(Expression.class), in.readNamedWriteable(Expression.class), ((PlanStreamInput) in).configuration() ); } @Override public void writeTo(StreamOutput out) throws IOException { source().writeTo(out); out.writeNamedWriteable(datePart()); out.writeNamedWriteable(field()); } Expression datePart() { return children().get(0); } Expression field() { return children().get(1); } @Override public String getWriteableName() { return ENTRY.name; } @Override public ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) { boolean isNanos = switch (field().dataType()) { case DATETIME -> false; case DATE_NANOS -> true; default -> throw new UnsupportedOperationException( "Unsupported field type [" + field().dataType().name() + "]. " + "If you're seeing this, there’s a bug in DateExtract.resolveType" ); }; ExpressionEvaluator.Factory fieldEvaluator = toEvaluator.apply(children().get(1)); // Constant chrono field if (children().get(0).foldable()) { ChronoField chrono = chronoField(toEvaluator.foldCtx()); if (chrono == null) { BytesRef field = (BytesRef) children().get(0).fold(toEvaluator.foldCtx()); throw new InvalidArgumentException("invalid date field for [{}]: {}", sourceText(), field.utf8ToString()); } if (isNanos) { return new DateExtractConstantNanosEvaluator.Factory(source(), fieldEvaluator, chrono, configuration().zoneId()); } else { return new DateExtractConstantMillisEvaluator.Factory(source(), fieldEvaluator, chrono, configuration().zoneId()); } } var chronoEvaluator = toEvaluator.apply(children().get(0)); if (isNanos) { return new DateExtractNanosEvaluator.Factory(source(), fieldEvaluator, chronoEvaluator, configuration().zoneId()); } else { return new DateExtractMillisEvaluator.Factory(source(), fieldEvaluator, chronoEvaluator, configuration().zoneId()); } } private ChronoField chronoField(FoldContext ctx) { // chronoField’s never checked (the return is). The foldability test is done twice and type is checked in resolveType() already. // TODO: move the slimmed down code here to toEvaluator? if (chronoField == null) { Expression field = children().get(0); try { if (field.foldable() && DataType.isString(field.dataType())) { chronoField = (ChronoField) STRING_TO_CHRONO_FIELD.convert(field.fold(ctx)); } } catch (Exception e) { return null; } } return chronoField; } @Evaluator(extraName = "Millis", warnExceptions = { IllegalArgumentException.class }) static long processMillis(long value, BytesRef chronoField, @Fixed ZoneId zone) { return chronoToLong(value, chronoField, zone); } @Evaluator(extraName = "ConstantMillis") static long processMillis(long value, @Fixed ChronoField chronoField, @Fixed ZoneId zone) { return chronoToLong(value, chronoField, zone); } @Evaluator(extraName = "Nanos", warnExceptions = { IllegalArgumentException.class }) static long processNanos(long value, BytesRef chronoField, @Fixed ZoneId zone) { return chronoToLongNanos(value, chronoField, zone); } @Evaluator(extraName = "ConstantNanos") static long processNanos(long value, @Fixed ChronoField chronoField, @Fixed ZoneId zone) { return chronoToLongNanos(value, chronoField, zone); } @Override public Expression replaceChildren(List<Expression> newChildren) { return new DateExtract(source(), newChildren.get(0), newChildren.get(1), configuration()); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, DateExtract::new, children().get(0), children().get(1), configuration()); } @Override public DataType dataType() { return DataType.LONG; } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } String operationName = sourceText(); return isStringAndExact(children().get(0), sourceText(), TypeResolutions.ParamOrdinal.FIRST).and( TypeResolutions.isType( children().get(1), DataType::isDate, operationName, TypeResolutions.ParamOrdinal.SECOND, "datetime or date_nanos" ) ); } @Override public boolean foldable() { return children().get(0).foldable() && children().get(1).foldable(); } }
DateExtract
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleOnErrorCompleteTest.java
{ "start": 976, "end": 3339 }
class ____ { @Test public void normal() { Single.just(1) .onErrorComplete() .test() .assertResult(1); } @Test public void error() throws Throwable { TestHelper.withErrorTracking(errors -> { Single.error(new TestException()) .onErrorComplete() .test() .assertResult(); assertTrue("" + errors, errors.isEmpty()); }); } @Test public void errorMatches() throws Throwable { TestHelper.withErrorTracking(errors -> { Single.error(new TestException()) .onErrorComplete(error -> error instanceof TestException) .test() .assertResult(); assertTrue("" + errors, errors.isEmpty()); }); } @Test public void errorNotMatches() throws Throwable { TestHelper.withErrorTracking(errors -> { Single.error(new IOException()) .onErrorComplete(error -> error instanceof TestException) .test() .assertFailure(IOException.class); assertTrue("" + errors, errors.isEmpty()); }); } @Test public void errorPredicateCrash() throws Throwable { TestHelper.withErrorTracking(errors -> { TestObserverEx<Object> to = Single.error(new IOException()) .onErrorComplete(error -> { throw new TestException(); }) .subscribeWith(new TestObserverEx<>()) .assertFailure(CompositeException.class); TestHelper.assertError(to, 0, IOException.class); TestHelper.assertError(to, 1, TestException.class); assertTrue("" + errors, errors.isEmpty()); }); } @Test public void dispose() { SingleSubject<Integer> ss = SingleSubject.create(); TestObserver<Integer> to = ss .onErrorComplete() .test(); assertTrue("No subscribers?!", ss.hasObservers()); to.dispose(); assertFalse("Still subscribers?!", ss.hasObservers()); } @Test public void onSubscribe() { TestHelper.checkDoubleOnSubscribeSingleToMaybe(f -> f.onErrorComplete()); } @Test public void isDisposed() { TestHelper.checkDisposed(SingleSubject.create().onErrorComplete()); } }
SingleOnErrorCompleteTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/SessionEventListener.java
{ "start": 560, "end": 853 }
class ____ be created for each new session. * * @apiNote This an incubating API, subject to change. * * @see org.hibernate.cfg.AvailableSettings#AUTO_SESSION_EVENTS_LISTENER * @see SessionBuilder#eventListeners(SessionEventListener...) * * @author Steve Ebersole */ @Incubating public
will
java
quarkusio__quarkus
extensions/smallrye-metrics/deployment/src/test/java/io/quarkus/smallrye/metrics/deployment/DevModeMetricRegistryTest.java
{ "start": 672, "end": 740 }
class ____ { @Path("/") public static
DevModeMetricRegistryTest
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/parser/EqlBaseParser.java
{ "start": 118357, "end": 118826 }
class ____ extends ParserRuleContext { public NumberContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_number; } public NumberContext() {} public void copyFrom(NumberContext ctx) { super.copyFrom(ctx); } } @SuppressWarnings("CheckReturnValue") public static
NumberContext
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/hook/FilterCheckHook.java
{ "start": 881, "end": 1019 }
interface ____ { String hookName(); boolean isFilterMatched(final boolean isUnitMode, final ByteBuffer byteBuffer); }
FilterCheckHook
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/erroneous/CircularInjectionNotSupportedTest.java
{ "start": 856, "end": 994 }
class ____ extends AbstractServiceImpl implements Foo { @Override public void ping() { } }
ActualServiceImpl
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
{ "start": 140616, "end": 140720 }
interface ____ { String API_V1 = "/v1"; String ARTICLES_PATH = API_V1 + "/articles"; }
ApiConstants
java
elastic__elasticsearch
modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/SharedGroupFactory.java
{ "start": 4249, "end": 4796 }
class ____ { private final RefCountedGroup refCountedGroup; private final AtomicBoolean isOpen = new AtomicBoolean(true); private SharedGroup(RefCountedGroup refCountedGroup) { this.refCountedGroup = refCountedGroup; } public EventLoopGroup getLowLevelGroup() { return refCountedGroup.eventLoopGroup; } public void shutdown() { if (isOpen.compareAndSet(true, false)) { refCountedGroup.decRef(); } } } }
SharedGroup
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/detached/MultipleCollectionListeners.java
{ "start": 2838, "end": 3185 }
class ____ extends AbstractListener implements PreCollectionRecreateEventListener { private PreCollectionRecreateListener( MultipleCollectionListeners listeners) { super(listeners); } public void onPreRecreateCollection(PreCollectionRecreateEvent event) { addEvent(event, this); } } public static
PreCollectionRecreateListener
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/AutowiredConfigurationErrorsIntegrationTests.java
{ "start": 6024, "end": 6257 }
class ____ { @Autowired @BeforeAll void beforeAll(TestInfo testInfo) { } @Test @DisplayName(DISPLAY_NAME) void test() { } } @SpringJUnitConfig(Config.class) @FailingTestCase static
NonStaticAutowiredBeforeAllMethod
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/distributed/DistributedHerderTest.java
{ "start": 41550, "end": 45514 }
class ____<Callback<ConfigInfos>> validateCallback = ArgumentCaptor.forClass(Callback.class); doAnswer(invocation -> { validateCallback.getValue().onCompletion(null, CONN2_INVALID_CONFIG_INFOS); return null; }).when(herder).validateConnectorConfig(eq(config), validateCallback.capture()); List<String> stages = expectRecordStages(putConnectorCallback); herder.putConnectorConfig(CONN2, config, false, putConnectorCallback); herder.tick(); // We don't need another rebalance to occur expectMemberEnsureActive(); herder.tick(); time.sleep(1000L); assertStatistics(3, 1, 100, 1000L); ArgumentCaptor<Throwable> error = ArgumentCaptor.forClass(Throwable.class); verify(putConnectorCallback).onCompletion(error.capture(), isNull()); assertInstanceOf(BadRequestException.class, error.getValue()); verifyNoMoreInteractions(worker, member, configBackingStore, statusBackingStore, putConnectorCallback); assertEquals( List.of( "awaiting startup", "ensuring membership in the cluster", "reading to the end of the config topic" ), stages ); } @Test public void testConnectorNameConflictsWithWorkerGroupId() { Map<String, String> config = new HashMap<>(CONN2_CONFIG); config.put(ConnectorConfig.NAME_CONFIG, "test-group"); SinkConnector connectorMock = mock(SinkConnector.class); // CONN2 creation should fail because the worker group id (connect-test-group) conflicts with // the consumer group id we would use for this sink Map<String, ConfigValue> validatedConfigs = herder.validateSinkConnectorConfig( connectorMock, SinkConnectorConfig.configDef(), config); ConfigValue nameConfig = validatedConfigs.get(ConnectorConfig.NAME_CONFIG); assertEquals( List.of("Consumer group for sink connector named test-group conflicts with Connect worker group connect-test-group"), nameConfig.errorMessages()); } @Test public void testConnectorGroupIdConflictsWithWorkerGroupId() { String overriddenGroupId = CONNECTOR_CLIENT_CONSUMER_OVERRIDES_PREFIX + GROUP_ID_CONFIG; Map<String, String> config = new HashMap<>(CONN2_CONFIG); config.put(overriddenGroupId, "connect-test-group"); SinkConnector connectorMock = mock(SinkConnector.class); // CONN2 creation should fail because the worker group id (connect-test-group) conflicts with // the consumer group id we would use for this sink Map<String, ConfigValue> validatedConfigs = herder.validateSinkConnectorConfig( connectorMock, SinkConnectorConfig.configDef(), config); ConfigValue overriddenGroupIdConfig = validatedConfigs.get(overriddenGroupId); assertEquals( List.of("Consumer group connect-test-group conflicts with Connect worker group connect-test-group"), overriddenGroupIdConfig.errorMessages()); ConfigValue nameConfig = validatedConfigs.get(ConnectorConfig.NAME_CONFIG); assertEquals( List.of(), nameConfig.errorMessages() ); } @Test public void testCreateConnectorAlreadyExists() { when(member.memberId()).thenReturn("leader"); when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V0); expectRebalance(1, List.of(), List.of(), true); expectConfigRefreshAndSnapshot(SNAPSHOT); when(statusBackingStore.connectors()).thenReturn(Set.of()); expectMemberPoll(); // mock the actual validation since its asynchronous nature is difficult to test and should // be covered sufficiently by the unit tests for the AbstractHerder
ArgumentCaptor
java
junit-team__junit5
documentation/src/tools/java/org/junit/api/tools/AsciidocApiReportWriter.java
{ "start": 396, "end": 1746 }
class ____ extends AbstractApiReportWriter { private static final String ASCIIDOC_FORMAT = "|%-" + NAME_COLUMN_WIDTH + "s | %-12s%n"; AsciidocApiReportWriter(ApiReport apiReport) { super(apiReport); } @Override protected String h1(String header) { return "= " + header; } @Override protected String h2(String header) { return "== " + header; } @Override protected String h4(String header) { return "[discrete]%n==== %s".formatted(header); } @Override protected String h5(String header) { return "[discrete]%n===== %s".formatted(header); } @Override protected String code(String element) { return "`" + element + "`"; } @Override protected String italic(String element) { return "_" + element + "_"; } @Override protected void printDeclarationTableHeader(PrintWriter out) { out.println("[cols=\"99,1\"]"); out.println("|==="); out.printf(ASCIIDOC_FORMAT, "Name", "Since"); out.println(); } @Override protected void printDeclarationTableRow(Declaration declaration, PrintWriter out) { out.printf(ASCIIDOC_FORMAT, // code(declaration.name().replace(".", ".&ZeroWidthSpace;")) + " " + italic("(" + declaration.kind() + ")"), // code(declaration.since()) // ); } @Override protected void printDeclarationTableFooter(PrintWriter out) { out.println("|==="); } }
AsciidocApiReportWriter
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
{ "start": 89308, "end": 89545 }
class ____ { private @Nullable Outer outer; @Nullable Outer getOuter() { return this.outer; } void setOuter(@Nullable Outer nested) { this.outer = nested; } } } @ConfigurationProperties("test") static
Nested
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson/DefaultOidcUserMixin.java
{ "start": 1741, "end": 2056 }
class ____ { @JsonCreator DefaultOidcUserMixin(@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities, @JsonProperty("idToken") OidcIdToken idToken, @JsonProperty("userInfo") OidcUserInfo userInfo, @JsonProperty("nameAttributeKey") String nameAttributeKey) { } }
DefaultOidcUserMixin
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/CollectionOfSoftDeleteTests.java
{ "start": 1217, "end": 3322 }
class ____ { @BeforeEach void createTestData(SessionFactoryScope scope) { scope.inTransaction( (session) -> { final Shelf horror = new Shelf( 1, "Horror" ); session.persist( horror ); final Book theShining = new Book( 1, "The Shining" ); horror.addBook( theShining ); session.persist( theShining ); session.flush(); session.doWork( (connection) -> { final Statement statement = connection.createStatement(); statement.execute( "update books set deleted = 'Y' where id = 1" ); } ); } ); } @AfterEach void dropTestData(SessionFactoryScope scope) { scope.dropData(); } @Test void testLoading(SessionFactoryScope scope) { final SQLStatementInspector sqlInspector = scope.getCollectingStatementInspector(); sqlInspector.clear(); scope.inTransaction( (session) -> { final Shelf loaded = session.get( Shelf.class, 1 ); assertThat( loaded ).isNotNull(); assertThat( sqlInspector.getSqlQueries() ).hasSize( 1 ); assertThat( sqlInspector.getSqlQueries().get( 0 ) ).doesNotContain( " join " ); sqlInspector.clear(); assertThat( loaded.getBooks() ).isNotNull(); assertThat( loaded.getBooks() ).isEmpty(); assertThat( sqlInspector.getSqlQueries() ).hasSize( 1 ); assertThat( sqlInspector.getSqlQueries().get( 0 ) ).containsAnyOf( ".deleted='N'", ".deleted=N'N'" ); } ); } @Test void testQueryJoin(SessionFactoryScope scope) { final SQLStatementInspector sqlInspector = scope.getCollectingStatementInspector(); sqlInspector.clear(); scope.inTransaction( (session) -> { final Shelf shelf = session .createSelectionQuery( "from Shelf join fetch books", Shelf.class ) .uniqueResult(); assertThat( shelf ).isNotNull(); assertThat( shelf.getBooks() ).isNotNull(); assertThat( sqlInspector.getSqlQueries() ).hasSize( 1 ); assertThat( sqlInspector.getSqlQueries().get( 0 ) ).contains( " join " ); assertThat( sqlInspector.getSqlQueries().get( 0 ) ).containsAnyOf( ".deleted='N'", ".deleted=N'N'" ); } ); } @Entity(name="Shelf") @Table(name="shelves") public static
CollectionOfSoftDeleteTests
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringCBRHeaderPredicateTest.java
{ "start": 1043, "end": 1312 }
class ____ extends CBRHeaderPredicateTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/CBRHeaderPredicateTest.xml"); } }
SpringCBRHeaderPredicateTest
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
{ "start": 144997, "end": 145234 }
class ____ implements IMyController { @Override public void handle(Writer writer, @RequestParam(value="p", required=false) String param) throws IOException { writer.write("handle " + param); } } abstract static
IMyControllerImpl
java
apache__flink
flink-filesystems/flink-s3-fs-hadoop/src/test/java/org/apache/flink/fs/s3hadoop/HadoopS3FileSystemBehaviorITCase.java
{ "start": 1385, "end": 2549 }
class ____ extends FileSystemBehaviorTestSuite { private static final String TEST_DATA_DIR = "tests-" + UUID.randomUUID(); @BeforeAll static void checkCredentialsAndSetup() { // check whether credentials exist S3TestCredentials.assumeCredentialsAvailable(); // initialize configuration with valid credentials final Configuration conf = new Configuration(); conf.setString("s3.access.key", S3TestCredentials.getS3AccessKey()); conf.setString("s3.secret.key", S3TestCredentials.getS3SecretKey()); FileSystem.initialize(conf, null); } @AfterAll static void clearFsConfig() throws IOException { FileSystem.initialize(new Configuration(), null); } @Override protected FileSystem getFileSystem() throws Exception { return getBasePath().getFileSystem(); } @Override protected Path getBasePath() throws Exception { return new Path(S3TestCredentials.getTestBucketUri() + TEST_DATA_DIR); } @Override protected FileSystemKind getFileSystemKind() { return FileSystemKind.OBJECT_STORE; } }
HadoopS3FileSystemBehaviorITCase
java
apache__rocketmq
tools/src/test/java/org/apache/rocketmq/tools/command/producer/ProducerSubCommandTest.java
{ "start": 1521, "end": 3298 }
class ____ { private ServerResponseMocker brokerMocker; private ServerResponseMocker nameServerMocker; @Before public void before() { brokerMocker = startOneBroker(); nameServerMocker = NameServerMocker.startByDefaultConf(brokerMocker.listenPort()); } @After public void after() { brokerMocker.shutdown(); nameServerMocker.shutdown(); } @Test public void testExecute() throws SubCommandException { ProducerSubCommand cmd = new ProducerSubCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[]{"-b 127.0.0.1:" + brokerMocker.listenPort()}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new DefaultParser()); cmd.execute(commandLine, options, null); } private ServerResponseMocker startOneBroker() { ConsumeStats consumeStats = new ConsumeStats(); HashMap<MessageQueue, OffsetWrapper> offsetTable = new HashMap<>(); MessageQueue messageQueue = new MessageQueue(); messageQueue.setBrokerName("mockBrokerName"); messageQueue.setQueueId(1); messageQueue.setBrokerName("mockTopicName"); OffsetWrapper offsetWrapper = new OffsetWrapper(); offsetWrapper.setBrokerOffset(1); offsetWrapper.setConsumerOffset(1); offsetWrapper.setLastTimestamp(System.currentTimeMillis()); offsetTable.put(messageQueue, offsetWrapper); consumeStats.setOffsetTable(offsetTable); // start broker return ServerResponseMocker.startServer(consumeStats.encode()); } }
ProducerSubCommandTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/delegation/web/DelegationTokenManager.java
{ "start": 3643, "end": 8442 }
class ____ extends ZKDelegationTokenSecretManager<DelegationTokenIdentifier> { private Text tokenKind; public ZKSecretManager(Configuration conf, Text tokenKind) { super(conf); this.tokenKind = tokenKind; } @Override public DelegationTokenIdentifier createIdentifier() { return new DelegationTokenIdentifier(tokenKind); } @Override public DelegationTokenIdentifier decodeTokenIdentifier( Token<DelegationTokenIdentifier> token) throws IOException { return DelegationTokenManager.decodeToken(token, tokenKind); } } private AbstractDelegationTokenSecretManager secretManager = null; private boolean managedSecretManager; public DelegationTokenManager(Configuration conf, Text tokenKind) { if (conf.getBoolean(ENABLE_ZK_KEY, false)) { this.secretManager = new ZKSecretManager(conf, tokenKind); } else { this.secretManager = new DelegationTokenSecretManager(conf, tokenKind); } managedSecretManager = true; } /** * Sets an external <code>DelegationTokenSecretManager</code> instance to * manage creation and verification of Delegation Tokens. * <p> * This is useful for use cases where secrets must be shared across multiple * services. * * @param secretManager a <code>DelegationTokenSecretManager</code> instance */ public void setExternalDelegationTokenSecretManager( AbstractDelegationTokenSecretManager secretManager) { this.secretManager.stopThreads(); this.secretManager = secretManager; managedSecretManager = false; } public void init() { if (managedSecretManager) { try { secretManager.startThreads(); } catch (IOException ex) { throw new RuntimeException("Could not start " + secretManager.getClass() + ": " + ex.toString(), ex); } } } public void destroy() { if (managedSecretManager) { secretManager.stopThreads(); } } @SuppressWarnings("unchecked") public Token<? extends AbstractDelegationTokenIdentifier> createToken( UserGroupInformation ugi, String renewer) { return createToken(ugi, renewer, null); } @SuppressWarnings("unchecked") public Token<? extends AbstractDelegationTokenIdentifier> createToken( UserGroupInformation ugi, String renewer, String service) { LOG.debug("Creating token with ugi:{}, renewer:{}, service:{}.", ugi, renewer, service !=null ? service : ""); renewer = (renewer == null) ? ugi.getShortUserName() : renewer; String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } AbstractDelegationTokenIdentifier tokenIdentifier = (AbstractDelegationTokenIdentifier) secretManager.createIdentifier(); tokenIdentifier.setOwner(owner); tokenIdentifier.setRenewer(new Text(renewer)); tokenIdentifier.setRealUser(realUser); Token token = new Token(tokenIdentifier, secretManager); if (service != null) { token.setService(new Text(service)); } return token; } @SuppressWarnings("unchecked") public long renewToken( Token<? extends AbstractDelegationTokenIdentifier> token, String renewer) throws IOException { LOG.debug("Renewing token:{} with renewer:{}.", token, renewer); return secretManager.renewToken(token, renewer); } @SuppressWarnings("unchecked") public void cancelToken( Token<? extends AbstractDelegationTokenIdentifier> token, String canceler) throws IOException { LOG.debug("Cancelling token:{} with canceler:{}.", token, canceler); canceler = (canceler != null) ? canceler : verifyToken(token).getShortUserName(); secretManager.cancelToken(token, canceler); } @SuppressWarnings("unchecked") public UserGroupInformation verifyToken( Token<? extends AbstractDelegationTokenIdentifier> token) throws IOException { AbstractDelegationTokenIdentifier id = secretManager.decodeTokenIdentifier(token); secretManager.verifyToken(id, token.getPassword()); return id.getUser(); } @VisibleForTesting @SuppressWarnings("rawtypes") public AbstractDelegationTokenSecretManager getDelegationTokenSecretManager() { return secretManager; } private static DelegationTokenIdentifier decodeToken( Token<DelegationTokenIdentifier> token, Text tokenKind) throws IOException { ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier()); DataInputStream dis = new DataInputStream(buf); DelegationTokenIdentifier id = new DelegationTokenIdentifier(tokenKind); id.readFields(dis); dis.close(); return id; } }
ZKSecretManager
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/search/query/QueryStringIT.java
{ "start": 1718, "end": 13236 }
class ____ extends ESIntegTestCase { @Before public void setup() throws Exception { String indexBody = copyToStringFromClasspath("/org/elasticsearch/search/query/all-query-index.json"); prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); ensureGreen("test"); } public void testBasicAllQuery() throws Exception { List<IndexRequestBuilder> reqs = new ArrayList<>(); reqs.add(prepareIndex("test").setId("1").setSource("f1", "foo bar baz")); reqs.add(prepareIndex("test").setId("2").setSource("f2", "Bar")); reqs.add(prepareIndex("test").setId("3").setSource("f3", "foo bar baz")); indexRandom(true, false, reqs); assertResponses(response -> { assertHitCount(response, 2L); assertHits(response.getHits(), "1", "3"); }, prepareSearch("test").setQuery(queryStringQuery("foo")), prepareSearch("test").setQuery(queryStringQuery("bar"))); assertResponse(prepareSearch("test").setQuery(queryStringQuery("Bar")), response -> { assertHitCount(response, 3L); assertHits(response.getHits(), "1", "2", "3"); }); } public void testWithDate() throws Exception { List<IndexRequestBuilder> reqs = new ArrayList<>(); reqs.add(prepareIndex("test").setId("1").setSource("f1", "foo", "f_date", "2015/09/02")); reqs.add(prepareIndex("test").setId("2").setSource("f1", "bar", "f_date", "2015/09/01")); indexRandom(true, false, reqs); assertResponses(response -> { assertHits(response.getHits(), "1", "2"); assertHitCount(response, 2L); }, prepareSearch("test").setQuery(queryStringQuery("foo bar")), prepareSearch("test").setQuery(queryStringQuery("bar \"2015/09/02\"")), prepareSearch("test").setQuery(queryStringQuery("\"2015/09/02\" \"2015/09/01\"")) ); assertResponse(prepareSearch("test").setQuery(queryStringQuery("\"2015/09/02\"")), response -> { assertHits(response.getHits(), "1"); assertHitCount(response, 1L); }); } public void testWithLotsOfTypes() throws Exception { List<IndexRequestBuilder> reqs = new ArrayList<>(); reqs.add(prepareIndex("test").setId("1").setSource("f1", "foo", "f_date", "2015/09/02", "f_float", "1.7", "f_ip", "127.0.0.1")); reqs.add(prepareIndex("test").setId("2").setSource("f1", "bar", "f_date", "2015/09/01", "f_float", "1.8", "f_ip", "127.0.0.2")); indexRandom(true, false, reqs); assertResponses(response -> { assertHits(response.getHits(), "1", "2"); assertHitCount(response, 2L); }, prepareSearch("test").setQuery(queryStringQuery("foo bar")), prepareSearch("test").setQuery(queryStringQuery("127.0.0.2 \"2015/09/02\"")), prepareSearch("test").setQuery(queryStringQuery("127.0.0.1 OR 1.8")) ); assertResponse(prepareSearch("test").setQuery(queryStringQuery("\"2015/09/02\"")), response -> { assertHits(response.getHits(), "1"); assertHitCount(response, 1L); }); } public void testDocWithAllTypes() throws Exception { List<IndexRequestBuilder> reqs = new ArrayList<>(); String docBody = copyToStringFromClasspath("/org/elasticsearch/search/query/all-example-document.json"); reqs.add(prepareIndex("test").setId("1").setSource(docBody, XContentType.JSON)); indexRandom(true, false, reqs); assertResponses( response -> assertHits(response.getHits(), "1"), prepareSearch("test").setQuery(queryStringQuery("foo")), prepareSearch("test").setQuery(queryStringQuery("Bar")), prepareSearch("test").setQuery(queryStringQuery("Baz")), prepareSearch("test").setQuery(queryStringQuery("19")), // nested doesn't match because it's hidden prepareSearch("test").setQuery(queryStringQuery("1476383971")), // bool doesn't match prepareSearch("test").setQuery(queryStringQuery("7")), prepareSearch("test").setQuery(queryStringQuery("23")), prepareSearch("test").setQuery(queryStringQuery("1293")), prepareSearch("test").setQuery(queryStringQuery("42")), prepareSearch("test").setQuery(queryStringQuery("1.7")), prepareSearch("test").setQuery(queryStringQuery("1.5")), prepareSearch("test").setQuery(queryStringQuery("127.0.0.1")) ); } public void testKeywordWithWhitespace() throws Exception { List<IndexRequestBuilder> reqs = new ArrayList<>(); reqs.add(prepareIndex("test").setId("1").setSource("f2", "Foo Bar")); reqs.add(prepareIndex("test").setId("2").setSource("f1", "bar")); reqs.add(prepareIndex("test").setId("3").setSource("f1", "foo bar")); indexRandom(true, false, reqs); assertResponse(prepareSearch("test").setQuery(queryStringQuery("foo")), response -> { assertHits(response.getHits(), "3"); assertHitCount(response, 1L); }); assertResponse(prepareSearch("test").setQuery(queryStringQuery("bar")), response -> { assertHits(response.getHits(), "2", "3"); assertHitCount(response, 2L); }); assertResponse(prepareSearch("test").setQuery(queryStringQuery("Foo Bar")), response -> { assertHits(response.getHits(), "1", "2", "3"); assertHitCount(response, 3L); }); } public void testAllFields() throws Exception { String indexBody = copyToStringFromClasspath("/org/elasticsearch/search/query/all-query-index.json"); Settings.Builder settings = Settings.builder().put("index.query.default_field", "*"); prepareCreate("test_1").setSource(indexBody, XContentType.JSON).setSettings(settings).get(); ensureGreen("test_1"); List<IndexRequestBuilder> reqs = new ArrayList<>(); reqs.add(prepareIndex("test_1").setId("1").setSource("f1", "foo", "f2", "eggplant")); indexRandom(true, false, reqs); assertHitCount(prepareSearch("test_1").setQuery(queryStringQuery("foo eggplant").defaultOperator(Operator.AND)), 0L); assertResponse(prepareSearch("test_1").setQuery(queryStringQuery("foo eggplant").defaultOperator(Operator.OR)), response -> { assertHits(response.getHits(), "1"); assertHitCount(response, 1L); }); } public void testPhraseQueryOnFieldWithNoPositions() throws Exception { List<IndexRequestBuilder> reqs = new ArrayList<>(); reqs.add(prepareIndex("test").setId("1").setSource("f1", "foo bar", "f4", "eggplant parmesan")); reqs.add(prepareIndex("test").setId("2").setSource("f1", "foo bar", "f4", "chicken parmesan")); indexRandom(true, false, reqs); assertHitCount(prepareSearch("test").setQuery(queryStringQuery("\"eggplant parmesan\"").lenient(true)), 0L); Exception exc = expectThrows( Exception.class, prepareSearch("test").setQuery(queryStringQuery("f4:\"eggplant parmesan\"").lenient(false)) ); IllegalArgumentException iae = (IllegalArgumentException) ExceptionsHelper.unwrap(exc, IllegalArgumentException.class); assertNotNull(iae); assertThat(iae.getMessage(), containsString("field:[f4] was indexed without position data; cannot run PhraseQuery")); } public void testBooleanStrictQuery() throws Exception { Exception e = expectThrows(Exception.class, prepareSearch("test").setQuery(queryStringQuery("foo").field("f_bool"))); assertThat( ExceptionsHelper.unwrap(e, IllegalArgumentException.class).getMessage(), containsString("Can't parse boolean value [foo], expected [true] or [false]") ); } public void testAllFieldsWithSpecifiedLeniency() throws IOException { Exception e = expectThrows( Exception.class, prepareSearch("test").setQuery(queryStringQuery("f_date:[now-2D TO now]").lenient(false)) ); assertThat(e.getCause().getMessage(), containsString("unit [D] not supported for date math [-2D]")); } public void testFieldAlias() throws Exception { List<IndexRequestBuilder> indexRequests = new ArrayList<>(); indexRequests.add(prepareIndex("test").setId("1").setSource("f3", "text", "f2", "one")); indexRequests.add(prepareIndex("test").setId("2").setSource("f3", "value", "f2", "two")); indexRequests.add(prepareIndex("test").setId("3").setSource("f3", "another value", "f2", "three")); indexRandom(true, false, indexRequests); assertNoFailuresAndResponse(prepareSearch("test").setQuery(queryStringQuery("value").field("f3_alias")), response -> { assertHitCount(response, 2); assertHits(response.getHits(), "2", "3"); }); } public void testFieldAliasWithEmbeddedFieldNames() throws Exception { List<IndexRequestBuilder> indexRequests = new ArrayList<>(); indexRequests.add(prepareIndex("test").setId("1").setSource("f3", "text", "f2", "one")); indexRequests.add(prepareIndex("test").setId("2").setSource("f3", "value", "f2", "two")); indexRequests.add(prepareIndex("test").setId("3").setSource("f3", "another value", "f2", "three")); indexRandom(true, false, indexRequests); assertNoFailuresAndResponse(prepareSearch("test").setQuery(queryStringQuery("f3_alias:value AND f2:three")), response -> { assertHitCount(response, 1); assertHits(response.getHits(), "3"); }); } public void testFieldAliasWithWildcardField() throws Exception { List<IndexRequestBuilder> indexRequests = new ArrayList<>(); indexRequests.add(prepareIndex("test").setId("1").setSource("f3", "text", "f2", "one")); indexRequests.add(prepareIndex("test").setId("2").setSource("f3", "value", "f2", "two")); indexRequests.add(prepareIndex("test").setId("3").setSource("f3", "another value", "f2", "three")); indexRandom(true, false, indexRequests); assertNoFailuresAndResponse(prepareSearch("test").setQuery(queryStringQuery("value").field("f3_*")), response -> { assertHitCount(response, 2); assertHits(response.getHits(), "2", "3"); }); } public void testFieldAliasOnDisallowedFieldType() throws Exception { List<IndexRequestBuilder> indexRequests = new ArrayList<>(); indexRequests.add(prepareIndex("test").setId("1").setSource("f3", "text", "f2", "one")); indexRandom(true, false, indexRequests); // The wildcard field matches aliases for both a text and geo_point field. // By default, the geo_point field should be ignored when building the query. assertNoFailuresAndResponse(prepareSearch("test").setQuery(queryStringQuery("text").field("f*_alias")), response -> { assertHitCount(response, 1); assertHits(response.getHits(), "1"); }); } private void assertHits(SearchHits hits, String... ids) { assertThat(hits.getTotalHits().value(), equalTo((long) ids.length)); Set<String> hitIds = new HashSet<>(); for (SearchHit hit : hits.getHits()) { hitIds.add(hit.getId()); } assertThat(hitIds, containsInAnyOrder(ids)); } }
QueryStringIT
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/TemplatingTest.java
{ "start": 23807, "end": 24727 }
class ____ {", " public <E extends Enum<E>> E example(E e) {", " return e;", " }", "}"); Template<?> template = UTemplater.createTemplate(context, getMethodDeclaration("example")); UTypeVar eVar = Iterables.getOnlyElement(template.templateTypeVariables()); assertThat(template) .isEqualTo( ExpressionTemplate.create( ImmutableClassToInstanceMap.of(), ImmutableList.of(UTypeVar.create("E", UClassType.create("java.lang.Enum", eVar))), ImmutableMap.of("e", eVar), UFreeIdent.create("e"), eVar)); } @Test public void localVariable() { compile( "import java.util.ArrayList;", "import java.util.Comparator;", "import java.util.Collection;", "import java.util.Collections;", "import java.util.List;", "
RecursiveTypeExample
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/BFloat16.java
{ "start": 600, "end": 2050 }
class ____ { public static final int BYTES = Short.BYTES; public static short floatToBFloat16(float f) { // this rounds towards 0 // zero - zero exp, zero fraction // denormal - zero exp, non-zero fraction // infinity - all-1 exp, zero fraction // NaN - all-1 exp, non-zero fraction // the Float.NaN constant is 0x7fc0_0000, so this won't turn the most common NaN values into // infinities return (short) (Float.floatToIntBits(f) >>> 16); } public static float truncateToBFloat16(float f) { return Float.intBitsToFloat(Float.floatToIntBits(f) & 0xffff0000); } public static float bFloat16ToFloat(short bf) { return Float.intBitsToFloat(bf << 16); } public static void floatToBFloat16(float[] floats, ShortBuffer bFloats) { for (float v : floats) { bFloats.put(floatToBFloat16(v)); } } public static void bFloat16ToFloat(byte[] bfBytes, float[] floats) { assert floats.length * 2 == bfBytes.length; for (int i = 0; i < floats.length; i++) { floats[i] = bFloat16ToFloat((short) BitUtil.VH_LE_SHORT.get(bfBytes, i * 2)); } } public static void bFloat16ToFloat(ShortBuffer bFloats, float[] floats) { for (int i = 0; i < floats.length; i++) { floats[i] = bFloat16ToFloat(bFloats.get()); } } private BFloat16() {} }
BFloat16
java
spring-projects__spring-boot
test-support/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCaptureExtension.java
{ "start": 2009, "end": 2563 }
class ____ { * * &#064;Test * void test(CapturedOutput output) { * System.out.println("ok"); * assertThat(output).contains("ok"); * System.err.println("error"); * } * * &#064;AfterEach * void after(CapturedOutput output) { * assertThat(output.getOut()).contains("ok"); * assertThat(output.getErr()).contains("error"); * } * * } * </pre> * * @author Madhura Bhave * @author Phillip Webb * @author Andy Wilkinson * @author Sam Brannen * @see CapturedOutput */ public
MyTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/date/DateAssert_isInSameMonthAs_Test.java
{ "start": 868, "end": 1516 }
class ____ extends AbstractDateAssertWithDateArg_Test { @Override protected DateAssert assertionInvocationWithDateArg() { return assertions.isInSameMonthAs(otherDate); } @Override protected DateAssert assertionInvocationWithStringArg(String date) { return assertions.isInSameMonthAs(date); } @Override protected void verifyAssertionInvocation(Date date) { verify(dates).assertIsInSameMonthAs(getInfo(assertions), getActual(assertions), date); } @Override protected DateAssert assertionInvocationWithInstantArg() { return assertions.isInSameMonthAs(otherDate.toInstant()); } }
DateAssert_isInSameMonthAs_Test
java
google__guava
android/guava-tests/test/com/google/common/collect/ImmutableSortedMultisetTest.java
{ "start": 2131, "end": 10516 }
class ____ extends TestCase { @AndroidIncompatible // test-suite builders public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(ImmutableSortedMultisetTest.class); suite.addTest( SortedMultisetTestSuiteBuilder.using( new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { return ImmutableSortedMultiset.copyOf(elements); } @Override public List<String> order(List<String> insertionOrder) { return Ordering.natural().sortedCopy(insertionOrder); } }) .named("ImmutableSortedMultiset") .withFeatures( CollectionSize.ANY, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS, CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); suite.addTest( ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override protected List<String> create(String[] elements) { return ImmutableSortedMultiset.copyOf(elements).asList(); } @Override public List<String> order(List<String> insertionOrder) { return Ordering.natural().sortedCopy(insertionOrder); } }) .named("ImmutableSortedMultiset.asList") .withFeatures( CollectionSize.ANY, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); suite.addTest( ListTestSuiteBuilder.using( new TestStringListGenerator() { @Override protected List<String> create(String[] elements) { Set<String> set = new HashSet<>(); ImmutableSortedMultiset.Builder<String> builder = ImmutableSortedMultiset.naturalOrder(); for (String s : elements) { checkArgument(set.add(s)); builder.addCopies(s, 2); } return builder.build().elementSet().asList(); } @Override public List<String> order(List<String> insertionOrder) { return Ordering.natural().sortedCopy(insertionOrder); } }) .named("ImmutableSortedMultiset.elementSet.asList") .withFeatures( CollectionSize.ANY, CollectionFeature.REJECTS_DUPLICATES_AT_CREATION, CollectionFeature.SERIALIZABLE, CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); return suite; } public void testCreation_noArgs() { Multiset<String> multiset = ImmutableSortedMultiset.of(); assertTrue(multiset.isEmpty()); } public void testCreation_oneElement() { Multiset<String> multiset = ImmutableSortedMultiset.of("a"); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCreation_twoElements() { Multiset<String> multiset = ImmutableSortedMultiset.of("a", "b"); assertEquals(HashMultiset.create(asList("a", "b")), multiset); } public void testCreation_threeElements() { Multiset<String> multiset = ImmutableSortedMultiset.of("a", "b", "c"); assertEquals(HashMultiset.create(asList("a", "b", "c")), multiset); } public void testCreation_fourElements() { Multiset<String> multiset = ImmutableSortedMultiset.of("a", "b", "c", "d"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d")), multiset); } public void testCreation_fiveElements() { Multiset<String> multiset = ImmutableSortedMultiset.of("a", "b", "c", "d", "e"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e")), multiset); } public void testCreation_sixElements() { Multiset<String> multiset = ImmutableSortedMultiset.of("a", "b", "c", "d", "e", "f"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e", "f")), multiset); } public void testCreation_sevenElements() { Multiset<String> multiset = ImmutableSortedMultiset.of("a", "b", "c", "d", "e", "f", "g"); assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e", "f", "g")), multiset); } public void testCreation_emptyArray() { String[] array = new String[0]; Multiset<String> multiset = ImmutableSortedMultiset.copyOf(array); assertTrue(multiset.isEmpty()); } public void testCreation_arrayOfOneElement() { String[] array = new String[] {"a"}; Multiset<String> multiset = ImmutableSortedMultiset.copyOf(array); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCreation_arrayOfArray() { Comparator<String[]> comparator = Ordering.natural().lexicographical().onResultOf(Arrays::asList); String[] array = new String[] {"a"}; Multiset<String[]> multiset = ImmutableSortedMultiset.orderedBy(comparator).add(array).build(); Multiset<String[]> expected = HashMultiset.create(); expected.add(array); assertEquals(expected, multiset); } public void testCreation_arrayContainingOnlyNull() { String[] array = new String[] {null}; assertThrows(NullPointerException.class, () -> ImmutableSortedMultiset.copyOf(array)); } public void testCopyOf_collection_empty() { Collection<String> c = MinimalCollection.of(); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(c); assertTrue(multiset.isEmpty()); } public void testCopyOf_collection_oneElement() { Collection<String> c = MinimalCollection.of("a"); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_collection_general() { Collection<String> c = MinimalCollection.of("a", "b", "a"); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_collectionContainingNull() { Collection<String> c = MinimalCollection.of("a", null, "b"); assertThrows(NullPointerException.class, () -> ImmutableSortedMultiset.copyOf(c)); } public void testCopyOf_multiset_empty() { Multiset<String> c = HashMultiset.create(); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(c); assertTrue(multiset.isEmpty()); } public void testCopyOf_multiset_oneElement() { Multiset<String> c = HashMultiset.create(asList("a")); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_multiset_general() { Multiset<String> c = HashMultiset.create(asList("a", "b", "a")); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(c); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_multisetContainingNull() { Multiset<String> c = HashMultiset.create(asList("a", null, "b")); assertThrows(NullPointerException.class, () -> ImmutableSortedMultiset.copyOf(c)); } public void testCopyOf_iterator_empty() { Iterator<String> iterator = emptyIterator(); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(iterator); assertTrue(multiset.isEmpty()); } public void testCopyOf_iterator_oneElement() { Iterator<String> iterator = singletonIterator("a"); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(iterator); assertEquals(HashMultiset.create(asList("a")), multiset); } public void testCopyOf_iterator_general() { Iterator<String> iterator = asList("a", "b", "a").iterator(); Multiset<String> multiset = ImmutableSortedMultiset.copyOf(iterator); assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset); } public void testCopyOf_iteratorContainingNull() { Iterator<String> iterator = asList("a", null, "b").iterator(); assertThrows(NullPointerException.class, () -> ImmutableSortedMultiset.copyOf(iterator)); } private static
ImmutableSortedMultisetTest
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ccr/action/FollowStatsAction.java
{ "start": 7601, "end": 8803 }
class ____ implements Writeable, ToXContentObject { private final ShardFollowNodeTaskStatus status; public ShardFollowNodeTaskStatus status() { return status; } public StatsResponse(final ShardFollowNodeTaskStatus status) { this.status = status; } public StatsResponse(final StreamInput in) throws IOException { this.status = new ShardFollowNodeTaskStatus(in); } @Override public void writeTo(final StreamOutput out) throws IOException { status.writeTo(out); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StatsResponse that = (StatsResponse) o; return Objects.equals(status, that.status); } @Override public int hashCode() { return Objects.hash(status); } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { return status.toXContent(builder, params); } } }
StatsResponse
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
{ "start": 3466, "end": 3499 }
class ____ thread-safe. */ public
is
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Langchain4jAgentComponentBuilderFactory.java
{ "start": 1376, "end": 1887 }
interface ____ { /** * LangChain4j Agent (camel-langchain4j-agent) * LangChain4j Agent component * * Category: ai * Since: 4.14 * Maven coordinates: org.apache.camel:camel-langchain4j-agent * * @return the dsl builder */ static Langchain4jAgentComponentBuilder langchain4jAgent() { return new Langchain4jAgentComponentBuilderImpl(); } /** * Builder for the LangChain4j Agent component. */
Langchain4jAgentComponentBuilderFactory
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/extension-removed-resources/runner/src/main/java/org/acme/MetaInfResource.java
{ "start": 377, "end": 936 }
class ____ { @GET @Produces(MediaType.TEXT_PLAIN) @Path("/{name}") public String hello(@PathParam("name") String name) { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); var url = cl.getResource("META-INF/" + name); if(url == null) { throw new BadRequestException(Response.status(Status.BAD_REQUEST).build()); } try(InputStream is = url.openStream()) { return new String(is.readAllBytes()); } catch (IOException e) { throw new RuntimeException("Failed to read " + url, e); } } }
MetaInfResource
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/server/TestServer.java
{ "start": 17190, "end": 18607 }
class ____ implements Service, XException.ERROR { private String id; private Class serviceInterface; private Class[] dependencies; private boolean failOnInit; private boolean failOnDestroy; protected MyService(String id, Class serviceInterface, Class[] dependencies, boolean failOnInit, boolean failOnDestroy) { this.id = id; this.serviceInterface = serviceInterface; this.dependencies = dependencies; this.failOnInit = failOnInit; this.failOnDestroy = failOnDestroy; } @Override public void init(Server server) throws ServiceException { ORDER.add(id + ".init"); if (failOnInit) { throw new ServiceException(this); } } @Override public void postInit() throws ServiceException { ORDER.add(id + ".postInit"); } @Override public String getTemplate() { return ""; } @Override public void destroy() { ORDER.add(id + ".destroy"); if (failOnDestroy) { throw new RuntimeException(); } } @Override public Class[] getServiceDependencies() { return dependencies; } @Override public Class getInterface() { return serviceInterface; } @Override public void serverStatusChange(Server.Status oldStatus, Server.Status newStatus) throws ServiceException { } } public static
MyService
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetomany/EmbeddablePersistAndQueryInSameTransactionTest.java
{ "start": 2719, "end": 3355 }
class ____ { private Integer age; @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL) private List<Child> children = new ArrayList<>(); @Embedded private NestedEmbeddable nestedEmbeddable = new NestedEmbeddable(); public List<Child> getChildren() { return Collections.unmodifiableList( children ); } public void addChild(Child child) { this.children.add( child ); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public void addDog(Dog dog) { nestedEmbeddable.addDog( dog ); } } @Entity(name = "Parent") public static
EmbeddedData
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ContainerExitStatus.java
{ "start": 1072, "end": 2663 }
class ____ { public static final int SUCCESS = 0; public static final int INVALID = -1000; /** * Containers killed by the framework, either due to being released by * the application or being 'lost' due to node failures etc. */ public static final int ABORTED = -100; /** * When threshold number of the nodemanager-local-directories or * threshold number of the nodemanager-log-directories become bad. */ public static final int DISKS_FAILED = -101; /** * Containers preempted by the framework. */ public static final int PREEMPTED = -102; /** * Container terminated because of exceeding allocated virtual memory. */ public static final int KILLED_EXCEEDED_VMEM = -103; /** * Container terminated because of exceeding allocated physical memory. */ public static final int KILLED_EXCEEDED_PMEM = -104; /** * Container was terminated by stop request by the app master. */ public static final int KILLED_BY_APPMASTER = -105; /** * Container was terminated by the resource manager. */ public static final int KILLED_BY_RESOURCEMANAGER = -106; /** * Container was terminated after the application finished. */ public static final int KILLED_AFTER_APP_COMPLETION = -107; /** * Container was terminated by the ContainerScheduler to make room * for another container... */ public static final int KILLED_BY_CONTAINER_SCHEDULER = -108; /** * Container was terminated for generating excess log data. */ public static final int KILLED_FOR_EXCESS_LOGS = -109; }
ContainerExitStatus
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
{ "start": 107409, "end": 108236 }
class ____ { int x; public Test(int foo) { x = -1; } public int foo(Suit suit) { switch (suit) { /* Comment before first case */ case /* LHS comment */ HEART: // Inline comment this.x <<= 2; break; case DIAMOND: x <<= (((x + 1) * (x * x)) << 1); break; case SPADE: throw new RuntimeException(); default: throw new NullPointerException(); } return x; } } """) .addOutputLines( "Test.java", """
Test
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/co/CoBroadcastWithNonKeyedOperator.java
{ "start": 7595, "end": 10094 }
class ____ extends BroadcastProcessFunction<IN1, IN2, OUT>.ReadOnlyContext { private final ExecutionConfig config; private final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> states; private final ProcessingTimeService timerService; private StreamRecord<IN1> element; ReadOnlyContextImpl( final ExecutionConfig executionConfig, final BroadcastProcessFunction<IN1, IN2, OUT> function, final Map<MapStateDescriptor<?, ?>, BroadcastState<?, ?>> broadcastStates, final ProcessingTimeService timerService) { function.super(); this.config = Preconditions.checkNotNull(executionConfig); this.states = Preconditions.checkNotNull(broadcastStates); this.timerService = Preconditions.checkNotNull(timerService); } void setElement(StreamRecord<IN1> e) { this.element = e; } @Override public Long timestamp() { checkState(element != null); return element.hasTimestamp() ? element.getTimestamp() : null; } @Override public <X> void output(OutputTag<X> outputTag, X value) { checkArgument(outputTag != null, "OutputTag must not be null."); output.collect(outputTag, new StreamRecord<>(value, element.getTimestamp())); } @Override public long currentProcessingTime() { return timerService.getCurrentProcessingTime(); } @Override public long currentWatermark() { return currentWatermark; } @Override public <K, V> ReadOnlyBroadcastState<K, V> getBroadcastState( MapStateDescriptor<K, V> stateDescriptor) { Preconditions.checkNotNull(stateDescriptor); stateDescriptor.initializeSerializerUnlessSet(config); ReadOnlyBroadcastState<K, V> state = (ReadOnlyBroadcastState<K, V>) states.get(stateDescriptor); if (state == null) { throw new IllegalArgumentException( "The requested state does not exist. " + "Check for typos in your state descriptor, or specify the state descriptor " + "in the datastream.broadcast(...) call if you forgot to register it."); } return state; } } }
ReadOnlyContextImpl
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/PathBasedTemplateAvailabilityProvider.java
{ "start": 2567, "end": 3105 }
class ____ { private String prefix; private String suffix; protected TemplateAvailabilityProperties(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } protected abstract List<String> getLoaderPath(); public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } } }
TemplateAvailabilityProperties
java
google__dagger
javatests/dagger/internal/codegen/DependencyCycleValidationTest.java
{ "start": 23336, "end": 23630 }
interface ____ {}"); Source module = CompilerTests.javaSource( "test.TestModule", "package test;", "", "import dagger.Binds;", "import dagger.Module;", "", "@Module", "abstract
SomeQualifier
java
quarkusio__quarkus
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddDeploymentResourceDecorator.java
{ "start": 271, "end": 1360 }
class ____ extends ResourceProvidingDecorator<KubernetesListFluent<?>> { private final String name; private final PlatformConfiguration config; @Override public void visit(KubernetesListFluent<?> list) { list.addToItems(new DeploymentBuilder() .withNewMetadata() .withName(name) .endMetadata() .withNewSpec() .withReplicas(1) .withNewSelector() .withMatchLabels(new HashMap<String, String>()) .endSelector() .withNewTemplate() .withNewMetadata() .endMetadata() .withNewSpec() .addNewContainer() .withName(name) .endContainer() .endSpec() .endTemplate() .endSpec() .build()); } public AddDeploymentResourceDecorator(String name, PlatformConfiguration config) { this.name = name; this.config = config; } }
AddDeploymentResourceDecorator
java
apache__flink
flink-end-to-end-tests/flink-stream-state-ttl-test/src/main/java/org/apache/flink/streaming/tests/verify/ValueWithTs.java
{ "start": 1924, "end": 4162 }
class ____ extends CompositeSerializer<ValueWithTs<?>> { private static final long serialVersionUID = -7300352863212438745L; public Serializer( TypeSerializer<?> valueSerializer, TypeSerializer<Long> timestampSerializer) { super(true, valueSerializer, timestampSerializer); } @SuppressWarnings("unchecked") Serializer(PrecomputedParameters precomputed, TypeSerializer<?>... fieldSerializers) { super(precomputed, fieldSerializers); } @Override public ValueWithTs<?> createInstance(@Nonnull Object... values) { return new ValueWithTs<>(values[0], (Long) values[1]); } @Override protected void setField(@Nonnull ValueWithTs<?> value, int index, Object fieldValue) { throw new UnsupportedOperationException(); } @Override protected Object getField(@Nonnull ValueWithTs<?> value, int index) { switch (index) { case 0: return value.getValue(); case 1: return value.getTimestamp(); default: throw new FlinkRuntimeException("Unexpected field index for ValueWithTs"); } } @SuppressWarnings("unchecked") @Override protected CompositeSerializer<ValueWithTs<?>> createSerializerInstance( PrecomputedParameters precomputed, TypeSerializer<?>... originalSerializers) { return new Serializer(precomputed, originalSerializers[0], originalSerializers[1]); } TypeSerializer<?> getValueSerializer() { return fieldSerializers[0]; } @SuppressWarnings("unchecked") TypeSerializer<Long> getTimestampSerializer() { TypeSerializer<?> fieldSerializer = fieldSerializers[1]; return (TypeSerializer<Long>) fieldSerializer; } @Override public TypeSerializerSnapshot<ValueWithTs<?>> snapshotConfiguration() { return new ValueWithTsSerializerSnapshot(this); } } /** A {@link TypeSerializerSnapshot} for ValueWithTs Serializer. */ public static final
Serializer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/stale/StaleOneToManyListTest.java
{ "start": 1281, "end": 4297 }
class ____ { @Test void test1(EntityManagerFactoryScope scope) { var entity = new StaleListTestParent(); entity.childList.add( new StaleListTestChild("hello") ); entity.childList.add( new StaleListTestChild("world") ); scope.inTransaction( session -> { session.persist( entity ); } ); scope.inTransaction( session -> { var e = session.find( StaleListTestParent.class, entity.id ); e.childList.set( 0, new StaleListTestChild("goodbye") ); scope.inTransaction( session2 -> { var e2 = session2.find( StaleListTestParent.class, entity.id ); e2.childList.set( 0, new StaleListTestChild("BYE") ); } ); } ); } @Test void test2(EntityManagerFactoryScope scope) { var entity = new StaleListTestParent(); entity.childList.add( new StaleListTestChild("hello") ); entity.childList.add( new StaleListTestChild("world") ); scope.inTransaction( session -> { session.persist( entity ); } ); scope.inTransaction( session -> { var e = session.find( StaleListTestParent.class, entity.id ); e.childList.set( 1, new StaleListTestChild("everyone") ); scope.inTransaction( session2 -> { var e2 = session2.find( StaleListTestParent.class, entity.id ); e2.childList.remove( 1 ); } ); } ); } @FailureExpected(reason = "ConstraintViolationException") @Test void test3(EntityManagerFactoryScope scope) { var parent1 = new StaleListTestParent(); var parent2 = new StaleListTestParent(); var child1 = new StaleListTestChild( "hello" ); var child2 = new StaleListTestChild( "world" ); parent1.childList.add( child1 ); parent1.childList.add( child2 ); scope.inTransaction( session -> { session.persist( parent1 ); session.persist( parent2 ); } ); scope.inTransaction( session1 -> { var p = session1.find( StaleListTestParent.class, parent1.id ); var c = session1.find( StaleListTestChild.class, child1.id ); p.childList.remove( c ); scope.inTransaction( session2 -> { var pp = session2.find( StaleListTestParent.class, parent2.id ); var cc = session2.find( StaleListTestChild.class, child1.id ); pp.childList.add( cc ); } ); } ); } @Test void test4(EntityManagerFactoryScope scope) { var parent1 = new StaleListTestParent(); var parent2 = new StaleListTestParent(); var child1 = new StaleListTestChild( "hello" ); var child2 = new StaleListTestChild( "world" ); parent1.childList.add( child1 ); parent1.childList.add( child2 ); scope.inTransaction( session -> { session.persist( parent1 ); session.persist( parent2 ); } ); scope.inTransaction( session1 -> { var p = session1.find( StaleListTestParent.class, parent1.id ); var c = session1.find( StaleListTestChild.class, child1.id ); p.childList.remove( c ); } ); scope.inTransaction( session2 -> { var pp = session2.find( StaleListTestParent.class, parent2.id ); var cc = session2.find( StaleListTestChild.class, child1.id ); pp.childList.add( cc ); } ); } static @Entity(name = "StaleParent")
StaleOneToManyListTest
java
apache__logging-log4j2
log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java
{ "start": 1047, "end": 7909 }
class ____ { private static final String MESSAGE = "MESSAGE"; private static final Object P0 = new Object(); private static final Object P1 = new Object(); private static final Object P2 = new Object(); private static final Object P3 = new Object(); private static final Object P4 = new Object(); private static final Object P5 = new Object(); private static final Object P6 = new Object(); private static final Object P7 = new Object(); private static final Object P8 = new Object(); private static final Object P9 = new Object(); private static final Object P10 = new Object(); private static final Throwable THROWABLE = new Throwable(); @Test void should_not_consume_last_object_parameter() { final MessageFactory2 factory = new ThrowableConsumingMessageFactory(); assertThat(factory.newMessage(MESSAGE, P0)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(1, null); assertThat(factory.newMessage(MESSAGE, P0, P1)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(2, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(3, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(4, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(5, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(6, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(7, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, P7)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(8, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, P7, P8)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(9, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(10, null); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(11, null); } @Test void should_consume_last_throwable_parameter() { final MessageFactory2 factory = new ThrowableConsumingMessageFactory(); assertThat(factory.newMessage(MESSAGE, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(0, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(1, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(2, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(3, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(4, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(5, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(6, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(7, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, P7, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(8, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, P7, P8, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(9, THROWABLE); assertThat(factory.newMessage(MESSAGE, P0, P1, P2, P3, P4, P5, P6, P7, P8, P9, THROWABLE)) .extracting(m -> m.getParameters().length, Message::getThrowable) .as("checking parameter count and throwable") .containsExactly(10, THROWABLE); } }
ThrowableConsumingMessageFactoryTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneTest.java
{ "start": 1796, "end": 9841 }
class ____ { @AfterEach void dropTestData(SessionFactoryScope factoryScope) { factoryScope.dropData(); } @Test public void testEager(SessionFactoryScope factoryScope) { var carId = factoryScope.fromTransaction( (session) -> { var color = new Color(); color.setName( "Yellow" ); session.persist( color ); var car = new Car(); car.setBodyColor( color ); session.persist( car ); return car.getId(); } ); factoryScope.inTransaction( (session) -> { var car = session.find( Car.class, carId ); assertNotNull( car ); assertNotNull( car.getBodyColor() ); assertEquals( "Yellow", car.getBodyColor().getName() ); } ); } @Test public void testDefaultMetadata(SessionFactoryScope factoryScope) { var carId = factoryScope.fromTransaction( (session) -> { var color = new Color(); color.setName( "Blue" ); session.persist( color ); var car = new Car(); car.setBodyColor( color ); session.persist( car ); return car.getId(); } ); factoryScope.inTransaction( (session) -> { var car = session.find( Car.class, carId ); assertNotNull( car ); assertNotNull( car.getBodyColor() ); assertEquals( "Blue", car.getBodyColor().getName() ); } ); } @Test public void testCreate(SessionFactoryScope factoryScope) throws Exception { factoryScope.inTransaction( (session) -> { Flight firstOne = new Flight(); firstOne.setId(1L); firstOne.setName( "AF0101" ); firstOne.setDuration(1000L); Company frenchOne = new Company(); frenchOne.setName( "Air France" ); firstOne.setCompany( frenchOne ); session.persist( firstOne ); session.persist( frenchOne ); } ); factoryScope.inTransaction( (session) -> { var flight = session.find( Flight.class, 1L ); assertNotNull( flight.getCompany() ); assertEquals( "Air France", flight.getCompany().getName() ); } ); } @Test public void testCascade(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { var discount = new Discount(); discount.setDiscount( 20.12 ); var customer = new Customer(); List<Discount> discounts = new ArrayList<>(); discounts.add( discount ); customer.setName( "Quentin Tarantino" ); discount.setOwner( customer ); customer.setDiscountTickets( discounts ); session.persist( discount ); } ); factoryScope.inTransaction( (session) -> { var discount = session.find( Discount.class, 1L ); assertNotNull( discount ); assertEquals( 20.12, discount.getDiscount(), 0.01 ); assertNotNull( discount.getOwner() ); var customer = new Customer(); customer.setName( "Clooney" ); discount.setOwner( customer ); List<Discount> discounts = new ArrayList<>(); discounts.add( discount ); customer.setDiscountTickets( discounts ); } ); factoryScope.inTransaction( (session) -> { var discount = session.find( Discount.class, 1L ); assertNotNull( discount ); assertNotNull( discount.getOwner() ); assertEquals( "Clooney", discount.getOwner().getName() ); } ); } @Test public void testFetch(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { var discount = new Discount(); discount.setDiscount( 20 ); var customer = new Customer(); List<Discount> discounts = new ArrayList<>(); discounts.add( discount ); customer.setName( "Quentin Tarantino" ); discount.setOwner( customer ); customer.setDiscountTickets( discounts ); session.persist( discount ); } ); factoryScope.inTransaction( (session) -> { var discount = session.find( Discount.class, 1L ); assertNotNull( discount ); assertFalse( Hibernate.isInitialized( discount.getOwner() ) ); } ); factoryScope.inTransaction( (session) -> { var discount = session.getReference( Discount.class, 1L ); assertNotNull( discount ); assertFalse( Hibernate.isInitialized( discount.getOwner() ) ); } ); } @Test public void testCompositeFK(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { var ppk = new ParentPk(); ppk.firstName = "John"; ppk.lastName = "Doe"; var p = new Parent(); p.age = 45; p.id = ppk; session.persist( p ); var c = new Child(); c.parent = p; session.persist( c ); } ); factoryScope.inTransaction( (session) -> { //FIXME: fix this when the small parser bug will be fixed var result = session.createQuery( "from Child c where c.parent.id.lastName = :lastName" ) .setParameter( "lastName", "Doe") .list(); assertEquals( 1, result.size() ); Child c2 = (Child) result.get( 0 ); assertEquals( 1, c2.id ); } ); } @Test public void testImplicitCompositeFk(SessionFactoryScope factoryScope) { var node2Pk = factoryScope.fromTransaction( (session) -> { var n1 = new Node(); n1.setDescription( "Parent" ); var n1pk = new NodePk(); n1pk.setLevel( 1 ); n1pk.setName( "Root" ); n1.setId( n1pk ); var n2 = new Node(); var n2pk = new NodePk(); n2pk.setLevel( 2 ); n2pk.setName( "Level 1: A" ); n2.setParent( n1 ); n2.setId( n2pk ); session.persist( n2 ); return n2pk; } ); factoryScope.inTransaction( (session) -> { var n2 = session.find( Node.class, node2Pk ); assertNotNull( n2 ); assertNotNull( n2.getParent() ); assertEquals( 1, n2.getParent().getId().getLevel() ); } ); } @Test public void testManyToOneNonPk(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { var order = new Order(); order.setOrderNbr( "123" ); session.persist( order ); var ol = new OrderLine(); ol.setItem( "Mouse" ); ol.setOrder( order ); session.persist( ol ); } ); factoryScope.inTransaction( (session) -> { var ol = session.find( OrderLine.class, 1 ); assertNotNull( ol.getOrder() ); assertEquals( "123", ol.getOrder().getOrderNbr() ); assertTrue( ol.getOrder().getOrderLines().contains( ol ) ); } ); } @Test public void testManyToOneNonPkSecondaryTable(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { var order = new Order(); order.setOrderNbr( "123" ); session.persist( order ); var ol = new OrderLine(); ol.setItem( "Mouse" ); ol.setReplacementOrder( order ); session.persist( ol ); } ); factoryScope.inTransaction( (session) -> { var ol = session.find( OrderLine.class, 1 ); assertNotNull( ol.getReplacementOrder() ); assertEquals( "123", ol.getReplacementOrder().getOrderNbr() ); assertFalse( ol.getReplacementOrder().getOrderLines().contains( ol ) ); } ); } @Test public void testTwoManyToOneNonPk(SessionFactoryScope factoryScope) { //2 many-to-one non pk pointing to the same referencedColumnName should not fail factoryScope.inTransaction( (session) -> { var customer = new org.hibernate.orm.test.annotations.manytoone.Customer(); customer.userId="123"; var customer2 = new org.hibernate.orm.test.annotations.manytoone.Customer(); customer2.userId="124"; session.persist( customer2 ); session.persist( customer ); var deal = new Deal(); deal.from = customer; deal.to = customer2; session.persist( deal ); } ); factoryScope.inTransaction( (session) -> { var deal = session.find( Deal.class, 1 ); assertNotNull( deal.from ); assertNotNull( deal.to ); } ); } @Test public void testFormulaOnOtherSide(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { var frame = new Frame(); frame.setName( "Prada" ); session.persist( frame ); var l = new Lens(); l.setFocal( 2.5f ); l.setFrame( frame ); session.persist( l ); var r = new Lens(); r.setFocal( 1.2f); r.setFrame( frame ); session.persist( r ); } ); factoryScope.inTransaction( (session) -> { var frame = session.find( Frame.class, 1L ); assertEquals( 2, frame.getLenses().size() ); assertTrue( frame.getLenses().iterator().next().getLength() <= 1 / 1.2f ); assertTrue( frame.getLenses().iterator().next().getLength() >= 1 / 2.5f ); } ); } }
ManyToOneTest
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/SignificantTermsSignificanceScoreIT.java
{ "start": 3607, "end": 4146 }
class ____ extends ESIntegTestCase { static final String INDEX_NAME = "testidx"; static final String TEXT_FIELD = "text"; static final String CLASS_FIELD = "class"; @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(TestScriptPlugin.class); } public String randomExecutionHint() { return randomBoolean() ? null : randomFrom(SignificantTermsAggregatorFactory.ExecutionMode.values()).toString(); } public static
SignificantTermsSignificanceScoreIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytomany/Employer.java
{ "start": 739, "end": 2106 }
class ____ implements Serializable { private Integer id; private Collection<Employee> employees; private List<Contractor> contractors; @ManyToMany( targetEntity = Contractor.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE} ) @JoinTable( name = "EMPLOYER_CONTRACTOR", joinColumns = {@JoinColumn(name = "EMPLOYER_ID")}, inverseJoinColumns = {@JoinColumn(name = "CONTRACTOR_ID")} ) @Cascade({org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE}) @OrderBy("name desc") public List<Contractor> getContractors() { return contractors; } public void setContractors(List<Contractor> contractors) { this.contractors = contractors; } @ManyToMany( targetEntity = Employee.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE} ) @JoinTable( name = "EMPLOYER_EMPLOYEE", joinColumns = {@JoinColumn(name = "EMPER_ID")}, inverseJoinColumns = {@JoinColumn(name = "EMPEE_ID")} ) @Cascade({org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE}) @OrderBy("name asc") public Collection<Employee> getEmployees() { return employees; } @Id @GeneratedValue public Integer getId() { return id; } public void setEmployees(Collection<Employee> set) { employees = set; } public void setId(Integer integer) { id = integer; } }
Employer
java
apache__camel
components/camel-aws/camel-aws2-sqs/src/main/java/org/apache/camel/component/aws2/sqs/Sqs2Consumer.java
{ "start": 3870, "end": 11046 }
class ____ extends ScheduledBatchPollingConsumer { private static final Logger LOG = LoggerFactory.getLogger(Sqs2Consumer.class); private TimeoutExtender timeoutExtender; private ScheduledFuture<?> scheduledFuture; private ScheduledExecutorService scheduledExecutor; private PollingTask pollingTask; private final String sqsConsumerToString; public Sqs2Consumer(Sqs2Endpoint endpoint, Processor processor) { super(endpoint, processor); sqsConsumerToString = "SqsConsumer[%s]".formatted(URISupport.sanitizeUri(endpoint.getEndpointUri())); } @Override protected int poll() throws Exception { // must reset for each poll shutdownRunningTask = null; pendingExchanges = 0; List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call(); // okay we have some response from aws so lets mark the consumer as // ready forceConsumerAsReady(); Queue<Exchange> exchanges = createExchanges(messages); return processBatch(CastUtils.cast(exchanges)); } protected Queue<Exchange> createExchanges(List<software.amazon.awssdk.services.sqs.model.Message> messages) { if (LOG.isTraceEnabled()) { LOG.trace("Received {} messages in this poll", messages.size()); } Queue<Exchange> answer = new LinkedList<>(); for (software.amazon.awssdk.services.sqs.model.Message message : messages) { if (message != null) { Exchange exchange = createExchange(message); answer.add(exchange); } } return answer; } @Override public int processBatch(Queue<Object> exchanges) throws Exception { int total = exchanges.size(); for (int index = 0; index < total && isBatchAllowed(); index++) { // only loop if we are started (allowed to run) final Exchange exchange = ObjectHelper.cast(Exchange.class, exchanges.poll()); // add current index and total as properties exchange.setProperty(ExchangePropertyKey.BATCH_INDEX, index); exchange.setProperty(ExchangePropertyKey.BATCH_SIZE, total); exchange.setProperty(ExchangePropertyKey.BATCH_COMPLETE, index == total - 1); // update pending number of exchanges pendingExchanges = total - index - 1; if (this.timeoutExtender != null) { timeoutExtender.add(exchange); } // add on completion to handle after work when the exchange is done exchange.getExchangeExtension().addOnCompletion(new Synchronization() { @Override public void onComplete(Exchange exchange) { processCommit(exchange); } @Override public void onFailure(Exchange exchange) { processRollback(exchange); } @Override public String toString() { return "SqsConsumerOnCompletion"; } }); // use default consumer callback AsyncCallback cb = defaultConsumerCallback(exchange, true); try { getAsyncProcessor().process(exchange, cb); } catch (Error e) { if (this.timeoutExtender != null) { // fatal error so stop the timeout extender timeoutExtender.cancel(); timeoutExtender.entries.clear(); } throw e; } } return total; } /** * Strategy to delete the message after being processed. * * @param exchange the exchange */ protected void processCommit(Exchange exchange) { try { if (shouldDelete(exchange)) { String receiptHandle = exchange.getIn().getHeader(Sqs2Constants.RECEIPT_HANDLE, String.class); DeleteMessageRequest.Builder deleteRequest = DeleteMessageRequest.builder().queueUrl(getQueueUrl()).receiptHandle(receiptHandle); LOG.trace("Deleting message with receipt handle {}...", receiptHandle); getClient().deleteMessage(deleteRequest.build()); LOG.trace("Deleted message with receipt handle {}...", receiptHandle); } } catch (SdkException e) { getExceptionHandler().handleException("Error occurred during deleting message. This exception is ignored.", exchange, e); } } private boolean shouldDelete(Exchange exchange) { boolean shouldDeleteByFilter = exchange.getProperty(Sqs2Constants.SQS_DELETE_FILTERED) != null && getConfiguration().isDeleteIfFiltered() && passedThroughFilter(exchange); return getConfiguration().isDeleteAfterRead() || shouldDeleteByFilter; } private static boolean passedThroughFilter(Exchange exchange) { return exchange.getProperty(Sqs2Constants.SQS_DELETE_FILTERED, false, Boolean.class); } /** * Strategy when processing the exchange failed. * * @param exchange the exchange */ protected void processRollback(Exchange exchange) { Exception cause = exchange.getException(); if (cause != null) { getExceptionHandler().handleException( "Error during processing exchange. Will attempt to process the message on next poll.", exchange, cause); } } protected Sqs2Configuration getConfiguration() { return getEndpoint().getConfiguration(); } protected SqsClient getClient() { return getEndpoint().getClient(); } protected String getQueueUrl() { return getEndpoint().getQueueUrl(); } @Override public Sqs2Endpoint getEndpoint() { return (Sqs2Endpoint) super.getEndpoint(); } public Exchange createExchange(software.amazon.awssdk.services.sqs.model.Message msg) { return createExchange(getEndpoint().getExchangePattern(), msg); } private Exchange createExchange(ExchangePattern pattern, software.amazon.awssdk.services.sqs.model.Message msg) { Exchange exchange = createExchange(true); exchange.setPattern(pattern); Message message = exchange.getIn(); message.setBody(msg.body()); message.setHeaders(new HashMap<>(msg.attributesAsStrings())); message.setHeader(Sqs2Constants.MESSAGE_ID, msg.messageId()); message.setHeader(Sqs2Constants.MD5_OF_BODY, msg.md5OfBody()); message.setHeader(Sqs2Constants.RECEIPT_HANDLE, msg.receiptHandle()); message.setHeader(Sqs2Constants.ATTRIBUTES, msg.attributes()); message.setHeader(Sqs2Constants.MESSAGE_ATTRIBUTES, msg.messageAttributes()); // Need to apply the SqsHeaderFilterStrategy this time HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy(); // add all sqs message attributes as camel message headers so that // knowledge of the Sqs
Sqs2Consumer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/OptionalNotPresentTest.java
{ "start": 3686, "end": 7146 }
class ____ { // False-negative public String getWhenUnknown(Optional<String> optional) { return optional.get(); } // False-negative public String getWhenUnknown_testNull(Optional<String> optional) { if (optional.get() != null) { return optional.get(); } return ""; } // False-negative public String getWhenAbsent_testAndNestUnrelated(Optional<String> optional) { if (true) { String str = optional.get(); if (!optional.isPresent()) { return ""; } return str; } return ""; } public String getWhenAbsent(Optional<String> testStr) { if (!testStr.isPresent()) { // BUG: Diagnostic contains: return testStr.get(); } return ""; } public String getWhenAbsent_multipleStatements(Optional<String> optional) { if (!optional.isPresent()) { String test = "test"; // BUG: Diagnostic contains: return test + optional.get(); } return ""; } public String getWhenAbsent_nestedCheck(Optional<String> optional) { if (!optional.isPresent() || true) { // BUG: Diagnostic contains: return !optional.isPresent() ? optional.get() : ""; } return ""; } public String getWhenAbsent_compoundIf_false(Optional<String> optional) { if (!optional.isPresent() && true) { // BUG: Diagnostic contains: return optional.get(); } return ""; } // False-negative public String getWhenAbsent_compoundIf_true(Optional<String> optional) { if (!optional.isPresent() || true) { return optional.get(); } return ""; } public String getWhenAbsent_elseClause(Optional<String> optional) { if (optional.isPresent()) { return optional.get(); } else { // BUG: Diagnostic contains: return optional.get(); } } // False-negative public String getWhenAbsent_localReassigned(Optional<String> optional) { if (!optional.isPresent()) { optional = Optional.empty(); } return optional.get(); } // False-negative public String getWhenAbsent_methodScoped(Optional<String> optional) { if (optional.isPresent()) { return ""; } return optional.get(); } }\ """) .doTest(); } @Test public void b80065837() { compilationTestHelper .addSourceLines( "Test.java", """ import java.util.Optional; import java.util.Map;
OptionalNotPresentPositiveCases
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/executor/NameThreadFactory.java
{ "start": 914, "end": 1466 }
class ____ implements ThreadFactory { private final AtomicInteger id = new AtomicInteger(0); private String name; public NameThreadFactory(String name) { if (!name.endsWith(StringUtils.DOT)) { name += StringUtils.DOT; } this.name = name; } @Override public Thread newThread(Runnable r) { String threadName = name + id.getAndIncrement(); Thread thread = new Thread(r, threadName); thread.setDaemon(true); return thread; } }
NameThreadFactory
java
apache__avro
lang/java/ipc/src/test/java/org/apache/avro/io/Perf.java
{ "start": 52068, "end": 52361 }
class ____ { float f1; float f2; float f3; float f4; Vals() { } Vals(Random r) { this.f1 = r.nextFloat(); this.f2 = r.nextFloat(); this.f3 = r.nextFloat(); this.f4 = r.nextFloat(); } } } static public
Vals
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/filecache/TestURIFragments.java
{ "start": 1075, "end": 5894 }
class ____ { /** * Tests {@link DistributedCache#checkURIs(URI[], URI[]). */ @Test public void testURIs() throws URISyntaxException { assertTrue(DistributedCache.checkURIs(null, null)); // uris with no fragments assertFalse(DistributedCache.checkURIs(new URI[] { new URI( "file://foo/bar/myCacheFile.txt") }, null)); assertFalse(DistributedCache.checkURIs(null, new URI[] { new URI("file://foo/bar/myCacheArchive.txt") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file"), new URI("file://foo/bar/myCacheFile2.txt") }, null)); assertFalse(DistributedCache.checkURIs(null, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt"), new URI("file://foo/bar/myCacheArchive2.txt#archive") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI( "file://foo/bar/myCacheFile.txt") }, new URI[] { new URI( "file://foo/bar/myCacheArchive.txt") })); // conflicts in fragment names assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file"), new URI("file://foo/bar/myCacheFile2.txt#file") }, null)); assertFalse(DistributedCache.checkURIs(null, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#archive"), new URI("file://foo/bar/myCacheArchive2.txt#archive") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI( "file://foo/bar/myCacheFile.txt#cache") }, new URI[] { new URI( "file://foo/bar/myCacheArchive.txt#cache") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file1"), new URI("file://foo/bar/myCacheFile2.txt#file2") }, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#archive"), new URI("file://foo/bar/myCacheArchive2.txt#archive") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file"), new URI("file://foo/bar/myCacheFile2.txt#file") }, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#archive1"), new URI("file://foo/bar/myCacheArchive2.txt#archive2") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file1"), new URI("file://foo/bar/myCacheFile2.txt#cache") }, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#cache"), new URI("file://foo/bar/myCacheArchive2.txt#archive2") })); // test ignore case assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file"), new URI("file://foo/bar/myCacheFile2.txt#FILE") }, null)); assertFalse(DistributedCache.checkURIs(null, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#archive"), new URI("file://foo/bar/myCacheArchive2.txt#ARCHIVE") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI( "file://foo/bar/myCacheFile.txt#cache") }, new URI[] { new URI( "file://foo/bar/myCacheArchive.txt#CACHE") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file1"), new URI("file://foo/bar/myCacheFile2.txt#file2") }, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#ARCHIVE"), new URI("file://foo/bar/myCacheArchive2.txt#archive") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#FILE"), new URI("file://foo/bar/myCacheFile2.txt#file") }, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#archive1"), new URI("file://foo/bar/myCacheArchive2.txt#archive2") })); assertFalse(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file1"), new URI("file://foo/bar/myCacheFile2.txt#CACHE") }, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#cache"), new URI("file://foo/bar/myCacheArchive2.txt#archive2") })); // allowed uri combinations assertTrue(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file1"), new URI("file://foo/bar/myCacheFile2.txt#file2") }, null)); assertTrue(DistributedCache.checkURIs(null, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#archive1"), new URI("file://foo/bar/myCacheArchive2.txt#archive2") })); assertTrue(DistributedCache.checkURIs(new URI[] { new URI("file://foo/bar/myCacheFile1.txt#file1"), new URI("file://foo/bar/myCacheFile2.txt#file2") }, new URI[] { new URI("file://foo/bar/myCacheArchive1.txt#archive1"), new URI("file://foo/bar/myCacheArchive2.txt#archive2") })); } }
TestURIFragments
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/sockjs/transport/handler/DefaultSockJsServiceTests.java
{ "start": 2573, "end": 13751 }
class ____ extends AbstractHttpRequestTests { private static final String sockJsPrefix = "/mysockjs"; private static final String sessionId = "session1"; private static final String sessionUrlPrefix = "/server1/" + sessionId + "/"; @Mock private SessionCreatingTransportHandler xhrHandler; @Mock private TransportHandler xhrSendHandler; @Mock private HandshakeTransportHandler wsTransportHandler; @Mock private WebSocketHandler wsHandler; @Mock private TaskScheduler taskScheduler; private TestSockJsSession session; private TransportHandlingSockJsService service; @Override @BeforeEach protected void setup() { super.setup(); Map<String, Object> attributes = Collections.emptyMap(); this.session = new TestSockJsSession(sessionId, new StubSockJsServiceConfig(), this.wsHandler, attributes); given(this.xhrHandler.getTransportType()).willReturn(TransportType.XHR); given(this.xhrHandler.createSession(sessionId, this.wsHandler, attributes)).willReturn(this.session); given(this.xhrSendHandler.getTransportType()).willReturn(TransportType.XHR_SEND); given(this.wsTransportHandler.getTransportType()).willReturn(TransportType.WEBSOCKET); this.service = new TransportHandlingSockJsService(this.taskScheduler, this.xhrHandler, this.xhrSendHandler); } @Test void defaultTransportHandlers() { DefaultSockJsService service = new DefaultSockJsService(mock()); Map<TransportType, TransportHandler> handlers = service.getTransportHandlers(); assertThat(handlers).hasSize(6); assertThat(handlers.get(TransportType.WEBSOCKET)).isNotNull(); assertThat(handlers.get(TransportType.XHR)).isNotNull(); assertThat(handlers.get(TransportType.XHR_SEND)).isNotNull(); assertThat(handlers.get(TransportType.XHR_STREAMING)).isNotNull(); assertThat(handlers.get(TransportType.HTML_FILE)).isNotNull(); assertThat(handlers.get(TransportType.EVENT_SOURCE)).isNotNull(); } @Test void defaultTransportHandlersWithOverride() { XhrReceivingTransportHandler xhrHandler = new XhrReceivingTransportHandler(); DefaultSockJsService service = new DefaultSockJsService(mock(), xhrHandler); Map<TransportType, TransportHandler> handlers = service.getTransportHandlers(); assertThat(handlers).hasSize(6); assertThat(handlers.get(xhrHandler.getTransportType())).isSameAs(xhrHandler); } @Test void invalidAllowedOrigins() { assertThatIllegalArgumentException().isThrownBy(() -> this.service.setAllowedOrigins(null)); } @Test void customizedTransportHandlerList() { TransportHandlingSockJsService service = new TransportHandlingSockJsService( mock(), new XhrPollingTransportHandler(), new XhrReceivingTransportHandler()); Map<TransportType, TransportHandler> actualHandlers = service.getTransportHandlers(); assertThat(actualHandlers).hasSize(2); } @Test void handleTransportRequestXhr() { String sockJsPath = sessionUrlPrefix + "xhr"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(200); verify(this.xhrHandler).handleRequest(this.request, this.response, this.wsHandler, this.session); verify(taskScheduler).scheduleAtFixedRate(any(Runnable.class), eq(Duration.ofMillis(this.service.getDisconnectDelay()))); assertThat(this.response.getHeaders().getCacheControl()).isEqualTo("no-store, no-cache, must-revalidate, max-age=0"); assertThat(this.servletResponse.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isNull(); assertThat(this.servletResponse.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isNull(); } @Test // SPR-12226 void handleTransportRequestXhrAllowedOriginsMatch() { String sockJsPath = sessionUrlPrefix + "xhr"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.setAllowedOrigins(Arrays.asList("https://mydomain1.example", "https://mydomain2.example")); this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain1.example"); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(200); } @Test // SPR-12226 void handleTransportRequestXhrAllowedOriginsNoMatch() { String sockJsPath = sessionUrlPrefix + "xhr"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.setAllowedOrigins(Arrays.asList("https://mydomain1.example", "https://mydomain2.example")); this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain3.example"); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(403); } @Test // SPR-13464 void handleTransportRequestXhrSameOrigin() { String sockJsPath = sessionUrlPrefix + "xhr"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.setAllowedOrigins(List.of("https://mydomain1.example")); this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain1.example"); this.servletRequest.setServerName("mydomain2.example"); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(200); } @Test // SPR-13545 void handleInvalidTransportType() { String sockJsPath = sessionUrlPrefix + "invalid"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.setAllowedOrigins(List.of("https://mydomain1.example")); this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain2.example"); this.servletRequest.setServerName("mydomain2.example"); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(404); } @Test void handleTransportRequestXhrOptions() { String sockJsPath = sessionUrlPrefix + "xhr"; setRequest("OPTIONS", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(204); assertThat(this.servletResponse.getHeader("Access-Control-Allow-Origin")).isNull(); assertThat(this.servletResponse.getHeader("Access-Control-Allow-Credentials")).isNull(); assertThat(this.servletResponse.getHeader("Access-Control-Allow-Methods")).isNull(); } @Test void handleTransportRequestNoSuitableHandler() { String sockJsPath = sessionUrlPrefix + "eventsource"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(404); } @Test void handleTransportRequestXhrSend() { String sockJsPath = sessionUrlPrefix + "xhr_send"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); // no session yet assertThat(this.servletResponse.getStatus()).isEqualTo(404); resetResponse(); sockJsPath = sessionUrlPrefix + "xhr"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); // session created assertThat(this.servletResponse.getStatus()).isEqualTo(200); verify(this.xhrHandler).handleRequest(this.request, this.response, this.wsHandler, this.session); resetResponse(); sockJsPath = sessionUrlPrefix + "xhr_send"; setRequest("POST", sockJsPrefix + sockJsPath); given(this.xhrSendHandler.checkSessionType(this.session)).willReturn(true); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); // session exists assertThat(this.servletResponse.getStatus()).isEqualTo(200); verify(this.xhrSendHandler).handleRequest(this.request, this.response, this.wsHandler, this.session); } @Test void handleTransportRequestXhrSendWithDifferentUser() { String sockJsPath = sessionUrlPrefix + "xhr"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); // session created assertThat(this.servletResponse.getStatus()).isEqualTo(200); verify(this.xhrHandler).handleRequest(this.request, this.response, this.wsHandler, this.session); this.session.setPrincipal(new TestPrincipal("little red riding hood")); this.servletRequest.setUserPrincipal(new TestPrincipal("wolf")); resetResponse(); reset(this.xhrSendHandler); sockJsPath = sessionUrlPrefix + "xhr_send"; setRequest("POST", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(404); verifyNoMoreInteractions(this.xhrSendHandler); } @Test void handleTransportRequestWebsocket() { TransportHandlingSockJsService wsService = new TransportHandlingSockJsService( this.taskScheduler, this.wsTransportHandler); String sockJsPath = "/websocket"; setRequest("GET", sockJsPrefix + sockJsPath); wsService.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isNotEqualTo(403); resetRequestAndResponse(); List<String> allowed = Collections.singletonList("https://mydomain1.example"); OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(allowed); wsService.setHandshakeInterceptors(Collections.singletonList(interceptor)); setRequest("GET", sockJsPrefix + sockJsPath); this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain1.example"); wsService.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isNotEqualTo(403); resetRequestAndResponse(); setRequest("GET", sockJsPrefix + sockJsPath); this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain2.example"); wsService.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(403); } @Test void handleTransportRequestIframe() { String sockJsPath = "/iframe.html"; setRequest("GET", sockJsPrefix + sockJsPath); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isNotEqualTo(404); assertThat(this.servletResponse.getHeader("X-Frame-Options")).isEqualTo("SAMEORIGIN"); resetRequestAndResponse(); setRequest("GET", sockJsPrefix + sockJsPath); this.service.setAllowedOrigins(Collections.singletonList("https://mydomain1.example")); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isEqualTo(404); assertThat(this.servletResponse.getHeader("X-Frame-Options")).isNull(); resetRequestAndResponse(); setRequest("GET", sockJsPrefix + sockJsPath); this.service.setAllowedOrigins(Collections.singletonList("*")); this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); assertThat(this.servletResponse.getStatus()).isNotEqualTo(404); assertThat(this.servletResponse.getHeader("X-Frame-Options")).isNull(); }
DefaultSockJsServiceTests
java
quarkusio__quarkus
extensions/reactive-mssql-client/deployment/src/test/java/io/quarkus/reactive/mssql/client/MultipleDataSourcesAndMSSQLPoolCreatorsTest.java
{ "start": 547, "end": 1521 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withConfigurationResource("application-multiple-datasources-with-erroneous-url.properties") .withApplicationRoot((jar) -> jar .addClasses(BeanUsingDefaultDataSource.class) .addClass(BeanUsingHibernateDataSource.class) .addClass(DefaultMSSQLPoolCreator.class) .addClass(HibernateMSSQLPoolCreator.class)); @Inject BeanUsingDefaultDataSource beanUsingDefaultDataSource; @Inject BeanUsingHibernateDataSource beanUsingHibernateDataSource; @Test public void testMultipleDataSources() { beanUsingDefaultDataSource.verify() .thenCompose(v -> beanUsingHibernateDataSource.verify()) .toCompletableFuture() .join(); } @ApplicationScoped static
MultipleDataSourcesAndMSSQLPoolCreatorsTest
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextExecutorServiceTests.java
{ "start": 1546, "end": 6377 }
class ____ extends AbstractDelegatingSecurityContextExecutorTests { @Mock private Future<Object> expectedFutureObject; @Mock private Object resultArg; protected DelegatingSecurityContextExecutorService executor; @BeforeEach public final void setUpExecutorService() { this.executor = create(); } @Override @Test public void constructorNullDelegate() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextExecutorService(null)); } @Test public void shutdown() { this.executor.shutdown(); verify(this.delegate).shutdown(); } @Test public void shutdownNow() { List<Runnable> result = this.executor.shutdownNow(); verify(this.delegate).shutdownNow(); assertThat(result).isEqualTo(this.delegate.shutdownNow()).isNotNull(); } @Test public void isShutdown() { boolean result = this.executor.isShutdown(); verify(this.delegate).isShutdown(); assertThat(result).isEqualTo(this.delegate.isShutdown()).isNotNull(); } @Test public void isTerminated() { boolean result = this.executor.isTerminated(); verify(this.delegate).isTerminated(); assertThat(result).isEqualTo(this.delegate.isTerminated()).isNotNull(); } @Test public void awaitTermination() throws InterruptedException { boolean result = this.executor.awaitTermination(1, TimeUnit.SECONDS); verify(this.delegate).awaitTermination(1, TimeUnit.SECONDS); assertThat(result).isEqualTo(this.delegate.awaitTermination(1, TimeUnit.SECONDS)).isNotNull(); } @Test public void submitCallable() { given(this.delegate.submit(this.wrappedCallable)).willReturn(this.expectedFutureObject); Future<Object> result = this.executor.submit(this.callable); verify(this.delegate).submit(this.wrappedCallable); assertThat(result).isEqualTo(this.expectedFutureObject); } @Test public void submitRunnableWithResult() { given(this.delegate.submit(this.wrappedRunnable, this.resultArg)).willReturn(this.expectedFutureObject); Future<Object> result = this.executor.submit(this.runnable, this.resultArg); verify(this.delegate).submit(this.wrappedRunnable, this.resultArg); assertThat(result).isEqualTo(this.expectedFutureObject); } @Test @SuppressWarnings("unchecked") public void submitRunnable() { given((Future<Object>) this.delegate.submit(this.wrappedRunnable)).willReturn(this.expectedFutureObject); Future<?> result = this.executor.submit(this.runnable); verify(this.delegate).submit(this.wrappedRunnable); assertThat(result).isEqualTo(this.expectedFutureObject); } @Test @SuppressWarnings("unchecked") public void invokeAll() throws Exception { List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject); List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable); given(this.delegate.invokeAll(wrappedCallables)).willReturn(exectedResult); List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable)); verify(this.delegate).invokeAll(wrappedCallables); assertThat(result).isEqualTo(exectedResult); } @Test @SuppressWarnings("unchecked") public void invokeAllTimeout() throws Exception { List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject); List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable); given(this.delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).willReturn(exectedResult); List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable), 1, TimeUnit.SECONDS); verify(this.delegate).invokeAll(wrappedCallables, 1, TimeUnit.SECONDS); assertThat(result).isEqualTo(exectedResult); } @Test @SuppressWarnings("unchecked") public void invokeAny() throws Exception { List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject); List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable); given(this.delegate.invokeAny(wrappedCallables)).willReturn(exectedResult); Object result = this.executor.invokeAny(Arrays.asList(this.callable)); verify(this.delegate).invokeAny(wrappedCallables); assertThat(result).isEqualTo(exectedResult); } @Test @SuppressWarnings("unchecked") public void invokeAnyTimeout() throws Exception { List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject); List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable); given(this.delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).willReturn(exectedResult); Object result = this.executor.invokeAny(Arrays.asList(this.callable), 1, TimeUnit.SECONDS); verify(this.delegate).invokeAny(wrappedCallables, 1, TimeUnit.SECONDS); assertThat(result).isEqualTo(exectedResult); } @Override protected abstract DelegatingSecurityContextExecutorService create(); }
AbstractDelegatingSecurityContextExecutorServiceTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/ReplaceSerializationTests.java
{ "start": 567, "end": 1643 }
class ____ extends AbstractExpressionSerializationTests<Replace> { @Override protected Replace createTestInstance() { Source source = randomSource(); Expression str = randomChild(); Expression regex = randomChild(); Expression newStr = randomChild(); return new Replace(source, str, regex, newStr); } @Override protected Replace mutateInstance(Replace instance) throws IOException { Source source = instance.source(); Expression str = instance.str(); Expression regex = instance.regex(); Expression newStr = instance.newStr(); switch (between(0, 2)) { case 0 -> str = randomValueOtherThan(str, AbstractExpressionSerializationTests::randomChild); case 1 -> regex = randomValueOtherThan(regex, AbstractExpressionSerializationTests::randomChild); case 2 -> newStr = randomValueOtherThan(newStr, AbstractExpressionSerializationTests::randomChild); } return new Replace(source, str, regex, newStr); } }
ReplaceSerializationTests
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/network/NetworkReceive.java
{ "start": 1207, "end": 5008 }
class ____ implements Receive { public static final String UNKNOWN_SOURCE = ""; public static final int UNLIMITED = -1; private static final Logger log = LoggerFactory.getLogger(NetworkReceive.class); private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); private final String source; private final ByteBuffer size; private final int maxSize; private final MemoryPool memoryPool; private int requestedBufferSize = -1; private ByteBuffer buffer; public NetworkReceive(String source, ByteBuffer buffer) { this(UNLIMITED, source); this.buffer = buffer; } public NetworkReceive(String source) { this(UNLIMITED, source); } public NetworkReceive(int maxSize, String source) { this(maxSize, source, MemoryPool.NONE); } public NetworkReceive(int maxSize, String source, MemoryPool memoryPool) { this.source = source; this.size = ByteBuffer.allocate(4); this.buffer = null; this.maxSize = maxSize; this.memoryPool = memoryPool; } public NetworkReceive() { this(UNKNOWN_SOURCE); } @Override public String source() { return source; } @Override public boolean complete() { return !size.hasRemaining() && buffer != null && !buffer.hasRemaining(); } public long readFrom(ScatteringByteChannel channel) throws IOException { int read = 0; if (size.hasRemaining()) { int bytesRead = channel.read(size); if (bytesRead < 0) throw new EOFException(); read += bytesRead; if (!size.hasRemaining()) { size.rewind(); int receiveSize = size.getInt(); if (receiveSize < 0) throw new InvalidReceiveException("Invalid receive (size = " + receiveSize + ")"); if (maxSize != UNLIMITED && receiveSize > maxSize) throw new InvalidReceiveException("Invalid receive (size = " + receiveSize + " larger than " + maxSize + ")"); requestedBufferSize = receiveSize; // may be 0 for some payloads (SASL) if (receiveSize == 0) { buffer = EMPTY_BUFFER; } } } if (buffer == null && requestedBufferSize != -1) { // we know the size we want but haven't been able to allocate it yet buffer = memoryPool.tryAllocate(requestedBufferSize); if (buffer == null) log.trace("Broker low on memory - could not allocate buffer of size {} for source {}", requestedBufferSize, source); } if (buffer != null) { int bytesRead = channel.read(buffer); if (bytesRead < 0) throw new EOFException(); read += bytesRead; } return read; } @Override public boolean requiredMemoryAmountKnown() { return requestedBufferSize != -1; } @Override public boolean memoryAllocated() { return buffer != null; } @Override public void close() throws IOException { if (buffer != null && buffer != EMPTY_BUFFER) { memoryPool.release(buffer); buffer = null; } } public ByteBuffer payload() { return this.buffer; } public int bytesRead() { if (buffer == null) return size.position(); return buffer.position() + size.position(); } /** * Returns the total size of the receive including payload and size buffer * for use in metrics. This is consistent with {@link NetworkSend#size()} */ public int size() { return payload().limit() + size.limit(); } }
NetworkReceive
java
apache__camel
components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpPostJsonNestedPojoListTest.java
{ "start": 1257, "end": 2942 }
class ____ extends BaseUndertowTest { @Test public void testPostPojoList() throws Exception { MockEndpoint mock = getMockEndpoint("mock:input"); mock.expectedMessageCount(1); String body = "[ {\"id\": 123, \"name\": \"Donald Duck\"}, {\"id\": 456, \"name\": \"John Doe\"} ]"; template.sendBody("undertow:http://localhost:{{port}}/users/new", body); MockEndpoint.assertIsSatisfied(context); List<?> list = mock.getReceivedExchanges().get(0).getIn().getBody(List.class); assertNotNull(list); assertEquals(2, list.size()); MyUserPojo user = (MyUserPojo) list.get(0); assertEquals(123, user.getId()); assertEquals("Donald Duck", user.getName()); user = (MyUserPojo) list.get(1); assertEquals(456, user.getId()); assertEquals("John Doe", user.getName()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // configure to use undertow on localhost with the given port // and enable auto binding mode restConfiguration() .component("undertow") .host("localhost") .port(getPort()) .bindingMode(RestBindingMode.auto); // use the rest DSL to define the rest services rest("/users/") .post("new").type(MyUserPojo[].class) .to("mock:input"); } }; } public static
RestUndertowHttpPostJsonNestedPojoListTest
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/admin/OffsetWrapper.java
{ "start": 863, "end": 1714 }
class ____ { private long brokerOffset; private long consumerOffset; private long pullOffset; private long lastTimestamp; public long getBrokerOffset() { return brokerOffset; } public void setBrokerOffset(long brokerOffset) { this.brokerOffset = brokerOffset; } public long getConsumerOffset() { return consumerOffset; } public void setConsumerOffset(long consumerOffset) { this.consumerOffset = consumerOffset; } public long getPullOffset() { return pullOffset; } public void setPullOffset(long pullOffset) { this.pullOffset = pullOffset; } public long getLastTimestamp() { return lastTimestamp; } public void setLastTimestamp(long lastTimestamp) { this.lastTimestamp = lastTimestamp; } }
OffsetWrapper
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/TestContextManagerListenerExecutionOrderTests.java
{ "start": 3444, "end": 4165 }
class ____ implements TestExecutionListener { private final String name; NamedTestExecutionListener(String name) { this.name = name; } @Override public void beforeTestMethod(TestContext testContext) { executionOrder.add("beforeTestMethod-" + this.name); } @Override public void beforeTestExecution(TestContext testContext) { executionOrder.add("beforeTestExecution-" + this.name); } @Override public void afterTestExecution(TestContext testContext) { executionOrder.add("afterTestExecution-" + this.name); } @Override public void afterTestMethod(TestContext testContext) { executionOrder.add("afterTestMethod-" + this.name); } } private static
NamedTestExecutionListener
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/ast/LoadPlanBuilderTest.java
{ "start": 6818, "end": 6959 }
class ____ { @Id private Integer pid; private String name; @OneToMany(mappedBy = "poster") private List<Message> messages; } }
Poster
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/FeatureScanner.java
{ "start": 781, "end": 1691 }
class ____ { final List<GeneratedClass> generatedClasses; final Map<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> transformers; public FeatureScanResult(List<GeneratedClass> generatedClasses, Map<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> transformers) { this.generatedClasses = generatedClasses; this.transformers = transformers; } public FeatureScanResult(List<GeneratedClass> generatedClasses) { this.generatedClasses = generatedClasses; this.transformers = Collections.emptyMap(); } public List<GeneratedClass> getGeneratedClasses() { return generatedClasses; } public Map<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> getTransformers() { return transformers; } } }
FeatureScanResult
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authentication/SecurityAssertions.java
{ "start": 1330, "end": 1614 }
class ____ { private SecurityAssertions() { } public static AuthenticationAssert assertThat(@Nullable Authentication authentication) { Assertions.assertThat(authentication).isNotNull(); return new AuthenticationAssert(authentication); } public static final
SecurityAssertions
java
elastic__elasticsearch
modules/mapper-extras/src/test/java/org/elasticsearch/index/mapper/extras/MatchOnlyTextFieldMapperTests.java
{ "start": 10201, "end": 17376 }
class ____ implements SyntheticSourceSupport { @Override public SyntheticSourceExample example(int maxValues) { if (randomBoolean()) { Tuple<String, String> v = generateValue(); return new SyntheticSourceExample(v.v1(), v.v2(), this::mapping); } List<Tuple<String, String>> values = randomList(1, maxValues, this::generateValue); List<String> in = values.stream().map(Tuple::v1).toList(); List<String> outList = values.stream().map(Tuple::v2).toList(); Object out = outList.size() == 1 ? outList.get(0) : outList; return new SyntheticSourceExample(in, out, this::mapping); } private Tuple<String, String> generateValue() { String v = randomList(1, 10, () -> randomAlphaOfLength(5)).stream().collect(Collectors.joining(" ")); return Tuple.tuple(v, v); } private void mapping(XContentBuilder b) throws IOException { b.field("type", "match_only_text"); } @Override public List<SyntheticSourceInvalidExample> invalidExample() throws IOException { return List.of(); } } public void testDocValues() throws IOException { MapperService mapper = createMapperService(fieldMapping(b -> b.field("type", "match_only_text"))); assertScriptDocValues(mapper, "foo", equalTo(List.of("foo"))); } public void testDocValuesLoadedFromSynthetic() throws IOException { MapperService mapper = createSytheticSourceMapperService(fieldMapping(b -> b.field("type", "match_only_text"))); assertScriptDocValues(mapper, "foo", equalTo(List.of("foo"))); } @Override protected IngestScriptSupport ingestScriptSupport() { throw new AssumptionViolatedException("not supported"); } public void testStoreParameterDefaultsSyntheticSource() throws IOException { var indexSettingsBuilder = getIndexSettingsBuilder(); indexSettingsBuilder.put(IndexSettings.INDEX_MAPPER_SOURCE_MODE_SETTING.getKey(), "synthetic"); var indexSettings = indexSettingsBuilder.build(); var mapping = mapping(b -> { b.startObject("name"); b.field("type", "match_only_text"); b.endObject(); }); DocumentMapper mapper = createMapperService(indexSettings, mapping).documentMapper(); var source = source(b -> b.field("name", "quick brown fox")); ParsedDocument doc = mapper.parse(source); { List<IndexableField> fields = doc.rootDoc().getFields("name"); IndexableFieldType fieldType = fields.get(0).fieldType(); assertThat(fieldType.stored(), is(false)); } { List<IndexableField> fields = doc.rootDoc().getFields("name._original"); IndexableFieldType fieldType = fields.get(0).fieldType(); assertThat(fieldType.stored(), is(true)); } } public void testStoreParameterDefaultsSyntheticSourceWithKeywordMultiField() throws IOException { var indexSettingsBuilder = getIndexSettingsBuilder(); indexSettingsBuilder.put(IndexSettings.INDEX_MAPPER_SOURCE_MODE_SETTING.getKey(), "synthetic"); var indexSettings = indexSettingsBuilder.build(); var mapping = mapping(b -> { b.startObject("name"); b.field("type", "match_only_text"); b.startObject("fields"); b.startObject("keyword"); b.field("type", "keyword"); b.endObject(); b.endObject(); b.endObject(); }); DocumentMapper mapper = createMapperService(indexSettings, mapping).documentMapper(); var source = source(b -> b.field("name", "quick brown fox")); ParsedDocument doc = mapper.parse(source); { List<IndexableField> fields = doc.rootDoc().getFields("name"); IndexableFieldType fieldType = fields.get(0).fieldType(); assertThat(fieldType.stored(), is(false)); } { List<IndexableField> fields = doc.rootDoc().getFields("name._original"); assertThat(fields, empty()); } } public void testStoreParameterDefaultsSyntheticSourceTextFieldIsMultiField() throws IOException { var indexSettingsBuilder = getIndexSettingsBuilder(); indexSettingsBuilder.put(IndexSettings.INDEX_MAPPER_SOURCE_MODE_SETTING.getKey(), "synthetic"); var indexSettings = indexSettingsBuilder.build(); var mapping = mapping(b -> { b.startObject("name"); b.field("type", "keyword"); b.startObject("fields"); b.startObject("text"); b.field("type", "match_only_text"); b.endObject(); b.endObject(); b.endObject(); }); DocumentMapper mapper = createMapperService(indexSettings, mapping).documentMapper(); var source = source(b -> b.field("name", "quick brown fox")); ParsedDocument doc = mapper.parse(source); { List<IndexableField> fields = doc.rootDoc().getFields("name.text"); IndexableFieldType fieldType = fields.get(0).fieldType(); assertThat(fieldType.stored(), is(false)); } { List<IndexableField> fields = doc.rootDoc().getFields("name.text._original"); assertThat(fields, empty()); } } public void testLoadSyntheticSourceFromStringOrBytesRef() throws IOException { var mappings = mapping(b -> { b.startObject("field1").field("type", "match_only_text").endObject(); b.startObject("field2").field("type", "match_only_text").endObject(); }); var settings = Settings.builder().put("index.mapping.source.mode", "synthetic").build(); DocumentMapper mapper = createMapperService(IndexVersions.UPGRADE_TO_LUCENE_10_2_2, settings, () -> true, mappings) .documentMapper(); try (Directory directory = newDirectory()) { RandomIndexWriter iw = indexWriterForSyntheticSource(directory); LuceneDocument document = new LuceneDocument(); document.add(new StringField("field1", "foo", Field.Store.NO)); document.add(new StoredField("field1._original", "foo")); document.add(new StringField("field2", "bar", Field.Store.NO)); document.add(new StoredField("field2._original", new BytesRef("bar"))); iw.addDocument(document); iw.close(); try (DirectoryReader indexReader = wrapInMockESDirectoryReader(DirectoryReader.open(directory))) { String syntheticSource = syntheticSource(mapper, null, indexReader, 0); assertEquals("{\"field1\":\"foo\",\"field2\":\"bar\"}", syntheticSource); } } } @Override protected List<SortShortcutSupport> getSortShortcutSupport() { return List.of(); } @Override protected boolean supportsDocValuesSkippers() { return false; } }
MatchOnlyTextSyntheticSourceSupport
java
apache__logging-log4j2
log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadContextBenchmark2.java
{ "start": 6321, "end": 9061 }
class ____ { public StringAppender appender; public LoggerContext context; public int counter; @Setup public void setup() { context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); PatternLayout layout = PatternLayout.newBuilder() .setConfiguration(config) .setPattern("%X %m%n") .build(); appender = StringAppender.createAppender("String", layout, null); appender.start(); config.getAppenders().forEach((name, app) -> app.stop()); config.getAppenders().clear(); config.addAppender(appender); final LoggerConfig root = config.getRootLogger(); root.getAppenders().forEach((name, appender) -> { root.removeAppender(name); }); root.addAppender(appender, Level.DEBUG, null); root.setLevel(Level.DEBUG); context.updateLoggers(); } @TearDown public void teardown() { System.out.println("Last entry: " + appender.getMessage()); context.stop(); counter = 0; } } @Benchmark public void populateThreadContext(final Blackhole blackhole, ThreadContextState state) { for (int i = 0; i < VALUES.length; i++) { ThreadContext.put(KEYS[i], VALUES[i]); } } @Benchmark public void threadContextMap(final Blackhole blackhole, ReadThreadContextState state) { for (int i = 0; i < VALUES.length; i++) { blackhole.consume(ThreadContext.get(KEYS[i])); } } /* * This is equivalent to the typical ScopedContext case. */ @Benchmark public void logThreadContextMap(final Blackhole blackhole, LogThreadContextState state) { LOGGER.info("log count: {}", state.counter++); } @Benchmark public void nestedThreadContextMap(final Blackhole blackhole, LogThreadContextState state) { for (int i = 0; i < 10; ++i) { LOGGER.info("outer log count: {}", i); } try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(KEYS[8], NESTED[0]) .put(KEYS[9], NESTED[1]) .put(KEYS[10], NESTED[2])) { for (int i = 0; i < 100; ++i) { LOGGER.info("inner log count: {}", i); } } } /* * Log the baseline - no context variables. */ @Benchmark public void logBaseline(final Blackhole blackhole, LogBaselineState state) { LOGGER.info("log count: {}", state.counter++); } }
LogBaselineState
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelNewExceptionTest.java
{ "start": 1054, "end": 1356 }
class ____ extends DeadLetterChannelNewExceptionTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/DeadLetterChannelNewExceptionTest.xml"); } }
SpringDeadLetterChannelNewExceptionTest
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/ProfileAWSCredentialsProvider.java
{ "start": 1447, "end": 4044 }
class ____ extends AbstractAWSCredentialProvider { private static final Logger LOG = LoggerFactory.getLogger(ProfileAWSCredentialsProvider.class); public static final String NAME = "org.apache.hadoop.fs.s3a.auth.ProfileAWSCredentialsProvider"; /** Conf setting for credentials file path.*/ public static final String PROFILE_FILE = "fs.s3a.auth.profile.file"; /** Conf setting for profile name.*/ public static final String PROFILE_NAME = "fs.s3a.auth.profile.name"; /** Environment variable for credentials file path.*/ public static final String CREDENTIALS_FILE_ENV = "AWS_SHARED_CREDENTIALS_FILE"; /** Environment variable for profile name.*/ public static final String PROFILE_ENV = "AWS_PROFILE"; private final ProfileCredentialsProvider pcp; private static Path getCredentialsPath(Configuration conf) { String credentialsFile = conf.get(PROFILE_FILE, null); if (credentialsFile == null) { credentialsFile = SystemUtils.getEnvironmentVariable(CREDENTIALS_FILE_ENV, null); if (credentialsFile != null) { LOG.debug("Fetched credentials file path from environment variable"); } } else { LOG.debug("Fetched credentials file path from conf"); } if (credentialsFile == null) { LOG.debug("Using default credentials file path"); return FileSystems.getDefault().getPath(SystemUtils.getUserHome().getPath(), ".aws", "credentials"); } else { return FileSystems.getDefault().getPath(credentialsFile); } } private static String getCredentialsName(Configuration conf) { String profileName = conf.get(PROFILE_NAME, null); if (profileName == null) { profileName = SystemUtils.getEnvironmentVariable(PROFILE_ENV, null); if (profileName == null) { profileName = "default"; LOG.debug("Using default profile name"); } else { LOG.debug("Fetched profile name from environment variable"); } } else { LOG.debug("Fetched profile name from conf"); } return profileName; } public ProfileAWSCredentialsProvider(URI uri, Configuration conf) { super(uri, conf); ProfileCredentialsProvider.Builder builder = ProfileCredentialsProvider.builder(); builder.profileName(getCredentialsName(conf)) .profileFile(ProfileFile.builder() .content(getCredentialsPath(conf)) .type(ProfileFile.Type.CREDENTIALS) .build()); pcp = builder.build(); } public AwsCredentials resolveCredentials() { return pcp.resolveCredentials(); } }
ProfileAWSCredentialsProvider
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/tasks/SystemProcessingTimeServiceTest.java
{ "start": 1674, "end": 14069 }
class ____ { /** * Tests that SystemProcessingTimeService#scheduleAtFixedRate is actually triggered multiple * times. */ @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) @Test void testScheduleAtFixedRate() throws Exception { final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final long period = 10L; final int countDown = 3; final SystemProcessingTimeService timer = createSystemProcessingTimeService(errorRef); final CountDownLatch countDownLatch = new CountDownLatch(countDown); try { timer.scheduleAtFixedRate(timestamp -> countDownLatch.countDown(), 0L, period); countDownLatch.await(); assertThat(errorRef.get()).isNull(); } finally { timer.shutdownService(); } } /** * Tests that shutting down the SystemProcessingTimeService will also cancel the scheduled at * fix rate future. */ @Test void testQuiesceAndAwaitingCancelsScheduledAtFixRateFuture() throws Exception { final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final long period = 10L; final SystemProcessingTimeService timer = createSystemProcessingTimeService(errorRef); try { Future<?> scheduledFuture = timer.scheduleAtFixedRate(timestamp -> {}, 0L, period); assertThat(scheduledFuture).isNotDone(); // this should cancel our future timer.quiesce().get(); // it may be that the cancelled status is not immediately visible after the // termination (not necessary a volatile update), so we need to "get()" the cancellation // exception to be on the safe side assertThatThrownBy(scheduledFuture::get) .as("scheduled future is not cancelled") .isInstanceOf(CancellationException.class); scheduledFuture = timer.scheduleAtFixedRate( timestamp -> { throw new Exception("Test exception."); }, 0L, 100L); assertThat(scheduledFuture).isNotNull(); assertThat(timer.getNumTasksScheduled()).isZero(); assertThat(errorRef.get()).isNull(); } finally { timer.shutdownService(); } } @Test void testImmediateShutdown() throws Exception { final CompletableFuture<Throwable> errorFuture = new CompletableFuture<>(); final SystemProcessingTimeService timer = createSystemProcessingTimeService(errorFuture); try { assertThat(timer.isTerminated()).isFalse(); final OneShotLatch latch = new OneShotLatch(); // the task should trigger immediately and sleep until terminated with interruption timer.registerTimer( System.currentTimeMillis(), timestamp -> { latch.trigger(); Thread.sleep(100000000); }); latch.await(); timer.shutdownService(); assertThat(timer.isTerminated()).isTrue(); assertThat(timer.getNumTasksScheduled()).isZero(); assertThatThrownBy( () -> timer.registerTimer( System.currentTimeMillis() + 1000, timestamp -> fail("should not be called"))) .isInstanceOf(IllegalStateException.class); assertThatThrownBy( () -> timer.scheduleAtFixedRate( timestamp -> fail("should not be called"), 0L, 100L)) .isInstanceOf(IllegalStateException.class); // check that the task eventually responded to interruption assertThat(errorFuture.get(30L, TimeUnit.SECONDS)) .isInstanceOf(InterruptedException.class); } finally { timer.shutdownService(); } } @Test void testQuiescing() throws Exception { final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final SystemProcessingTimeService timer = createSystemProcessingTimeService(errorRef); try { final OneShotLatch latch = new OneShotLatch(); final ReentrantLock scopeLock = new ReentrantLock(); timer.registerTimer( timer.getCurrentProcessingTime() + 20L, timestamp -> { scopeLock.lock(); try { latch.trigger(); // delay a bit before leaving the method Thread.sleep(5); } finally { scopeLock.unlock(); } }); // after the task triggered, shut the timer down cleanly, waiting for the task to finish latch.await(); timer.quiesce().get(); // should be able to immediately acquire the lock, since the task must have exited by // now assertThat(scopeLock.tryLock()).isTrue(); // should be able to schedule more tasks (that never get executed) Future<?> future = timer.registerTimer( timer.getCurrentProcessingTime() - 5L, timestamp -> { throw new Exception("test"); }); assertThat(future).isNotNull(); // nothing should be scheduled right now assertThat(timer.getNumTasksScheduled()).isZero(); // check that no asynchronous error was reported - that ensures that the newly scheduled // triggerable did, in fact, not trigger assertThat(errorRef.get()).isNull(); } finally { timer.shutdownService(); } } @Test void testFutureCancellation() { final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final SystemProcessingTimeService timer = createSystemProcessingTimeService(errorRef); try { assertThat(timer.getNumTasksScheduled()).isZero(); // schedule something ScheduledFuture<?> future = timer.registerTimer(System.currentTimeMillis() + 100000000, timestamp -> {}); assertThat(timer.getNumTasksScheduled()).isOne(); future.cancel(false); assertThat(timer.getNumTasksScheduled()).isZero(); future = timer.scheduleAtFixedRate(timestamp -> {}, 10000000000L, 50L); assertThat(timer.getNumTasksScheduled()).isOne(); future.cancel(false); assertThat(timer.getNumTasksScheduled()).isZero(); // check that no asynchronous error was reported assertThat(errorRef.get()).isNull(); } finally { timer.shutdownService(); } } @Test void testShutdownAndWaitPending() throws Exception { final OneShotLatch blockUntilTriggered = new OneShotLatch(); final AtomicBoolean timerExecutionFinished = new AtomicBoolean(false); final SystemProcessingTimeService timeService = createBlockingSystemProcessingTimeService( blockUntilTriggered, timerExecutionFinished); assertThat(timeService.isTerminated()).isFalse(); // Check that we wait for the timer to terminate. As the timer blocks on the second latch, // this should time out. assertThat(timeService.shutdownAndAwaitPending(1, TimeUnit.SECONDS)).isFalse(); // Let the timer proceed. blockUntilTriggered.trigger(); // Now we should succeed in terminating the timer. assertThat(timeService.shutdownAndAwaitPending(60, TimeUnit.SECONDS)).isTrue(); assertThat(timerExecutionFinished).isTrue(); assertThat(timeService.isTerminated()).isTrue(); } @Test void testShutdownServiceUninterruptible() { final OneShotLatch blockUntilTriggered = new OneShotLatch(); final AtomicBoolean timerFinished = new AtomicBoolean(false); final SystemProcessingTimeService timeService = createBlockingSystemProcessingTimeService(blockUntilTriggered, timerFinished); assertThat(timeService.isTerminated()).isFalse(); final Thread interruptTarget = Thread.currentThread(); final AtomicBoolean runInterrupts = new AtomicBoolean(true); final Thread interruptCallerThread = new Thread( () -> { while (runInterrupts.get()) { interruptTarget.interrupt(); try { Thread.sleep(1); } catch (InterruptedException ignore) { } } }); interruptCallerThread.start(); final long timeoutMs = 50L; final long startTime = System.nanoTime(); assertThat(timeService.isTerminated()).isFalse(); // check that termination did not succeed (because of blocking timer execution) assertThat(timeService.shutdownServiceUninterruptible(timeoutMs)).isFalse(); // check that termination flag was set. assertThat(timeService.isTerminated()).isTrue(); // check that the blocked timer is still in flight. assertThat(timerFinished).isFalse(); // check that we waited until timeout assertThat(System.nanoTime() - startTime).isGreaterThanOrEqualTo(1_000_000L * timeoutMs); runInterrupts.set(false); do { try { interruptCallerThread.join(); } catch (InterruptedException ignore) { } } while (interruptCallerThread.isAlive()); // clear the interrupted flag in case join didn't do it final boolean ignored = Thread.interrupted(); blockUntilTriggered.trigger(); assertThat(timeService.shutdownServiceUninterruptible(timeoutMs)).isTrue(); assertThat(timerFinished).isTrue(); } private static SystemProcessingTimeService createSystemProcessingTimeService( CompletableFuture<Throwable> errorFuture) { Preconditions.checkArgument(!errorFuture.isDone()); return new SystemProcessingTimeService(errorFuture::complete); } private static SystemProcessingTimeService createSystemProcessingTimeService( AtomicReference<Throwable> errorRef) { Preconditions.checkArgument(errorRef.get() == null); return new SystemProcessingTimeService(ex -> errorRef.compareAndSet(null, ex)); } private static SystemProcessingTimeService createBlockingSystemProcessingTimeService( final OneShotLatch blockUntilTriggered, final AtomicBoolean check) { final OneShotLatch waitUntilTimerStarted = new OneShotLatch(); Preconditions.checkState(!check.get()); final SystemProcessingTimeService timeService = new SystemProcessingTimeService(exception -> {}); timeService.scheduleAtFixedRate( timestamp -> { waitUntilTimerStarted.trigger(); boolean unblocked = false; while (!unblocked) { try { blockUntilTriggered.await(); unblocked = true; } catch (InterruptedException ignore) { } } check.set(true); }, 0L, 10L); try { waitUntilTimerStarted.await(); } catch (InterruptedException e) { fail("Problem while starting up service."); } return timeService; } }
SystemProcessingTimeServiceTest
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/OffsetTimeAssert.java
{ "start": 685, "end": 1003 }
class ____ extends AbstractOffsetTimeAssert<OffsetTimeAssert> { /** * Creates a new <code>{@link org.assertj.core.api.OffsetTimeAssert}</code>. * * @param actual the actual value to verify */ protected OffsetTimeAssert(OffsetTime actual) { super(actual, OffsetTimeAssert.class); } }
OffsetTimeAssert
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggesterTest.java
{ "start": 5530, "end": 5946 }
class ____ { @CanIgnoreReturnValue public String method(String name) { return (name); } } """) .doTest(); } @Test public void returnInputParams_multipleParams() { helper .addInputLines( "ReturnInputParam.java", """ package com.google.frobber; public final
Client