language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsonschema/NewSchemaTest.java
{ "start": 2853, "end": 2952 }
class ____ { public BigDecimal dec; public BigInteger bigInt; } static
Numbers
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/BlockingHashCommandsImpl.java
{ "start": 396, "end": 3780 }
class ____<K, F, V> extends AbstractRedisCommandGroup implements HashCommands<K, F, V> { private final ReactiveHashCommands<K, F, V> reactive; public BlockingHashCommandsImpl(RedisDataSource ds, ReactiveHashCommands<K, F, V> reactive, Duration timeout) { super(ds, timeout); this.reactive = reactive; } @Override public int hdel(K key, F... fields) { return reactive.hdel(key, fields) .await().atMost(timeout); } @Override public boolean hexists(K key, F field) { return reactive.hexists(key, field) .await().atMost(timeout); } @Override public V hget(K key, F field) { return reactive.hget(key, field) .await().atMost(timeout); } @Override public long hincrby(K key, F field, long amount) { return reactive.hincrby(key, field, amount) .await().atMost(timeout); } @Override public double hincrbyfloat(K key, F field, double amount) { return reactive.hincrbyfloat(key, field, amount) .await().atMost(timeout); } @Override public Map<F, V> hgetall(K key) { return reactive.hgetall(key) .await().atMost(timeout); } @Override public List<F> hkeys(K key) { return reactive.hkeys(key).await().atMost(timeout); } @Override public long hlen(K key) { return reactive.hlen(key) .await().atMost(timeout); } @Override public Map<F, V> hmget(K key, F... fields) { return reactive.hmget(key, fields) .await().atMost(timeout); } @Override public void hmset(K key, Map<F, V> map) { reactive.hmset(key, map) .await().atMost(timeout); } @Override public F hrandfield(K key) { return reactive.hrandfield(key) .await().atMost(timeout); } @Override public List<F> hrandfield(K key, long count) { return reactive.hrandfield(key, count) .await().atMost(timeout); } @Override public Map<F, V> hrandfieldWithValues(K key, long count) { return reactive.hrandfieldWithValues(key, count) .await().atMost(timeout); } @Override public HashScanCursor<F, V> hscan(K key) { return new HashScanBlockingCursorImpl<>(reactive.hscan(key), timeout); } @Override public HashScanCursor<F, V> hscan(K key, ScanArgs scanArgs) { return new HashScanBlockingCursorImpl<>(reactive.hscan(key, scanArgs), timeout); } @Override public boolean hset(K key, F field, V value) { return reactive.hset(key, field, value) .await().atMost(timeout); } @Override public long hset(K key, Map<F, V> map) { return reactive.hset(key, map) .await().atMost(timeout); } @Override public boolean hsetnx(K key, F field, V value) { return reactive.hsetnx(key, field, value) .await().atMost(timeout); } @Override public long hstrlen(K key, F field) { return reactive.hstrlen(key, field) .await().atMost(timeout); } @Override public List<V> hvals(K key) { return reactive.hvals(key) .await().atMost(timeout); } }
BlockingHashCommandsImpl
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/AnnotationVisitor.java
{ "start": 1750, "end": 1980 }
class ____ be called in the following * order: ( {@code visit} | {@code visitEnum} | {@code visitAnnotation} | {@code visitArray} )* * {@code visitEnd}. * * @author Eric Bruneton * @author Eugene Kuleshov */ public abstract
must
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NonOverridingEquals.java
{ "start": 5831, "end": 7462 }
enum ____ can safely be compared by reference " + "equality, so please delete this") .addFix(SuggestedFix.delete(methodTree)) .build(); } else { /* Otherwise, change the covariant equals method to override Object.equals. */ SuggestedFix.Builder fix = SuggestedFix.builder(); // Add @Override annotation if not present. if (ASTHelpers.getAnnotation(methodTree, Override.class) == null) { fix.prefixWith(methodTree, "@Override\n"); } // Change method signature, substituting Object for parameter type. JCTree parameterType = (JCTree) methodTree.getParameters().getFirst().getType(); Name parameterName = ((JCVariableDecl) methodTree.getParameters().getFirst()).getName(); fix.replace(parameterType, "Object"); // If there is a method body... if (methodTree.getBody() != null) { // Add type check at start String typeCheckStmt = "if (!(" + parameterName + " instanceof " + state.getSourceForNode(parameterType) + ")) {\n" + " return false;\n" + "}\n"; fix.prefixWith(methodTree.getBody().getStatements().getFirst(), typeCheckStmt); // Cast all uses of the parameter name using a recursive TreeScanner. new CastScanner() .scan( methodTree.getBody(), new CastState(parameterName, state.getSourceForNode(parameterType), fix)); } return describeMatch(methodTree, fix.build()); } } private static
instances
java
apache__camel
components/camel-mail/src/test/java/org/apache/camel/component/mail/AdditionalMailPropertiesTest.java
{ "start": 1329, "end": 2824 }
class ____ extends CamelTestSupport { private static final MailboxUser user = Mailbox.getOrCreateUser("additionalMailProperties"); @Test public void testAdditionalMailProperties() { // clear mailbox Mailbox.clearAll(); MailEndpoint endpoint = context.getEndpoint( user.uriPrefix(Protocol.pop3) + "&mail.pop3.forgettopheaders=true&initialDelay=100&delay=100", MailEndpoint.class); Properties prop = endpoint.getConfiguration().getAdditionalJavaMailProperties(); assertEquals("true", prop.get("mail.pop3.forgettopheaders")); } @Test public void testConsumeWithAdditionalProperties() throws Exception { // clear mailbox Mailbox.clearAll(); MockEndpoint mock = getMockEndpoint("mock:result"); template.sendBodyAndHeader(user.uriPrefix(Protocol.smtp), "Hello james how are you?\r\n", "subject", "Hello"); mock.expectedBodiesReceived("Hello james how are you?\r\n"); mock.expectedHeaderReceived("subject", "Hello"); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(user.uriPrefix(Protocol.pop3) + "&mail.pop3.forgettopheaders=true&initialDelay=100&delay=100") .to("mock:result"); } }; } }
AdditionalMailPropertiesTest
java
elastic__elasticsearch
libs/core/src/main/java/org/elasticsearch/core/IOUtils.java
{ "start": 1477, "end": 10109 }
class ____ { /** * UTF-8 charset string. * <p>Where possible, use {@link StandardCharsets#UTF_8} instead, * as using the String constant may slow things down. * @see StandardCharsets#UTF_8 */ public static final String UTF_8 = StandardCharsets.UTF_8.name(); private IOUtils() { // Static utils methods } /** * Closes all given {@link Closeable}s. Some of the {@linkplain Closeable}s may be null; they are * ignored. After everything is closed, the method either throws the first exception it hit * while closing with other exceptions added as suppressed, or completes normally if there were * no exceptions. * * @param objects objects to close */ public static void close(final Closeable... objects) throws IOException { close(null, objects); } /** * @see #close(Closeable...) */ public static void close(@Nullable Closeable closeable) throws IOException { if (closeable != null) { closeable.close(); } } /** * Closes all given {@link Closeable}s. Some of the {@linkplain Closeable}s may be null; they are * ignored. After everything is closed, the method adds any exceptions as suppressed to the * original exception, or throws the first exception it hit if {@code Exception} is null. If * no exceptions are encountered and the passed in exception is null, it completes normally. * * @param objects objects to close */ public static void close(final Exception ex, final Closeable... objects) throws IOException { Exception firstException = ex; for (final Closeable object : objects) { try { close(object); } catch (final IOException | RuntimeException e) { firstException = addOrSuppress(firstException, e); } } if (firstException != null) { throwRuntimeOrIOException(firstException); } } private static void throwRuntimeOrIOException(Exception firstException) throws IOException { if (firstException instanceof IOException) { throw (IOException) firstException; } else { // since we only assigned an IOException or a RuntimeException to ex above, in this case ex must be a RuntimeException throw (RuntimeException) firstException; } } /** * Closes all given {@link Closeable}s. Some of the {@linkplain Closeable}s may be null; they are * ignored. After everything is closed, the method either throws the first exception it hit * while closing with other exceptions added as suppressed, or completes normally if there were * no exceptions. * * @param objects objects to close */ public static void close(final Iterable<? extends Closeable> objects) throws IOException { Exception firstException = null; for (final Closeable object : objects) { try { close(object); } catch (final IOException | RuntimeException e) { firstException = addOrSuppress(firstException, e); } } if (firstException != null) { throwRuntimeOrIOException(firstException); } } private static Exception addOrSuppress(Exception firstException, Exception e) { if (firstException == null) { firstException = e; } else { firstException.addSuppressed(e); } return firstException; } /** * Closes all given {@link Closeable}s, suppressing all thrown exceptions. Some of the {@link Closeable}s may be null, they are ignored. * * @param objects objects to close */ public static void closeWhileHandlingException(final Closeable... objects) { for (final Closeable object : objects) { closeWhileHandlingException(object); } } /** * Closes all given {@link Closeable}s, suppressing all thrown exceptions. * * @param objects objects to close * * @see #closeWhileHandlingException(Closeable...) */ public static void closeWhileHandlingException(final Iterable<? extends Closeable> objects) { for (final Closeable object : objects) { closeWhileHandlingException(object); } } /** * @see #closeWhileHandlingException(Closeable...) */ public static void closeWhileHandlingException(final Closeable closeable) { // noinspection EmptyCatchBlock try { close(closeable); } catch (final IOException | RuntimeException e) {} } /** * Deletes all given files, suppressing all thrown {@link IOException}s. Some of the files may be null, if so they are ignored. * * @param files the paths of files to delete */ public static void deleteFilesIgnoringExceptions(final Path... files) { for (final Path name : files) { if (name != null) { // noinspection EmptyCatchBlock try { Files.delete(name); } catch (final IOException ignored) { } } } } /** * Deletes one or more files or directories (and everything underneath it). * * @throws IOException if any of the given files (or their sub-hierarchy files in case of directories) cannot be removed. */ public static void rm(final Path... locations) throws IOException { final LinkedHashMap<Path, Throwable> unremoved = rm(new LinkedHashMap<>(), locations); if (unremoved.isEmpty() == false) { final StringBuilder b = new StringBuilder("could not remove the following files (in the order of attempts):\n"); for (final Map.Entry<Path, Throwable> kv : unremoved.entrySet()) { b.append(" ").append(kv.getKey().toAbsolutePath()).append(": ").append(kv.getValue()).append("\n"); } throw new IOException(b.toString()); } } private static LinkedHashMap<Path, Throwable> rm(final LinkedHashMap<Path, Throwable> unremoved, final Path... locations) { if (locations != null) { for (final Path location : locations) { // TODO: remove this leniency if (location != null && Files.exists(location)) { try { Files.walkFileTree(location, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException impossible) throws IOException { assert impossible == null; try { Files.delete(dir); } catch (final IOException e) { unremoved.put(dir, e); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { try { Files.delete(file); } catch (final IOException exc) { unremoved.put(file, exc); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException { if (exc != null) { unremoved.put(file, exc); } return FileVisitResult.CONTINUE; } }); } catch (final IOException impossible) { throw new AssertionError("visitor threw exception", impossible); } } } } return unremoved; } // TODO: replace with constants
IOUtils
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/aggs/frequentitemsets/TransactionStoreTests.java
{ "start": 1721, "end": 9920 }
class ____ implements CircuitBreaker { @Override public void circuitBreak(String fieldName, long bytesNeeded) {} @Override public void addEstimateBytesAndMaybeBreak(long bytes, String label) throws CircuitBreakingException { if (random().nextInt(20) == 0) { throw new CircuitBreakingException("cbe", Durability.PERMANENT); } } @Override public void addWithoutBreaking(long bytes) {} @Override public long getUsed() { return 0; } @Override public long getLimit() { return 0; } @Override public double getOverhead() { return 0; } @Override public long getTrippedCount() { return 0; } @Override public String getName() { return CircuitBreaker.FIELDDATA; } @Override public Durability getDurability() { return null; } @Override public void setLimitAndOverhead(long limit, double overhead) { } }; private final CircuitBreaker breaker = new RandomlyThrowingCircuitBreaker(); @Override public CircuitBreaker getBreaker(String name) { return breaker; } @Override public AllCircuitBreakerStats stats() { return new AllCircuitBreakerStats(new CircuitBreakerStats[] { stats(CircuitBreaker.FIELDDATA) }); } @Override public CircuitBreakerStats stats(String name) { return new CircuitBreakerStats(CircuitBreaker.FIELDDATA, -1, -1, 0, 0); } } private BigArrays mockBigArrays() { return new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService()); } private BigArrays mockBigArraysWithThrowingCircuitBreaker() { return new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new ThrowingCircuitBreakerService()).withCircuitBreaking(); } public void testDontLeak() { TransactionStore store = null; boolean thrown = false; try { // cbe's are thrown at random, test teardown checks if all buffers have been closed store = new HashBasedTransactionStore(mockBigArraysWithThrowingCircuitBreaker()); } catch (CircuitBreakingException ce) { assertEquals("cbe", ce.getMessage()); thrown = true; } if (thrown == false) { assertNotNull(store); store.close(); } } public void testDontLeakAfterDeserializing() throws IOException { HashBasedTransactionStore store = new HashBasedTransactionStore(mockBigArrays()); addRandomTransactions(store, randomIntBetween(100, 10000)); boolean thrown = false; TransactionStore storeCopy = null; try { // cbe's are thrown at random, test teardown checks if all buffers have been closed storeCopy = copyInstance( store, writableRegistry(), StreamOutput::writeWriteable, in -> new HashBasedTransactionStore(in, mockBigArraysWithThrowingCircuitBreaker()), TransportVersion.current() ); } catch (CircuitBreakingException ce) { assertEquals("cbe", ce.getMessage()); thrown = true; } if (thrown == false) { assertNotNull(store); storeCopy.close(); } store.close(); } public void testCreateImmutableTransactionStore() throws IOException { HashBasedTransactionStore store = new HashBasedTransactionStore(mockBigArrays()); addRandomTransactions(store, randomIntBetween(100, 10000)); // create a copy HashBasedTransactionStore storeCopy = copyInstance( store, writableRegistry(), StreamOutput::writeWriteable, in -> new HashBasedTransactionStore(in, mockBigArrays()), TransportVersion.current() ); // create an immutable version ImmutableTransactionStore immutableStore = storeCopy.createImmutableTransactionStore(); storeCopy.close(); assertEquality(store, immutableStore); immutableStore.close(); store.close(); } public void testItemBow() { Tuple<Long, Long> item1 = tuple(0L, 2L); Tuple<Long, Long> item2 = tuple(1L, 2L); Tuple<Long, Long> item3 = tuple(2L, 1L); Tuple<Long, Long> item4 = tuple(3L, 3L); Tuple<Long, Long> item5 = tuple(4L, 4L); assertEquals(-1, HashBasedTransactionStore.ITEMS_BY_COUNT_COMPARATOR.compare(item1, item2)); assertEquals(1, HashBasedTransactionStore.ITEMS_BY_COUNT_COMPARATOR.compare(item2, item1)); assertEquals(-1, HashBasedTransactionStore.ITEMS_BY_COUNT_COMPARATOR.compare(item1, item3)); assertEquals(1, HashBasedTransactionStore.ITEMS_BY_COUNT_COMPARATOR.compare(item3, item5)); List<Tuple<Long, Long>> items = new ArrayList<>(); items.add(item1); items.add(item2); items.add(item3); items.add(item4); items.add(item5); items.sort(HashBasedTransactionStore.ITEMS_BY_COUNT_COMPARATOR); assertEquals(List.of(item5, item4, item1, item2, item3), items); // test that compareItems produces exactly the same order try (LongArray itemCounts = mockBigArrays().newLongArray(5)) { itemCounts.set(0, item1.v2()); itemCounts.set(1, item2.v2()); itemCounts.set(2, item3.v2()); itemCounts.set(3, item4.v2()); itemCounts.set(4, item5.v2()); List<Long> itemsAsList = new ArrayList<>(); itemsAsList.add(item1.v1()); itemsAsList.add(item2.v1()); itemsAsList.add(item3.v1()); itemsAsList.add(item4.v1()); itemsAsList.add(item5.v1()); itemsAsList.sort(HashBasedTransactionStore.compareItems(itemCounts)); assertEquals(List.of(item5.v1(), item4.v1(), item1.v1(), item2.v1(), item3.v1()), itemsAsList); } } private void addRandomTransactions(HashBasedTransactionStore store, int n) { List<Field> randomFields = new ArrayList<>(); String[] randomFieldNames = generateRandomStringArray(randomIntBetween(5, 50), randomIntBetween(5, 50), false, false); int id = 0; for (String fieldName : randomFieldNames) { randomFields.add(createKeywordFieldTestInstance(fieldName, id++)); } for (int i = 0; i < n; ++i) { store.add(randomFields.stream().filter(p -> randomBoolean()).map(f -> { List<Object> l = new ArrayList<Object>( Arrays.asList(generateRandomStringArray(randomIntBetween(1, 10), randomIntBetween(5, 50), false, false)) ); return new Tuple<Field, List<Object>>(f, l); })); } } private void assertEquality(TransactionStore original, TransactionStore copy) throws IOException { assertEquals(original.getTotalItemCount(), copy.getTotalItemCount()); assertEquals(original.getTotalTransactionCount(), copy.getTotalTransactionCount()); assertEquals(original.getUniqueItemsCount(), copy.getUniqueItemsCount()); BytesRef orgBytesRef = new BytesRef(); BytesRef copyBytesRef = new BytesRef(); for (int i = 0; i < original.getUniqueItemsCount(); ++i) { original.getItem(i, orgBytesRef); copy.getItem(i, copyBytesRef); assertEquals(orgBytesRef, copyBytesRef); } for (int i = 0; i < original.getUniqueTransactionCount(); ++i) { original.getTransaction(i, orgBytesRef); copy.getTransaction(i, copyBytesRef); assertEquals(orgBytesRef, copyBytesRef); } } }
RandomlyThrowingCircuitBreaker
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/ProcessWorkerExecutorService.java
{ "start": 853, "end": 2397 }
class ____ extends AbstractProcessWorkerExecutorService<Runnable> { /** * @param contextHolder the thread context holder * @param processName the name of the process to be used in logging * @param queueCapacity the capacity of the queue holding operations. If an operation is added * for execution when the queue is full a 429 error is thrown. */ @SuppressForbidden(reason = "properly rethrowing errors, see EsExecutors.rethrowErrors") public ProcessWorkerExecutorService(ThreadContext contextHolder, String processName, int queueCapacity) { super(contextHolder, processName, queueCapacity, LinkedBlockingQueue::new); } @Override public synchronized void execute(Runnable command) { if (command instanceof AbstractInitializableRunnable initializableRunnable) { initializableRunnable.init(); } if (isShutdown()) { EsRejectedExecutionException rejected = new EsRejectedExecutionException(processName + " worker service has shutdown", true); if (command instanceof AbstractRunnable runnable) { runnable.onRejection(rejected); return; } else { throw rejected; } } boolean added = queue.offer(contextHolder.preserveContext(command)); if (added == false) { throw new EsRejectedExecutionException(processName + " queue is full. Unable to execute command", false); } } }
ProcessWorkerExecutorService
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/IfSectionHelper.java
{ "start": 7392, "end": 7835 }
interface ____ { CompletionStage<Object> evaluate(SectionResolutionContext context); Operator getOperator(); default boolean isEmpty() { return false; } default Object getLiteralValue() { return null; } default Boolean logicalComplement(Object val) { return Booleans.isFalsy(val) ? Boolean.TRUE : Boolean.FALSE; } } static
Condition
java
apache__camel
components/camel-univocity-parsers/src/main/java/org/apache/camel/dataformat/univocity/Marshaller.java
{ "start": 1350, "end": 1525 }
class ____ the exchange body using an uniVocity writer. It can automatically generates headers and keep * their order in memory. * * @param <W> Writer class */ final
marshalls
java
apache__camel
components/camel-stitch/src/test/java/org/apache/camel/component/stitch/StitchProducerTest.java
{ "start": 7466, "end": 7966 }
class ____ implements StitchClient { @Override public Mono<StitchResponse> batch(StitchRequestBody requestBody) { final StitchResponse response = new StitchResponse( 200, Collections.singletonMap("header-1", "test"), "OK", "All good!"); return Mono.just(response); } @Override public void close() { // noop } } static
TestClient
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/file/tfile/BCFile.java
{ "start": 3664, "end": 3767 }
class ____ maintain the state of a Writable Compression * Block. */ private static final
that
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/AbstractShapeGeometryFieldMapper.java
{ "start": 3445, "end": 6986 }
class ____.beginPositionEntry(); builder.appendInt(extent.top); builder.appendInt(extent.bottom); builder.appendInt(extent.negLeft); builder.appendInt(extent.negRight); builder.appendInt(extent.posLeft); builder.appendInt(extent.posRight); builder.endPositionEntry(); } @Override public BlockLoader.AllReader reader(LeafReaderContext context) throws IOException { return new BlockLoader.AllReader() { @Override public BlockLoader.Block read( BlockLoader.BlockFactory factory, BlockLoader.Docs docs, int offset, boolean nullsFiltered ) throws IOException { var binaryDocValues = context.reader().getBinaryDocValues(fieldName); var reader = new GeometryDocValueReader(); try (var builder = factory.ints(docs.count() - offset)) { for (int i = offset; i < docs.count(); i++) { read(binaryDocValues, docs.get(i), reader, builder); } return builder.build(); } } @Override public void read(int docId, BlockLoader.StoredFields storedFields, BlockLoader.Builder builder) throws IOException { var binaryDocValues = context.reader().getBinaryDocValues(fieldName); var reader = new GeometryDocValueReader(); read(binaryDocValues, docId, reader, (IntBuilder) builder); } private void read(BinaryDocValues binaryDocValues, int doc, GeometryDocValueReader reader, IntBuilder builder) throws IOException { if (binaryDocValues.advanceExact(doc) == false) { builder.appendNull(); return; } reader.reset(binaryDocValues.binaryValue()); writeExtent(builder, reader.getExtent()); } @Override public boolean canReuse(int startingDocID) { return true; } }; } @Override public BlockLoader.Builder builder(BlockLoader.BlockFactory factory, int expectedCount) { return factory.ints(expectedCount); } } } protected Explicit<Boolean> coerce; protected Explicit<Orientation> orientation; protected AbstractShapeGeometryFieldMapper( String simpleName, MappedFieldType mappedFieldType, BuilderParams builderParams, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce, Explicit<Boolean> ignoreZValue, Explicit<Orientation> orientation, Parser<T> parser ) { super(simpleName, mappedFieldType, builderParams, ignoreMalformed, ignoreZValue, parser); this.coerce = coerce; this.orientation = orientation; } public boolean coerce() { return coerce.value(); } public Orientation orientation() { return orientation.value(); } }
builder
java
google__guice
core/test/com/google/inject/RestrictedBindingSourceTest.java
{ "start": 25831, "end": 28270 }
class ____ extends PrivateModule { @Override protected void configure() { install( new AbstractModule() { @Override protected void configure() { bindConstant().annotatedWith(GatewayIpAdress.class).to(0); } }); expose(Key.get(Integer.class, GatewayIpAdress.class)); } } @Test public void parentHasPermit_childPrivateModuleCanExposeBinding() { Guice.createInjector( new NetworkModuleThatInstalls( // Allowed because the parent has the @NetworkLibrary permit. new PrivateModuleExposesNetworkBinding())); } @Test public void noPermitOnStack_childPrivateModuleCantExposeBinding() { AbstractModule rogueModule = new AbstractModule() { @Override protected void configure() { // Disallowed because there's no permit on the module stack. install(new PrivateModuleExposesNetworkBinding()); } }; CreationException expected = assertThatInjectorCreationFails(rogueModule); assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR); assertThat(expected).hasMessageThat().contains(USE_NETWORK_MODULE); } // -------------------------------------------------------------------------- // Child Injector tests // -------------------------------------------------------------------------- @Test public void childInjectorCantBindRestrictedBindingWithoutPermit() { Injector parent = Guice.createInjector(new NetworkModule()); AbstractModule rogueModule = new AbstractModule() { @Provides RoutingTable provideRoutingTable() { return destinationIp -> 0; } }; CreationException expected = assertThrows(CreationException.class, () -> parent.createChildInjector(rogueModule)); assertThat(expected).hasMessageThat().contains(BINDING_PERMISSION_ERROR); assertThat(expected).hasMessageThat().contains(USE_ROUTING_MODULE); } @Test public void childInjectorCanBindRestrictedBindingWithPermit() { Injector parent = Guice.createInjector(new NetworkModule()); parent.createChildInjector(new RoutingModule()); } CreationException assertThatInjectorCreationFails(Module... modules) { return assertThrows(CreationException.class, () -> Guice.createInjector(modules)); } }
PrivateModuleExposesNetworkBinding
java
playframework__playframework
persistence/play-jdbc-evolutions/src/main/java/play/db/evolutions/EvolutionsReader.java
{ "start": 351, "end": 1240 }
class ____ implements play.api.db.evolutions.EvolutionsReader { public final Seq<play.api.db.evolutions.Evolution> evolutions(String db) { Collection<Evolution> evolutions = getEvolutions(db); if (evolutions != null) { List<play.api.db.evolutions.Evolution> scalaEvolutions = evolutions.stream() .map( e -> new play.api.db.evolutions.Evolution( e.getRevision(), e.getSqlUp(), e.getSqlDown())) .collect(toList()); return Scala.asScala(scalaEvolutions); } else { return Scala.asScala(Collections.emptyList()); } } /** * Get the evolutions for the given database name. * * @param db The name of the database. * @return The collection of evolutions. */ public abstract Collection<Evolution> getEvolutions(String db); }
EvolutionsReader
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/caching/mocked/CacheKeyImplementationHashCodeTest.java
{ "start": 2653, "end": 2723 }
class ____ { @Id @GeneratedValue private int id; } }
AnotherEntity
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmnode/UpdatedContainerInfo.java
{ "start": 1041, "end": 2073 }
class ____ { private List<ContainerStatus> newlyLaunchedContainers; private List<ContainerStatus> completedContainers; private List<Map.Entry<ApplicationId, ContainerStatus>> updateContainers; public UpdatedContainerInfo() { } public UpdatedContainerInfo(List<ContainerStatus> newlyLaunchedContainers, List<ContainerStatus> completedContainers, List<Map.Entry<ApplicationId, ContainerStatus>> updateContainers) { this.newlyLaunchedContainers = newlyLaunchedContainers; this.completedContainers = completedContainers; this.updateContainers = updateContainers; } public List<ContainerStatus> getNewlyLaunchedContainers() { return this.newlyLaunchedContainers; } public List<ContainerStatus> getCompletedContainers() { return this.completedContainers; } public List<Map.Entry<ApplicationId, ContainerStatus>> getUpdateContainers() { return this.updateContainers; } }
UpdatedContainerInfo
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/codec/json/Jackson2CodecSupport.java
{ "start": 3251, "end": 5876 }
class ____: "; private static final List<MimeType> defaultMimeTypes = List.of( MediaType.APPLICATION_JSON, new MediaType("application", "*+json"), MediaType.APPLICATION_NDJSON); protected final Log logger = HttpLogging.forLogName(getClass()); private ObjectMapper defaultObjectMapper; private @Nullable Map<Class<?>, Map<MimeType, ObjectMapper>> objectMapperRegistrations; private final List<MimeType> mimeTypes; /** * Constructor with a Jackson {@link ObjectMapper} to use. */ protected Jackson2CodecSupport(ObjectMapper objectMapper, MimeType... mimeTypes) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.defaultObjectMapper = objectMapper; this.mimeTypes = (!ObjectUtils.isEmpty(mimeTypes) ? List.of(mimeTypes) : defaultMimeTypes); } /** * Configure the default ObjectMapper instance to use. * @param objectMapper the ObjectMapper instance * @since 5.3.4 */ public void setObjectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); this.defaultObjectMapper = objectMapper; } /** * Return the {@link #setObjectMapper configured} default ObjectMapper. */ public ObjectMapper getObjectMapper() { return this.defaultObjectMapper; } /** * Configure the {@link ObjectMapper} instances to use for the given * {@link Class}. This is useful when you want to deviate from the * {@link #getObjectMapper() default} ObjectMapper or have the * {@code ObjectMapper} vary by {@code MediaType}. * <p><strong>Note:</strong> Use of this method effectively turns off use of * the default {@link #getObjectMapper() ObjectMapper} and supported * {@link #getMimeTypes() MimeTypes} for the given class. Therefore it is * important for the mappings configured here to * {@link MediaType#includes(MediaType) include} every MediaType that must * be supported for the given class. * @param clazz the type of Object to register ObjectMapper instances for * @param registrar a consumer to populate or otherwise update the * MediaType-to-ObjectMapper associations for the given Class * @since 5.3.4 */ public void registerObjectMappersForType(Class<?> clazz, Consumer<Map<MimeType, ObjectMapper>> registrar) { if (this.objectMapperRegistrations == null) { this.objectMapperRegistrations = new LinkedHashMap<>(); } Map<MimeType, ObjectMapper> registrations = this.objectMapperRegistrations.computeIfAbsent(clazz, c -> new LinkedHashMap<>()); registrar.accept(registrations); } /** * Return ObjectMapper registrations for the given class, if any. * @param clazz the
argument
java
apache__maven
compat/maven-compat/src/main/java/org/apache/maven/repository/metadata/DefaultClasspathTransformation.java
{ "start": 2918, "end": 5191 }
class ____ { MetadataGraph graph; ClasspathContainer cpc; List<MetadataGraphVertex> visited; // ----------------------------------------------------------------------- protected ClasspathGraphVisitor(MetadataGraph cleanGraph, ClasspathContainer cpc) { this.cpc = cpc; this.graph = cleanGraph; visited = new ArrayList<>(cleanGraph.getVertices().size()); } // ----------------------------------------------------------------------- protected void visit(MetadataGraphVertex node) { ArtifactMetadata md = node.getMd(); if (visited.contains(node)) { return; } cpc.add(md); List<MetadataGraphEdge> exits = graph.getExcidentEdges(node); if (exits != null && !exits.isEmpty()) { MetadataGraphEdge[] sortedExits = exits.toArray(new MetadataGraphEdge[0]); Arrays.sort(sortedExits, (e1, e2) -> { if (e1.getDepth() == e2.getDepth()) { if (e2.getPomOrder() == e1.getPomOrder()) { return e1.getTarget() .toString() .compareTo(e2.getTarget().toString()); } return e2.getPomOrder() - e1.getPomOrder(); } return e2.getDepth() - e1.getDepth(); }); for (MetadataGraphEdge e : sortedExits) { MetadataGraphVertex targetNode = e.getTarget(); targetNode.getMd().setArtifactScope(e.getScope()); targetNode.getMd().setWhy(e.getSource().getMd().toString()); visit(targetNode); } } } // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- } // ---------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------- }
ClasspathGraphVisitor
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/InstantiationUtil.java
{ "start": 14581, "end": 14705 }
class ____ a proper class, i.e. not abstract or an interface, and not a * primitive type. * * @param clazz The
is
java
apache__camel
components/camel-infinispan/camel-infinispan-embedded/src/test/java/org/apache/camel/component/infinispan/embedded/spring/SpringInfinispanEmbeddedIdempotentRepositorySpringTest.java
{ "start": 1096, "end": 1498 }
class ____ extends SpringInfinispanEmbeddedIdempotentRepositoryTestSupport { @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/component/infinispan/spring/SpringInfinispanEmbeddedIdempotentRepositorySpringTest.xml"); } }
SpringInfinispanEmbeddedIdempotentRepositorySpringTest
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/parsetools/JsonParserTest.java
{ "start": 21322, "end": 28842 }
class ____ { private String f; public TheObject() { } public TheObject(String f) { this.f = f; } public void setF(String f) { this.f = f; } @Override public boolean equals(Object obj) { TheObject that = (TheObject) obj; return Objects.equals(f, that.f); } } @Test public void testParseConcatedJSONStream() { JsonParser parser = JsonParser.newParser(); AtomicInteger startCount = new AtomicInteger(); AtomicInteger endCount = new AtomicInteger(); parser.handler(event -> { switch (event.type()) { case START_OBJECT: startCount.incrementAndGet(); break; case END_OBJECT: endCount.incrementAndGet(); break; default: fail(); break; } }); parser.handle(Buffer.buffer("{}{}")); assertEquals(2, startCount.get()); assertEquals(2, endCount.get()); } @Test public void testParseLineDelimitedJSONStream() { JsonParser parser = JsonParser.newParser(); AtomicInteger startCount = new AtomicInteger(); AtomicInteger endCount = new AtomicInteger(); AtomicInteger numberCount = new AtomicInteger(); AtomicInteger nullCount = new AtomicInteger(); AtomicInteger stringCount = new AtomicInteger(); parser.handler(event -> { switch (event.type()) { case START_OBJECT: startCount.incrementAndGet(); break; case END_OBJECT: endCount.incrementAndGet(); break; case VALUE: if (event.isNull()) { nullCount.incrementAndGet(); } else if (event.isNumber()) { numberCount.incrementAndGet(); } else if (event.isString()) { stringCount.incrementAndGet(); } else { fail("Unexpected " + event.type()); } break; default: fail("Unexpected " + event.type()); break; } }); parser.handle(Buffer.buffer("{}\r\n1\r\nnull\r\n\"foo\"")); assertEquals(1, startCount.get()); assertEquals(1, endCount.get()); assertEquals(1, numberCount.get()); assertEquals(1, nullCount.get()); assertEquals(1, stringCount.get()); } @Test public void testStreamHandle() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(events::add); stream.handle("{}"); assertFalse(stream.isPaused()); assertEquals(2, events.size()); } @Test public void testStreamPause() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(events::add); parser.pause(); stream.handle("1234"); assertTrue(stream.isPaused()); assertEquals(0, events.size()); } @Test public void testStreamResume() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(events::add); parser.pause(); stream.handle("{}"); parser.resume(); assertEquals(2, events.size()); assertFalse(stream.isPaused()); } @Test public void testStreamFetch() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(events::add); parser.pause(); stream.handle("{}"); parser.fetch(1); assertEquals(1, events.size()); assertTrue(stream.isPaused()); } @Test public void testStreamFetchNames() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(events::add); parser.pause(); stream.handle("{\"foo\":\"bar\"}"); parser.fetch(3); assertEquals(3, events.size()); assertTrue(stream.isPaused()); } @Test public void testStreamPauseInHandler() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(event -> { assertTrue(events.isEmpty()); events.add(event); parser.pause(); }); stream.handle("{}"); assertEquals(1, events.size()); assertTrue(stream.isPaused()); } @Test public void testStreamFetchInHandler() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(event -> { events.add(event); stream.fetch(1); }); stream.pause(); stream.fetch(1); stream.handle("{}"); assertEquals(2, events.size()); assertFalse(stream.isPaused()); } @Test public void testStreamEnd() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(events::add); AtomicInteger ended = new AtomicInteger(); parser.endHandler(v -> ended.incrementAndGet()); stream.end(); assertEquals(0, events.size()); assertEquals(1, ended.get()); //regression check for #2790 - ensure that by accident resume method is not called. assertEquals(0, stream.pauseCount()); assertEquals(0, stream.resumeCount()); } @Test public void testStreamPausedEnd() { FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); List<JsonEvent> events = new ArrayList<>(); parser.handler(events::add); AtomicInteger ended = new AtomicInteger(); parser.endHandler(v -> ended.incrementAndGet()); parser.pause(); stream.handle("{}"); stream.end(); assertEquals(0, ended.get()); assertEquals(0, events.size()); parser.fetch(1); assertEquals(1, events.size()); assertEquals(0, ended.get()); parser.fetch(1); assertEquals(2, events.size()); assertEquals(1, ended.get()); } @Test public void testPauseAndResumeInHandler() throws Exception { AtomicInteger counter = new AtomicInteger(0); FakeStream stream = new FakeStream(); JsonParser parser = JsonParser.newParser(stream); parser.objectValueMode(); parser.handler(event -> { parser.pause(); // Needed pause for doing something assertNotNull(event); assertEquals(JsonEventType.VALUE, event.type()); counter.incrementAndGet(); parser.resume(); // There and then resume }); parser.exceptionHandler(t -> { throw new AssertionError(t); }); CountDownLatch latch = new CountDownLatch(1); parser.endHandler(end -> { assertEquals(4, counter.get()); latch.countDown(); }); stream.handle("" + "{\"field_0\": \"value"); stream.handle("_0\"}{\"field_1\": \"value_1\"}"); stream.handle("{\"field_2\": \"val"); stream.handle("ue_2\"}{\"field_3\": \"value_3\"}"); stream.end(); assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test public void testStreamResume3886() { JsonParser parser = JsonParser.newParser(); List<JsonEvent> events = new ArrayList<>(); parser.handler(event -> { events.add(event); }); parser.pause(); Buffer b = Buffer.buffer("{ \"a\":\"y\" }"); parser.handle(b); parser.handle(b); parser.resume(); parser.end(); assertEquals(3 * 2, events.size()); } }
TheObject
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/cdi/QualifiedFragment.java
{ "start": 707, "end": 757 }
interface ____ { int returnOne(); }
QualifiedFragment
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java
{ "start": 50582, "end": 51052 }
class ____ { public String getMessage() { fail(); return null; } } """) .doTest(); } @Test public void negativeCases_unreachableFailNonCanonicalImport() { createCompilationTestHelper() .addSourceLines( "com/foo/BarTestCase.java", """ package foo; import junit.framework.TestCase;
LiteralNullReturnTest
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultSettingsBuilder.java
{ "start": 2790, "end": 10868 }
class ____ implements SettingsBuilder { private final DefaultSettingsValidator settingsValidator = new DefaultSettingsValidator(); private final SettingsMerger settingsMerger = new SettingsMerger() { @Override protected KeyComputer<Repository> getRepositoryKey() { return IdentifiableBase::getId; } }; private final SettingsXmlFactory settingsXmlFactory; private final Interpolator interpolator; private final Map<String, Dispatcher> dispatchers; /** * In Maven4 the {@link SecDispatcher} is injected and build settings are fully decrypted as well. */ @Inject public DefaultSettingsBuilder( SettingsXmlFactory settingsXmlFactory, Interpolator interpolator, Map<String, Dispatcher> dispatchers) { this.settingsXmlFactory = settingsXmlFactory; this.interpolator = interpolator; this.dispatchers = dispatchers; } @Override public SettingsBuilderResult build(SettingsBuilderRequest request) throws SettingsBuilderException { ProblemCollector<BuilderProblem> problems = ProblemCollector.create(request.getSession()); Source installationSource = request.getInstallationSettingsSource().orElse(null); Settings installation = readSettings(installationSource, false, request, problems); Source projectSource = request.getProjectSettingsSource().orElse(null); Settings project = readSettings(projectSource, true, request, problems); Source userSource = request.getUserSettingsSource().orElse(null); Settings user = readSettings(userSource, false, request, problems); Settings effective = settingsMerger.merge(user, settingsMerger.merge(project, installation, false, null), false, null); // If no repository is defined in the user/global settings, // it means that we have "old" settings (as those are new in 4.0) // so add central to the computed settings for backward compatibility. if (effective.getRepositories().isEmpty() && effective.getPluginRepositories().isEmpty()) { Repository central = Repository.newBuilder() .id("central") .name("Central Repository") .url("https://repo.maven.apache.org/maven2") .snapshots(RepositoryPolicy.newBuilder().enabled(false).build()) .build(); Repository centralWithNoUpdate = central.withReleases( RepositoryPolicy.newBuilder().updatePolicy("never").build()); effective = Settings.newBuilder(effective) .repositories(List.of(central)) .pluginRepositories(List.of(centralWithNoUpdate)) .build(); } // for the special case of a drive-relative Windows path, make sure it's absolute to save plugins from trouble String localRepository = effective.getLocalRepository(); if (localRepository != null && !localRepository.isEmpty()) { Path file = Paths.get(localRepository); if (!file.isAbsolute() && file.toString().startsWith(File.separator)) { effective = effective.withLocalRepository(file.toAbsolutePath().toString()); } } if (problems.hasErrorProblems()) { throw new SettingsBuilderException("Error building settings", problems); } return new DefaultSettingsBuilderResult(request, effective, problems); } private Settings readSettings( Source settingsSource, boolean isProjectSettings, SettingsBuilderRequest request, ProblemCollector<BuilderProblem> problems) { if (settingsSource == null) { return Settings.newInstance(); } Settings settings; try { try (InputStream is = settingsSource.openStream()) { settings = settingsXmlFactory.read(XmlReaderRequest.builder() .inputStream(is) .location(settingsSource.getLocation()) .strict(true) .build()); } catch (XmlReaderException e) { try (InputStream is = settingsSource.openStream()) { settings = settingsXmlFactory.read(XmlReaderRequest.builder() .inputStream(is) .location(settingsSource.getLocation()) .strict(false) .build()); Location loc = e.getCause() instanceof XMLStreamException xe ? xe.getLocation() : null; problems.reportProblem(new DefaultBuilderProblem( settingsSource.getLocation(), loc != null ? loc.getLineNumber() : -1, loc != null ? loc.getColumnNumber() : -1, e, e.getMessage(), BuilderProblem.Severity.WARNING)); } } } catch (XmlReaderException e) { Location loc = e.getCause() instanceof XMLStreamException xe ? xe.getLocation() : null; problems.reportProblem(new DefaultBuilderProblem( settingsSource.getLocation(), loc != null ? loc.getLineNumber() : -1, loc != null ? loc.getColumnNumber() : -1, e, "Non-parseable settings " + settingsSource.getLocation() + ": " + e.getMessage(), BuilderProblem.Severity.FATAL)); return Settings.newInstance(); } catch (IOException e) { problems.reportProblem(new DefaultBuilderProblem( settingsSource.getLocation(), -1, -1, e, "Non-readable settings " + settingsSource.getLocation() + ": " + e.getMessage(), BuilderProblem.Severity.FATAL)); return Settings.newInstance(); } settings = interpolate(settings, request, problems); settings = decrypt(settingsSource, settings, request, problems); settingsValidator.validate(settings, isProjectSettings, problems); if (isProjectSettings) { settings = Settings.newBuilder(settings, true) .localRepository(null) .interactiveMode(false) .offline(false) .proxies(List.of()) .usePluginRegistry(false) .servers(settings.getServers().stream() .map(s -> Server.newBuilder(s, true) .username(null) .passphrase(null) .privateKey(null) .password(null) .filePermissions(null) .directoryPermissions(null) .build()) .toList()) .build(); } return settings; } private Settings interpolate( Settings settings, SettingsBuilderRequest request, ProblemCollector<BuilderProblem> problems) { UnaryOperator<String> src; if (request.getInterpolationSource().isPresent()) { src = request.getInterpolationSource().get(); } else { Map<String, String> userProperties = request.getSession().getUserProperties(); Map<String, String> systemProperties = request.getSession().getSystemProperties(); src = Interpolator.chain(userProperties::get, systemProperties::get); } return new DefSettingsTransformer(value -> value != null ? interpolator.interpolate(value, src) : null) .visit(settings); } static
DefaultSettingsBuilder
java
apache__thrift
lib/java/src/test/java/org/apache/thrift/transport/ReadCountingTransport.java
{ "start": 891, "end": 2175 }
class ____ extends TTransport { public int readCount = 0; private TTransport trans; private boolean open = true; public ReadCountingTransport(TTransport underlying) { trans = underlying; } @Override public void close() { open = false; } @Override public boolean isOpen() { return open; } @Override public void open() throws TTransportException { open = true; } @Override public int read(byte[] buf, int off, int len) throws TTransportException { if (!isOpen()) { throw new TTransportException(TTransportException.NOT_OPEN, "Transport is closed"); } readCount++; return trans.read(buf, off, len); } @Override public void write(byte[] buf, int off, int len) throws TTransportException { if (!isOpen()) { throw new TTransportException(TTransportException.NOT_OPEN, "Transport is closed"); } } @Override public TConfiguration getConfiguration() { return trans.getConfiguration(); } @Override public void updateKnownMessageSize(long size) throws TTransportException { trans.updateKnownMessageSize(size); } @Override public void checkReadBytesAvailable(long numBytes) throws TTransportException { trans.checkReadBytesAvailable(numBytes); } }
ReadCountingTransport
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3153/Issue3153Mapper.java
{ "start": 852, "end": 886 }
enum ____ { PR, } }
Target
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNullTest.java
{ "start": 7548, "end": 8433 }
class ____ { private int a; @Override // BUG: Diagnostic contains: if (o == null) { return false; } public boolean equals(Object o) { if (o != null && !(o instanceof VerySillyInstanceofCheck)) { return false; } VerySillyInstanceofCheck that = (VerySillyInstanceofCheck) o; return that.a == a; } } }\ """) .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceLines( "EqualsBrokenForNullNegativeCases.java", """ package com.google.errorprone.bugpatterns.nullness.testdata; /** * Negative test cases for EqualsBrokenForNull check. * * @author bhagwani@google.com (Sumit Bhagwani) */ public
VerySillyInstanceofCheck
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java
{ "start": 15228, "end": 15438 }
class ____ { @Bean @ConfigurationProperties("bar") SelfReferential foo() { return new SelfReferential(); } } @Configuration(proxyBeanMethods = false) @Import(Base.class) static
MetadataCycleConfig
java
apache__logging-log4j2
log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/ExceptionResolver.java
{ "start": 6985, "end": 16437 }
class ____ implements EventResolver { private static final Logger LOGGER = StatusLogger.getLogger(); private static final EventResolver NULL_RESOLVER = (ignored, jsonGenerator) -> jsonGenerator.writeNull(); private final boolean stackTraceEnabled; private final EventResolver internalResolver; ExceptionResolver(final EventResolverContext context, final TemplateResolverConfig config) { this.stackTraceEnabled = context.isStackTraceEnabled(); this.internalResolver = createInternalResolver(context, config); } EventResolver createInternalResolver(final EventResolverContext context, final TemplateResolverConfig config) { final String fieldName = config.getString("field"); if ("className".equals(fieldName)) { return createClassNameResolver(); } else if ("message".equals(fieldName)) { return createMessageResolver(); } else if ("stackTrace".equals(fieldName)) { return createStackTraceResolver(context, config); } throw new IllegalArgumentException("unknown field: " + config); } private EventResolver createClassNameResolver() { return (final LogEvent logEvent, final JsonWriter jsonWriter) -> { final Throwable exception = extractThrowable(logEvent); if (exception == null) { jsonWriter.writeNull(); } else { final String exceptionClassName = exception.getClass().getCanonicalName(); jsonWriter.writeString(exceptionClassName); } }; } private EventResolver createMessageResolver() { return (final LogEvent logEvent, final JsonWriter jsonWriter) -> { final Throwable exception = extractThrowable(logEvent); if (exception == null) { jsonWriter.writeNull(); } else { final String exceptionMessage = exception.getMessage(); jsonWriter.writeString(exceptionMessage); } }; } private EventResolver createStackTraceResolver( final EventResolverContext context, final TemplateResolverConfig config) { if (!context.isStackTraceEnabled()) { return NULL_RESOLVER; } final boolean stringified = isStackTraceStringified(config); return stringified ? createStackTraceStringResolver(context, config) : createStackTraceObjectResolver(context, config); } private static boolean isStackTraceStringified(final TemplateResolverConfig config) { final Boolean stringifiedOld = config.getBoolean("stringified"); if (stringifiedOld != null) { LOGGER.warn("\"stringified\" flag at the root level of an exception " + "[root cause] resolver is deprecated in favor of " + "\"stackTrace.stringified\""); } final Object stringifiedNew = config.getObject(new String[] {"stackTrace", "stringified"}); if (stringifiedOld == null && stringifiedNew == null) { return false; } else if (stringifiedNew == null) { return stringifiedOld; } else { return !(stringifiedNew instanceof Boolean) || (boolean) stringifiedNew; } } private EventResolver createStackTraceStringResolver( final EventResolverContext context, final TemplateResolverConfig config) { // Read the configuration. final String truncationSuffix = readTruncationSuffix(context, config); final List<String> truncationPointMatcherStrings = readTruncationPointMatcherStrings(config); final List<String> truncationPointMatcherRegexes = readTruncationPointMatcherRegexes(config); // Create the resolver. final StackTraceStringResolver resolver = new StackTraceStringResolver( context, truncationSuffix, truncationPointMatcherStrings, truncationPointMatcherRegexes); // Create the null-protected resolver. return (final LogEvent logEvent, final JsonWriter jsonWriter) -> { final Throwable exception = extractThrowable(logEvent); if (exception == null) { jsonWriter.writeNull(); } else { resolver.resolve(exception, jsonWriter); } }; } private static String readTruncationSuffix( final EventResolverContext context, final TemplateResolverConfig config) { final String suffix = config.getString(new String[] {"stackTrace", "stringified", "truncation", "suffix"}); return suffix != null ? suffix : context.getTruncatedStringSuffix(); } private static List<String> readTruncationPointMatcherStrings(final TemplateResolverConfig config) { List<String> strings = config.getList( new String[] {"stackTrace", "stringified", "truncation", "pointMatcherStrings"}, String.class); if (strings == null) { strings = Collections.emptyList(); } return strings; } private static List<String> readTruncationPointMatcherRegexes(final TemplateResolverConfig config) { // Extract the regexes. List<String> regexes = config.getList( new String[] {"stackTrace", "stringified", "truncation", "pointMatcherRegexes"}, String.class); if (regexes == null) { regexes = Collections.emptyList(); } // Check the regex syntax. for (int i = 0; i < regexes.size(); i++) { final String regex = regexes.get(i); try { Pattern.compile(regex); } catch (final PatternSyntaxException error) { final String message = String.format("invalid truncation point matcher regex at index %d: %s", i, regex); throw new IllegalArgumentException(message, error); } } // Return the extracted regexes. return regexes; } private static final Map<String, StackTraceElementResolverFactory> STACK_TRACE_ELEMENT_RESOLVER_FACTORY_BY_NAME; static { final StackTraceElementResolverFactory stackTraceElementResolverFactory = StackTraceElementResolverFactory.getInstance(); STACK_TRACE_ELEMENT_RESOLVER_FACTORY_BY_NAME = Collections.singletonMap(stackTraceElementResolverFactory.getName(), stackTraceElementResolverFactory); } private EventResolver createStackTraceObjectResolver( final EventResolverContext context, final TemplateResolverConfig config) { final TemplateResolver<StackTraceElement> stackTraceElementResolver = createStackTraceElementResolver(context, config); final StackTraceObjectResolver stackTraceResolver = new StackTraceObjectResolver(stackTraceElementResolver); return (final LogEvent logEvent, final JsonWriter jsonWriter) -> { final Throwable throwable = extractThrowable(logEvent); if (throwable == null) { jsonWriter.writeNull(); } else { stackTraceResolver.resolve(throwable, jsonWriter); } }; } private static TemplateResolver<StackTraceElement> createStackTraceElementResolver( final EventResolverContext context, final TemplateResolverConfig config) { final StackTraceElementResolverStringSubstitutor substitutor = new StackTraceElementResolverStringSubstitutor( context.getSubstitutor().getInternalSubstitutor()); final StackTraceElementResolverContext stackTraceElementResolverContext = StackTraceElementResolverContext.newBuilder() .setResolverFactoryByName(STACK_TRACE_ELEMENT_RESOLVER_FACTORY_BY_NAME) .setSubstitutor(substitutor) .setJsonWriter(context.getJsonWriter()) .build(); final String stackTraceElementTemplate = findEffectiveStackTraceElementTemplate(context, config); return TemplateResolvers.ofTemplate(stackTraceElementResolverContext, stackTraceElementTemplate); } private static String findEffectiveStackTraceElementTemplate( final EventResolverContext context, final TemplateResolverConfig config) { // First, check the template configured in the resolver configuration. final Object stackTraceElementTemplateObject = config.getObject(new String[] {"stackTrace", "elementTemplate"}); if (stackTraceElementTemplateObject != null) { final JsonWriter jsonWriter = context.getJsonWriter(); return jsonWriter.use(() -> jsonWriter.writeValue(stackTraceElementTemplateObject)); } // Otherwise, use the template provided in the context. return context.getStackTraceElementTemplate(); } Throwable extractThrowable(final LogEvent logEvent) { return logEvent.getThrown(); } @Override public boolean isResolvable() { return stackTraceEnabled; } @Override public boolean isResolvable(final LogEvent logEvent) { return stackTraceEnabled && logEvent.getThrown() != null; } @Override public void resolve(final LogEvent logEvent, final JsonWriter jsonWriter) { internalResolver.resolve(logEvent, jsonWriter); } }
ExceptionResolver
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestParallelShortCircuitReadNoChecksum.java
{ "start": 1218, "end": 2329 }
class ____ extends TestParallelReadUtil { private static TemporarySocketDirectory sockDir; @BeforeAll static public void setupCluster() throws Exception { if (DomainSocket.getLoadingFailureReason() != null) return; DFSInputStream.tcpReadsDisabledForTesting = true; sockDir = new TemporarySocketDirectory(); HdfsConfiguration conf = new HdfsConfiguration(); conf.set(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY, new File(sockDir.getDir(), "TestParallelLocalRead.%d.sock").getAbsolutePath()); conf.setBoolean(HdfsClientConfigKeys.Read.ShortCircuit.KEY, true); conf.setBoolean(HdfsClientConfigKeys.Read.ShortCircuit.SKIP_CHECKSUM_KEY, true); DomainSocket.disableBindPathValidation(); setupCluster(1, conf); } @BeforeEach public void before() { assumeThat(DomainSocket.getLoadingFailureReason()).isNull(); } @AfterAll static public void teardownCluster() throws Exception { if (DomainSocket.getLoadingFailureReason() != null) return; sockDir.close(); TestParallelReadUtil.teardownCluster(); } }
TestParallelShortCircuitReadNoChecksum
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithRemoteRegistryPushTest.java
{ "start": 400, "end": 1601 }
class ____ extends BaseOpenshiftWithRemoteRegistry { private static final String APP_NAME = "openshift-with-remote-docker-registry-push"; @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName(APP_NAME) .setApplicationVersion("0.1-SNAPSHOT") .overrideConfigKey("quarkus.container-image.group", "user") .overrideConfigKey("quarkus.container-image.registry", "quay.io") .overrideConfigKey("quarkus.container-image.username", "me") .overrideConfigKey("quarkus.container-image.password", "pass") .overrideConfigKey("quarkus.openshift.generate-image-pull-secret", "true") .setForcedDependencies(List.of(Dependency.of("io.quarkus", "quarkus-openshift", Version.getVersion()))); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { assertGeneratedResources(APP_NAME, "0.1-SNAPSHOT", prodModeTestResults.getBuildDir()); } }
OpenshiftWithRemoteRegistryPushTest
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/RollingRandomAccessFileAppender.java
{ "start": 2516, "end": 2652 }
class ____ extends AbstractOutputStreamAppender<RollingRandomAccessFileManager> { public static
RollingRandomAccessFileAppender
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/OnCompletionIssueTest.java
{ "start": 1246, "end": 3720 }
class ____ extends ContextTestSupport { @Test public void testOnCompletionIssue() throws Exception { MockEndpoint end = getMockEndpoint("mock:end"); end.expectedMessageCount(1); MockEndpoint complete = getMockEndpoint("mock:complete"); complete.expectedBodiesReceivedInAnyOrder("finish", "stop", "ile", "markRollback"); MockEndpoint failed = getMockEndpoint("mock:failed"); failed.expectedBodiesReceivedInAnyOrder("npe", "rollback"); template.sendBody("direct:input", "finish"); template.sendBody("direct:input", "stop"); template.sendBody("direct:input", "ile"); template.sendBody("direct:input", "markRollback"); CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> template.sendBody("direct:input", "npe"), "Should have thrown exception"); assertEquals("Darn NPE", e.getCause().getMessage()); CamelExecutionException ex = assertThrows(CamelExecutionException.class, () -> template.sendBody("direct:input", "rollback"), "Should have thrown exception"); assertIsInstanceOf(RollbackExchangeException.class, ex.getCause()); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { onCompletion().onFailureOnly().parallelProcessing().log("failing ${body}").to("mock:failed"); onCompletion().onCompleteOnly().parallelProcessing().log("completing ${body}").to("mock:complete"); from("direct:input").onException(IllegalArgumentException.class).handled(true).end().choice() .when(simple("${body} == 'stop'")).log("stopping").stop() .when(simple("${body} == 'ile'")).log("excepting") .throwException(new IllegalArgumentException("Exception requested")).when(simple("${body} == 'npe'")) .log("excepting").throwException(new NullPointerException("Darn NPE")) .when(simple("${body} == 'rollback'")).log("rollback").rollback() .when(simple("${body} == 'markRollback'")).log("markRollback").markRollbackOnly().end().log("finishing") .to("mock:end"); } }; } }
OnCompletionIssueTest
java
apache__camel
components/camel-platform-http-vertx/src/main/java/org/apache/camel/component/platform/http/vertx/VertxPlatformHttpSupport.java
{ "start": 2193, "end": 2391 }
class ____ part of the component's hot-path, therefore, please be mindful * about the performance implications of the code (i.e.: keep methods small, avoid costly operations, etc). */ public final
are
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/OpenSslCertificateCompressionAlgorithm.java
{ "start": 870, "end": 2967 }
interface ____ { /** * Compress the given input with the specified algorithm and return the compressed bytes. * * @param engine the {@link SSLEngine} * @param uncompressedCertificate the uncompressed certificate * @return the compressed form of the certificate * @throws Exception thrown if an error occurs while compressing */ byte[] compress(SSLEngine engine, byte[] uncompressedCertificate) throws Exception; /** * Decompress the given input with the specified algorithm and return the decompressed bytes. * * <h3>Implementation * <a href="https://tools.ietf.org/html/rfc8879#section-5">Security Considerations</a></h3> * <p>Implementations SHOULD bound the memory usage when decompressing the CompressedCertificate message.</p> * <p> * Implementations MUST limit the size of the resulting decompressed chain to the specified {@code uncompressedLen}, * and they MUST abort the connection (throw an exception) if the size of the output of the decompression * function exceeds that limit. * </p> * * @param engine the {@link SSLEngine} * @param uncompressedLen the expected length of the decompressed certificate that will be returned. * @param compressedCertificate the compressed form of the certificate * @return the decompressed form of the certificate * @throws Exception thrown if an error occurs while decompressing or output size exceeds * {@code uncompressedLen} */ byte[] decompress(SSLEngine engine, int uncompressedLen, byte[] compressedCertificate) throws Exception; /** * Return the ID for the compression algorithm provided for by a given implementation. * * @return compression algorithm ID as specified by * <a href="https://datatracker.ietf.org/doc/html/rfc8879">RFC8879</a>. */ int algorithmId(); }
OpenSslCertificateCompressionAlgorithm
java
elastic__elasticsearch
x-pack/plugin/spatial/src/internalClusterTest/java/org/elasticsearch/xpack/spatial/search/ShapeQueryOverShapeTests.java
{ "start": 2035, "end": 16043 }
class ____ extends ShapeQueryTestCase { private static String INDEX = "test"; private static String IGNORE_MALFORMED_INDEX = INDEX + "_ignore_malformed"; private static String FIELD = "shape"; private static Geometry queryGeometry = null; private int numDocs; @Override protected XContentBuilder createDefaultMapping() throws Exception { final boolean isIndexed = randomBoolean(); final boolean hasDocValues = isIndexed == false || randomBoolean(); return XContentFactory.jsonBuilder() .startObject() .startObject("properties") .startObject(defaultFieldName) .field("type", "shape") .field("index", isIndexed) .field("doc_values", hasDocValues) .endObject() .endObject() .endObject(); } @Override public void setUp() throws Exception { super.setUp(); // create test index assertAcked(indicesAdmin().prepareCreate(INDEX).setMapping(FIELD, "type=shape", "alias", "type=alias,path=" + FIELD).get()); // create index that ignores malformed geometry assertAcked( indicesAdmin().prepareCreate(IGNORE_MALFORMED_INDEX) .setMapping(FIELD, "type=shape,ignore_malformed=true", "_source", "enabled=false") ); ensureGreen(); // index random shapes numDocs = randomIntBetween(25, 50); // reset query geometry to make sure we pick one from the indexed shapes queryGeometry = null; Geometry geometry; for (int i = 0; i < numDocs; ++i) { geometry = ShapeTestUtils.randomGeometry(false); if (geometry.type() == ShapeType.CIRCLE) continue; if (queryGeometry == null && geometry.type() != ShapeType.MULTIPOINT) { queryGeometry = geometry; } XContentBuilder geoJson = GeoJson.toXContent(geometry, XContentFactory.jsonBuilder().startObject().field(FIELD), null) .endObject(); try { prepareIndex(INDEX).setSource(geoJson).setRefreshPolicy(IMMEDIATE).get(); prepareIndex(IGNORE_MALFORMED_INDEX).setRefreshPolicy(IMMEDIATE).setSource(geoJson).get(); } catch (Exception e) { // sometimes GeoTestUtil will create invalid geometry; catch and continue: if (queryGeometry == geometry) { // reset query geometry as it didn't get indexed queryGeometry = null; } --i; continue; } } } public void testIndexedShapeReferenceSourceDisabled() throws Exception { Rectangle rectangle = new Rectangle(-45, 45, 45, -45); prepareIndex(IGNORE_MALFORMED_INDEX).setId("Big_Rectangle") .setSource(jsonBuilder().startObject().field(FIELD, WellKnownText.toWKT(rectangle)).endObject()) .setRefreshPolicy(IMMEDIATE) .get(); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> client().prepareSearch(IGNORE_MALFORMED_INDEX) .setQuery(new ShapeQueryBuilder(FIELD, "Big_Rectangle").indexedShapeIndex(IGNORE_MALFORMED_INDEX)) .get() ); assertThat(e.getMessage(), containsString("source disabled")); } public void testShapeFetchingPath() throws Exception { String indexName = "shapes_index"; String searchIndex = "search_index"; createIndex(indexName); indicesAdmin().prepareCreate(searchIndex).setMapping("location", "type=shape").get(); String location = """ "location" : {"type":"polygon", "coordinates":[[[-10,-10],[10,-10],[10,10],[-10,10],[-10,-10]]]}"""; prepareIndex(indexName).setId("1").setSource(Strings.format(""" { %s, "1" : { %s, "2" : { %s, "3" : { %s } }} } """, location, location, location, location), XContentType.JSON).setRefreshPolicy(IMMEDIATE).get(); prepareIndex(searchIndex).setId("1") .setSource( jsonBuilder().startObject() .startObject("location") .field("type", "polygon") .startArray("coordinates") .startArray() .startArray() .value(-20) .value(-20) .endArray() .startArray() .value(20) .value(-20) .endArray() .startArray() .value(20) .value(20) .endArray() .startArray() .value(-20) .value(20) .endArray() .startArray() .value(-20) .value(-20) .endArray() .endArray() .endArray() .endObject() .endObject() ) .setRefreshPolicy(IMMEDIATE) .get(); ShapeQueryBuilder filter = new ShapeQueryBuilder("location", "1").relation(ShapeRelation.INTERSECTS) .indexedShapeIndex(indexName) .indexedShapePath("location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(QueryBuilders.matchAllQuery()).setPostFilter(filter), 1L); filter = new ShapeQueryBuilder("location", "1").relation(ShapeRelation.INTERSECTS) .indexedShapeIndex(indexName) .indexedShapePath("1.location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(QueryBuilders.matchAllQuery()).setPostFilter(filter), 1L); filter = new ShapeQueryBuilder("location", "1").relation(ShapeRelation.INTERSECTS) .indexedShapeIndex(indexName) .indexedShapePath("1.2.location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(QueryBuilders.matchAllQuery()).setPostFilter(filter), 1L); filter = new ShapeQueryBuilder("location", "1").relation(ShapeRelation.INTERSECTS) .indexedShapeIndex(indexName) .indexedShapePath("1.2.3.location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(QueryBuilders.matchAllQuery()).setPostFilter(filter), 1L); // now test the query variant ShapeQueryBuilder query = new ShapeQueryBuilder("location", "1").indexedShapeIndex(indexName).indexedShapePath("location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(query), 1L); query = new ShapeQueryBuilder("location", "1").indexedShapeIndex(indexName).indexedShapePath("1.location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(query), 1L); query = new ShapeQueryBuilder("location", "1").indexedShapeIndex(indexName).indexedShapePath("1.2.location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(query), 1L); query = new ShapeQueryBuilder("location", "1").indexedShapeIndex(indexName).indexedShapePath("1.2.3.location"); assertHitCountAndNoFailures(client().prepareSearch(searchIndex).setQuery(query), 1L); } /** * Test that ignore_malformed on GeoShapeFieldMapper does not fail the entire document */ public void testIgnoreMalformed() { assertHitCount(client().prepareSearch(IGNORE_MALFORMED_INDEX).setQuery(matchAllQuery()), numDocs); } /** * Test that the indexed shape routing can be provided if it is required */ public void testIndexShapeRouting() { Object[] args = new Object[] { -Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE, -Float.MAX_VALUE }; String source = Strings.format(""" { "shape" : { "type" : "bbox", "coordinates" : [[%s,%s], [%s, %s]] } }""", args); prepareIndex(INDEX).setId("0").setSource(source, XContentType.JSON).setRouting("ABC").get(); indicesAdmin().prepareRefresh(INDEX).get(); assertHitCount( client().prepareSearch(INDEX).setQuery(new ShapeQueryBuilder(FIELD, "0").indexedShapeIndex(INDEX).indexedShapeRouting("ABC")), (long) numDocs + 1 ); } public void testNullShape() { // index a null shape prepareIndex(INDEX).setId("aNullshape").setSource("{\"" + FIELD + "\": null}", XContentType.JSON).setRefreshPolicy(IMMEDIATE).get(); prepareIndex(IGNORE_MALFORMED_INDEX).setId("aNullshape") .setSource("{\"" + FIELD + "\": null}", XContentType.JSON) .setRefreshPolicy(IMMEDIATE) .get(); GetResponse result = client().prepareGet(INDEX, "aNullshape").get(); assertThat(result.getField(FIELD), nullValue()); } public void testExistsQuery() { ExistsQueryBuilder eqb = QueryBuilders.existsQuery(FIELD); assertHitCountAndNoFailures(client().prepareSearch(INDEX).setQuery(eqb), numDocs); } public void testFieldAlias() { assertResponse( client().prepareSearch(INDEX).setQuery(new ShapeQueryBuilder("alias", queryGeometry).relation(ShapeRelation.INTERSECTS)), response -> { assertTrue(response.getHits().getTotalHits().value() > 0); } ); } public void testContainsShapeQuery() { indicesAdmin().prepareCreate("test_contains").setMapping("location", "type=shape").get(); String doc = """ {"location" : {"type":"envelope", "coordinates":[ [-100.0, 100.0], [100.0, -100.0]]}}"""; prepareIndex("test_contains").setId("1").setSource(doc, XContentType.JSON).setRefreshPolicy(IMMEDIATE).get(); // index the mbr of the collection Rectangle rectangle = new Rectangle(-50, 50, 50, -50); ShapeQueryBuilder queryBuilder = new ShapeQueryBuilder("location", rectangle).relation(ShapeRelation.CONTAINS); assertHitCountAndNoFailures(client().prepareSearch("test_contains").setQuery(queryBuilder), 1L); } public void testGeometryCollectionRelations() throws IOException { XContentBuilder mapping = XContentFactory.jsonBuilder() .startObject() .startObject("_doc") .startObject("properties") .startObject("geometry") .field("type", "shape") .endObject() .endObject() .endObject() .endObject(); createIndex("test_collections", Settings.builder().put("index.number_of_shards", 1).build(), mapping); Rectangle rectangle = new Rectangle(-10, 10, 10, -10); client().index( new IndexRequest("test_collections").source( jsonBuilder().startObject().field("geometry", WellKnownText.toWKT(rectangle)).endObject() ).setRefreshPolicy(IMMEDIATE) ).actionGet(); { // A geometry collection that is fully within the indexed shape GeometryCollection<Geometry> collection = new GeometryCollection<>(List.of(new Point(1, 2), new Point(-2, -1))); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", collection).relation(ShapeRelation.CONTAINS)), 1L ); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", collection).relation(ShapeRelation.INTERSECTS)), 1L ); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", collection).relation(ShapeRelation.DISJOINT)), 0L ); } { // A geometry collection (as multi point) that is partially within the indexed shape MultiPoint multiPoint = new MultiPoint(List.of(new Point(1, 2), new Point(20, 30))); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", multiPoint).relation(ShapeRelation.CONTAINS)), 0L ); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", multiPoint).relation(ShapeRelation.INTERSECTS)), 1L ); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", multiPoint).relation(ShapeRelation.DISJOINT)), 0L ); } { // A geometry collection that is disjoint with the indexed shape MultiPoint multiPoint = new MultiPoint(List.of(new Point(-20, -30), new Point(20, 30))); GeometryCollection<Geometry> collection = new GeometryCollection<>(List.of(multiPoint)); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", collection).relation(ShapeRelation.CONTAINS)), 0L ); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", collection).relation(ShapeRelation.INTERSECTS)), 0L ); assertHitCount( client().prepareSearch("test_collections") .setQuery(new ShapeQueryBuilder("geometry", collection).relation(ShapeRelation.DISJOINT)), 1L ); } } }
ShapeQueryOverShapeTests
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/repositories/RepositoriesStatsArchiveTests.java
{ "start": 843, "end": 5069 }
class ____ extends ESTestCase { public void testStatsAreEvictedOnceTheyAreOlderThanRetentionPeriod() { int retentionTimeInMillis = randomIntBetween(100, 1000); AtomicLong fakeRelativeClock = new AtomicLong(); RepositoriesStatsArchive repositoriesStatsArchive = new RepositoriesStatsArchive( TimeValue.timeValueMillis(retentionTimeInMillis), 100, fakeRelativeClock::get ); for (int i = 0; i < randomInt(10); i++) { RepositoryStatsSnapshot repoStats = createRepositoryStats(RepositoryStats.EMPTY_STATS); repositoriesStatsArchive.archive(repoStats); } fakeRelativeClock.set(retentionTimeInMillis * 2); int statsToBeRetainedCount = randomInt(10); for (int i = 0; i < statsToBeRetainedCount; i++) { RepositoryStatsSnapshot repoStats = createRepositoryStats(new RepositoryStats(Map.of("GET", new BlobStoreActionStats(10, 13)))); repositoriesStatsArchive.archive(repoStats); } List<RepositoryStatsSnapshot> archivedStats = repositoriesStatsArchive.getArchivedStats(); assertThat(archivedStats.size(), equalTo(statsToBeRetainedCount)); for (RepositoryStatsSnapshot repositoryStatsSnapshot : archivedStats) { assertThat(repositoryStatsSnapshot.getRepositoryStats().actionStats, equalTo(Map.of("GET", new BlobStoreActionStats(10, 13)))); } } public void testStatsAreRejectedIfTheArchiveIsFull() { int retentionTimeInMillis = randomIntBetween(100, 1000); AtomicLong fakeRelativeClock = new AtomicLong(); RepositoriesStatsArchive repositoriesStatsArchive = new RepositoriesStatsArchive( TimeValue.timeValueMillis(retentionTimeInMillis), 1, fakeRelativeClock::get ); assertTrue(repositoriesStatsArchive.archive(createRepositoryStats(RepositoryStats.EMPTY_STATS))); fakeRelativeClock.set(retentionTimeInMillis * 2); // Now there's room since the previous stats should be evicted assertTrue(repositoriesStatsArchive.archive(createRepositoryStats(RepositoryStats.EMPTY_STATS))); // There's no room for stats with the same creation time assertFalse(repositoriesStatsArchive.archive(createRepositoryStats(RepositoryStats.EMPTY_STATS))); } public void testClearArchive() { int retentionTimeInMillis = randomIntBetween(100, 1000); AtomicLong fakeRelativeClock = new AtomicLong(); RepositoriesStatsArchive repositoriesStatsArchive = new RepositoriesStatsArchive( TimeValue.timeValueMillis(retentionTimeInMillis), 100, fakeRelativeClock::get ); int archivedStatsWithVersionZero = randomIntBetween(1, 20); for (int i = 0; i < archivedStatsWithVersionZero; i++) { repositoriesStatsArchive.archive(createRepositoryStats(RepositoryStats.EMPTY_STATS, 0)); } int archivedStatsWithNewerVersion = randomIntBetween(1, 20); for (int i = 0; i < archivedStatsWithNewerVersion; i++) { repositoriesStatsArchive.archive(createRepositoryStats(RepositoryStats.EMPTY_STATS, 1)); } List<RepositoryStatsSnapshot> removedStats = repositoriesStatsArchive.clear(0L); assertThat(removedStats.size(), equalTo(archivedStatsWithVersionZero)); assertThat(repositoriesStatsArchive.getArchivedStats().size(), equalTo(archivedStatsWithNewerVersion)); } private RepositoryStatsSnapshot createRepositoryStats(RepositoryStats repositoryStats) { return createRepositoryStats(repositoryStats, 0); } private RepositoryStatsSnapshot createRepositoryStats(RepositoryStats repositoryStats, long clusterVersion) { RepositoryInfo repositoryInfo = new RepositoryInfo( UUIDs.randomBase64UUID(), randomAlphaOfLength(10), randomAlphaOfLength(10), Map.of("bucket", randomAlphaOfLength(10)), System.currentTimeMillis(), null ); return new RepositoryStatsSnapshot(repositoryInfo, repositoryStats, clusterVersion, true); } }
RepositoriesStatsArchiveTests
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/test/java/org/springframework/boot/webmvc/autoconfigure/DispatcherServletAutoConfigurationTests.java
{ "start": 8421, "end": 8924 }
class ____ { @Bean ServletRegistrationBean<?> dispatcherServletRegistration(DispatcherServlet dispatcherServlet) { ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean<>(dispatcherServlet, "/foo"); registration.setName("customDispatcher"); return registration; } @Bean DispatcherServletPath dispatcherServletPath() { return mock(DispatcherServletPath.class); } } @Configuration(proxyBeanMethods = false) static
CustomAutowiredRegistration
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.java
{ "start": 38376, "end": 38888 }
class ____ { Object o = new @A Object(); } """) .doTest(); } @Test public void instantiationWithThreadSafeTypeParameter() { compilationHelper .addSourceLines( "Test.java", """ import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.ThreadSafe; import com.google.errorprone.annotations.ThreadSafeTypeParameter; @ThreadSafe public
Test
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/proxy/config/legacy/ProxyTest.java
{ "start": 341, "end": 498 }
class ____ extends AbstractProxyTest { @RegisterExtension static final QuarkusUnitTest config = config("proxy-test-application.properties"); }
ProxyTest
java
apache__camel
test-infra/camel-test-infra-ollama/src/test/java/org/apache/camel/test/infra/ollama/services/OllamaService.java
{ "start": 970, "end": 1038 }
interface ____ extends TestService, OllamaInfraService { }
OllamaService
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckStatus.java
{ "start": 853, "end": 1227 }
class ____ implements Serializable { private static final long serialVersionUID = -5791320072773064978L; public AtomicBoolean isBeingChecked = new AtomicBoolean(false); public AtomicInteger checkFailCount = new AtomicInteger(0); public AtomicInteger checkOkCount = new AtomicInteger(0); public long checkRt = -1L; }
HealthCheckStatus
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/WithClauseTest.java
{ "start": 8120, "end": 10866 }
class ____ { public void prepare(SessionFactoryScope scope) { scope.inTransaction( (session) -> { Human mother = new Human(); mother.setBodyWeight( 10 ); mother.setDescription( "mother" ); Human father = new Human(); father.setBodyWeight( 15 ); father.setDescription( "father" ); Human child1 = new Human(); child1.setBodyWeight( 5 ); child1.setDescription( "child1" ); Human child2 = new Human(); child2.setBodyWeight( 6 ); child2.setDescription( "child2" ); Human friend = new Human(); friend.setBodyWeight( 20 ); friend.setDescription( "friend" ); friend.setIntValue( 1 ); Human friend2 = new Human(); friend2.setBodyWeight( 20 ); friend2.setDescription( "friend2" ); friend.setIntValue( 2 ); child1.setMother( mother ); child1.setFather( father ); mother.addOffspring( child1 ); father.addOffspring( child1 ); child2.setMother( mother ); child2.setFather( father ); mother.addOffspring( child2 ); father.addOffspring( child2 ); father.setFriends( new ArrayList() ); father.getFriends().add( friend ); father.getFriends().add( friend2 ); session.persist( mother ); session.persist( father ); session.persist( child1 ); session.persist( child2 ); session.persist( friend ); session.persist( friend2 ); father.setFamily( new HashMap() ); father.getFamily().put( "son1", child1 ); father.getFamily().put( "son2", child2 ); } ); } public void cleanup(SessionFactoryScope scope) { scope.inTransaction( (session) -> { Human father = (Human) session.createQuery( "from Human where description = 'father'" ).uniqueResult(); if ( father != null ) { father.getFriends().clear(); father.getFamily().clear(); session.flush(); } session.remove( session.createQuery( "from Human where description = 'friend2'" ).uniqueResult() ); session.remove( session.createQuery( "from Human where description = 'friend'" ).uniqueResult() ); session.remove( session.createQuery( "from Human where description = 'child1'" ).uniqueResult() ); session.remove( session.createQuery( "from Human where description = 'child2'" ).uniqueResult() ); session.remove( session.createQuery( "from Human where description = 'mother'" ).uniqueResult() ); session.remove( father ); session.createQuery( "delete Animal" ).executeUpdate(); session.createQuery( "delete SimpleAssociatedEntity" ).executeUpdate(); session.createQuery( "delete SimpleEntityWithAssociation" ).executeUpdate(); } ); } } }
TestData
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/javadoc/UrlInSee.java
{ "start": 1936, "end": 2792 }
class ____ extends BugChecker implements ClassTreeMatcher, MethodTreeMatcher, VariableTreeMatcher { @Override public Description matchClass(ClassTree classTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new UrlInSeeChecker(state).scan(path, null); } return NO_MATCH; } @Override public Description matchMethod(MethodTree methodTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new UrlInSeeChecker(state).scan(path, null); } return NO_MATCH; } @Override public Description matchVariable(VariableTree variableTree, VisitorState state) { DocTreePath path = getDocTreePath(state); if (path != null) { new UrlInSeeChecker(state).scan(path, null); } return NO_MATCH; } private final
UrlInSee
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java
{ "start": 2151, "end": 3357 }
class ____ { @Bean String bar() { return "bar"; } } // ------------------------------------------------------------------------- @Autowired private WebApplicationContext wac; @Autowired private String foo; @Autowired private String bar; @Test void verifyRootWacSupport() { assertThat(foo).isEqualTo("foo"); assertThat(bar).isEqualTo("bar"); ApplicationContext parent = wac.getParent(); assertThat(parent).isNotNull(); assertThat(parent).isInstanceOf(WebApplicationContext.class); WebApplicationContext root = (WebApplicationContext) parent; assertThat(root.getBeansOfType(String.class).containsKey("bar")).isFalse(); ServletContext childServletContext = wac.getServletContext(); assertThat(childServletContext).isNotNull(); ServletContext rootServletContext = root.getServletContext(); assertThat(rootServletContext).isNotNull(); assertThat(rootServletContext).isSameAs(childServletContext); assertThat(rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(root); assertThat(childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(root); } }
WebConfig
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java
{ "start": 73559, "end": 73973 }
class ____ implements SingleArcTransition<JobImpl, JobEvent> { @Override public void transition(JobImpl job, JobEvent event) { job.addDiagnostic(JOB_KILLED_DIAG); for (Task task : job.tasks.values()) { job.eventHandler.handle( new TaskEvent(task.getID(), TaskEventType.T_KILL)); } job.metrics.endRunningJob(job); } } private static
KillTasksTransition
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelLogAction.java
{ "start": 2554, "end": 21626 }
class ____ implements Iterable<String> { public PrefixCompletionCandidates() { } @Override public Iterator<String> iterator() { return List.of("auto", "true", "false").iterator(); } } @CommandLine.Parameters(description = "Name or pid of running Camel integration. (default selects all)", arity = "0..1") String name = "*"; @CommandLine.Option(names = { "--logging-color" }, defaultValue = "true", description = "Use colored logging") boolean loggingColor = true; @CommandLine.Option(names = { "--timestamp" }, defaultValue = "true", description = "Print timestamp.") boolean timestamp = true; @CommandLine.Option(names = { "--follow" }, defaultValue = "true", description = "Keep following and outputting new log lines (press enter to exit).") boolean follow = true; @CommandLine.Option(names = { "--startup" }, defaultValue = "false", description = "Only shows logs from the starting phase to make it quick to look at how Camel was started.") boolean startup; @CommandLine.Option(names = { "--prefix" }, defaultValue = "auto", completionCandidates = PrefixCompletionCandidates.class, description = "Print prefix with running Camel integration name. auto=only prefix when running multiple integrations. true=always prefix. false=prefix off.") String prefix = "auto"; @CommandLine.Option(names = { "--tail" }, defaultValue = "-1", description = "The number of lines from the end of the logs to show. Use -1 to read from the beginning. Use 0 to read only new lines. Defaults to showing all logs from beginning.") int tail = -1; @CommandLine.Option(names = { "--since" }, description = "Return logs newer than a relative duration like 5s, 2m, or 1h. The value is in seconds if no unit specified.") String since; @CommandLine.Option(names = { "--find" }, description = "Find and highlight matching text (ignore case).", arity = "0..*") String[] find; @CommandLine.Option(names = { "--grep" }, description = "Filter logs to only output lines matching text (ignore case).", arity = "0..*") String[] grep; String findAnsi; private int nameMaxWidth; private boolean prefixShown; private final Map<String, Ansi.Color> colors = new HashMap<>(); public CamelLogAction(CamelJBangMain main) { super(main); } @Override public Integer doCall() throws Exception { Map<Long, Row> rows = new LinkedHashMap<>(); // find new pids updatePids(rows); if (!rows.isEmpty()) { // read existing log files (skip by tail/since) if (find != null) { findAnsi = Ansi.ansi().fg(Ansi.Color.BLACK).bg(Ansi.Color.YELLOW).a("$0").reset().toString(); for (int i = 0; i < find.length; i++) { String f = find[i]; f = Pattern.quote(f); find[i] = f; } } if (grep != null) { findAnsi = Ansi.ansi().fg(Ansi.Color.BLACK).bg(Ansi.Color.YELLOW).a("$0").reset().toString(); for (int i = 0; i < grep.length; i++) { String f = grep[i]; f = Pattern.quote(f); grep[i] = f; } } Date limit = null; if (since != null) { long millis; if (StringHelper.isDigit(since)) { // is in seconds by default millis = TimePatternConverter.toMilliSeconds(since) * 1000; } else { millis = TimePatternConverter.toMilliSeconds(since); } limit = new Date(System.currentTimeMillis() - millis); } if (startup) { follow = false; // only log startup logs until Camel was started tailStartupLogFiles(rows); dumpLogFiles(rows, 0); } else if (tail != 0) { // dump existing log lines tailLogFiles(rows, tail, limit); dumpLogFiles(rows, tail); } } if (follow) { boolean waitMessage = true; final AtomicBoolean running = new AtomicBoolean(true); Thread t = new Thread(() -> { waitUserTask = new CommandHelper.ReadConsoleTask(() -> running.set(false)); waitUserTask.run(); }, "WaitForUser"); t.start(); StopWatch watch = new StopWatch(); do { if (rows.isEmpty()) { if (waitMessage) { printer().println("Waiting for logs ..."); waitMessage = false; } Thread.sleep(500); updatePids(rows); } else { waitMessage = true; if (watch.taken() > 500) { // check for new logs updatePids(rows); watch.restart(); } int lines = readLogFiles(rows); if (lines > 0) { dumpLogFiles(rows, 0); } else { Thread.sleep(100); } } } while (running.get()); } return 0; } private void updatePids(Map<Long, Row> rows) { List<Long> pids = findPids(name); ProcessHandle.allProcesses() .filter(ph -> pids.contains(ph.pid())) .forEach(ph -> { JsonObject root = loadStatus(ph.pid()); if (root != null) { Row row = new Row(); row.pid = Long.toString(ph.pid()); JsonObject context = (JsonObject) root.get("context"); if (context == null) { return; } row.name = context.getString("name"); if ("CamelJBang".equals(row.name)) { row.name = ProcessHelper.extractName(root, ph); } int len = row.name.length(); if (len < NAME_MIN_WIDTH) { len = NAME_MIN_WIDTH; } if (len > NAME_MAX_WIDTH) { len = NAME_MAX_WIDTH; } if (len > nameMaxWidth) { nameMaxWidth = len; } if (!rows.containsKey(ph.pid())) { rows.put(ph.pid(), row); } } }); // remove pids that are no long active from the rows Set<Long> remove = new HashSet<>(); for (long pid : rows.keySet()) { if (!pids.contains(pid)) { remove.add(pid); } } for (long pid : remove) { rows.remove(pid); } } private int readLogFiles(Map<Long, Row> rows) throws Exception { int lines = 0; for (Row row : rows.values()) { if (row.reader == null) { Path file = logFile(row.pid); if (Files.exists(file)) { row.reader = new LineNumberReader(Files.newBufferedReader(file)); if (tail == 0) { // only read new lines so forward to end of reader long size = Files.size(file); row.reader.skip(size); } } } if (row.reader != null) { String line; do { try { line = row.reader.readLine(); if (line != null) { line = alignTimestamp(line); boolean valid = true; if (grep != null) { valid = isValidGrep(line); } if (valid) { lines++; // switch fifo to be unlimited as we use it for new log lines if (row.fifo == null || row.fifo instanceof ArrayBlockingQueue) { row.fifo = new ArrayDeque<>(); } row.fifo.offer(line); } } } catch (IOException e) { // ignore line = null; } } while (line != null); } } return lines; } private void dumpLogFiles(Map<Long, Row> rows, int tail) { Set<String> names = new HashSet<>(); List<String> lines = new ArrayList<>(); for (Row row : rows.values()) { Queue<String> queue = row.fifo; if (queue != null) { for (String l : queue) { names.add(row.name); lines.add(row.name + "| " + l); } row.fifo.clear(); } } // only sort if there are multiple Camels running if (names.size() > 1) { // sort lines final SimpleDateFormat sdf = new SimpleDateFormat(TIMESTAMP_MAIN); lines.sort((l1, l2) -> { l1 = unescapeAnsi(l1); l2 = unescapeAnsi(l2); String n1 = StringHelper.before(l1, "| "); String t1 = StringHelper.after(l1, "| "); t1 = StringHelper.before(t1, " "); String n2 = StringHelper.before(l2, "| "); String t2 = StringHelper.after(l2, "| "); t2 = StringHelper.before(t2, " "); // there may be a stacktrace and no timestamps if (t1 != null) { try { sdf.parse(t1); } catch (ParseException e) { t1 = null; } } if (t2 != null) { try { sdf.parse(t2); } catch (ParseException e) { t2 = null; } } if (t1 == null && t2 == null) { return 0; } else if (t1 == null) { return -1; } else if (t2 == null) { return 1; } return t1.compareTo(t2); }); } if (tail > 0) { // cut according to tail int pos = lines.size() - tail; if (pos > 0) { lines = lines.subList(pos, lines.size()); } } lines.forEach(l -> { String name = StringHelper.before(l, "| "); String line = StringHelper.after(l, "| "); printLine(name, rows.size(), line); }); } protected void printLine(String name, int pids, String line) { if (!prefixShown) { // compute whether to show prefix or not if ("false".equals(prefix) || "auto".equals(prefix) && pids <= 1) { name = null; } } prefixShown = name != null; if (!timestamp) { // after timestamp is after 2 sine-space int pos = line.indexOf(' '); pos = line.indexOf(' ', pos + 1); if (pos != -1) { line = line.substring(pos + 1); } } if (loggingColor) { if (name != null) { Ansi.Color color = colors.get(name); if (color == null) { // grab a new color int idx = (colors.size() % 6) + 1; color = Ansi.Color.values()[idx]; colors.put(name, color); } String n = String.format("%-" + nameMaxWidth + "s", name); AnsiConsole.out().print(Ansi.ansi().fg(color).a(n).a("| ").reset()); } } else { line = unescapeAnsi(line); if (name != null) { String n = String.format("%-" + nameMaxWidth + "s", name); printer().print(n); printer().print("| "); } } if (find != null || grep != null) { boolean dashes = line.contains(" --- "); String before = null; String after = line; if (dashes) { before = StringHelper.before(line, "---"); after = StringHelper.after(line, "---", line); } if (find != null) { for (String f : find) { after = after.replaceAll("(?i)" + f, findAnsi); } } if (grep != null) { for (String g : grep) { after = after.replaceAll("(?i)" + g, findAnsi); } } line = before != null ? before + "---" + after : after; } if (loggingColor) { AnsiConsole.out().println(line); } else { printer().println(line); } } private static Path logFile(String pid) { String name = pid + ".log"; Path parent = CommandLineHelper.getCamelDir(); return parent.resolve(name); } private void tailStartupLogFiles(Map<Long, Row> rows) throws Exception { for (Row row : rows.values()) { Path log = logFile(row.pid); if (Files.exists(log)) { row.fifo = new ArrayDeque<>(); row.reader = new LineNumberReader(Files.newBufferedReader(log)); String line; do { line = row.reader.readLine(); if (line != null) { row.fifo.offer(line); boolean found = line.contains("AbstractCamelContext") && line.contains("Apache Camel ") && line.contains(" started in ") && line.contains("(build:"); if (found) { line = null; } } } while (line != null); } } } private void tailLogFiles(Map<Long, Row> rows, int tail, Date limit) throws Exception { for (Row row : rows.values()) { Path log = logFile(row.pid); if (Files.exists(log)) { row.reader = new LineNumberReader(Files.newBufferedReader(log)); String line; if (tail <= 0) { row.fifo = new ArrayDeque<>(); } else { row.fifo = new ArrayBlockingQueue<>(tail); } do { line = row.reader.readLine(); if (line != null) { line = alignTimestamp(line); boolean valid = isValidSince(limit, line); if (valid && grep != null) { valid = isValidGrep(line); } if (valid) { while (!row.fifo.offer(line)) { row.fifo.poll(); } } } } while (line != null); } } } private String alignTimestamp(String line) { // if using spring boot then adjust the timestamp to uniform camel-main style String ts = StringHelper.before(line, " "); if (ts != null && ts.contains("T")) { SimpleDateFormat sdf = new SimpleDateFormat(TIMESTAMP_SB); try { // the log can be in color or not so we need to unescape always sdf.parse(unescapeAnsi(ts)); int dot = ts.indexOf('.'); if (dot != -1) { int pos1 = dot + 3; // skip millis and timezone int pos2 = dot + 9; if (pos2 < ts.length()) { ts = ts.substring(0, pos1) + ts.substring(pos2); String after = StringHelper.after(line, " "); ts = ts.replace('T', ' '); return ts + " " + after; } } } catch (Exception e) { // ignore } } return line; } private boolean isValidSince(Date limit, String line) { if (limit == null) { return true; } // the log can be in color or not so we need to unescape always line = unescapeAnsi(line); String ts = StringHelper.before(line, " "); if (ts != null && !ts.isBlank()) { SimpleDateFormat sdf = new SimpleDateFormat(TIMESTAMP_MAIN); try { Date row = sdf.parse(ts); return row.compareTo(limit) >= 0; } catch (ParseException e) { // ignore } } return false; } private boolean isValidGrep(String line) { if (grep == null) { return true; } // the log can be in color or not so we need to unescape always line = unescapeAnsi(line); String after = StringHelper.after(line, "---", line); for (String g : grep) { boolean m = Pattern.compile("(?i)" + g).matcher(after).find(); if (m) { return true; } } return false; } private String unescapeAnsi(String line) { // unescape ANSI colors StringBuilder sb = new StringBuilder(); boolean escaping = false; char[] arr = line.toCharArray(); for (int i = 0; i < arr.length; i++) { char ch = arr[i]; if (escaping) { if (ch == 'm') { escaping = false; } continue; } char ch2 = i < arr.length - 1 ? arr[i + 1] : 0; if (ch == 27 && ch2 == '[') { escaping = true; continue; } sb.append(ch); } return sb.toString(); } private static
PrefixCompletionCandidates
java
apache__camel
components/camel-openstack/src/generated/java/org/apache/camel/component/openstack/swift/SwiftEndpointConfigurer.java
{ "start": 742, "end": 3857 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { SwiftEndpoint target = (SwiftEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": target.setApiVersion(property(camelContext, java.lang.String.class, value)); return true; case "config": target.setConfig(property(camelContext, org.openstack4j.core.transport.Config.class, value)); return true; case "domain": target.setDomain(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "operation": target.setOperation(property(camelContext, java.lang.String.class, value)); return true; case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true; case "project": target.setProject(property(camelContext, java.lang.String.class, value)); return true; case "subsystem": target.setSubsystem(property(camelContext, java.lang.String.class, value)); return true; case "username": target.setUsername(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": return java.lang.String.class; case "config": return org.openstack4j.core.transport.Config.class; case "domain": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "operation": return java.lang.String.class; case "password": return java.lang.String.class; case "project": return java.lang.String.class; case "subsystem": return java.lang.String.class; case "username": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { SwiftEndpoint target = (SwiftEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiversion": case "apiVersion": return target.getApiVersion(); case "config": return target.getConfig(); case "domain": return target.getDomain(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "operation": return target.getOperation(); case "password": return target.getPassword(); case "project": return target.getProject(); case "subsystem": return target.getSubsystem(); case "username": return target.getUsername(); default: return null; } } }
SwiftEndpointConfigurer
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/AbstractStyleNameConverter.java
{ "start": 2260, "end": 3143 }
class ____ extends AbstractStyleNameConverter { /** Black */ protected static final String NAME = "black"; /** * Constructs the converter. This constructor must be public. * * @param formatters The PatternFormatters to generate the text to manipulate. * @param styling The styling that should encapsulate the pattern. */ public Black(final List<PatternFormatter> formatters, final String styling) { super(NAME, formatters, styling); } /** * Gets an instance of the class (called via reflection). * * @param config The current Configuration. * @param options The pattern options, may be null. If the first element is "short", only the first line of the * throwable will be formatted. * @return new instance of
Black
java
apache__camel
components/camel-spring-parent/camel-spring/src/main/java/org/apache/camel/language/spel/RootObject.java
{ "start": 986, "end": 2417 }
class ____ { private final Exchange exchange; public RootObject(Exchange exchange) { this.exchange = exchange; } public Exchange getExchange() { return exchange; } public CamelContext getContext() { return exchange.getContext(); } public Throwable getException() { return exchange.getException(); } public String getExchangeId() { return exchange.getExchangeId(); } public Object getBody() { return exchange.getIn().getBody(); } public Message getRequest() { return exchange.getIn(); } public Message getMessage() { return exchange.getMessage(); } @Deprecated public Message getResponse() { return exchange.getOut(); } public Map<String, Object> getProperties() { return exchange.getAllProperties(); } public Object getProperty(String name) { return exchange.getProperty(name); } public <T> T getProperty(String name, Class<T> type) { return exchange.getProperty(name, type); } public Map<String, Object> getHeaders() { return exchange.getMessage().getHeaders(); } public Object getHeader(String name) { return exchange.getMessage().getHeader(name); } public <T> T getHeader(String name, Class<T> type) { return exchange.getMessage().getHeader(name, type); } }
RootObject
java
spring-projects__spring-boot
module/spring-boot-freemarker/src/test/java/org/springframework/boot/freemarker/autoconfigure/FreeMarkerAutoConfigurationTests.java
{ "start": 1730, "end": 4224 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); @Test @WithResource(name = "templates/message.ftlh", content = "Message: ${greeting}") void renderNonWebAppTemplate() { this.contextRunner.run((context) -> { freemarker.template.Configuration freemarker = context.getBean(freemarker.template.Configuration.class); StringWriter writer = new StringWriter(); freemarker.getTemplate("message.ftlh").process(new DataModel(), writer); assertThat(writer.toString()).contains("Hello World"); }); } @Test void nonExistentTemplateLocation(CapturedOutput output) { this.contextRunner .withPropertyValues("spring.freemarker.templateLoaderPath:" + "classpath:/does-not-exist/,classpath:/also-does-not-exist") .run((context) -> assertThat(output).contains("Cannot find template location")); } @Test void emptyTemplateLocation(CapturedOutput output, @TempDir Path tempDir) { this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:file:" + tempDir.toAbsolutePath()) .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test void nonExistentLocationAndEmptyLocation(CapturedOutput output, @TempDir Path tempDir) { this.contextRunner .withPropertyValues("spring.freemarker.templateLoaderPath:" + "classpath:/does-not-exist/,file:" + tempDir.toAbsolutePath()) .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test void variableCustomizerShouldBeApplied() { FreeMarkerVariablesCustomizer customizer = mock(FreeMarkerVariablesCustomizer.class); this.contextRunner.withBean(FreeMarkerVariablesCustomizer.class, () -> customizer) .run((context) -> then(customizer).should().customizeFreeMarkerVariables(any())); } @Test @SuppressWarnings("unchecked") void variableCustomizersShouldBeAppliedInOrder() { this.contextRunner.withUserConfiguration(VariablesCustomizersConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(freemarker.template.Configuration.class); freemarker.template.Configuration configuration = context.getBean(freemarker.template.Configuration.class); assertThat(configuration.getSharedVariableNames()).contains("order", "one", "two"); assertThat(configuration.getSharedVariable("order")).hasToString("5"); }); } public static
FreeMarkerAutoConfigurationTests
java
apache__camel
components/camel-platform-http-vertx/src/main/java/org/apache/camel/component/platform/http/vertx/VertxPlatformHttpServerConfiguration.java
{ "start": 4303, "end": 8008 }
class ____ { private boolean enabled; private SessionStoreType storeType = SessionStoreType.LOCAL; private String sessionCookieName = SessionHandler.DEFAULT_SESSION_COOKIE_NAME; private String sessionCookiePath = SessionHandler.DEFAULT_SESSION_COOKIE_PATH; private long sessionTimeOut = SessionHandler.DEFAULT_SESSION_TIMEOUT; private boolean cookieSecure = SessionHandler.DEFAULT_COOKIE_SECURE_FLAG; private boolean cookieHttpOnly = SessionHandler.DEFAULT_COOKIE_HTTP_ONLY_FLAG; private int sessionIdMinLength = SessionHandler.DEFAULT_SESSIONID_MIN_LENGTH; private CookieSameSite cookieSameSite = CookieSameSite.STRICT; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public SessionStoreType getStoreType() { return this.storeType; } public void setStoreType(SessionStoreType storeType) { this.storeType = storeType; } public String getSessionCookieName() { return this.sessionCookieName; } public void setSessionCookieName(String sessionCookieName) { this.sessionCookieName = sessionCookieName; } public String getSessionCookiePath() { return this.sessionCookiePath; } public void setSessionCookiePath(String sessionCookiePath) { this.sessionCookiePath = sessionCookiePath; } public long getSessionTimeOut() { return this.sessionTimeOut; } public void setSessionTimeout(long timeout) { this.sessionTimeOut = timeout; } public boolean isCookieSecure() { return this.cookieSecure; } // Instructs browsers to only send the cookie over HTTPS when set. public void setCookieSecure(boolean cookieSecure) { this.cookieSecure = cookieSecure; } public boolean isCookieHttpOnly() { return this.cookieHttpOnly; } // Instructs browsers to prevent Javascript access to the cookie. // Defends against XSS attacks. public void setCookieHttpOnly(boolean cookieHttpOnly) { this.cookieHttpOnly = cookieHttpOnly; } public int getSessionIdMinLength() { return this.sessionIdMinLength; } public void setSessionIdMinLength(int sessionIdMinLength) { this.sessionIdMinLength = sessionIdMinLength; } public CookieSameSite getCookieSameSite() { return this.cookieSameSite; } public void setCookieSameSite(CookieSameSite cookieSameSite) { this.cookieSameSite = cookieSameSite; } public SessionHandler createSessionHandler(Vertx vertx) { SessionStore sessionStore = storeType.create(vertx); SessionHandler handler = SessionHandler.create(sessionStore); configure(handler); return handler; } private void configure(SessionHandler handler) { handler.setSessionTimeout(this.sessionTimeOut) .setSessionCookieName(this.sessionCookieName) .setSessionCookiePath(this.sessionCookiePath) .setSessionTimeout(this.sessionTimeOut) .setCookieHttpOnlyFlag(this.cookieHttpOnly) .setCookieSecureFlag(this.cookieSecure) .setMinLength(this.sessionIdMinLength) .setCookieSameSite(this.cookieSameSite); } } public
SessionConfig
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/querycache/CriteriaQueryCacheNormalResultTransformerTest.java
{ "start": 209, "end": 400 }
class ____ extends CriteriaQueryCachePutResultTransformerTest { @Override protected CacheMode getQueryCacheMode() { return CacheMode.NORMAL; } }
CriteriaQueryCacheNormalResultTransformerTest
java
google__guava
guava/src/com/google/common/collect/RegularImmutableMap.java
{ "start": 13097, "end": 14019 }
class ____<K> extends IndexedImmutableSet<K> { private final RegularImmutableMap<K, ?> map; KeySet(RegularImmutableMap<K, ?> map) { this.map = map; } @Override K get(int index) { return map.entries[index].getKey(); } @Override public boolean contains(@Nullable Object object) { return map.containsKey(object); } @Override boolean isPartialView() { return true; } @Override public int size() { return map.size(); } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible @GwtIncompatible Object writeReplace() { return super.writeReplace(); } // No longer used for new writes, but kept so that old data can still be read. @GwtIncompatible @J2ktIncompatible @SuppressWarnings("unused") private static final
KeySet
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/internal/JmxUtil.java
{ "start": 1191, "end": 1380 }
class ____ { public static boolean isJmxDisabled() { return PropertiesUtil.getProperties().getBooleanProperty("log4j2.disable.jmx", true); } private JmxUtil() {} }
JmxUtil
java
apache__flink
flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/SqlClientSSLTest.java
{ "start": 1518, "end": 4506 }
class ____ extends SqlClientTestBase { @RegisterExtension @Order(1) public static final SqlGatewayServiceExtension SQL_GATEWAY_SERVICE_EXTENSION = new SqlGatewayServiceExtension(Configuration::new); @RegisterExtension @Order(2) private static final SqlGatewayRestEndpointExtension SQL_GATEWAY_REST_ENDPOINT_EXTENSION = new SqlGatewayRestEndpointExtension( SQL_GATEWAY_SERVICE_EXTENSION::getService, SqlClientSSLTest::withSSL); private static final String truststorePath = getTestResource("ssl/local127.truststore"); private static final String keystorePath = getTestResource("ssl/local127.keystore"); @Test void testEmbeddedMode() throws Exception { String[] args = new String[] {"embedded"}; String actual = runSqlClient(args, String.join("\n", "SET;", "QUIT;"), false); assertThat(actual).contains(SecurityOptions.SSL_REST_ENABLED.key(), "true"); } @Test void testGatewayMode() throws Exception { String[] args = new String[] { "gateway", "-e", String.format( "%s:%d", SQL_GATEWAY_REST_ENDPOINT_EXTENSION.getTargetAddress(), SQL_GATEWAY_REST_ENDPOINT_EXTENSION.getTargetPort()) }; String actual = runSqlClient(args, String.join("\n", "SET;", "QUIT;"), false); assertThat(actual).contains(SecurityOptions.SSL_REST_ENABLED.key(), "true"); } private static void withSSL(Configuration configuration) { configuration.set(SecurityOptions.SSL_REST_ENABLED, true); configuration.set(SecurityOptions.SSL_REST_TRUSTSTORE, truststorePath); configuration.set(SecurityOptions.SSL_REST_TRUSTSTORE_PASSWORD, "password"); configuration.set(SecurityOptions.SSL_REST_KEYSTORE, keystorePath); configuration.set(SecurityOptions.SSL_REST_KEYSTORE_PASSWORD, "password"); configuration.set(SecurityOptions.SSL_REST_KEY_PASSWORD, "password"); } @Override protected void writeConfigOptionsToConfYaml(Path confYamlPath) throws IOException { Configuration configuration = new Configuration(); withSSL(configuration); Files.write( confYamlPath, configuration.toMap().entrySet().stream() .map(entry -> entry.getKey() + ": " + entry.getValue()) .collect(Collectors.toList())); } private static String getTestResource(final String fileName) { final ClassLoader classLoader = ClassLoader.getSystemClassLoader(); final URL resource = classLoader.getResource(fileName); if (resource == null) { throw new IllegalArgumentException( String.format("Test resource %s does not exist", fileName)); } return resource.getFile(); } }
SqlClientSSLTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orphan/one2one/OneToOneProxyOrphanRemovalTest.java
{ "start": 2607, "end": 2870 }
class ____ { private Integer id; private String name; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } @Entity(name = "Parent") public static
Child
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/http/DefaultFilterChainValidatorTests.java
{ "start": 2959, "end": 7379 }
class ____ { private DefaultFilterChainValidator validator; private FilterChainProxy chain; private FilterChainProxy chainAuthorizationFilter; @Mock private Log logger; @Mock private DefaultFilterInvocationSecurityMetadataSource metadataSource; @Mock private AccessDecisionManager accessDecisionManager; private FilterSecurityInterceptor authorizationInterceptor; @Mock private AuthorizationManager<HttpServletRequest> authorizationManager; private AuthorizationFilter authorizationFilter; @BeforeEach public void setUp() { AnonymousAuthenticationFilter aaf = new AnonymousAuthenticationFilter("anonymous"); this.authorizationInterceptor = new FilterSecurityInterceptor(); this.authorizationInterceptor.setAccessDecisionManager(this.accessDecisionManager); this.authorizationInterceptor.setSecurityMetadataSource(this.metadataSource); this.authorizationFilter = new AuthorizationFilter(this.authorizationManager); AuthenticationEntryPoint authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint("/login"); ExceptionTranslationFilter etf = new ExceptionTranslationFilter(authenticationEntryPoint); DefaultSecurityFilterChain securityChain = new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, aaf, etf, this.authorizationInterceptor); this.chain = new FilterChainProxy(securityChain); DefaultSecurityFilterChain securityChainAuthorizationFilter = new DefaultSecurityFilterChain( AnyRequestMatcher.INSTANCE, aaf, etf, this.authorizationFilter); this.chainAuthorizationFilter = new FilterChainProxy(securityChainAuthorizationFilter); this.validator = new DefaultFilterChainValidator(); ReflectionTestUtils.setField(this.validator, "logger", this.logger); } @Test void validateWhenFilterSecurityInterceptorConfiguredThenValidates() { assertThatNoException().isThrownBy(() -> this.validator.validate(this.chain)); } // SEC-1878 @SuppressWarnings("unchecked") @Test public void validateCheckLoginPageIsntProtectedThrowsIllegalArgumentException() { IllegalArgumentException toBeThrown = new IllegalArgumentException("failed to eval expression"); willThrow(toBeThrown).given(this.accessDecisionManager) .decide(any(Authentication.class), any(), any(Collection.class)); this.validator.validate(this.chain); verify(this.logger).info( "Unable to check access to the login page to determine if anonymous access is allowed. This might be an error, but can happen under normal circumstances.", toBeThrown); } @Test public void validateCheckLoginPageAllowsAnonymous() { given(this.authorizationManager.authorize(any(), any())).willReturn(new AuthorizationDecision(false)); this.validator.validate(this.chainAuthorizationFilter); verify(this.logger).warn("Anonymous access to the login page doesn't appear to be enabled. " + "This is almost certainly an error. Please check your configuration allows unauthenticated " + "access to the configured login page. (Simulated access was rejected)"); } // SEC-1957 @Test public void validateCustomMetadataSource() { FilterInvocationSecurityMetadataSource customMetaDataSource = mock( FilterInvocationSecurityMetadataSource.class); this.authorizationInterceptor.setSecurityMetadataSource(customMetaDataSource); this.validator.validate(this.chain); verify(customMetaDataSource, atLeastOnce()).getAttributes(any()); } @Test void validateWhenSameRequestMatchersArePresentThenUnreachableFilterChainException() { PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults(); AnonymousAuthenticationFilter authenticationFilter = mock(AnonymousAuthenticationFilter.class); ExceptionTranslationFilter exceptionTranslationFilter = mock(ExceptionTranslationFilter.class); SecurityFilterChain chain1 = new DefaultSecurityFilterChain(builder.matcher("/api"), authenticationFilter, exceptionTranslationFilter, this.authorizationInterceptor); SecurityFilterChain chain2 = new DefaultSecurityFilterChain(builder.matcher("/api"), authenticationFilter, exceptionTranslationFilter, this.authorizationInterceptor); List<SecurityFilterChain> chains = new ArrayList<>(); chains.add(chain2); chains.add(chain1); FilterChainProxy proxy = new FilterChainProxy(chains); assertThatExceptionOfType(UnreachableFilterChainException.class) .isThrownBy(() -> this.validator.validate(proxy)); } }
DefaultFilterChainValidatorTests
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/parallel/ParallelTransformer.java
{ "start": 917, "end": 1362 }
interface ____<@NonNull Upstream, @NonNull Downstream> { /** * Applies a function to the upstream ParallelFlowable and returns a ParallelFlowable with * optionally different element type. * @param upstream the upstream ParallelFlowable instance * @return the transformed ParallelFlowable instance */ @NonNull ParallelFlowable<Downstream> apply(@NonNull ParallelFlowable<Upstream> upstream); }
ParallelTransformer
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/ClientStreamListener.java
{ "start": 2138, "end": 2575 }
enum ____ { /** * The RPC may have been processed by the server. */ PROCESSED, /** * Some part of the RPC may have been sent, but the server has guaranteed it didn't process any * part of the RPC. */ REFUSED, /** * The RPC is dropped (by load balancer). */ DROPPED, /** * The stream is closed even before anything leaves the client. */ MISCARRIED } }
RpcProgress
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/proxy/CallableStatementProxyImplTest.java
{ "start": 1358, "end": 5279 }
class ____ extends TestCase { protected void tearDown() throws Exception { DruidDriver.getProxyDataSources().clear(); assertEquals(0, JdbcStatManager.getInstance().getSqlList().size()); } public void test_call() throws Exception { DataSourceProxyConfig config = new DataSourceProxyConfig(); DataSourceProxy dataSource = new DataSourceProxyImpl(null, config); FilterEventAdapter filter = new FilterEventAdapter() { }; filter.init(dataSource); config.getFilters().add(filter); String sql = "CALL P_0(?, ?)"; CallableStatementProxyImpl rawCallStatement = new FakeCallableStatement(new ConnectionProxyImpl(null, null, null, 0), null, sql, 1001); ConnectionProxy connection = new ConnectionProxyImpl(dataSource, null, new Properties(), 1001); CallableStatementProxyImpl cstmt = new CallableStatementProxyImpl(connection, rawCallStatement, sql, 2001); cstmt.registerOutParameter(1, Types.VARCHAR); cstmt.registerOutParameter(1, Types.VARCHAR, "VARCHAR"); cstmt.registerOutParameter(1, Types.VARCHAR, 3); cstmt.registerOutParameter("1", Types.VARCHAR); cstmt.registerOutParameter("1", Types.VARCHAR, "VARCHAR"); cstmt.registerOutParameter("1", Types.VARCHAR, 3); cstmt.setBoolean("1", true); cstmt.setByte("1", (byte) 0); cstmt.setShort("1", (short) 0); cstmt.setInt("1", 0); cstmt.setLong("1", 0); cstmt.setFloat("1", 0); cstmt.setDouble("1", 0); cstmt.setBigDecimal("1", new BigDecimal("111")); cstmt.setString("1", "X"); cstmt.setURL("1", null); cstmt.setSQLXML("1", null); cstmt.setBytes("1", null); cstmt.setDate("1", null); cstmt.setDate("1", null, Calendar.getInstance()); cstmt.setTime("1", null); cstmt.setTime("1", null, Calendar.getInstance()); cstmt.setTimestamp("1", null); cstmt.setTimestamp("1", null, Calendar.getInstance()); cstmt.setAsciiStream("1", null); cstmt.setAsciiStream("1", null, 0); cstmt.setAsciiStream("1", null, 0L); cstmt.setBinaryStream("1", null); cstmt.setBinaryStream("1", null, 0); cstmt.setBinaryStream("1", null, 0L); cstmt.setObject("1", null); cstmt.setObject("1", null, Types.VARCHAR); cstmt.setObject("1", null, Types.VARCHAR, 3); cstmt.setCharacterStream("1", null); cstmt.setCharacterStream("1", null, 0); cstmt.setCharacterStream("1", null, 0L); cstmt.setNull("1", Types.VARCHAR); cstmt.setNull("1", Types.VARCHAR, "VARCHAR"); cstmt.setRowId("1", null); cstmt.setNString("1", null); cstmt.setNCharacterStream("1", null); cstmt.setNCharacterStream("1", null, 0); cstmt.setNClob("1", (NClob) null); cstmt.setNClob("1", (Reader) null); cstmt.setNClob("1", (Reader) null, 0); cstmt.setClob("1", (Clob) null); cstmt.setClob("1", (Reader) null); cstmt.setClob("1", (Reader) null, 0); cstmt.setBlob("1", (Blob) null); cstmt.setBlob("1", (InputStream) null); cstmt.setBlob("1", (InputStream) null, 0); cstmt.setURL(1, null); cstmt.setSQLXML(1, null); cstmt.setArray(1, null); cstmt.setNCharacterStream(1, null); cstmt.setNCharacterStream(1, null, 0); cstmt.setNClob(1, (NClob) null); cstmt.setNClob(1, (Reader) null); cstmt.setNClob(1, (Reader) null, 0); cstmt.setNString(1, null); cstmt.setObject(1, null); cstmt.setRef(1, null); cstmt.setRowId(1, null); cstmt.setUnicodeStream(1, null, 0); cstmt.getClob(1); cstmt.getClob("1"); cstmt.cancel(); cstmt.getResultSet(); } private static final
CallableStatementProxyImplTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestRPCCompatibility.java
{ "start": 3091, "end": 3403 }
class ____ extends TestImpl0 implements TestProtocol1 { @Override public String echo(String value) { return value; } @Override public long getProtocolVersion(String protocol, long clientVersion) throws IOException { return TestProtocol1.versionID; } } public static
TestImpl1
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MethodCanBeStaticTest.java
{ "start": 2450, "end": 2915 }
class ____ { public int f(int x) { return x; } private int a(int x) { return b(x) + f(x); } private int b(int x) { return a(x) + f(x); } } """) .doTest(); } @Test public void positiveChain() { refactoringHelper .addInputLines( "Test.java", """
Test
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupBuilder.java
{ "start": 56144, "end": 56673 }
class ____ [" + targetCanonicalClassName + "] must have exactly one constructor"); } Class<?>[] constructorParameterTypes = javaConstructor.getParameterTypes(); for (int typeParameterIndex = 0; typeParameterIndex < constructorParameterTypes.length; ++typeParameterIndex) { Class<?> typeParameter = typeParameters.get(typeParameterIndex); if (isValidType(typeParameter) == false) { throw lookupException( "type parameter [%s] not found for
binding
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webmvc/src/test/java/org/springframework/cloud/gateway/server/mvc/filter/BodyFilterFunctionsTests.java
{ "start": 3511, "end": 4433 }
class ____ { @Bean public RouterFunction<ServerResponse> gatewayRouterFunctionsModifyResponseBodySimple() { // @formatter:off return route("modify_response_body_simple") .GET("/anything/modifyresponsebodysimple", http()) .before(new HttpbinUriResolver()) .after(modifyResponseBody(String.class, String.class, null, (request, response, s) -> s.replace("fooval", "FOOVAL"))) .build(); // @formatter:on } @Bean public RouterFunction<ServerResponse> gatewayRouterFunctionsModifyResponseBodyComplex() { // @formatter:off return route("modify_response_body_simple") .GET("/deny", http()) .before(new HttpbinUriResolver()) .after(modifyResponseBody(String.class, Message.class, MediaType.APPLICATION_JSON_VALUE, (request, response, s) -> new Message(s))) .build(); // @formatter:on } } record Message(String message) { } }
TestConfiguration
java
quarkusio__quarkus
core/launcher/src/main/java/io/quarkus/launcher/JBangIntegration.java
{ "start": 4989, "end": 5621 }
class ____ return null; } return super.getResource(name); } @Override public Enumeration<URL> getResources(String name) throws IOException { if (name.startsWith("org/") && !(name.startsWith("org/xml/") || name.startsWith("org/w3c/") || name.startsWith("org/jboss/"))) { //jbang has some but not all the maven resolver classes we need on its //
path
java
apache__camel
components/camel-aws/camel-aws2-sts/src/test/java/org/apache/camel/component/aws2/sts/STS2ComponentClientRegistryTest.java
{ "start": 1129, "end": 2512 }
class ____ extends CamelTestSupport { @Test public void createEndpointWithMinimalSTSClientConfiguration() throws Exception { AmazonSTSClientMock clientMock = new AmazonSTSClientMock(); context.getRegistry().bind("amazonStsClient", clientMock); STS2Component component = context.getComponent("aws2-sts", STS2Component.class); STS2Endpoint endpoint = (STS2Endpoint) component.createEndpoint("aws2-sts://TestDomain"); assertNotNull(endpoint.getConfiguration().getStsClient()); } @Test public void createEndpointWithMinimalSTSClientMisconfiguration() { STS2Component component = context.getComponent("aws2-sts", STS2Component.class); assertThrows(IllegalArgumentException.class, () -> { component.createEndpoint("aws2-sts://TestDomain"); }); } @Test public void createEndpointWithAutowire() throws Exception { AmazonSTSClientMock clientMock = new AmazonSTSClientMock(); context.getRegistry().bind("amazonStsClient", clientMock); STS2Component component = context.getComponent("aws2-sts", STS2Component.class); STS2Endpoint endpoint = (STS2Endpoint) component.createEndpoint("aws2-sts://TestDomain?accessKey=xxx&secretKey=yyy"); assertSame(clientMock, endpoint.getConfiguration().getStsClient()); } }
STS2ComponentClientRegistryTest
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/interceptor/RollbackRuleAttribute.java
{ "start": 5327, "end": 6303 }
class ____ * @throws IllegalArgumentException if the supplied {@code exceptionPattern} * is {@code null} or empty */ public RollbackRuleAttribute(String exceptionPattern) { Assert.hasText(exceptionPattern, "'exceptionPattern' cannot be null or empty"); this.exceptionPattern = exceptionPattern; this.exceptionType = null; } /** * Get the configured exception name pattern that this rule uses for matching. * @see #getDepth(Throwable) */ public String getExceptionName() { return this.exceptionPattern; } /** * Return the depth of the superclass matching, with the following semantics. * <ul> * <li>{@code -1} means this rule does not match the supplied {@code exception}.</li> * <li>{@code 0} means this rule matches the supplied {@code exception} directly.</li> * <li>Any other positive value means this rule matches the supplied {@code exception} * within the superclass hierarchy, where the value is the number of levels in the *
name
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DataFormatEndpointBuilderFactory.java
{ "start": 4418, "end": 6440 }
interface ____ { /** * Data Format (camel-dataformat) * Use a Camel Data Format as a regular Camel Component. * * Category: core,transformation * Since: 2.12 * Maven coordinates: org.apache.camel:camel-dataformat * * Syntax: <code>dataformat:name:operation</code> * * Path parameter: name (required) * Name of data format * * Path parameter: operation (required) * Operation to use either marshal or unmarshal * There are 2 enums and the value can be one of: marshal, unmarshal * * @param path name:operation * @return the dsl builder */ default DataFormatEndpointBuilder dataformat(String path) { return DataFormatEndpointBuilderFactory.endpointBuilder("dataformat", path); } /** * Data Format (camel-dataformat) * Use a Camel Data Format as a regular Camel Component. * * Category: core,transformation * Since: 2.12 * Maven coordinates: org.apache.camel:camel-dataformat * * Syntax: <code>dataformat:name:operation</code> * * Path parameter: name (required) * Name of data format * * Path parameter: operation (required) * Operation to use either marshal or unmarshal * There are 2 enums and the value can be one of: marshal, unmarshal * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path name:operation * @return the dsl builder */ default DataFormatEndpointBuilder dataformat(String componentName, String path) { return DataFormatEndpointBuilderFactory.endpointBuilder(componentName, path); } } static DataFormatEndpointBuilder endpointBuilder(String componentName, String path) {
DataFormatBuilders
java
apache__flink
flink-python/src/main/java/org/apache/flink/table/runtime/arrow/vectors/ArrowSmallIntColumnVector.java
{ "start": 1125, "end": 1584 }
class ____ implements ShortColumnVector { private final SmallIntVector smallIntVector; public ArrowSmallIntColumnVector(SmallIntVector smallIntVector) { this.smallIntVector = Preconditions.checkNotNull(smallIntVector); } @Override public short getShort(int i) { return smallIntVector.get(i); } @Override public boolean isNullAt(int i) { return smallIntVector.isNull(i); } }
ArrowSmallIntColumnVector
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest17.java
{ "start": 1025, "end": 2270 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "CREATE TABLE t1 (" + " ts TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6)" + ");"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); statemen.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("t1"))); assertTrue(visitor.getColumns().contains(new Column("t1", "ts"))); } }
MySqlCreateTableTest17
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GrpcEndpointBuilderFactory.java
{ "start": 79161, "end": 80684 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final GrpcHeaderNameBuilder INSTANCE = new GrpcHeaderNameBuilder(); /** * Method name handled by the consumer service. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code GrpcMethodName}. */ public String grpcMethodName() { return "CamelGrpcMethodName"; } /** * If provided, the given agent will prepend the gRPC library's user * agent information. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code GrpcUserAgent}. */ public String grpcUserAgent() { return "CamelGrpcUserAgent"; } /** * Received event type from the sent request. Possible values: onNext * onCompleted onError. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code GrpcEventType}. */ public String grpcEventType() { return "CamelGrpcEventType"; } } static GrpcEndpointBuilder endpointBuilder(String componentName, String path) {
GrpcHeaderNameBuilder
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/api/QueryOperationTestPrograms.java
{ "start": 80946, "end": 82634 }
class ____ extends ScalarFunction { public Integer eval(Integer i) { return i + 1; } } static final TableTestProgram INLINE_FUNCTION_SERIALIZATION = TableTestProgram.of( "inline-function-serialization", "verifies SQL serialization of inline functions") .setupTableSource( SourceTestStep.newBuilder("t") .addSchema("a INT", "b INT") .producedValues(Row.of(1, 1), Row.of(2, 2)) .build()) .setupTableSink( SinkTestStep.newBuilder("sink") .addSchema("a INT", "b INT") .consumedValues(Row.of(2, 1), Row.of(3, 2)) .build()) .runSql( "SELECT (inlineFunction$00(`$$T_PROJECT`.`a`)) AS `_c0`, `$$T_PROJECT`.`b` FROM (\n" + " SELECT `$$T_SOURCE`.`a`, `$$T_SOURCE`.`b` FROM `default_catalog`.`default_database`.`t` $$T_SOURCE\n" + ") $$T_PROJECT") .runTableApi( env -> env.from("t") .select( call(new SimpleScalarFunction(), $("a")), $("b")), "sink") .build(); }
SimpleScalarFunction
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/SettableAnyProperty.java
{ "start": 12172, "end": 13221 }
class ____ extends SettableAnyProperty { public MethodAnyProperty(BeanProperty property, AnnotatedMember field, JavaType valueType, KeyDeserializer keyDeser, ValueDeserializer<Object> valueDeser, TypeDeserializer typeDeser) { super(property, field, valueType, keyDeser, valueDeser, typeDeser); } @Override protected void _set(DeserializationContext ctxt, Object instance, Object propName, Object value) throws Exception { // note: cannot use 'setValue()' due to taking 2 args ((AnnotatedMethod) _setter).callOnWith(instance, propName, value); } @Override public SettableAnyProperty withValueDeserializer(ValueDeserializer<Object> deser) { return new MethodAnyProperty(_property, _setter, _type, _keyDeserializer, deser, _valueTypeDeserializer); } } /** * @since 2.14 */ protected static
MethodAnyProperty
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/stereotypes/DeeplyTransitiveStereotypesTest.java
{ "start": 879, "end": 1786 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer( Stereotype1.class, Stereotype2.class, Stereotype3.class, Stereotype4.class, Stereotype5.class, Stereotype6.class, Stereotype7.class, MyBean.class); @Test public void test() { InjectableBean<MyBean> bean = Arc.container().instance(MyBean.class).getBean(); assertEquals(RequestScoped.class, bean.getScope()); assertEquals("myBean", bean.getName()); assertTrue(bean.isAlternative()); assertEquals(123, bean.getPriority()); } // stereotype transitivity: // 1 --> 2 // 2 --> 3 // 3 --> 4, 5 // 4 --> 6 // 5 --> 7 @Stereotype2 @Stereotype @Target({ TYPE, METHOD, FIELD }) @Retention(RUNTIME) @
DeeplyTransitiveStereotypesTest
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/functions/AggregateFunction.java
{ "start": 1486, "end": 2271 }
class ____ of {@link ScalarFunction} for the mapping between * {@link DataType} and the JVM type. * <p> * All implementations must support partial aggregation by implementing merge so that Spark can * partially aggregate and shuffle intermediate results, instead of shuffling all rows for an * aggregate. This reduces the impact of data skew and the amount of data shuffled to produce the * result. * <p> * Intermediate aggregation state must be {@link Serializable} so that state produced by parallel * tasks can be serialized, shuffled, and then merged to produce a final result. * * @param <S> the JVM type for the aggregation's intermediate state; must be {@link Serializable} * @param <R> the JVM type of result values * * @since 3.2.0 */ @Evolving public
documentation
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/instrument/classloading/tomcat/package-info.java
{ "start": 19, "end": 116 }
class ____ on Tomcat. */ package org.springframework.instrument.classloading.tomcat;
instrumentation
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/naming/ImplicitIndexNameSource.java
{ "start": 188, "end": 323 }
interface ____ extends ImplicitConstraintNameSource { @Override default Kind kind() { return Kind.INDEX; } }
ImplicitIndexNameSource
java
apache__flink
flink-formats/flink-avro/src/test/java/org/apache/flink/formats/avro/typeutils/AvroTypeExtractionTest.java
{ "start": 2506, "end": 15133 }
class ____ { private static final int PARALLELISM = 4; @RegisterExtension private static final MiniClusterExtension MINI_CLUSTER_RESOURCE = new MiniClusterExtension( new MiniClusterResourceConfiguration.Builder() .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(PARALLELISM) .build()); private File inFile; private String resultPath; private String expected; @BeforeEach public void before(@TempDir java.nio.file.Path tmpDir) throws Exception { resultPath = tmpDir.resolve("out").toUri().toString(); inFile = tmpDir.resolve("in.avro").toFile(); AvroRecordInputFormatTest.writeTestFile(inFile); } @AfterEach public void after() throws Exception { TestBaseUtils.compareResultsByLinesInMemory(expected, resultPath); } @ParameterizedTest @ValueSource(booleans = {true, false}) void testSimpleAvroRead(boolean useMiniCluster, @InjectMiniCluster MiniCluster miniCluster) throws Exception { final StreamExecutionEnvironment env = getExecutionEnvironment(useMiniCluster, miniCluster); Path in = new Path(inFile.getAbsoluteFile().toURI()); AvroInputFormat<User> users = new AvroInputFormat<>(in, User.class); DataStream<User> usersDS = env.createInput(users).map((value) -> value); usersDS.sinkTo( FileSink.forRowFormat(new Path(resultPath), new SimpleStringEncoder<User>()) .build()); env.execute("Simple Avro read job"); expected = "{\"name\": \"Alyssa\", \"favorite_number\": 256, \"favorite_color\": null, " + "\"type_long_test\": null, \"type_double_test\": 123.45, \"type_null_test\": null, " + "\"type_bool_test\": true, \"type_array_string\": [\"ELEMENT 1\", \"ELEMENT 2\"], " + "\"type_array_boolean\": [true, false], \"type_nullable_array\": null, \"type_enum\": \"GREEN\", " + "\"type_map\": {\"KEY 2\": 17554, \"KEY 1\": 8546456}, \"type_fixed\": null, \"type_union\": null, " + "\"type_nested\": {\"num\": 239, \"street\": \"Baker Street\", \"city\": \"London\", " + "\"state\": \"London\", \"zip\": \"NW1 6XE\"}, " + "\"type_bytes\": \"\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\", " + "\"type_date\": \"2014-03-01\", \"type_time_millis\": \"12:12:12\", \"type_time_micros\": \"00:00:00.123456\", " + "\"type_timestamp_millis\": \"2014-03-01T12:12:12.321Z\", " + "\"type_timestamp_micros\": \"1970-01-01T00:00:00.123456Z\", " + "\"type_decimal_bytes\": \"\\u0007Ð\", \"type_decimal_fixed\": [7, -48]}\n" + "{\"name\": \"Charlie\", \"favorite_number\": null, " + "\"favorite_color\": \"blue\", \"type_long_test\": 1337, \"type_double_test\": 1.337, " + "\"type_null_test\": null, \"type_bool_test\": false, \"type_array_string\": [], " + "\"type_array_boolean\": [], \"type_nullable_array\": null, \"type_enum\": \"RED\", \"type_map\": {}, " + "\"type_fixed\": null, \"type_union\": null, " + "\"type_nested\": {\"num\": 239, \"street\": \"Baker Street\", \"city\": \"London\", \"state\": \"London\", " + "\"zip\": \"NW1 6XE\"}, " + "\"type_bytes\": \"\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\", " + "\"type_date\": \"2014-03-01\", \"type_time_millis\": \"12:12:12\", \"type_time_micros\": \"00:00:00.123456\", " + "\"type_timestamp_millis\": \"2014-03-01T12:12:12.321Z\", " + "\"type_timestamp_micros\": \"1970-01-01T00:00:00.123456Z\", " + "\"type_decimal_bytes\": \"\\u0007Ð\", " + "\"type_decimal_fixed\": [7, -48]}\n"; } @ParameterizedTest @ValueSource(booleans = {true, false}) void testSerializeWithAvro(boolean useMiniCluster, @InjectMiniCluster MiniCluster miniCluster) throws Exception { final StreamExecutionEnvironment env = getExecutionEnvironment(useMiniCluster, miniCluster); ((SerializerConfigImpl) env.getConfig().getSerializerConfig()).setForceKryoAvro(true); Path in = new Path(inFile.getAbsoluteFile().toURI()); AvroInputFormat<User> users = new AvroInputFormat<>(in, User.class); DataStream<User> usersDS = env.createInput(users) .map( (MapFunction<User, User>) value -> { Map<CharSequence, Long> ab = new HashMap<>(1); ab.put("hehe", 12L); value.setTypeMap(ab); return value; }); usersDS.sinkTo( FileSink.forRowFormat(new Path(resultPath), new SimpleStringEncoder<User>()) .build()); env.execute("Simple Avro read job"); expected = "{\"name\": \"Alyssa\", \"favorite_number\": 256, \"favorite_color\": null," + " \"type_long_test\": null, \"type_double_test\": 123.45, \"type_null_test\": null," + " \"type_bool_test\": true, \"type_array_string\": [\"ELEMENT 1\", \"ELEMENT 2\"]," + " \"type_array_boolean\": [true, false], \"type_nullable_array\": null, \"type_enum\": \"GREEN\"," + " \"type_map\": {\"hehe\": 12}, \"type_fixed\": null, \"type_union\": null," + " \"type_nested\": {\"num\": 239, \"street\": \"Baker Street\", \"city\": \"London\"," + " \"state\": \"London\", \"zip\": \"NW1 6XE\"}," + " \"type_bytes\": \"\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\", " + "\"type_date\": \"2014-03-01\", \"type_time_millis\": \"12:12:12\", \"type_time_micros\": \"00:00:00.123456\", " + "\"type_timestamp_millis\": \"2014-03-01T12:12:12.321Z\", " + "\"type_timestamp_micros\": \"1970-01-01T00:00:00.123456Z\", " + "\"type_decimal_bytes\": \"\\u0007Ð\", \"type_decimal_fixed\": [7, -48]}\n" + "{\"name\": \"Charlie\", \"favorite_number\": null, " + "\"favorite_color\": \"blue\", \"type_long_test\": 1337, \"type_double_test\": 1.337, " + "\"type_null_test\": null, \"type_bool_test\": false, \"type_array_string\": [], " + "\"type_array_boolean\": [], \"type_nullable_array\": null, \"type_enum\": \"RED\", " + "\"type_map\": {\"hehe\": 12}, \"type_fixed\": null, \"type_union\": null, " + "\"type_nested\": {\"num\": 239, \"street\": \"Baker Street\", \"city\": \"London\", \"state\": \"London\", " + "\"zip\": \"NW1 6XE\"}, " + "\"type_bytes\": \"\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\\u0000\", " + "\"type_date\": \"2014-03-01\", \"type_time_millis\": \"12:12:12\", \"type_time_micros\": \"00:00:00.123456\", " + "\"type_timestamp_millis\": \"2014-03-01T12:12:12.321Z\", " + "\"type_timestamp_micros\": \"1970-01-01T00:00:00.123456Z\", " + "\"type_decimal_bytes\": \"\\u0007Ð\", \"type_decimal_fixed\": [7, -48]}\n"; } @ParameterizedTest @ValueSource(booleans = {true, false}) void testKeySelection(boolean useMiniCluster, @InjectMiniCluster MiniCluster miniCluster) throws Exception { final StreamExecutionEnvironment env = getExecutionEnvironment(useMiniCluster, miniCluster); env.getConfig().enableObjectReuse(); Path in = new Path(inFile.getAbsoluteFile().toURI()); AvroInputFormat<User> users = new AvroInputFormat<>(in, User.class); DataStream<User> usersDS = env.createInput(users); DataStream<Tuple2<String, Integer>> res = usersDS.keyBy(User::getName) .map( (MapFunction<User, Tuple2<String, Integer>>) value -> new Tuple2<>(value.getName().toString(), 1)) .returns(Types.TUPLE(Types.STRING, Types.INT)); res.sinkTo( FileSink.forRowFormat( new Path(resultPath), new SimpleStringEncoder<Tuple2<String, Integer>>()) .build()); env.execute("Avro Key selection"); expected = "(Alyssa,1)\n(Charlie,1)\n"; } @ParameterizedTest @ValueSource(booleans = {true, false}) void testWithAvroGenericSer(boolean useMiniCluster, @InjectMiniCluster MiniCluster miniCluster) throws Exception { final StreamExecutionEnvironment env = getExecutionEnvironment(useMiniCluster, miniCluster); ((SerializerConfigImpl) env.getConfig().getSerializerConfig()).setForceKryoAvro(true); Path in = new Path(inFile.getAbsoluteFile().toURI()); AvroInputFormat<User> users = new AvroInputFormat<>(in, User.class); DataStreamSource<User> usersDS = env.createInput(users); DataStream<Tuple2<String, Integer>> res = usersDS.keyBy(User::getName) .map( (MapFunction<User, Tuple2<String, Integer>>) value -> new Tuple2<>(value.getName().toString(), 1)) .returns(Types.TUPLE(Types.STRING, Types.INT)); res.sinkTo( FileSink.forRowFormat( new Path(resultPath), new SimpleStringEncoder<Tuple2<String, Integer>>()) .build()); env.execute("Avro Key selection"); expected = "(Charlie,1)\n(Alyssa,1)\n"; } @ParameterizedTest @ValueSource(booleans = {true, false}) void testWithKryoGenericSer(boolean useMiniCluster, @InjectMiniCluster MiniCluster miniCluster) throws Exception { final StreamExecutionEnvironment env = getExecutionEnvironment(useMiniCluster, miniCluster); ((SerializerConfigImpl) env.getConfig().getSerializerConfig()).setForceKryoAvro(true); Path in = new Path(inFile.getAbsoluteFile().toURI()); AvroInputFormat<User> users = new AvroInputFormat<>(in, User.class); DataStreamSource<User> usersDS = env.createInput(users); DataStream<Tuple2<String, Integer>> res = usersDS.keyBy(User::getName) .map( (MapFunction<User, Tuple2<String, Integer>>) value -> new Tuple2<>(value.getName().toString(), 1)) .returns(Types.TUPLE(Types.STRING, Types.INT)); res.sinkTo( FileSink.forRowFormat( new Path(resultPath), new SimpleStringEncoder<Tuple2<String, Integer>>()) .build()); env.execute("Avro Key selection"); expected = "(Charlie,1)\n(Alyssa,1)\n"; } private static Stream<Arguments> testField() { return Arrays.stream(new Boolean[] {true, false}) .flatMap( env -> Stream.of( Arguments.of(env, "name"), Arguments.of(env, "type_enum"), Arguments.of(env, "type_double_test"))); } private static StreamExecutionEnvironment getExecutionEnvironment( boolean useMiniCluster, MiniCluster miniCluster) { return useMiniCluster ? new TestStreamEnvironment(miniCluster, PARALLELISM) : StreamExecutionEnvironment.getExecutionEnvironment(); } }
AvroTypeExtractionTest
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/codec/ByteBufferDecoderTests.java
{ "start": 1164, "end": 2825 }
class ____ extends AbstractDecoderTests<ByteBufferDecoder> { private final byte[] fooBytes = "foo".getBytes(StandardCharsets.UTF_8); private final byte[] barBytes = "bar".getBytes(StandardCharsets.UTF_8); ByteBufferDecoderTests() { super(new ByteBufferDecoder()); } @Override @Test protected void canDecode() { assertThat(this.decoder.canDecode(ResolvableType.forClass(ByteBuffer.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); assertThat(this.decoder.canDecode(ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN)).isFalse(); assertThat(this.decoder.canDecode(ResolvableType.forClass(ByteBuffer.class), MimeTypeUtils.APPLICATION_JSON)).isTrue(); } @Override @Test protected void decode() { Flux<DataBuffer> input = Flux.concat( dataBuffer(this.fooBytes), dataBuffer(this.barBytes)); testDecodeAll(input, ByteBuffer.class, step -> step .consumeNextWith(expectByteBuffer(ByteBuffer.wrap(this.fooBytes))) .consumeNextWith(expectByteBuffer(ByteBuffer.wrap(this.barBytes))) .verifyComplete()); } @Override @Test protected void decodeToMono() { Flux<DataBuffer> input = Flux.concat( dataBuffer(this.fooBytes), dataBuffer(this.barBytes)); ByteBuffer expected = ByteBuffer.allocate(this.fooBytes.length + this.barBytes.length); expected.put(this.fooBytes).put(this.barBytes).flip(); testDecodeToMonoAll(input, ByteBuffer.class, step -> step .consumeNextWith(expectByteBuffer(expected)) .verifyComplete()); } private Consumer<ByteBuffer> expectByteBuffer(ByteBuffer expected) { return actual -> assertThat(actual).isEqualTo(expected); } }
ByteBufferDecoderTests
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/MethodOrderer.java
{ "start": 9667, "end": 11017 }
class ____ implements MethodOrderer { private static final Logger logger = LoggerFactory.getLogger(Random.class); static { logger.config(() -> "MethodOrderer.Random default seed: " + RandomOrdererUtils.DEFAULT_SEED); } /** * Property name used to set the random seed used by this * {@code MethodOrderer}: {@value} * * <p>The same property is used by {@link ClassOrderer.Random} for * consistency between the two random orderers. * * <h4>Supported Values</h4> * * <p>Supported values include any string that can be converted to a * {@link Long} via {@link Long#valueOf(String)}. * * <p>If not specified or if the specified value cannot be converted to * a {@link Long}, the default random seed will be used (see the * {@linkplain Random class-level Javadoc} for details). * * @see ClassOrderer.Random */ public static final String RANDOM_SEED_PROPERTY_NAME = RandomOrdererUtils.RANDOM_SEED_PROPERTY_NAME; public Random() { } /** * Order the methods encapsulated in the supplied * {@link MethodOrdererContext} pseudo-randomly. */ @Override public void orderMethods(MethodOrdererContext context) { Collections.shuffle(context.getMethodDescriptors(), new java.util.Random(RandomOrdererUtils.getSeed(context::getConfigurationParameter, logger))); } } }
Random
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/AnnotationsScannerTests.java
{ "start": 26010, "end": 26127 }
interface ____<T extends CharSequence> { @TestAnnotation2 void method(T argument); } }
GenericNonOverrideInterface
java
google__truth
core/src/test/java/com/google/common/truth/IntegerSubjectTest.java
{ "start": 1117, "end": 7939 }
class ____ { @Test @SuppressWarnings("TruthSelfEquals") public void simpleEquality() { assertThat(4).isEqualTo(4); } @Test public void simpleInequality() { assertThat(4).isNotEqualTo(5); } @Test public void equalityWithLongs() { assertThat(0).isEqualTo(0L); expectFailure(whenTesting -> whenTesting.that(0).isNotEqualTo(0L)); } @Test public void equalityFail() { expectFailure(whenTesting -> whenTesting.that(4).isEqualTo(5)); } @SuppressWarnings("SelfAssertion") @Test public void inequalityFail() { expectFailure(whenTesting -> whenTesting.that(4).isNotEqualTo(4)); } @Test public void equalityOfNulls() { assertThat((Integer) null).isEqualTo(null); } @Test public void equalityOfNullsFail_nullActual() { expectFailure(whenTesting -> whenTesting.that((Integer) null).isEqualTo(5)); } @Test public void equalityOfNullsFail_nullExpected() { expectFailure(whenTesting -> whenTesting.that(5).isEqualTo(null)); } @Test public void inequalityOfNulls() { assertThat(4).isNotEqualTo(null); assertThat((Integer) null).isNotEqualTo(4); } @Test public void inequalityOfNullsFail() { expectFailure(whenTesting -> whenTesting.that((Integer) null).isNotEqualTo(null)); } @Test public void overflowOnPrimitives() { assertThat(Long.MIN_VALUE).isNotEqualTo(Integer.MIN_VALUE); assertThat(Long.MAX_VALUE).isNotEqualTo(Integer.MAX_VALUE); assertThat(Integer.MIN_VALUE).isNotEqualTo(Long.MIN_VALUE); assertThat(Integer.MAX_VALUE).isNotEqualTo(Long.MAX_VALUE); assertThat(Integer.MIN_VALUE).isEqualTo((long) Integer.MIN_VALUE); assertThat(Integer.MAX_VALUE).isEqualTo((long) Integer.MAX_VALUE); } @Test public void overflowOnPrimitives_shouldBeEqualAfterCast_min() { expectFailure( whenTesting -> whenTesting.that(Integer.MIN_VALUE).isNotEqualTo((long) Integer.MIN_VALUE)); } @Test public void overflowOnPrimitives_shouldBeEqualAfterCast_max() { expectFailure( whenTesting -> whenTesting.that(Integer.MAX_VALUE).isNotEqualTo((long) Integer.MAX_VALUE)); } @Test public void overflowBetweenIntegerAndLong_shouldBeDifferent_min() { expectFailure(whenTesting -> whenTesting.that(Integer.MIN_VALUE).isEqualTo(Long.MIN_VALUE)); } @Test public void overflowBetweenIntegerAndLong_shouldBeDifferent_max() { expectFailure(whenTesting -> whenTesting.that(Integer.MAX_VALUE).isEqualTo(Long.MAX_VALUE)); } @Test public void isWithinOf() { assertThat(20000).isWithin(0).of(20000); assertThat(20000).isWithin(1).of(20000); assertThat(20000).isWithin(10000).of(20000); assertThat(20000).isWithin(10000).of(30000); assertThat(Integer.MIN_VALUE).isWithin(1).of(Integer.MIN_VALUE + 1); assertThat(Integer.MAX_VALUE).isWithin(1).of(Integer.MAX_VALUE - 1); assertThat(Integer.MAX_VALUE / 2).isWithin(Integer.MAX_VALUE).of(-Integer.MAX_VALUE / 2); assertThat(-Integer.MAX_VALUE / 2).isWithin(Integer.MAX_VALUE).of(Integer.MAX_VALUE / 2); assertThatIsWithinFails(20000, 9999, 30000); assertThatIsWithinFails(20000, 10000, 30001); assertThatIsWithinFails(Integer.MIN_VALUE, 0, Integer.MAX_VALUE); assertThatIsWithinFails(Integer.MAX_VALUE, 0, Integer.MIN_VALUE); assertThatIsWithinFails(Integer.MIN_VALUE, 1, Integer.MIN_VALUE + 2); assertThatIsWithinFails(Integer.MAX_VALUE, 1, Integer.MAX_VALUE - 2); // Don't fall for rollover assertThatIsWithinFails(Integer.MIN_VALUE, 1, Integer.MAX_VALUE); assertThatIsWithinFails(Integer.MAX_VALUE, 1, Integer.MIN_VALUE); } private static void assertThatIsWithinFails(int actual, int tolerance, int expected) { AssertionError e = expectFailure(whenTesting -> whenTesting.that(actual).isWithin(tolerance).of(expected)); assertThat(e).factKeys().containsExactly("expected", "but was", "outside tolerance").inOrder(); assertThat(e).factValue("expected").isEqualTo(formatNumericValue(expected)); assertThat(e).factValue("but was").isEqualTo(formatNumericValue(actual)); assertThat(e).factValue("outside tolerance").isEqualTo(formatNumericValue(tolerance)); } @Test public void isNotWithinOf() { assertThatIsNotWithinFails(20000, 0, 20000); assertThatIsNotWithinFails(20000, 1, 20000); assertThatIsNotWithinFails(20000, 10000, 20000); assertThatIsNotWithinFails(20000, 10000, 30000); assertThatIsNotWithinFails(Integer.MIN_VALUE, 1, Integer.MIN_VALUE + 1); assertThatIsNotWithinFails(Integer.MAX_VALUE, 1, Integer.MAX_VALUE - 1); assertThatIsNotWithinFails(Integer.MAX_VALUE / 2, Integer.MAX_VALUE, -Integer.MAX_VALUE / 2); assertThatIsNotWithinFails(-Integer.MAX_VALUE / 2, Integer.MAX_VALUE, Integer.MAX_VALUE / 2); assertThat(20000).isNotWithin(9999).of(30000); assertThat(20000).isNotWithin(10000).of(30001); assertThat(Integer.MIN_VALUE).isNotWithin(0).of(Integer.MAX_VALUE); assertThat(Integer.MAX_VALUE).isNotWithin(0).of(Integer.MIN_VALUE); assertThat(Integer.MIN_VALUE).isNotWithin(1).of(Integer.MIN_VALUE + 2); assertThat(Integer.MAX_VALUE).isNotWithin(1).of(Integer.MAX_VALUE - 2); // Don't fall for rollover assertThat(Integer.MIN_VALUE).isNotWithin(1).of(Integer.MAX_VALUE); assertThat(Integer.MAX_VALUE).isNotWithin(1).of(Integer.MIN_VALUE); } private static void assertThatIsNotWithinFails(int actual, int tolerance, int expected) { AssertionError e = expectFailure(whenTesting -> whenTesting.that(actual).isNotWithin(tolerance).of(expected)); assertThat(e).factValue("expected not to be").isEqualTo(formatNumericValue(expected)); assertThat(e).factValue("within tolerance").isEqualTo(formatNumericValue(tolerance)); } @Test public void isWithinNegativeTolerance() { isWithinNegativeToleranceFails(0, -10, 0); isWithinNegativeToleranceFails(0, -10, 0); isNotWithinNegativeToleranceFails(0, -10, 0); isNotWithinNegativeToleranceFails(0, -10, 0); } private static void isWithinNegativeToleranceFails(int actual, int tolerance, int expected) { AssertionError e = expectFailure(whenTesting -> whenTesting.that(actual).isWithin(tolerance).of(expected)); assertFailureKeys( e, "could not perform approximate-equality check because tolerance was negative", "expected", "was", "tolerance"); } private static void isNotWithinNegativeToleranceFails(int actual, int tolerance, int expected) { AssertionError e = expectFailure(whenTesting -> whenTesting.that(actual).isNotWithin(tolerance).of(expected)); assertFailureKeys( e, "could not perform approximate-equality check because tolerance was negative", "expected", "was", "tolerance"); } }
IntegerSubjectTest
java
apache__camel
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PackageJaxbMojo.java
{ "start": 2486, "end": 3189 }
class ____ extends AbstractGeneratorMojo { /** * The name of the index file. Default's to 'target/classes/META-INF/jandex.idx' */ @Parameter(defaultValue = "${project.build.directory}/META-INF/jandex.idx") protected File index; /** * The output directory for the generated component files */ @Parameter(defaultValue = "${project.basedir}/src/generated/resources") protected File jaxbIndexOutDir; @Inject public PackageJaxbMojo(MavenProjectHelper projectHelper, BuildContext buildContext) { super(projectHelper, buildContext); } /** * Execute goal. * * @throws MojoExecutionException execution of the main
PackageJaxbMojo
java
apache__maven
its/core-it-suite/src/test/resources/mng-5783-plugin-dependency-filtering/plugin/src/main/java/org/apache/maven/its/mng5783/plugin/TestMojo.java
{ "start": 2112, "end": 3003 }
class ____ extends AbstractMojo { @Parameter(defaultValue = "${project.build.directory}", readonly = true) private File target; @Parameter(defaultValue = "${plugin.artifacts}", readonly = true) private List<Artifact> artifacts; public void execute() throws MojoExecutionException { try { File file = new File(target, "dependencies.txt"); file.getParentFile().mkdirs(); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); try { for (Artifact artifact : artifacts) { w.write(artifact.getId()); w.newLine(); } } finally { w.close(); } } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } }
TestMojo
java
apache__dubbo
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java
{ "start": 1170, "end": 1662 }
class ____ extends AbstractServerHttpChannelObserver<HttpChannel> { public Http1ServerChannelObserver(HttpChannel httpChannel) { super(httpChannel); } @Override protected HttpMetadata encodeHttpMetadata(boolean endStream) { return new Http1Metadata(new NettyHttp1HttpHeaders()); } @Override protected void doOnCompleted(Throwable throwable) { getHttpChannel().writeMessage(HttpOutputMessage.EMPTY_MESSAGE); } }
Http1ServerChannelObserver
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/GlobalAggregateManager.java
{ "start": 1330, "end": 1953 }
interface ____ { /** * Update the global aggregate and return the new value. * * @param aggregateName The name of the aggregate to update * @param aggregand The value to add to the aggregate * @param aggregateFunction The function to apply to the current aggregate and aggregand to * obtain the new aggregate value * @return The updated aggregate */ <IN, ACC, OUT> OUT updateGlobalAggregate( String aggregateName, Object aggregand, AggregateFunction<IN, ACC, OUT> aggregateFunction) throws IOException; }
GlobalAggregateManager
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3678/Issue3678Mapper.java
{ "start": 2185, "end": 2685 }
class ____ { private final String name; private final String description; private Target(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } public static Builder builder() { return new Builder(); } public static
Target
java
quarkusio__quarkus
integration-tests/smallrye-metrics/src/test/java/io/quarkus/it/metrics/MetricsOnClassTestCase.java
{ "start": 219, "end": 1257 }
class ____ { @Test public void testCounterOnMethod() { assertMetricExactValue("application", "foo.method", "application_foo_method_total", "0.0"); RestAssured.when().get("/metricsonclass/method"); assertMetricExactValue("application", "foo.method", "application_foo_method_total", "1.0"); } @Test public void testCounterOnConstructor() { assertMetricExists("application", "foo.MetricsOnClassResource", "application_foo_MetricsOnClassResource_total"); } private void assertMetricExactValue(String scope, String name, String expectedNameInOutput, String val) { RestAssured.when().get("/q/metrics/" + scope + "/" + name).then() .body(containsString(expectedNameInOutput + " " + val)); } private void assertMetricExists(String scope, String name, String expectedNameInOutput) { RestAssured.when().get("/q/metrics/" + scope + "/" + name).then() .body(containsString(expectedNameInOutput + " ")); } }
MetricsOnClassTestCase
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/ast/GenericElement.java
{ "start": 2149, "end": 2786 }
class ____ can be a resolved as a generic element and this element should return the actual * type that is generic element is representing. * * @return The resolved value of the generic element. * @since 4.2.0 */ default Optional<ClassElement> getResolved() { return Optional.empty(); } /** * Tries to resolve underneath type using {@link #getResolved()} or returns this type otherwise. * * @return The resolved value of the generic element or this type. * @since 4.2.0 */ default ClassElement resolved() { return getResolved().orElse(this); } }
element
java
elastic__elasticsearch
build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/BuildToolsConventionsPlugin.java
{ "start": 934, "end": 1728 }
class ____ implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().apply(LicenseHeadersPrecommitPlugin.class); int defaultParallel = ParallelDetector.findDefaultParallel(project); project.getTasks().withType(Test.class).configureEach(test -> { test.onlyIf("FIPS mode disabled", (t) -> Util.getBooleanProperty("tests.fips.enabled", false) == false); test.setMaxParallelForks(defaultParallel); }); // we put all our distributable files under distributions project.getTasks().withType(Jar.class).configureEach(j -> j.getDestinationDirectory().set(new File(project.getBuildDir(), "distributions")) ); } }
BuildToolsConventionsPlugin
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/DefaultConstructorInjectionPoint.java
{ "start": 1382, "end": 1870 }
class ____<T> implements ConstructorInjectionPoint<T>, EnvironmentConfigurable { private final BeanDefinition<T> declaringBean; private final Class<T> declaringType; private final Class<?>[] argTypes; private final AnnotationMetadata annotationMetadata; private final Argument<?>[] arguments; private Environment environment; /** * @param declaringBean The declaring bean * @param declaringType The declaring
DefaultConstructorInjectionPoint
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/BasicCriteriaExecutionTests.java
{ "start": 1032, "end": 5946 }
class ____ { @Test public void testExecutingBasicCriteriaQuery(SessionFactoryScope scope) { scope.inTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery(); final Root<BasicEntity> root = criteria.from( BasicEntity.class ); criteria.select( root ); session.createQuery( criteria ).list(); } ); } @Test public void testIt(SessionFactoryScope scope) { scope.inTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<BasicEntity> criteria = criteriaBuilder.createQuery( BasicEntity.class ); criteria.from( BasicEntity.class ); session.createQuery( criteria ).list(); } ); } @Test public void testExecutingBasicCriteriaQueryInStatelessSession(SessionFactoryScope scope) { scope.inTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery(); final Root<BasicEntity> root = criteria.from( BasicEntity.class ); criteria.select( root ); session.createQuery( criteria ).list(); } ); } @Test public void testExecutingBasicCriteriaQueryLiteralPredicate(SessionFactoryScope scope) { scope.inTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery(); final Root<BasicEntity> root = criteria.from( BasicEntity.class ); criteria.select( root ); criteria.where( criteriaBuilder.equal( criteriaBuilder.literal( 1 ), criteriaBuilder.literal( 1 ) ) ); session.createQuery( criteria ).list(); } ); } @Test public void testExecutingBasicCriteriaQueryLiteralPredicateInStatelessSession(SessionFactoryScope scope) { scope.inStatelessTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery(); final Root<BasicEntity> root = criteria.from( BasicEntity.class ); criteria.select( root ); criteria.where( criteriaBuilder.equal( criteriaBuilder.literal( 1 ), criteriaBuilder.literal( 1 ) ) ); session.createQuery( criteria ).list(); } ); } // Doing ... where ? = ? ... is only allowed in a few DBs. Since this is useless, we don't bother to emulate this @Test @RequiresDialect(H2Dialect.class) @SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support comparing parameters against each other") public void testExecutingBasicCriteriaQueryParameterPredicate(SessionFactoryScope scope) { scope.inStatelessTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery(); final Root<BasicEntity> root = criteria.from( BasicEntity.class ); criteria.select( root ); final ParameterExpression<Integer> param = criteriaBuilder.parameter( Integer.class ); criteria.where( criteriaBuilder.equal( param, param ) ); session.createQuery( criteria ).setParameter( param, 1 ).list(); } ); } // Doing ... where ? = ? ... is only allowed in a few DBs. Since this is useless, we don't bother to emulate this @Test @RequiresDialect(H2Dialect.class) @SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support comparing parameters against each other") public void testExecutingBasicCriteriaQueryParameterPredicateInStatelessSession(SessionFactoryScope scope) { scope.inStatelessTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery(); final Root<BasicEntity> root = criteria.from( BasicEntity.class ); criteria.select( root ); final ParameterExpression<Integer> param = criteriaBuilder.parameter( Integer.class ); criteria.where( criteriaBuilder.equal( param, param ) ); session.createQuery( criteria ).setParameter( param, 1 ).list(); } ); } @Test public void testCriteriaEntityJoin(SessionFactoryScope scope) { scope.inStatelessTransaction( session -> { final HibernateCriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); final JpaCriteriaQuery<Object> criteria = criteriaBuilder.createQuery(); final JpaRoot<BasicEntity> root = criteria.from( BasicEntity.class ); root.join( BasicEntity.class, JoinType.CROSS ); criteria.select( root ); session.createQuery( criteria ).list(); } ); } }
BasicCriteriaExecutionTests
java
apache__kafka
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
{ "start": 1412, "end": 28348 }
class ____ { /** * The streams group member which is reconciled. */ private final StreamsGroupMember member; /** * The target assignment epoch. */ private int targetAssignmentEpoch; /** * The target assignment. */ private TasksTuple targetAssignment; /** * A function which returns the current process ID of an active task or null if the active task * is not assigned. The current process ID is the process ID of the current owner. */ private BiFunction<String, Integer, String> currentActiveTaskProcessId; /** * A function which returns the current process IDs of a standby task or null if the standby * task is not assigned. The current process IDs are the process IDs of all current owners. */ private BiFunction<String, Integer, Set<String>> currentStandbyTaskProcessIds; /** * A function which returns the current process IDs of a warmup task or null if the warmup task * is not assigned. The current process IDs are the process IDs of all current owners. */ private BiFunction<String, Integer, Set<String>> currentWarmupTaskProcessIds; /** * The tasks owned by the member. This may be provided by the member in the StreamsGroupHeartbeat request. */ private Optional<TasksTuple> ownedTasks = Optional.empty(); /** * Constructs the CurrentAssignmentBuilder based on the current state of the provided streams group member. * * @param member The streams group member that must be reconciled. */ public CurrentAssignmentBuilder(StreamsGroupMember member) { this.member = Objects.requireNonNull(member); } /** * Sets the target assignment epoch and the target assignment that the streams group member must be reconciled to. * * @param targetAssignmentEpoch The target assignment epoch. * @param targetAssignment The target assignment. * @return This object. */ public CurrentAssignmentBuilder withTargetAssignment(int targetAssignmentEpoch, TasksTuple targetAssignment) { this.targetAssignmentEpoch = targetAssignmentEpoch; this.targetAssignment = Objects.requireNonNull(targetAssignment); return this; } /** * Sets a BiFunction which allows to retrieve the current process ID of an active task. This is * used by the state machine to determine if an active task is free or still used by another * member, and if there is still a task on a specific process that is not yet revoked. * * @param currentActiveTaskProcessId A BiFunction which gets the process ID of a subtopology ID / * partition ID pair. * @return This object. */ public CurrentAssignmentBuilder withCurrentActiveTaskProcessId(BiFunction<String, Integer, String> currentActiveTaskProcessId) { this.currentActiveTaskProcessId = Objects.requireNonNull(currentActiveTaskProcessId); return this; } /** * Sets a BiFunction which allows to retrieve the current process IDs of a standby task. This is * used by the state machine to determine if there is still a task on a specific process that is * not yet revoked. * * @param currentStandbyTaskProcessIds A BiFunction which gets the process IDs of a subtopology * ID / partition ID pair. * @return This object. */ public CurrentAssignmentBuilder withCurrentStandbyTaskProcessIds( BiFunction<String, Integer, Set<String>> currentStandbyTaskProcessIds ) { this.currentStandbyTaskProcessIds = Objects.requireNonNull(currentStandbyTaskProcessIds); return this; } /** * Sets a BiFunction which allows to retrieve the current process IDs of a warmup task. This is * used by the state machine to determine if there is still a task on a specific process that is * not yet revoked. * * @param currentWarmupTaskProcessIds A BiFunction which gets the process IDs of a subtopology ID * / partition ID pair. * @return This object. */ public CurrentAssignmentBuilder withCurrentWarmupTaskProcessIds(BiFunction<String, Integer, Set<String>> currentWarmupTaskProcessIds) { this.currentWarmupTaskProcessIds = Objects.requireNonNull(currentWarmupTaskProcessIds); return this; } /** * Sets the tasks currently owned by the member. This comes directly from the last StreamsGroupHeartbeat request. This is used to * determine if the member has revoked the necessary tasks. Passing null into this function means that the member did not provide * its owned tasks in this heartbeat. * * @param ownedAssignment A collection of active, standby and warm-up tasks * @return This object. */ public CurrentAssignmentBuilder withOwnedAssignment(TasksTuple ownedAssignment) { this.ownedTasks = Optional.ofNullable(ownedAssignment); return this; } /** * Builds the next state for the member or keep the current one if it is not possible to move forward with the current state. * * @return A new StreamsGroupMember or the current one. */ public StreamsGroupMember build() { switch (member.state()) { case STABLE: // When the member is in the STABLE state, we verify if a newer // epoch (or target assignment) is available. If it is, we can // reconcile the member towards it. Otherwise, we return. if (member.memberEpoch() != targetAssignmentEpoch) { return computeNextAssignment( member.memberEpoch(), member.assignedTasks() ); } else { return member; } case UNREVOKED_TASKS: // When the member is in the UNREVOKED_TASKS state, we wait // until the member has revoked the necessary tasks. They are // considered revoked when they are not anymore reported in the // owned tasks set in the StreamsGroupHeartbeat API. // If the member provides its owned tasks, we verify if it still // owns any of the revoked tasks. If it did not provide it's // owned tasks, or we still own some of the revoked tasks, we // cannot progress. if ( ownedTasks.isEmpty() || ownedTasks.get().containsAny(member.tasksPendingRevocation()) ) { return member; } // When the member has revoked all the pending tasks, it can // transition to the next epoch (current + 1) and we can reconcile // its state towards the latest target assignment. return computeNextAssignment( member.memberEpoch() + 1, member.assignedTasks() ); case UNRELEASED_TASKS: // When the member is in the UNRELEASED_TASKS, we reconcile the // member towards the latest target assignment. This will assign any // of the unreleased tasks when they become available. return computeNextAssignment( member.memberEpoch(), member.assignedTasks() ); case UNKNOWN: // We could only end up in this state if a new state is added in the // future and the group coordinator is downgraded. In this case, the // best option is to fence the member to force it to rejoin the group // without any tasks and to reconcile it again from scratch. if ((ownedTasks.isEmpty() || !ownedTasks.get().isEmpty())) { throw new FencedMemberEpochException( "The streams group member is in a unknown state. " + "The member must abandon all its tasks and rejoin."); } return computeNextAssignment( targetAssignmentEpoch, member.assignedTasks() ); } return member; } /** * Takes the current currentAssignment and the targetAssignment, and generates three * collections: * * - the resultAssignedTasks: the tasks that are assigned in both the current and target * assignments. * - the resultTasksPendingRevocation: the tasks that are assigned in the current * assignment but not in the target assignment. * - the resultTasksPendingAssignment: the tasks that are assigned in the target assignment but * not in the current assignment, and can be assigned currently (i.e., they are not owned by * another member, as defined by the `isUnreleasedTask` predicate). */ private boolean computeAssignmentDifference(Map<String, Set<Integer>> currentAssignment, Map<String, Set<Integer>> targetAssignment, Map<String, Set<Integer>> resultAssignedTasks, Map<String, Set<Integer>> resultTasksPendingRevocation, Map<String, Set<Integer>> resultTasksPendingAssignment, BiPredicate<String, Integer> isUnreleasedTask) { boolean hasUnreleasedTasks = false; Set<String> allSubtopologyIds = new HashSet<>(targetAssignment.keySet()); allSubtopologyIds.addAll(currentAssignment.keySet()); for (String subtopologyId : allSubtopologyIds) { hasUnreleasedTasks |= computeAssignmentDifferenceForOneSubtopology( subtopologyId, currentAssignment.getOrDefault(subtopologyId, Set.of()), targetAssignment.getOrDefault(subtopologyId, Set.of()), resultAssignedTasks, resultTasksPendingRevocation, resultTasksPendingAssignment, isUnreleasedTask ); } return hasUnreleasedTasks; } private static boolean computeAssignmentDifferenceForOneSubtopology(final String subtopologyId, final Set<Integer> currentTasksForThisSubtopology, final Set<Integer> targetTasksForThisSubtopology, final Map<String, Set<Integer>> resultAssignedTasks, final Map<String, Set<Integer>> resultTasksPendingRevocation, final Map<String, Set<Integer>> resultTasksPendingAssignment, final BiPredicate<String, Integer> isUnreleasedTask) { // Result Assigned Tasks = Current Tasks ∩ Target Tasks // i.e. we remove all tasks from the current assignment that are not in the target // assignment Set<Integer> resultAssignedTasksForThisSubtopology = new HashSet<>(currentTasksForThisSubtopology); resultAssignedTasksForThisSubtopology.retainAll(targetTasksForThisSubtopology); // Result Tasks Pending Revocation = Current Tasks - Result Assigned Tasks // i.e. we will ask the member to revoke all tasks in its current assignment that // are not in the target assignment Set<Integer> resultTasksPendingRevocationForThisSubtopology = new HashSet<>(currentTasksForThisSubtopology); resultTasksPendingRevocationForThisSubtopology.removeAll(resultAssignedTasksForThisSubtopology); // Result Tasks Pending Assignment = Target Tasks - Result Assigned Tasks - Unreleased Tasks // i.e. we will ask the member to assign all tasks in its target assignment, // except those that are already assigned, and those that are unreleased Set<Integer> resultTasksPendingAssignmentForThisSubtopology = new HashSet<>(targetTasksForThisSubtopology); resultTasksPendingAssignmentForThisSubtopology.removeAll(resultAssignedTasksForThisSubtopology); boolean hasUnreleasedTasks = resultTasksPendingAssignmentForThisSubtopology.removeIf(taskId -> isUnreleasedTask.test(subtopologyId, taskId) ); if (!resultAssignedTasksForThisSubtopology.isEmpty()) { resultAssignedTasks.put(subtopologyId, resultAssignedTasksForThisSubtopology); } if (!resultTasksPendingRevocationForThisSubtopology.isEmpty()) { resultTasksPendingRevocation.put(subtopologyId, resultTasksPendingRevocationForThisSubtopology); } if (!resultTasksPendingAssignmentForThisSubtopology.isEmpty()) { resultTasksPendingAssignment.put(subtopologyId, resultTasksPendingAssignmentForThisSubtopology); } return hasUnreleasedTasks; } /** * Takes the current currentAssignment and the targetAssignment, and generates three * collections: * * - the resultAssignedTasks: the tasks that are assigned in both the current and target * assignments. * - the resultTasksPendingRevocation: the tasks that are assigned in the current * assignment but not in the target assignment. * - the resultTasksPendingAssignment: the tasks that are assigned in the target assignment but * not in the current assignment, and can be assigned currently (i.e., they are not owned by * another member, as defined by the `isUnreleasedTask` predicate). * * Epoch Handling: * - For tasks in resultAssignedTasks and resultTasksPendingRevocation, the epoch from currentAssignment is preserved. * - For tasks in resultTasksPendingAssignment, the targetAssignmentEpoch is used. */ private boolean computeAssignmentDifferenceWithEpoch(Map<String, Map<Integer, Integer>> currentAssignment, Map<String, Set<Integer>> targetAssignment, int targetAssignmentEpoch, Map<String, Map<Integer, Integer>> resultAssignedTasks, Map<String, Map<Integer, Integer>> resultTasksPendingRevocation, Map<String, Map<Integer, Integer>> resultTasksPendingAssignment, BiPredicate<String, Integer> isUnreleasedTask) { boolean hasUnreleasedTasks = false; Set<String> allSubtopologyIds = new HashSet<>(targetAssignment.keySet()); allSubtopologyIds.addAll(currentAssignment.keySet()); for (String subtopologyId : allSubtopologyIds) { hasUnreleasedTasks |= computeAssignmentDifferenceForOneSubtopologyWithEpoch( subtopologyId, currentAssignment.getOrDefault(subtopologyId, Map.of()), targetAssignment.getOrDefault(subtopologyId, Set.of()), targetAssignmentEpoch, resultAssignedTasks, resultTasksPendingRevocation, resultTasksPendingAssignment, isUnreleasedTask ); } return hasUnreleasedTasks; } private static boolean computeAssignmentDifferenceForOneSubtopologyWithEpoch(final String subtopologyId, final Map<Integer, Integer> currentTasksForThisSubtopology, final Set<Integer> targetTasksForThisSubtopology, final int targetAssignmentEpoch, final Map<String, Map<Integer, Integer>> resultAssignedTasks, final Map<String, Map<Integer, Integer>> resultTasksPendingRevocation, final Map<String, Map<Integer, Integer>> resultTasksPendingAssignment, final BiPredicate<String, Integer> isUnreleasedTask) { // Result Assigned Tasks = Current Tasks ∩ Target Tasks // i.e. we remove all tasks from the current assignment that are not in the target // assignment Map<Integer, Integer> resultAssignedTasksForThisSubtopology = new HashMap<>(); for (Map.Entry<Integer, Integer> entry : currentTasksForThisSubtopology.entrySet()) { if (targetTasksForThisSubtopology.contains(entry.getKey())) { resultAssignedTasksForThisSubtopology.put(entry.getKey(), entry.getValue()); } } // Result Tasks Pending Revocation = Current Tasks - Result Assigned Tasks // i.e. we will ask the member to revoke all tasks in its current assignment that // are not in the target assignment Map<Integer, Integer> resultTasksPendingRevocationForThisSubtopology = new HashMap<>(currentTasksForThisSubtopology); resultTasksPendingRevocationForThisSubtopology.keySet().removeAll(resultAssignedTasksForThisSubtopology.keySet()); // Result Tasks Pending Assignment = Target Tasks - Result Assigned Tasks - Unreleased Tasks // i.e. we will ask the member to assign all tasks in its target assignment, // except those that are already assigned, and those that are unreleased Map<Integer, Integer> resultTasksPendingAssignmentForThisSubtopology = new HashMap<>(); for (Integer taskId : targetTasksForThisSubtopology) { if (!resultAssignedTasksForThisSubtopology.containsKey(taskId)) { resultTasksPendingAssignmentForThisSubtopology.put(taskId, targetAssignmentEpoch); } } boolean hasUnreleasedTasks = resultTasksPendingAssignmentForThisSubtopology.keySet().removeIf(taskId -> isUnreleasedTask.test(subtopologyId, taskId) ); if (!resultAssignedTasksForThisSubtopology.isEmpty()) { resultAssignedTasks.put(subtopologyId, resultAssignedTasksForThisSubtopology); } if (!resultTasksPendingRevocationForThisSubtopology.isEmpty()) { resultTasksPendingRevocation.put(subtopologyId, resultTasksPendingRevocationForThisSubtopology); } if (!resultTasksPendingAssignmentForThisSubtopology.isEmpty()) { resultTasksPendingAssignment.put(subtopologyId, resultTasksPendingAssignmentForThisSubtopology); } return hasUnreleasedTasks; } /** * Computes the next assignment. * * @param memberEpoch The epoch of the member to use. This may be different from * the epoch in {@link CurrentAssignmentBuilder#member}. * @param memberAssignedTasks The assigned tasks of the member to use. * @return A new StreamsGroupMember. */ private StreamsGroupMember computeNextAssignment(int memberEpoch, TasksTupleWithEpochs memberAssignedTasks) { Map<String, Map<Integer, Integer>> newActiveAssignedTasks = new HashMap<>(); Map<String, Map<Integer, Integer>> newActiveTasksPendingRevocation = new HashMap<>(); Map<String, Map<Integer, Integer>> newActiveTasksPendingAssignment = new HashMap<>(); Map<String, Set<Integer>> newStandbyAssignedTasks = new HashMap<>(); Map<String, Set<Integer>> newStandbyTasksPendingRevocation = new HashMap<>(); Map<String, Set<Integer>> newStandbyTasksPendingAssignment = new HashMap<>(); Map<String, Set<Integer>> newWarmupAssignedTasks = new HashMap<>(); Map<String, Set<Integer>> newWarmupTasksPendingRevocation = new HashMap<>(); Map<String, Set<Integer>> newWarmupTasksPendingAssignment = new HashMap<>(); boolean hasUnreleasedActiveTasks = computeAssignmentDifferenceWithEpoch( memberAssignedTasks.activeTasksWithEpochs(), targetAssignment.activeTasks(), targetAssignmentEpoch, newActiveAssignedTasks, newActiveTasksPendingRevocation, newActiveTasksPendingAssignment, (subtopologyId, partitionId) -> currentActiveTaskProcessId.apply(subtopologyId, partitionId) != null || currentStandbyTaskProcessIds.apply(subtopologyId, partitionId) .contains(member.processId()) || currentWarmupTaskProcessIds.apply(subtopologyId, partitionId) .contains(member.processId()) ); boolean hasUnreleasedStandbyTasks = computeAssignmentDifference( memberAssignedTasks.standbyTasks(), targetAssignment.standbyTasks(), newStandbyAssignedTasks, newStandbyTasksPendingRevocation, newStandbyTasksPendingAssignment, (subtopologyId, partitionId) -> Objects.equals(currentActiveTaskProcessId.apply(subtopologyId, partitionId), member.processId()) || currentStandbyTaskProcessIds.apply(subtopologyId, partitionId) .contains(member.processId()) || currentWarmupTaskProcessIds.apply(subtopologyId, partitionId) .contains(member.processId()) ); boolean hasUnreleasedWarmupTasks = computeAssignmentDifference( memberAssignedTasks.warmupTasks(), targetAssignment.warmupTasks(), newWarmupAssignedTasks, newWarmupTasksPendingRevocation, newWarmupTasksPendingAssignment, (subtopologyId, partitionId) -> Objects.equals(currentActiveTaskProcessId.apply(subtopologyId, partitionId), member.processId()) || currentStandbyTaskProcessIds.apply(subtopologyId, partitionId) .contains(member.processId()) || currentWarmupTaskProcessIds.apply(subtopologyId, partitionId) .contains(member.processId()) ); return buildNewMember( memberEpoch, new TasksTupleWithEpochs( newActiveTasksPendingRevocation, newStandbyTasksPendingRevocation, newWarmupTasksPendingRevocation ), new TasksTupleWithEpochs( newActiveAssignedTasks, newStandbyAssignedTasks, newWarmupAssignedTasks ), new TasksTupleWithEpochs( newActiveTasksPendingAssignment, newStandbyTasksPendingAssignment, newWarmupTasksPendingAssignment ), hasUnreleasedActiveTasks || hasUnreleasedStandbyTasks || hasUnreleasedWarmupTasks ); } private StreamsGroupMember buildNewMember(final int memberEpoch, final TasksTupleWithEpochs newTasksPendingRevocation, final TasksTupleWithEpochs newAssignedTasks, final TasksTupleWithEpochs newTasksPendingAssignment, final boolean hasUnreleasedTasks) { final boolean hasTasksToBeRevoked = (!newTasksPendingRevocation.isEmpty()) && (ownedTasks.isEmpty() || ownedTasks.get().containsAny(newTasksPendingRevocation)); if (hasTasksToBeRevoked) { // If there are tasks to be revoked, the member remains in its current // epoch and requests the revocation of those tasks. It transitions to // the UNREVOKED_TASKS state to wait until the client acknowledges the // revocation of the tasks. return new StreamsGroupMember.Builder(member) .setState(MemberState.UNREVOKED_TASKS) .updateMemberEpoch(memberEpoch) .setAssignedTasks(newAssignedTasks) .setTasksPendingRevocation(newTasksPendingRevocation) .build(); } else if (!newTasksPendingAssignment.isEmpty()) { // If there are tasks to be assigned, the member transitions to the // target epoch and requests the assignment of those tasks. Note that // the tasks are directly added to the assigned tasks set. The // member transitions to the STABLE state or to the UNRELEASED_TASKS // state depending on whether there are unreleased tasks or not. MemberState newState = hasUnreleasedTasks ? MemberState.UNRELEASED_TASKS : MemberState.STABLE; return new StreamsGroupMember.Builder(member) .setState(newState) .updateMemberEpoch(targetAssignmentEpoch) .setAssignedTasks(newAssignedTasks.merge(newTasksPendingAssignment)) .setTasksPendingRevocation(TasksTupleWithEpochs.EMPTY) .build(); } else if (hasUnreleasedTasks) { // If there are no tasks to be revoked nor to be assigned but some // tasks are not available yet, the member transitions to the target // epoch, to the UNRELEASED_TASKS state and waits. return new StreamsGroupMember.Builder(member) .setState(MemberState.UNRELEASED_TASKS) .updateMemberEpoch(targetAssignmentEpoch) .setAssignedTasks(newAssignedTasks) .setTasksPendingRevocation(TasksTupleWithEpochs.EMPTY) .build(); } else { // Otherwise, the member transitions to the target epoch and to the // STABLE state. return new StreamsGroupMember.Builder(member) .setState(MemberState.STABLE) .updateMemberEpoch(targetAssignmentEpoch) .setAssignedTasks(newAssignedTasks) .setTasksPendingRevocation(TasksTupleWithEpochs.EMPTY) .build(); } } }
CurrentAssignmentBuilder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java
{ "start": 28660, "end": 30797 }
class ____ are set. */ protected void initInputReaders() throws Exception { final int numInputs = getNumTaskInputs(); final MutableReader<?>[] inputReaders = new MutableReader<?>[numInputs]; int currentReaderOffset = 0; for (int i = 0; i < numInputs; i++) { // ---------------- create the input readers --------------------- // in case where a logical input unions multiple physical inputs, create a union reader final int groupSize = this.config.getGroupSize(i); if (groupSize == 1) { // non-union case inputReaders[i] = new MutableRecordReader<>( getEnvironment().getInputGate(currentReaderOffset), getEnvironment().getTaskManagerInfo().getTmpDirectories()); } else if (groupSize > 1) { // union case IndexedInputGate[] readers = new IndexedInputGate[groupSize]; for (int j = 0; j < groupSize; ++j) { readers[j] = getEnvironment().getInputGate(currentReaderOffset + j); } inputReaders[i] = new MutableRecordReader<>( new UnionInputGate(readers), getEnvironment().getTaskManagerInfo().getTmpDirectories()); } else { throw new Exception("Illegal input group size in task configuration: " + groupSize); } currentReaderOffset += groupSize; } this.inputReaders = inputReaders; // final sanity check if (currentReaderOffset != this.config.getNumInputs()) { throw new Exception( "Illegal configuration: Number of input gates and group sizes are not consistent."); } } /** * Creates the record readers for the extra broadcast inputs as configured by {@link * TaskConfig#getNumBroadcastInputs()}. This method requires that the task configuration, the * driver, and the user-code
loader
java
quarkusio__quarkus
extensions/jdbc/jdbc-postgresql/runtime/src/main/java/io/quarkus/jdbc/postgresql/runtime/PostgreSQLServiceBindingConverter.java
{ "start": 1236, "end": 4840 }
class ____ extends DatasourceServiceBindingConfigSourceFactory.Jdbc { @Override protected String formatUrl(String urlFormat, String type, String host, String database, String portPart) { String result = super.formatUrl(urlFormat, type, host, database, portPart); Map<String, String> sbProps = serviceBinding.getProperties(); //process ssl params //https://www.postgresql.org/docs/14/libpq-connect.html StringBuilder sslparam = new StringBuilder(); String sslmode = sbProps.getOrDefault(SSL_MODE, ""); String sslRootCert = sbProps.getOrDefault(SSL_ROOT_CERT, ""); if (!"".equals(sslmode)) { sslparam.append(SSL_MODE).append("=").append(sslmode); } if (!"".equals(sslRootCert)) { if (!"".equals(sslmode)) { sslparam.append("&"); } sslparam.append(SSL_ROOT_CERT).append("=") .append(serviceBinding.getBindingDirectory()).append(FileSystems.getDefault().getSeparator()) .append(sslRootCert); } //cockroachdb cloud uses options parameter to pass in the cluster routing-id //https://www.cockroachlabs.com/docs/v21.2/connection-parameters#additional-connection-parameters String options = sbProps.getOrDefault(OPTIONS, ""); String crdbOption = ""; List<String> postgreOptions = new ArrayList<>(); if (!options.equals("")) { String[] allOpts = options.split("&"); for (String o : allOpts) { String[] keyval = o.split("="); if (keyval.length != 2 || keyval[0].length() == 0 || keyval[1].length() == 0) { continue; } if (keyval[0].equals("--cluster")) { crdbOption = keyval[0] + "=" + keyval[1]; } else { postgreOptions.add("-c " + keyval[0] + "=" + keyval[1]); } } } String combinedOptions = crdbOption; if (postgreOptions.size() > 0) { String otherOpts = String.join(" ", postgreOptions); if (!combinedOptions.equals("")) { combinedOptions = combinedOptions + " " + otherOpts; } else { combinedOptions = otherOpts; } } try { combinedOptions = combinedOptions.length() > 0 ? OPTIONS + "=" + encode(combinedOptions).replace("+", "%20") : ""; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("failed to encode options params" + options, e); } if (sslparam.length() > 0 && !combinedOptions.equals("")) { combinedOptions = sslparam + "&" + combinedOptions; } else if (sslparam.length() > 0) { combinedOptions = sslparam.toString(); } if (!"".equals(combinedOptions)) { //append sslmode and options to the URL result += "?" + combinedOptions; } return result; } private String encode(String str) throws UnsupportedEncodingException { return URLEncoder.encode(str, StandardCharsets.UTF_8.toString()); } } }
PostgreSQLDatasourceServiceBindingConfigSourceFactory
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/analyze/PlanAdvice.java
{ "start": 2211, "end": 2460 }
enum ____ { /** Indicate the advice is not specific to a {@link org.apache.calcite.rel.RelNode}. */ QUERY_LEVEL, /** Indicate the advice is specific to a {@link org.apache.calcite.rel.RelNode}. */ NODE_LEVEL } }
Scope
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/Rounding.java
{ "start": 10203, "end": 13425 }
interface ____ { /** * Rounds the given value. */ long round(long utcMillis); /** * Given the rounded value (which was potentially generated by * {@link #round(long)}, returns the next rounding value. For * example, with interval based rounding, if the interval is * 3, {@code nextRoundValue(6) = 9}. */ long nextRoundingValue(long utcMillis); /** * Given the rounded value, returns the size between this value and the * next rounded value in specified units if possible. */ double roundingSize(long utcMillis, DateTimeUnit timeUnit); /** * Returns the size of each rounding bucket in timeUnits. */ double roundingSize(DateTimeUnit timeUnit); /** * If this rounding mechanism precalculates rounding points then * this array stores dates such that each date between each entry. * if the rounding mechanism doesn't precalculate points then this * is {@code null}. */ long[] fixedRoundingPoints(); } /** * Prepare to round many times. */ public abstract Prepared prepare(long minUtcMillis, long maxUtcMillis); /** * Prepare to round many dates over an unknown range. Prefer * {@link #prepare(long, long)} if you can find the range because * it'll be much more efficient. */ public abstract Prepared prepareForUnknown(); /** * Prepare rounding forcing the java time implementation. Prefer * {@link #prepare} or {@link #prepareForUnknown} which can be much * faster. */ public abstract Prepared prepareJavaTime(); /** * Rounds the given value. * @deprecated Prefer {@link #prepare} and then {@link Prepared#round(long)} */ @Deprecated public final long round(long utcMillis) { return prepare(utcMillis, utcMillis).round(utcMillis); } /** * Given the rounded value (which was potentially generated by * {@link #round(long)}, returns the next rounding value. For * example, with interval based rounding, if the interval is * 3, {@code nextRoundValue(6) = 9}. * @deprecated Prefer {@link #prepare} and then {@link Prepared#nextRoundingValue(long)} */ @Deprecated public final long nextRoundingValue(long utcMillis) { return prepare(utcMillis, utcMillis).nextRoundingValue(utcMillis); } /** * How "offset" this rounding is from the traditional "start" of the period. * @deprecated We're in the process of abstracting offset *into* Rounding * so keep any usage to migratory shims */ @Deprecated public abstract long offset(); /** * Strip the {@code offset} from these bounds. */ public abstract Rounding withoutOffset(); @Override public abstract boolean equals(Object obj); @Override public abstract int hashCode(); public static Builder builder(DateTimeUnit unit) { return new Builder(unit); } public static Builder builder(TimeValue interval) { return new Builder(interval); } public static
Prepared
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_containsIgnoringCase_CharSequence_Test.java
{ "start": 931, "end": 1314 }
class ____ extends CharSequenceAssertBaseTest { @Override protected CharSequenceAssert invoke_api_method() { return assertions.containsIgnoringCase("od"); } @Override protected void verify_internal_effects() { verify(strings).assertContainsIgnoringCase(getInfo(assertions), getActual(assertions), "od"); } }
CharSequenceAssert_containsIgnoringCase_CharSequence_Test