proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
crate_crate
crate/benchmarks/src/main/java/io/crate/execution/engine/sort/SortingLimitAndOffsetCollectorBenchmark.java
SortingLimitAndOffsetCollectorBenchmark
measureBoundedSortingCollector
class SortingLimitAndOffsetCollectorBenchmark { private static final Comparator<Object[]> COMPARATOR = (o1, o2) -> Integer.compare((int) o2[0], (int) o1[0]); private static final RowCollectExpression INPUT = new RowCollectExpression(0); private static final List<Input<?>> INPUTS = List.of(INPUT); private static final Iterable<CollectExpression<Row, ?>> COLLECT_EXPRESSIONS = List.of(INPUT); private List<RowN> rows; private Collector<Row, ?, Bucket> boundedSortingCollector; private Collector<Row, ?, Bucket> unboundedSortingCollector; @Setup public void setUp() { rows = IntStream.range(0, 10_000_000) .mapToObj(RowN::new) .toList(); boundedSortingCollector = new BoundedSortingLimitAndOffsetCollector( new RowAccounting<Object[]>() { @Override public long accountForAndMaybeBreak(Object[] row) { return 42; } @Override public void release() { } }, INPUTS, COLLECT_EXPRESSIONS, 1, COMPARATOR, 10_000, 0); unboundedSortingCollector = new UnboundedSortingLimitAndOffsetCollector( new RowAccounting<Object[]>() { @Override public long accountForAndMaybeBreak(Object[] row) { return 42; } @Override public void release() { } }, INPUTS, COLLECT_EXPRESSIONS, 1, COMPARATOR, 10_000, 10_000, 0); } @Benchmark public Object measureBoundedSortingCollector() throws Exception {<FILL_FUNCTION_BODY>} @Benchmark public Object measureUnboundedSortingCollector() throws Exception { BatchIterator<Row> it = new InMemoryBatchIterator<>(rows, SENTINEL, false); BatchIterator<Row> sortingBatchIterator = CollectingBatchIterator.newInstance(it, unboundedSortingCollector); return sortingBatchIterator.loadNextBatch().toCompletableFuture().join(); } }
BatchIterator<Row> it = new InMemoryBatchIterator<>(rows, SENTINEL, false); BatchIterator<Row> sortingBatchIterator = CollectingBatchIterator.newInstance(it, boundedSortingCollector); return sortingBatchIterator.loadNextBatch().toCompletableFuture().join();
618
77
695
<no_super_class>
crate_crate
crate/benchmarks/src/main/java/io/crate/operation/aggregation/HyperLogLogDistinctAggregationBenchmark.java
HyperLogLogDistinctAggregationBenchmark
benchmarkHLLPlusPlusMurmur128
class HyperLogLogDistinctAggregationBenchmark { private final List<Row1> rows = IntStream.range(0, 10_000).mapToObj(i -> new Row1(String.valueOf(i))).toList(); private HyperLogLogPlusPlus hyperLogLogPlusPlus; private AggregateCollector onHeapCollector; private OnHeapMemoryManager onHeapMemoryManager; private OffHeapMemoryManager offHeapMemoryManager; private AggregateCollector offHeapCollector; private MurmurHash3.Hash128 hash; @SuppressWarnings("unchecked") @Setup public void setUp() throws Exception { hash = new MurmurHash3.Hash128(); final RowCollectExpression inExpr0 = new RowCollectExpression(0); Functions functions = Functions.load(Settings.EMPTY, new SessionSettingRegistry(Set.of())); final HyperLogLogDistinctAggregation hllAggregation = (HyperLogLogDistinctAggregation) functions.getQualified( Signature.aggregate( HyperLogLogDistinctAggregation.NAME, DataTypes.STRING.getTypeSignature(), DataTypes.LONG.getTypeSignature() ), List.of(DataTypes.STRING), DataTypes.STRING ); onHeapMemoryManager = new OnHeapMemoryManager(bytes -> {}); offHeapMemoryManager = new OffHeapMemoryManager(); hyperLogLogPlusPlus = new HyperLogLogPlusPlus(HyperLogLogPlusPlus.DEFAULT_PRECISION, onHeapMemoryManager::allocate); onHeapCollector = new AggregateCollector( Collections.singletonList(inExpr0), RamAccounting.NO_ACCOUNTING, onHeapMemoryManager, Version.CURRENT, AggregateMode.ITER_FINAL, new AggregationFunction[] { hllAggregation }, Version.CURRENT, new Input[][] { { inExpr0 } }, new Input[] { Literal.BOOLEAN_TRUE } ); offHeapCollector = new AggregateCollector( Collections.singletonList(inExpr0), RamAccounting.NO_ACCOUNTING, offHeapMemoryManager, Version.CURRENT, AggregateMode.ITER_FINAL, new AggregationFunction[] { hllAggregation }, Version.CURRENT, new Input[][] { { inExpr0 } }, new Input[] { Literal.BOOLEAN_TRUE } ); } @TearDown public void tearDown() { onHeapMemoryManager.close(); offHeapMemoryManager.close(); } @Benchmark public long benchmarkHLLPlusPlusMurmur128() throws Exception {<FILL_FUNCTION_BODY>} @Benchmark public long benchmarkHLLPlusPlusMurmur64() throws Exception { for (int i = 0; i < rows.size(); i++) { String value = DataTypes.STRING.sanitizeValue(rows.get(i).get(0)); byte[] bytes = value.getBytes(StandardCharsets.UTF_8); hyperLogLogPlusPlus.collect(MurmurHash3.hash64(bytes, 0, bytes.length)); } return hyperLogLogPlusPlus.cardinality(); } @Benchmark public Iterable<Row> benchmarkHLLAggregationOnHeap() throws Exception { Object[] state = onHeapCollector.supplier().get(); BiConsumer<Object[], Row> accumulator = onHeapCollector.accumulator(); Function<Object[], Iterable<Row>> finisher = onHeapCollector.finisher(); for (int i = 0; i < rows.size(); i++) { accumulator.accept(state, rows.get(i)); } return finisher.apply(state); } @Benchmark public Iterable<Row> benchmarkHLLAggregationOffHeap() throws Exception { Object[] state = offHeapCollector.supplier().get(); BiConsumer<Object[], Row> accumulator = offHeapCollector.accumulator(); Function<Object[], Iterable<Row>> finisher = offHeapCollector.finisher(); for (int i = 0; i < rows.size(); i++) { accumulator.accept(state, rows.get(i)); } return finisher.apply(state); } }
for (int i = 0; i < rows.size(); i++) { String value = DataTypes.STRING.sanitizeValue(rows.get(i).get(0)); byte[] bytes = value.getBytes(StandardCharsets.UTF_8); MurmurHash3.Hash128 hash128 = MurmurHash3.hash128(bytes, 0, bytes.length, 0, hash); hyperLogLogPlusPlus.collect(hash128.h1); } return hyperLogLogPlusPlus.cardinality();
1,159
141
1,300
<no_super_class>
crate_crate
crate/extensions/jmx-monitoring/src/main/java/io/crate/beans/ThreadPools.java
ThreadPoolInfo
getThreadPoolInfo
class ThreadPoolInfo { private final String name; private final int poolSize; private final int queueSize; private final int largestPoolSize; private final int active; private final long completed; private final long rejected; @ConstructorProperties({"name", "poolSize", "queueSize", "largestPoolSize", "active", "completed", "rejected"}) public ThreadPoolInfo(String name, int poolSize, int queueSize, int largestPoolSize, int active, long completed, long rejected) { this.name = name; this.poolSize = poolSize; this.queueSize = queueSize; this.largestPoolSize = largestPoolSize; this.active = active; this.completed = completed; this.rejected = rejected; } @SuppressWarnings("unused") public String getName() { return name; } @SuppressWarnings("unused") public int getPoolSize() { return poolSize; } @SuppressWarnings("unused") public int getQueueSize() { return queueSize; } @SuppressWarnings("unused") public int getLargestPoolSize() { return largestPoolSize; } @SuppressWarnings("unused") public int getActive() { return active; } @SuppressWarnings("unused") public long getCompleted() { return completed; } @SuppressWarnings("unused") public long getRejected() { return rejected; } } public static final String NAME = "io.crate.monitoring:type=ThreadPools"; private final ThreadPool threadPool; public ThreadPools(ThreadPool threadPool) { this.threadPool = threadPool; } @Nullable private ThreadPoolInfo getThreadPoolInfo(String name) {<FILL_FUNCTION_BODY>
for (ThreadPoolStats.Stats stats : threadPool.stats()) { if (stats.getName().equals(name)) { return new ThreadPoolInfo( stats.getName(), stats.getThreads(), stats.getQueue(), stats.getLargest(), stats.getActive(), stats.getCompleted(), stats.getRejected()); } } return null;
521
105
626
<no_super_class>
crate_crate
crate/libs/cli/src/main/java/org/elasticsearch/cli/Command.java
Command
main
class Command implements Closeable { /** A description of the command, used in the help output. */ protected final String description; private final Runnable beforeMain; /** The option parser for this command. */ protected final OptionParser parser = new OptionParser(); private final OptionSpec<Void> helpOption = parser.acceptsAll(Arrays.asList("h", "help"), "show help").forHelp(); private final OptionSpec<Void> silentOption = parser.acceptsAll(Arrays.asList("s", "silent"), "show minimal output"); private final OptionSpec<Void> verboseOption = parser.acceptsAll(Arrays.asList("v", "verbose"), "show verbose output").availableUnless(silentOption); /** * Construct the command with the specified command description and runnable to execute before main is invoked. * * @param description the command description * @param beforeMain the before-main runnable */ public Command(final String description, final Runnable beforeMain) { this.description = description; this.beforeMain = beforeMain; } /** Parses options for this command from args and executes it. */ public final int main(String[] args, Terminal terminal) throws Exception {<FILL_FUNCTION_BODY>} /** * Executes the command, but all errors are thrown. */ public void mainWithoutErrorHandling(String[] args, Terminal terminal) throws Exception { final OptionSet options = parser.parse(args); if (options.has(helpOption)) { printHelp(terminal); return; } if (options.has(silentOption)) { terminal.setVerbosity(Terminal.Verbosity.SILENT); } else if (options.has(verboseOption)) { terminal.setVerbosity(Terminal.Verbosity.VERBOSE); } else { terminal.setVerbosity(Terminal.Verbosity.NORMAL); } execute(terminal, options); } /** Prints a help message for the command to the terminal. */ private void printHelp(Terminal terminal) throws IOException { terminal.println(description); terminal.println(""); printAdditionalHelp(terminal); parser.printHelpOn(terminal.getWriter()); } /** * Prints additional help information, specific to the command */ protected void printAdditionalHelp(Terminal terminal) { } @SuppressForbidden(reason = "Allowed to exit explicitly from #main()") protected static void exit(int status) { System.exit(status); } /** * Executes this command. * * Any runtime user errors (like an input file that does not exist), should throw a {@link UserException}. */ protected abstract void execute(Terminal terminal, OptionSet options) throws Exception; @Override public void close() throws IOException { } }
Thread shutdownHookThread = new Thread(() -> { try { this.close(); } catch (final IOException e) { try ( StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); terminal.println(sw.toString()); } catch (final IOException impossible) { // StringWriter#close declares a checked IOException from the Closeable interface but the Javadocs for StringWriter // say that an exception here is impossible throw new AssertionError(impossible); } } }); Runtime.getRuntime().addShutdownHook(shutdownHookThread); beforeMain.run(); try { mainWithoutErrorHandling(args, terminal); } catch (OptionException e) { printHelp(terminal); terminal.println(Terminal.Verbosity.SILENT, "ERROR: " + e.getMessage()); return ExitCodes.USAGE; } catch (UserException e) { if (e.exitCode == ExitCodes.USAGE) { printHelp(terminal); } terminal.println(Terminal.Verbosity.SILENT, "ERROR: " + e.getMessage()); return e.exitCode; } return ExitCodes.OK;
744
330
1,074
<no_super_class>
crate_crate
crate/libs/cli/src/main/java/org/elasticsearch/cli/Terminal.java
SystemTerminal
readText
class SystemTerminal extends Terminal { private static final PrintWriter WRITER = newWriter(); SystemTerminal() { super(System.lineSeparator()); } @SuppressForbidden(reason = "Writer for System.out") private static PrintWriter newWriter() { return new PrintWriter(System.out); } @Override public PrintWriter getWriter() { return WRITER; } @Override public String readText(String text) {<FILL_FUNCTION_BODY>} }
getWriter().print(text); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset())); try { final String line = reader.readLine(); if (line == null) { throw new IllegalStateException("unable to read from standard input; is standard input open and a tty attached?"); } return line; } catch (IOException ioe) { throw new RuntimeException(ioe); }
142
122
264
<no_super_class>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/AsyncFlatMapBatchIterator.java
AsyncFlatMapBatchIterator
moveNext
class AsyncFlatMapBatchIterator<I, O> implements BatchIterator<O> { private final BatchIterator<I> source; private final AsyncFlatMapper<I, O> mapper; private NextAction nextAction = NextAction.SOURCE; private O current = null; private CloseableIterator<O> mappedElements; private boolean sourceExhausted = false; private enum NextAction { SOURCE, MAPPER, } public AsyncFlatMapBatchIterator(BatchIterator<I> source, AsyncFlatMapper<I, O> mapper) { this.source = source; this.mapper = mapper; } @Override public void kill(Throwable throwable) { source.kill(throwable); } @Override public O currentElement() { return current; } @Override public void moveToStart() { source.moveToStart(); sourceExhausted = false; mappedElements = null; nextAction = NextAction.SOURCE; current = null; } @Override public boolean moveNext() {<FILL_FUNCTION_BODY>} @Override public void close() { if (mappedElements != null) { mappedElements.close(); mappedElements = null; } source.close(); try { mapper.close(); } catch (Exception e) { throw Exceptions.toRuntimeException(e); } } @Override public CompletionStage<?> loadNextBatch() throws Exception { if (nextAction == NextAction.SOURCE) { return source.loadNextBatch(); } else { return mapper.apply(source.currentElement(), sourceExhausted).thenAccept(rows -> { mappedElements = rows; }); } } @Override public boolean allLoaded() { return source.allLoaded() && nextAction == NextAction.SOURCE; } @Override public boolean hasLazyResultSet() { return true; } }
while (true) { if (nextAction == NextAction.SOURCE) { if (source.moveNext()) { nextAction = NextAction.MAPPER; } else { sourceExhausted = source.allLoaded(); } return false; } else { if (mappedElements == null) { // This is the case if a consumer didn't call loadNextBatch after a previous moveNext call returned false return false; } if (mappedElements.hasNext()) { current = mappedElements.next(); return true; } else { // Make sure objects can be GCd early; // Otherwise it would have to wait for the next loadNextBatch call+completion of the async operation mappedElements.close(); mappedElements = null; nextAction = NextAction.SOURCE; continue; } } }
546
225
771
<no_super_class>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/CapturingRowConsumer.java
CapturingRowConsumer
accept
class CapturingRowConsumer implements RowConsumer { private final CompletableFuture<BatchIterator<Row>> batchIterator; private final CompletableFuture<?> completionFuture; private final boolean requiresScroll; public CapturingRowConsumer(boolean requiresScroll, CompletableFuture<?> completionFuture) { this.batchIterator = new CompletableFuture<>(); this.completionFuture = completionFuture; this.requiresScroll = requiresScroll; } @Override public void accept(BatchIterator<Row> iterator, @Nullable Throwable failure) {<FILL_FUNCTION_BODY>} public CompletableFuture<BatchIterator<Row>> capturedBatchIterator() { return batchIterator; } @Override public CompletableFuture<?> completionFuture() { return completionFuture; } @Override public boolean requiresScroll() { return requiresScroll; } @Override public String toString() { return "CapturingRowConsumer{captured=" + batchIterator.isDone() + '}'; } }
if (failure == null) { batchIterator.complete(iterator); } else { batchIterator.completeExceptionally(failure); }
269
42
311
<no_super_class>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/CollectingBatchIterator.java
CollectingBatchIterator
newInstance
class CollectingBatchIterator<T> implements BatchIterator<T> { private final Supplier<CompletableFuture<? extends Iterable<? extends T>>> loadItems; private final Runnable onClose; private final Consumer<? super Throwable> onKill; private final boolean involvesIO; private CompletableFuture<? extends Iterable<? extends T>> resultFuture; private Iterator<? extends T> it = Collections.emptyIterator(); private T current; private volatile Throwable killed; private CollectingBatchIterator(Supplier<CompletableFuture<? extends Iterable<? extends T>>> loadItems, Runnable onClose, Consumer<? super Throwable> onKill, boolean involvesIO) { this.loadItems = loadItems; this.onClose = onClose; this.onKill = onKill; this.involvesIO = involvesIO; } /** * Create a BatchIterator which will consume the source, summing up the first column (must be of type long). * * <pre> * source BatchIterator: * [ 1, 2, 2, 1 ] * * output: * [ 6 ] * </pre> */ public static BatchIterator<Row> summingLong(BatchIterator<Row> source) { return newInstance( source, Collectors.collectingAndThen( Collectors.summingLong(r -> (long) r.get(0)), sum -> Collections.singletonList(new Row1(sum)))); } public static <T, A> BatchIterator<T> newInstance(BatchIterator<T> source, Collector<T, A, ? extends Iterable<? extends T>> collector) {<FILL_FUNCTION_BODY>} public static <I, O> BatchIterator<O> newInstance(BatchIterator<I> source, Function<BatchIterator<I>, CompletableFuture<? extends Iterable<? extends O>>> processSource, boolean involvesIO) { return newInstance( source::close, source::kill, () -> processSource.apply(source).whenComplete((r, f) -> source.close()), involvesIO); } public static <T> BatchIterator<T> newInstance(Runnable onClose, Consumer<? super Throwable> onKill, Supplier<CompletableFuture<? extends Iterable<? extends T>>> loadItems, boolean involvesIO) { return new CollectingBatchIterator<>(loadItems, onClose, onKill, involvesIO); } @Override public T currentElement() { return current; } @Override public void moveToStart() { raiseIfKilled(); if (resultFuture != null) { if (resultFuture.isDone() == false) { throw new IllegalStateException("BatchIterator is loading"); } it = resultFuture.join().iterator(); } current = null; } @Override public boolean moveNext() { raiseIfKilled(); if (it.hasNext()) { current = it.next(); return true; } current = null; return false; } @Override public void close() { onClose.run(); killed = BatchIterator.CLOSED; } @Override public CompletionStage<?> loadNextBatch() throws Exception { if (resultFuture == null) { resultFuture = loadItems.get() .whenComplete((r, t) -> { if (t == null) { it = r.iterator(); } else if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw new RuntimeException(t); } }); return resultFuture; } throw new IllegalStateException("BatchIterator already loaded"); } @Override public boolean allLoaded() { return resultFuture != null; } @Override public void kill(@NotNull Throwable throwable) { onKill.accept(throwable); killed = throwable; } @Override public boolean hasLazyResultSet() { return involvesIO; } private void raiseIfKilled() { if (killed != null) { Exceptions.rethrowUnchecked(killed); } } }
return newInstance( source::close, source::kill, () -> source.collect(collector), source.hasLazyResultSet() );
1,152
46
1,198
<no_super_class>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/CompositeBatchIterator.java
AsyncCompositeBI
loadNextBatch
class AsyncCompositeBI<T> extends AbstractCompositeBI<T> { private final Executor executor; private final IntSupplier availableThreads; AsyncCompositeBI(Executor executor, IntSupplier availableThreads, BatchIterator<T>[] iterators) { super(iterators); this.executor = executor; this.availableThreads = availableThreads; } @Override public boolean moveNext() { while (idx < iterators.length) { BatchIterator<T> iterator = iterators[idx]; if (iterator.moveNext()) { return true; } idx++; } idx = 0; return false; } private int numIteratorsActive() { int activeIts = 0; for (var it : iterators) { if (!it.allLoaded()) { activeIts++; } } return activeIts; } @Override public CompletionStage<?> loadNextBatch() throws Exception {<FILL_FUNCTION_BODY>} }
if (allLoaded()) { throw new IllegalStateException("BatchIterator already loaded"); } int activeIts = numIteratorsActive(); int numThreads = Math.max(1, availableThreads.getAsInt()); final int usedThreads = Math.min(numThreads, activeIts); ArrayList<CompletableFuture<CompletableFuture<?>>> nestedFutures = new ArrayList<>(usedThreads); for (int t = 0; t < usedThreads; t++) { final int thread = t; nestedFutures.add(supplyAsync(() -> { ArrayList<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < iterators.length; i++) { var it = iterators[i]; if (it.allLoaded() || i % usedThreads != thread) { continue; } try { futures.add(it.loadNextBatch().toCompletableFuture()); } catch (Exception e) { throw Exceptions.toRuntimeException(e); } } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); }, executor)); } return CompletableFutures.allAsList(nestedFutures) .thenCompose(innerFutures -> CompletableFuture.allOf(innerFutures.toArray(new CompletableFuture[0])));
283
356
639
<no_super_class>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/FilteringBatchIterator.java
FilteringBatchIterator
moveNext
class FilteringBatchIterator<T> extends ForwardingBatchIterator<T> { private final BatchIterator<T> delegate; private final Predicate<T> filter; public FilteringBatchIterator(BatchIterator<T> delegate, Predicate<T> filter) { this.delegate = delegate; this.filter = filter; } @Override protected BatchIterator<T> delegate() { return delegate; } @Override public boolean moveNext() {<FILL_FUNCTION_BODY>} }
while (delegate.moveNext()) { if (filter.test(delegate.currentElement())) { return true; } } return false;
140
47
187
<methods>public non-sealed void <init>() ,public T currentElement() ,public boolean hasLazyResultSet() <variables>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/FlatMapBatchIterator.java
FlatMapBatchIterator
moveNext
class FlatMapBatchIterator<TIn, TOut> implements BatchIterator<TOut> { private final BatchIterator<TIn> source; private final Function<TIn, ? extends Iterator<TOut>> mapper; private TOut current = null; private boolean onSourceRow = false; private Iterator<TOut> mappedElements; public FlatMapBatchIterator(BatchIterator<TIn> source, Function<TIn, ? extends Iterator<TOut>> mapper) { this.source = source; this.mapper = mapper; } @Override public TOut currentElement() { return current; } @Override public void moveToStart() { current = null; mappedElements = null; onSourceRow = false; source.moveToStart(); } @Override public boolean moveNext() {<FILL_FUNCTION_BODY>} @Override public void close() { source.close(); } @Override public CompletionStage<?> loadNextBatch() throws Exception { return source.loadNextBatch(); } @Override public boolean allLoaded() { return source.allLoaded(); } @Override public void kill(@NotNull Throwable throwable) { source.kill(throwable); } @Override public boolean hasLazyResultSet() { return source.hasLazyResultSet(); } }
while (true) { if (onSourceRow) { if (mappedElements == null) { mappedElements = mapper.apply(source.currentElement()); } if (mappedElements.hasNext()) { current = mappedElements.next(); return true; } else { onSourceRow = false; mappedElements = null; // continue with source.moveNext() } } else { onSourceRow = source.moveNext(); if (!onSourceRow) { return false; } } }
380
146
526
<no_super_class>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/RowN.java
RowN
cells
class RowN extends Row { private final int size; private Object[] cells; public RowN(int size) { this.size = size; } public RowN(Object ... cells) { this(cells.length); this.cells = cells; } @Override public int numColumns() { return size; } public void cells(Object[] cells) {<FILL_FUNCTION_BODY>} @Override public Object get(int index) { assert cells != null : "cells must not be null"; return cells[index]; } @Override public Object[] materialize() { Object[] result = new Object[size]; System.arraycopy(cells, 0, result, 0, size); return result; } @Override public String toString() { return "RowN{" + Arrays.toString(cells) + '}'; } }
assert cells != null : "cells must not be null"; this.cells = cells;
254
28
282
<methods>public non-sealed void <init>() ,public final boolean equals(java.lang.Object) ,public abstract java.lang.Object get(int) ,public final int hashCode() ,public java.lang.Object[] materialize() ,public abstract int numColumns() <variables>public static final io.crate.data.Row EMPTY
crate_crate
crate/libs/dex/src/main/java/io/crate/data/breaker/BlockBasedRamAccounting.java
BlockBasedRamAccounting
addBytes
class BlockBasedRamAccounting implements RamAccounting { public static final int MAX_BLOCK_SIZE_IN_BYTES = 2 * 1024 * 1024; /** * 2 GB × 0.001 ➞ MB * = 2 MB * * 256 MB × 0.001 ➞ MB * * = 0.256 MB */ private static final double BREAKER_LIMIT_PERCENTAGE = 0.001; private final LongConsumer reserveMemory; private final int blockSizeInBytes; private long usedBytes = 0; private long reservedBytes = 0; /** * Scale the block size that is eagerly allocated depending on the circuit breakers current limit and the shards * on the node. */ public static int blockSizeInBytesPerShard(long breakerLimit, int shardsUsedOnNode) { int blockSize = Math.min((int) (breakerLimit * BREAKER_LIMIT_PERCENTAGE), MAX_BLOCK_SIZE_IN_BYTES); return blockSize / Math.max(shardsUsedOnNode, 1); } public static int blockSizeInBytes(long breakerLimit) { return Math.min((int) (breakerLimit * BREAKER_LIMIT_PERCENTAGE), MAX_BLOCK_SIZE_IN_BYTES); } public BlockBasedRamAccounting(LongConsumer reserveMemory, int blockSizeInBytes) { this.reserveMemory = reserveMemory; this.blockSizeInBytes = blockSizeInBytes; } @Override public void addBytes(long bytes) {<FILL_FUNCTION_BODY>} @Override public long totalBytes() { return usedBytes; } @Override public void release() { reserveMemory.accept(- reservedBytes); usedBytes = 0; reservedBytes = 0; } @Override public void close() { release(); } @Override public String toString() { return "RamAccounting{" + "usedBytes=" + usedBytes + ", reservedBytes=" + reservedBytes + '}'; } }
usedBytes += bytes; if ((reservedBytes - usedBytes) < 0) { long reserveBytes = bytes > blockSizeInBytes ? bytes : blockSizeInBytes; try { reserveMemory.accept(reserveBytes); } catch (Exception e) { usedBytes -= bytes; throw e; } reservedBytes += reserveBytes; } assert reservedBytes >= usedBytes : "reservedBytes must be >= usedBytes: " + toString();
583
120
703
<no_super_class>
crate_crate
crate/libs/dex/src/main/java/io/crate/data/join/CombinedRow.java
CombinedRow
get
class CombinedRow extends Row implements ElementCombiner<Row, Row, Row> { private final int numCols; private final int leftNumCols; private Row left; private Row right; public CombinedRow(int leftNumCols, int rightNumCols) { this.leftNumCols = leftNumCols; this.numCols = leftNumCols + rightNumCols; } @Override public int numColumns() { return numCols; } @Override public Object get(int index) {<FILL_FUNCTION_BODY>} @Override public Row currentElement() { return this; } public void nullLeft() { left = null; } public void nullRight() { right = null; } @Override public void setRight(Row o) { right = o; } @Override public void setLeft(Row o) { left = o; } @Override public String toString() { return "CombinedRow{" + "lhs=" + left + ", rhs=" + right + '}'; } }
if (index < leftNumCols) { if (left == null) { return null; } return left.get(index); } index = index - leftNumCols; if (right == null) { return null; } return right.get(index);
317
81
398
<methods>public non-sealed void <init>() ,public final boolean equals(java.lang.Object) ,public abstract java.lang.Object get(int) ,public final int hashCode() ,public java.lang.Object[] materialize() ,public abstract int numColumns() <variables>public static final io.crate.data.Row EMPTY
crate_crate
crate/libs/dex/src/main/java/io/crate/data/join/LeftJoinNLBatchIterator.java
LeftJoinNLBatchIterator
tryAdvanceRight
class LeftJoinNLBatchIterator<L, R, C> extends JoinBatchIterator<L, R, C> { private final Predicate<C> joinCondition; private boolean hadMatch = false; public LeftJoinNLBatchIterator(BatchIterator<L> left, BatchIterator<R> right, ElementCombiner<L, R, C> combiner, Predicate<C> joinCondition) { super(left, right, combiner); this.joinCondition = joinCondition; } @Override public boolean moveNext() { while (true) { if (activeIt == left) { return moveLeftSide(); } Boolean x = tryAdvanceRight(); if (x != null) { return x; } activeIt = left; } } private boolean moveLeftSide() { activeIt = right; while (tryMoveLeft()) { Boolean x = tryAdvanceRight(); if (x != null) { return x; } } activeIt = left; return false; } /** * try to move the right side * * @return true -> moved and matched * false -> need to load more data * null -> reached it's end and moved back to start -> left side needs to continue */ private Boolean tryAdvanceRight() {<FILL_FUNCTION_BODY>} }
while (tryMoveRight()) { if (joinCondition.test(combiner.currentElement())) { hadMatch = true; return true; } } if (right.allLoaded() == false) { return false; } right.moveToStart(); if (hadMatch == false) { activeIt = left; combiner.nullRight(); return true; } hadMatch = false; return null;
370
122
492
<methods>public boolean allLoaded() ,public void close() ,public C currentElement() ,public boolean hasLazyResultSet() ,public void kill(java.lang.Throwable) ,public CompletionStage<?> loadNextBatch() throws java.lang.Exception,public void moveToStart() <variables>protected BatchIterator<?> activeIt,protected final non-sealed ElementCombiner<L,R,C> combiner,protected final non-sealed BatchIterator<L> left,protected final non-sealed BatchIterator<R> right
crate_crate
crate/libs/es-x-content/src/main/java/org/elasticsearch/common/xcontent/ParseField.java
ParseField
match
class ParseField { private final String name; private final String[] deprecatedNames; private String allReplacedWith = null; private final String[] allNames; private static final String[] EMPTY = new String[0]; /** * @param name * the primary name for this field. This will be returned by * {@link #getPreferredName()} * @param deprecatedNames * names for this field which are deprecated and will not be * accepted when strict matching is used. */ public ParseField(String name, String... deprecatedNames) { this.name = name; if (deprecatedNames == null || deprecatedNames.length == 0) { this.deprecatedNames = EMPTY; } else { final HashSet<String> set = new HashSet<>(); Collections.addAll(set, deprecatedNames); this.deprecatedNames = set.toArray(new String[set.size()]); } Set<String> allNames = new HashSet<>(); allNames.add(name); Collections.addAll(allNames, this.deprecatedNames); this.allNames = allNames.toArray(new String[allNames.size()]); } /** * @return the preferred name used for this field */ public String getPreferredName() { return name; } /** * @return All names for this field regardless of whether they are * deprecated */ public String[] getAllNamesIncludedDeprecated() { return allNames; } /** * @param deprecatedNames * deprecated names to include with the returned * {@link ParseField} * @return a new {@link ParseField} using the preferred name from this one * but with the specified deprecated names */ public ParseField withDeprecation(String... deprecatedNames) { return new ParseField(this.name, deprecatedNames); } /** * Does {@code fieldName} match this field? * @param fieldName * the field name to match against this {@link ParseField} * @param deprecationHandler called if {@code fieldName} is deprecated * @return true if <code>fieldName</code> matches any of the acceptable * names for this {@link ParseField}. */ public boolean match(String fieldName, DeprecationHandler deprecationHandler) {<FILL_FUNCTION_BODY>} @Override public String toString() { return getPreferredName(); } /** * @return the message to use if this {@link ParseField} has been entirely * deprecated in favor of something else. This method will return * <code>null</code> if the ParseField has not been completely * deprecated. */ public String getAllReplacedWith() { return allReplacedWith; } /** * @return an array of the names for the {@link ParseField} which are * deprecated. */ public String[] getDeprecatedNames() { return deprecatedNames; } }
Objects.requireNonNull(fieldName, "fieldName cannot be null"); // if this parse field has not been completely deprecated then try to // match the preferred name if (allReplacedWith == null && fieldName.equals(name)) { return true; } // Now try to match against one of the deprecated names. Note that if // the parse field is entirely deprecated (allReplacedWith != null) all // fields will be in the deprecatedNames array for (String depName : deprecatedNames) { if (fieldName.equals(depName)) { if (allReplacedWith == null) { deprecationHandler.usedDeprecatedName(fieldName, name); } else { deprecationHandler.usedDeprecatedField(fieldName, allReplacedWith); } return true; } } return false;
808
221
1,029
<no_super_class>
crate_crate
crate/libs/es-x-content/src/main/java/org/elasticsearch/common/xcontent/json/JsonXContentParser.java
JsonXContentParser
convertToken
class JsonXContentParser extends AbstractXContentParser { final JsonParser parser; public JsonXContentParser(NamedXContentRegistry xContentRegistry, DeprecationHandler deprecationHandler, JsonParser parser) { super(xContentRegistry, deprecationHandler); this.parser = parser; } @Override public XContentType contentType() { return XContentType.JSON; } @Override public Token nextToken() throws IOException { return convertToken(parser.nextToken()); } @Override public void skipChildren() throws IOException { parser.skipChildren(); } @Override public Token currentToken() { return convertToken(parser.getCurrentToken()); } @Override public NumberType numberType() throws IOException { return convertNumberType(parser.getNumberType()); } @Override public String currentName() throws IOException { return parser.getCurrentName(); } @Override protected boolean doBooleanValue() throws IOException { return parser.getBooleanValue(); } @Override public String text() throws IOException { if (currentToken().isValue()) { return parser.getText(); } throw new IllegalStateException("Can't get text on a " + currentToken() + " at " + getTokenLocation()); } @Override public CharBuffer charBuffer() throws IOException { return CharBuffer.wrap(parser.getTextCharacters(), parser.getTextOffset(), parser.getTextLength()); } @Override public Object objectText() throws IOException { JsonToken currentToken = parser.getCurrentToken(); if (currentToken == JsonToken.VALUE_STRING) { return text(); } else if (currentToken == JsonToken.VALUE_NUMBER_INT || currentToken == JsonToken.VALUE_NUMBER_FLOAT) { return parser.getNumberValue(); } else if (currentToken == JsonToken.VALUE_TRUE) { return Boolean.TRUE; } else if (currentToken == JsonToken.VALUE_FALSE) { return Boolean.FALSE; } else if (currentToken == JsonToken.VALUE_NULL) { return null; } else { return text(); } } @Override public boolean hasTextCharacters() { return parser.hasTextCharacters(); } @Override public char[] textCharacters() throws IOException { return parser.getTextCharacters(); } @Override public int textLength() throws IOException { return parser.getTextLength(); } @Override public int textOffset() throws IOException { return parser.getTextOffset(); } @Override public Number numberValue() throws IOException { return parser.getNumberValue(); } @Override public short doShortValue() throws IOException { return parser.getShortValue(); } @Override public int doIntValue() throws IOException { return parser.getIntValue(); } @Override public long doLongValue() throws IOException { return parser.getLongValue(); } @Override public float doFloatValue() throws IOException { return parser.getFloatValue(); } @Override public double doDoubleValue() throws IOException { return parser.getDoubleValue(); } @Override public byte[] binaryValue() throws IOException { return parser.getBinaryValue(); } @Override public XContentLocation getTokenLocation() { JsonLocation loc = parser.getTokenLocation(); if (loc == null) { return null; } return new XContentLocation(loc.getLineNr(), loc.getColumnNr()); } @Override public void close() { IOUtils.closeWhileHandlingException(parser); } private NumberType convertNumberType(JsonParser.NumberType numberType) { switch (numberType) { case INT: return NumberType.INT; case LONG: return NumberType.LONG; case FLOAT: return NumberType.FLOAT; case DOUBLE: return NumberType.DOUBLE; default: throw new IllegalStateException("No matching token for number_type [" + numberType + "]"); } } private Token convertToken(JsonToken token) {<FILL_FUNCTION_BODY>} @Override public boolean isClosed() { return parser.isClosed(); } }
if (token == null) { return null; } switch (token) { case FIELD_NAME: return Token.FIELD_NAME; case VALUE_FALSE: case VALUE_TRUE: return Token.VALUE_BOOLEAN; case VALUE_STRING: return Token.VALUE_STRING; case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: return Token.VALUE_NUMBER; case VALUE_NULL: return Token.VALUE_NULL; case START_OBJECT: return Token.START_OBJECT; case END_OBJECT: return Token.END_OBJECT; case START_ARRAY: return Token.START_ARRAY; case END_ARRAY: return Token.END_ARRAY; case VALUE_EMBEDDED_OBJECT: return Token.VALUE_EMBEDDED_OBJECT; default: throw new IllegalStateException("No matching token for json_token [" + token + "]"); }
1,141
282
1,423
<methods>public void <init>(org.elasticsearch.common.xcontent.NamedXContentRegistry, org.elasticsearch.common.xcontent.DeprecationHandler) ,public boolean booleanValue() throws java.io.IOException,public double doubleValue() throws java.io.IOException,public double doubleValue(boolean) throws java.io.IOException,public float floatValue() throws java.io.IOException,public float floatValue(boolean) throws java.io.IOException,public org.elasticsearch.common.xcontent.DeprecationHandler getDeprecationHandler() ,public org.elasticsearch.common.xcontent.NamedXContentRegistry getXContentRegistry() ,public int intValue() throws java.io.IOException,public int intValue(boolean) throws java.io.IOException,public boolean isBooleanValue() throws java.io.IOException,public abstract boolean isClosed() ,public List<java.lang.Object> list() throws java.io.IOException,public List<java.lang.Object> listOrderedMap() throws java.io.IOException,public long longValue() throws java.io.IOException,public long longValue(boolean) throws java.io.IOException,public Map<java.lang.String,java.lang.Object> map() throws java.io.IOException,public Map<java.lang.String,T> map(Supplier<Map<java.lang.String,T>>, CheckedFunction<org.elasticsearch.common.xcontent.XContentParser,T,java.io.IOException>) throws java.io.IOException,public Map<java.lang.String,java.lang.Object> mapOrdered() throws java.io.IOException,public Map<java.lang.String,java.lang.String> mapStrings() throws java.io.IOException,public T namedObject(Class<T>, java.lang.String, java.lang.Object) throws java.io.IOException,public short shortValue(boolean) throws java.io.IOException,public final java.lang.String textOrNull() throws java.io.IOException<variables>public static final boolean DEFAULT_NUMBER_COERCE_POLICY,static final org.elasticsearch.common.xcontent.support.AbstractXContentParser.MapFactory ORDERED_MAP_FACTORY,static final org.elasticsearch.common.xcontent.support.AbstractXContentParser.MapStringsFactory ORDERED_MAP_STRINGS_FACTORY,static final org.elasticsearch.common.xcontent.support.AbstractXContentParser.MapFactory SIMPLE_MAP_FACTORY,static final org.elasticsearch.common.xcontent.support.AbstractXContentParser.MapStringsFactory SIMPLE_MAP_STRINGS_FACTORY,private final non-sealed org.elasticsearch.common.xcontent.DeprecationHandler deprecationHandler,private final non-sealed org.elasticsearch.common.xcontent.NamedXContentRegistry xContentRegistry
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/AbstractModule.java
AbstractModule
configure
class AbstractModule implements Module { Binder binder; @Override public final synchronized void configure(Binder builder) {<FILL_FUNCTION_BODY>} /** * Configures a {@link Binder} via the exposed methods. */ protected abstract void configure(); /** * Gets direct access to the underlying {@code Binder}. */ protected Binder binder() { return binder; } /** * @see Binder#bindScope(Class, Scope) */ protected void bindScope(Class<? extends Annotation> scopeAnnotation, Scope scope) { binder.bindScope(scopeAnnotation, scope); } /** * @see Binder#bind(Key) */ protected <T> LinkedBindingBuilder<T> bind(Key<T> key) { return binder.bind(key); } /** * @see Binder#bind(TypeLiteral) */ protected <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) { return binder.bind(typeLiteral); } /** * @see Binder#bind(Class) */ protected <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz) { return binder.bind(clazz); } /** * @see Binder#bindConstant() */ protected AnnotatedConstantBindingBuilder bindConstant() { return binder.bindConstant(); } /** * @see Binder#install(Module) */ protected void install(Module module) { binder.install(module); } /** * @see Binder#addError(String, Object[]) */ protected void addError(String message, Object... arguments) { binder.addError(message, arguments); } /** * @see Binder#addError(Throwable) */ protected void addError(Throwable t) { binder.addError(t); } /** * @see Binder#addError(Message) * @since 2.0 */ protected void addError(Message message) { binder.addError(message); } /** * @see Binder#requestInjection(Object) * @since 2.0 */ protected void requestInjection(Object instance) { binder.requestInjection(instance); } /** * @see Binder#requestStaticInjection(Class[]) */ protected void requestStaticInjection(Class<?>... types) { binder.requestStaticInjection(types); } /** * Adds a dependency from this module to {@code key}. When the injector is * created, Guice will report an error if {@code key} cannot be injected. * Note that this requirement may be satisfied by implicit binding, such as * a public no-arguments constructor. * * @since 2.0 */ protected void requireBinding(Key<?> key) { binder.getProvider(key); } /** * Adds a dependency from this module to {@code type}. When the injector is * created, Guice will report an error if {@code type} cannot be injected. * Note that this requirement may be satisfied by implicit binding, such as * a public no-arguments constructor. * * @since 2.0 */ protected void requireBinding(Class<?> type) { binder.getProvider(type); } /** * @see Binder#getProvider(Key) * @since 2.0 */ protected <T> Provider<T> getProvider(Key<T> key) { return binder.getProvider(key); } /** * @see Binder#getProvider(Class) * @since 2.0 */ protected <T> Provider<T> getProvider(Class<T> type) { return binder.getProvider(type); } /** * @see Binder#convertToTypes * @since 2.0 */ protected void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter) { binder.convertToTypes(typeMatcher, converter); } /** * @see Binder#currentStage() * @since 2.0 */ protected Stage currentStage() { return binder.currentStage(); } /** * @see Binder#getMembersInjector(Class) * @since 2.0 */ protected <T> MembersInjector<T> getMembersInjector(Class<T> type) { return binder.getMembersInjector(type); } /** * @see Binder#getMembersInjector(TypeLiteral) * @since 2.0 */ protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) { return binder.getMembersInjector(type); } /** * @see Binder#bindListener(org.elasticsearch.common.inject.matcher.Matcher, * org.elasticsearch.common.inject.spi.TypeListener) * @since 2.0 */ protected void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener) { binder.bindListener(typeMatcher, listener); } }
if (this.binder != null) { throw new IllegalStateException("Re-entry is not allowed."); } this.binder = Objects.requireNonNull(builder, "builder"); try { configure(); } finally { this.binder = null; }
1,434
78
1,512
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/BoundProviderFactory.java
BoundProviderFactory
notify
class BoundProviderFactory<T> implements InternalFactory<T>, CreationListener { private final InjectorImpl injector; final Key<? extends Provider<? extends T>> providerKey; final Object source; private InternalFactory<? extends Provider<? extends T>> providerFactory; BoundProviderFactory( InjectorImpl injector, Key<? extends Provider<? extends T>> providerKey, Object source) { this.injector = injector; this.providerKey = providerKey; this.source = source; } @Override public void notify(Errors errors) {<FILL_FUNCTION_BODY>} @Override public T get(Errors errors, InternalContext context, Dependency<?> dependency) throws ErrorsException { errors = errors.withSource(providerKey); Provider<? extends T> provider = providerFactory.get(errors, context, dependency); try { return errors.checkForNull(provider.get(), source, dependency); } catch (RuntimeException userException) { throw errors.errorInProvider(userException).toException(); } } @Override public String toString() { return providerKey.toString(); } }
try { providerFactory = injector.getInternalFactory(providerKey, errors.withSource(source)); } catch (ErrorsException e) { errors.merge(e.getErrors()); }
317
53
370
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/DefaultConstructionProxyFactory.java
DefaultConstructionProxyFactory
create
class DefaultConstructionProxyFactory<T> implements ConstructionProxyFactory<T> { private final InjectionPoint injectionPoint; /** * @param injectionPoint an injection point whose member is a constructor of {@code T}. */ DefaultConstructionProxyFactory(InjectionPoint injectionPoint) { this.injectionPoint = injectionPoint; } @Override public ConstructionProxy<T> create() {<FILL_FUNCTION_BODY>} }
@SuppressWarnings("unchecked") // the injection point is for a constructor of T final Constructor<T> constructor = (Constructor<T>) injectionPoint.getMember(); return new ConstructionProxy<T>() { @Override public T newInstance(Object... arguments) throws InvocationTargetException { try { return constructor.newInstance(arguments); } catch (InstantiationException e) { throw new AssertionError(e); // shouldn't happen, we know this is a concrete type } catch (IllegalAccessException e) { throw new AssertionError("Wrong access modifiers on " + constructor, e); // a security manager is blocking us, we're hosed } } @Override public InjectionPoint getInjectionPoint() { return injectionPoint; } @Override public Constructor<T> getConstructor() { return constructor; } };
115
234
349
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/FactoryProxy.java
FactoryProxy
notify
class FactoryProxy<T> implements InternalFactory<T>, BindingProcessor.CreationListener { private final InjectorImpl injector; private final Key<T> key; private final Key<? extends T> targetKey; private final Object source; private InternalFactory<? extends T> targetFactory; FactoryProxy(InjectorImpl injector, Key<T> key, Key<? extends T> targetKey, Object source) { this.injector = injector; this.key = key; this.targetKey = targetKey; this.source = source; } @Override public void notify(final Errors errors) {<FILL_FUNCTION_BODY>} @Override public T get(Errors errors, InternalContext context, Dependency<?> dependency) throws ErrorsException { return targetFactory.get(errors.withSource(targetKey), context, dependency); } @Override public String toString() { return new ToStringBuilder(FactoryProxy.class) .add("key", key) .add("provider", targetFactory) .toString(); } }
try { targetFactory = injector.getInternalFactory(targetKey, errors.withSource(source)); } catch (ErrorsException e) { errors.merge(e.getErrors()); }
290
53
343
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/Initializables.java
Initializables
of
class Initializables { /** * Returns an initializable for an instance that requires no initialization. */ static <T> Initializable<T> of(final T instance) {<FILL_FUNCTION_BODY>} }
return new Initializable<T>() { @Override public T get(Errors errors) throws ErrorsException { return instance; } @Override public String toString() { return String.valueOf(instance); } };
60
69
129
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/LookupProcessor.java
LookupProcessor
visit
class LookupProcessor extends AbstractProcessor { LookupProcessor(Errors errors) { super(errors); } @Override public <T> Boolean visit(MembersInjectorLookup<T> lookup) {<FILL_FUNCTION_BODY>} @Override public <T> Boolean visit(ProviderLookup<T> lookup) { // ensure the provider can be created try { Provider<T> provider = injector.getProviderOrThrow(lookup.getKey(), errors); lookup.initializeDelegate(provider); } catch (ErrorsException e) { errors.merge(e.getErrors()); // TODO: source } return true; } }
try { MembersInjector<T> membersInjector = injector.membersInjectorStore.get(lookup.getType(), errors); lookup.initializeDelegate(membersInjector); } catch (ErrorsException e) { errors.merge(e.getErrors()); // TODO: source } return true;
177
89
266
<methods>public void process(Iterable<org.elasticsearch.common.inject.InjectorShell>) ,public void process(org.elasticsearch.common.inject.InjectorImpl, List<org.elasticsearch.common.inject.spi.Element>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.Message) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.ScopeBinding) ,public java.lang.Boolean visit(InjectionRequest#RAW) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.StaticInjectionRequest) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.TypeConverterBinding) ,public java.lang.Boolean visit(Binding<T>) ,public java.lang.Boolean visit(ProviderLookup<T>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.PrivateElements) ,public java.lang.Boolean visit(MembersInjectorLookup<T>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.TypeListenerBinding) <variables>protected org.elasticsearch.common.inject.internal.Errors errors,protected org.elasticsearch.common.inject.InjectorImpl injector
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/PrivateElementProcessor.java
PrivateElementProcessor
visit
class PrivateElementProcessor extends AbstractProcessor { private final Stage stage; private final List<InjectorShell.Builder> injectorShellBuilders = new ArrayList<>(); PrivateElementProcessor(Errors errors, Stage stage) { super(errors); this.stage = stage; } @Override public Boolean visit(PrivateElements privateElements) {<FILL_FUNCTION_BODY>} public List<InjectorShell.Builder> getInjectorShellBuilders() { return injectorShellBuilders; } }
InjectorShell.Builder builder = new InjectorShell.Builder() .parent(injector) .stage(stage) .privateElements(privateElements); injectorShellBuilders.add(builder); return true;
136
63
199
<methods>public void process(Iterable<org.elasticsearch.common.inject.InjectorShell>) ,public void process(org.elasticsearch.common.inject.InjectorImpl, List<org.elasticsearch.common.inject.spi.Element>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.Message) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.ScopeBinding) ,public java.lang.Boolean visit(InjectionRequest#RAW) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.StaticInjectionRequest) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.TypeConverterBinding) ,public java.lang.Boolean visit(Binding<T>) ,public java.lang.Boolean visit(ProviderLookup<T>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.PrivateElements) ,public java.lang.Boolean visit(MembersInjectorLookup<T>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.TypeListenerBinding) <variables>protected org.elasticsearch.common.inject.internal.Errors errors,protected org.elasticsearch.common.inject.InjectorImpl injector
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/ScopeBindingProcessor.java
ScopeBindingProcessor
visit
class ScopeBindingProcessor extends AbstractProcessor { ScopeBindingProcessor(Errors errors) { super(errors); } @Override public Boolean visit(ScopeBinding command) {<FILL_FUNCTION_BODY>} }
Scope scope = command.getScope(); Class<? extends Annotation> annotationType = command.getAnnotationType(); if (!Annotations.isScopeAnnotation(annotationType)) { errors.withSource(annotationType).missingScopeAnnotation(); // Go ahead and bind anyway so we don't get collateral errors. } if (!Annotations.isRetainedAtRuntime(annotationType)) { errors.withSource(annotationType) .missingRuntimeRetention(command.getSource()); // Go ahead and bind anyway so we don't get collateral errors. } Scope existing = injector.state.getScope(Objects.requireNonNull(annotationType, "annotation type")); if (existing != null) { errors.duplicateScopes(existing, annotationType, scope); } else { injector.state.putAnnotation(annotationType, Objects.requireNonNull(scope, "scope")); } return true;
61
242
303
<methods>public void process(Iterable<org.elasticsearch.common.inject.InjectorShell>) ,public void process(org.elasticsearch.common.inject.InjectorImpl, List<org.elasticsearch.common.inject.spi.Element>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.Message) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.ScopeBinding) ,public java.lang.Boolean visit(InjectionRequest#RAW) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.StaticInjectionRequest) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.TypeConverterBinding) ,public java.lang.Boolean visit(Binding<T>) ,public java.lang.Boolean visit(ProviderLookup<T>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.PrivateElements) ,public java.lang.Boolean visit(MembersInjectorLookup<T>) ,public java.lang.Boolean visit(org.elasticsearch.common.inject.spi.TypeListenerBinding) <variables>protected org.elasticsearch.common.inject.internal.Errors errors,protected org.elasticsearch.common.inject.InjectorImpl injector
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/SingleFieldInjector.java
SingleFieldInjector
inject
class SingleFieldInjector implements SingleMemberInjector { final Field field; final InjectionPoint injectionPoint; final Dependency<?> dependency; final InternalFactory<?> factory; SingleFieldInjector(InjectorImpl injector, InjectionPoint injectionPoint, Errors errors) throws ErrorsException { this.injectionPoint = injectionPoint; this.field = (Field) injectionPoint.getMember(); this.dependency = injectionPoint.getDependencies().get(0); factory = injector.getInternalFactory(dependency.getKey(), errors); } @Override public InjectionPoint getInjectionPoint() { return injectionPoint; } @Override public void inject(Errors errors, InternalContext context, Object o) {<FILL_FUNCTION_BODY>} }
errors = errors.withSource(dependency); context.setDependency(dependency); try { Object value = factory.get(errors, context, dependency); field.set(o, value); } catch (ErrorsException e) { errors.withSource(injectionPoint).merge(e.getErrors()); } catch (IllegalAccessException e) { throw new AssertionError(e); // a security manager is blocking us, we're hosed } finally { context.setDependency(null); }
209
133
342
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/assistedinject/Parameter.java
Parameter
getBindingAnnotation
class Parameter { private final Type type; private final boolean isAssisted; private final Annotation bindingAnnotation; private final boolean isProvider; Parameter(Type type, Annotation[] annotations) { this.type = type; this.bindingAnnotation = getBindingAnnotation(annotations); this.isAssisted = hasAssistedAnnotation(annotations); this.isProvider = isProvider(type); } public boolean isProvidedByFactory() { return isAssisted; } public Type getType() { return type; } @Override public String toString() { StringBuilder result = new StringBuilder(); if (isAssisted) { result.append("@Assisted"); result.append(" "); } if (bindingAnnotation != null) { result.append(bindingAnnotation.toString()); result.append(" "); } result.append(type.toString()); return result.toString(); } private boolean hasAssistedAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { if (annotation.annotationType().equals(Assisted.class)) { return true; } } return false; } /** * Returns the Guice {@link Key} for this parameter. */ public Object getValue(Injector injector) { return isProvider ? injector.getProvider(getBindingForType(getProvidedType(type))) : injector.getInstance(getPrimaryBindingKey()); } Key<?> getPrimaryBindingKey() { return isProvider ? getBindingForType(getProvidedType(type)) : getBindingForType(type); } private Type getProvidedType(Type type) { return ((ParameterizedType) type).getActualTypeArguments()[0]; } private boolean isProvider(Type type) { return type instanceof ParameterizedType && ((ParameterizedType) type).getRawType() == Provider.class; } private Key<?> getBindingForType(Type type) { return bindingAnnotation != null ? Key.get(type, bindingAnnotation) : Key.get(type); } /** * Returns the unique binding annotation from the specified list, or * {@code null} if there are none. * * @throws IllegalStateException if multiple binding annotations exist. */ private Annotation getBindingAnnotation(Annotation[] annotations) {<FILL_FUNCTION_BODY>} }
Annotation bindingAnnotation = null; for (Annotation a : annotations) { if (a.annotationType().getAnnotation(BindingAnnotation.class) != null) { if (bindingAnnotation != null) { throw new IllegalArgumentException("Parameter has multiple binding annotations: " + bindingAnnotation + " and " + a); } bindingAnnotation = a; } } return bindingAnnotation;
646
103
749
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/Annotations.java
Annotations
findBindingAnnotation
class Annotations { /** * Returns true if the given annotation is retained at runtime. */ public static boolean isRetainedAtRuntime(Class<? extends Annotation> annotationType) { Retention retention = annotationType.getAnnotation(Retention.class); return retention != null && retention.value() == RetentionPolicy.RUNTIME; } /** * Returns the scope annotation on {@code type}, or null if none is specified. */ public static Class<? extends Annotation> findScopeAnnotation( Errors errors, Class<?> implementation) { return findScopeAnnotation(errors, implementation.getAnnotations()); } /** * Returns the scoping annotation, or null if there isn't one. */ public static Class<? extends Annotation> findScopeAnnotation(Errors errors, Annotation[] annotations) { Class<? extends Annotation> found = null; for (Annotation annotation : annotations) { if (annotation.annotationType().getAnnotation(ScopeAnnotation.class) != null) { if (found != null) { errors.duplicateScopeAnnotations(found, annotation.annotationType()); } else { found = annotation.annotationType(); } } } return found; } public static boolean isScopeAnnotation(Class<? extends Annotation> annotationType) { return annotationType.getAnnotation(ScopeAnnotation.class) != null; } /** * Adds an error if there is a misplaced annotations on {@code type}. Scoping * annotations are not allowed on abstract classes or interfaces. */ public static void checkForMisplacedScopeAnnotations( Class<?> type, Object source, Errors errors) { if (Classes.isConcrete(type)) { return; } Class<? extends Annotation> scopeAnnotation = findScopeAnnotation(errors, type); if (scopeAnnotation != null) { errors.withSource(type).scopeAnnotationOnAbstractType(scopeAnnotation, type, source); } } /** * Gets a key for the given type, member and annotations. */ public static Key<?> getKey(TypeLiteral<?> type, Member member, Annotation[] annotations, Errors errors) throws ErrorsException { int numErrorsBefore = errors.size(); Annotation found = findBindingAnnotation(errors, member, annotations); errors.throwIfNewErrors(numErrorsBefore); return found == null ? Key.get(type) : Key.get(type, found); } /** * Returns the binding annotation on {@code member}, or null if there isn't one. */ public static Annotation findBindingAnnotation( Errors errors, Member member, Annotation[] annotations) {<FILL_FUNCTION_BODY>} }
Annotation found = null; for (Annotation annotation : annotations) { if (annotation.annotationType().getAnnotation(BindingAnnotation.class) != null) { if (found != null) { errors.duplicateBindingAnnotations(member, found.annotationType(), annotation.annotationType()); } else { found = annotation; } } } return found;
710
105
815
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/BindingBuilder.java
BindingBuilder
toInstance
class BindingBuilder<T> extends AbstractBindingBuilder<T> implements AnnotatedBindingBuilder<T> { public BindingBuilder(Binder binder, List<Element> elements, Object source, Key<T> key) { super(binder, elements, source, key); } @Override public BindingBuilder<T> annotatedWith(Class<? extends Annotation> annotationType) { annotatedWithInternal(annotationType); return this; } @Override public BindingBuilder<T> annotatedWith(Annotation annotation) { annotatedWithInternal(annotation); return this; } @Override public BindingBuilder<T> to(Class<? extends T> implementation) { return to(Key.get(implementation)); } @Override public BindingBuilder<T> to(TypeLiteral<? extends T> implementation) { return to(Key.get(implementation)); } @Override public BindingBuilder<T> to(Key<? extends T> linkedKey) { Objects.requireNonNull(linkedKey, "linkedKey"); checkNotTargetted(); BindingImpl<T> base = getBinding(); setBinding(new LinkedBindingImpl<>( base.getSource(), base.getKey(), base.getScoping(), linkedKey)); return this; } @Override public void toInstance(T instance) {<FILL_FUNCTION_BODY>} @Override public BindingBuilder<T> toProvider(Provider<? extends T> provider) { Objects.requireNonNull(provider, "provider"); checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(provider.getClass()); } catch (ConfigurationException e) { for (Message message : e.getErrorMessages()) { binder.addError(message); } injectionPoints = unmodifiableSet(new HashSet<InjectionPoint>(e.getPartialValue())); } BindingImpl<T> base = getBinding(); setBinding(new ProviderInstanceBindingImpl<>( base.getSource(), base.getKey(), base.getScoping(), injectionPoints, provider)); return this; } @Override public BindingBuilder<T> toProvider(Class<? extends Provider<? extends T>> providerType) { return toProvider(Key.get(providerType)); } @Override public BindingBuilder<T> toProvider(Key<? extends Provider<? extends T>> providerKey) { Objects.requireNonNull(providerKey, "providerKey"); checkNotTargetted(); BindingImpl<T> base = getBinding(); setBinding(new LinkedProviderBindingImpl<>( base.getSource(), base.getKey(), base.getScoping(), providerKey)); return this; } @Override public String toString() { return "BindingBuilder<" + getBinding().getKey().getTypeLiteral() + ">"; } }
checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; if (instance != null) { try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(instance.getClass()); } catch (ConfigurationException e) { for (Message message : e.getErrorMessages()) { binder.addError(message); } injectionPoints = unmodifiableSet(new HashSet<InjectionPoint>(e.getPartialValue())); } } else { binder.addError(BINDING_TO_NULL); injectionPoints = emptySet(); } BindingImpl<T> base = getBinding(); setBinding(new InstanceBindingImpl<>( base.getSource(), base.getKey(), base.getScoping(), injectionPoints, instance));
794
222
1,016
<methods>public void <init>(org.elasticsearch.common.inject.Binder, List<org.elasticsearch.common.inject.spi.Element>, java.lang.Object, Key<T>) ,public void asEagerSingleton() ,public void in(Class<? extends java.lang.annotation.Annotation>) ,public void in(org.elasticsearch.common.inject.Scope) <variables>public static final java.lang.String ANNOTATION_ALREADY_SPECIFIED,public static final java.lang.String BINDING_TO_NULL,public static final java.lang.String CONSTANT_VALUE_ALREADY_SET,public static final java.lang.String IMPLEMENTATION_ALREADY_SET,protected static final Key<?> NULL_KEY,public static final java.lang.String SCOPE_ALREADY_SET,public static final java.lang.String SINGLE_INSTANCE_AND_SCOPE,protected final non-sealed org.elasticsearch.common.inject.Binder binder,private BindingImpl<T> binding,protected List<org.elasticsearch.common.inject.spi.Element> elements,protected int position
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/BindingImpl.java
BindingImpl
getProvider
class BindingImpl<T> implements Binding<T> { private final Injector injector; private final Key<T> key; private final Object source; private final Scoping scoping; private final InternalFactory<? extends T> internalFactory; public BindingImpl(Injector injector, Key<T> key, Object source, InternalFactory<? extends T> internalFactory, Scoping scoping) { this.injector = injector; this.key = key; this.source = source; this.internalFactory = internalFactory; this.scoping = scoping; } protected BindingImpl(Object source, Key<T> key, Scoping scoping) { this.internalFactory = null; this.injector = null; this.source = source; this.key = key; this.scoping = scoping; } @Override public Key<T> getKey() { return key; } @Override public Object getSource() { return source; } private volatile Provider<T> provider; @Override public Provider<T> getProvider() {<FILL_FUNCTION_BODY>} public InternalFactory<? extends T> getInternalFactory() { return internalFactory; } public Scoping getScoping() { return scoping; } /** * Is this a constant binding? This returns true for constant bindings as * well as toInstance() bindings. */ public boolean isConstant() { return this instanceof InstanceBinding; } @Override public <V> V acceptVisitor(ElementVisitor<V> visitor) { return visitor.visit(this); } @Override public <V> V acceptScopingVisitor(BindingScopingVisitor<V> visitor) { return scoping.acceptVisitor(visitor); } protected BindingImpl<T> withScoping(Scoping scoping) { throw new AssertionError(); } protected BindingImpl<T> withKey(Key<T> key) { throw new AssertionError(); } @Override public String toString() { return new ToStringBuilder(Binding.class) .add("key", key) .add("scope", scoping) .add("source", source) .toString(); } public Injector getInjector() { return injector; } }
if (provider == null) { if (injector == null) { throw new UnsupportedOperationException("getProvider() not supported for module bindings"); } provider = injector.getProvider(key); } return provider;
644
66
710
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/ExposedBindingImpl.java
ExposedBindingImpl
toString
class ExposedBindingImpl<T> extends BindingImpl<T> implements ExposedBinding<T> { private final PrivateElements privateElements; public ExposedBindingImpl(Injector injector, Object source, Key<T> key, InternalFactory<T> factory, PrivateElements privateElements) { super(injector, key, source, factory, Scoping.UNSCOPED); this.privateElements = privateElements; } public ExposedBindingImpl(Object source, Key<T> key, Scoping scoping, PrivateElements privateElements) { super(source, key, scoping); this.privateElements = privateElements; } @Override public <V> V acceptTargetVisitor(BindingTargetVisitor<? super T, V> visitor) { return visitor.visit(this); } @Override public Set<Dependency<?>> getDependencies() { return singleton(Dependency.get(Key.get(Injector.class))); } @Override public PrivateElements getPrivateElements() { return privateElements; } @Override public BindingImpl<T> withScoping(Scoping scoping) { return new ExposedBindingImpl<>(getSource(), getKey(), scoping, privateElements); } @Override public ExposedBindingImpl<T> withKey(Key<T> key) { return new ExposedBindingImpl<>(getSource(), key, getScoping(), privateElements); } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public void applyTo(Binder binder) { throw new UnsupportedOperationException("This element represents a synthetic binding."); } }
return new ToStringBuilder(ExposedBinding.class) .add("key", getKey()) .add("source", getSource()) .add("privateElements", privateElements) .toString();
437
53
490
<methods>public void <init>(org.elasticsearch.common.inject.Injector, Key<T>, java.lang.Object, InternalFactory<? extends T>, org.elasticsearch.common.inject.internal.Scoping) ,public V acceptScopingVisitor(BindingScopingVisitor<V>) ,public V acceptVisitor(ElementVisitor<V>) ,public org.elasticsearch.common.inject.Injector getInjector() ,public InternalFactory<? extends T> getInternalFactory() ,public Key<T> getKey() ,public Provider<T> getProvider() ,public org.elasticsearch.common.inject.internal.Scoping getScoping() ,public java.lang.Object getSource() ,public boolean isConstant() ,public java.lang.String toString() <variables>private final non-sealed org.elasticsearch.common.inject.Injector injector,private final non-sealed InternalFactory<? extends T> internalFactory,private final non-sealed Key<T> key,private volatile Provider<T> provider,private final non-sealed org.elasticsearch.common.inject.internal.Scoping scoping,private final non-sealed java.lang.Object source
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/FailableCache.java
FailableCache
get
class FailableCache<K, V> { private final ConcurrentHashMap<K, Object> cache = new ConcurrentHashMap<>(); protected abstract V create(K key, Errors errors) throws ErrorsException; public V get(K key, Errors errors) throws ErrorsException {<FILL_FUNCTION_BODY>} private Object load(K key) { Errors errors = new Errors(); V result = null; try { result = create(key, errors); } catch (ErrorsException e) { errors.merge(e.getErrors()); } return errors.hasErrors() ? errors : result; } }
Object resultOrError = cache.get(key); if (resultOrError == null) { synchronized (this) { resultOrError = load(key); // we can't use cache.computeIfAbsent since this might be recursively call this API cache.putIfAbsent(key, resultOrError); } } if (resultOrError instanceof Errors) { errors.merge((Errors) resultOrError); throw errors.toException(); } else { @SuppressWarnings("unchecked") // create returned a non-error result, so this is safe V result = (V) resultOrError; return result; }
170
171
341
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/InstanceBindingImpl.java
InstanceBindingImpl
getDependencies
class InstanceBindingImpl<T> extends BindingImpl<T> implements InstanceBinding<T> { final T instance; final Provider<T> provider; final Set<InjectionPoint> injectionPoints; public InstanceBindingImpl(Injector injector, Key<T> key, Object source, InternalFactory<? extends T> internalFactory, Set<InjectionPoint> injectionPoints, T instance) { super(injector, key, source, internalFactory, Scoping.UNSCOPED); this.injectionPoints = injectionPoints; this.instance = instance; this.provider = Providers.of(instance); } public InstanceBindingImpl(Object source, Key<T> key, Scoping scoping, Set<InjectionPoint> injectionPoints, T instance) { super(source, key, scoping); this.injectionPoints = injectionPoints; this.instance = instance; this.provider = Providers.of(instance); } @Override public Provider<T> getProvider() { return this.provider; } @Override public <V> V acceptTargetVisitor(BindingTargetVisitor<? super T, V> visitor) { return visitor.visit(this); } @Override public T getInstance() { return instance; } @Override public Set<InjectionPoint> getInjectionPoints() { return injectionPoints; } @Override public Set<Dependency<?>> getDependencies() {<FILL_FUNCTION_BODY>} @Override public BindingImpl<T> withScoping(Scoping scoping) { return new InstanceBindingImpl<>(getSource(), getKey(), scoping, injectionPoints, instance); } @Override public BindingImpl<T> withKey(Key<T> key) { return new InstanceBindingImpl<>(getSource(), key, getScoping(), injectionPoints, instance); } @Override public void applyTo(Binder binder) { // instance bindings aren't scoped binder.withSource(getSource()).bind(getKey()).toInstance(instance); } @Override public String toString() { return new ToStringBuilder(InstanceBinding.class) .add("key", getKey()) .add("source", getSource()) .add("instance", instance) .toString(); } }
return instance instanceof HasDependencies ? unmodifiableSet(new HashSet<>((((HasDependencies) instance).getDependencies()))) : Dependency.forInjectionPoints(injectionPoints);
619
52
671
<methods>public void <init>(org.elasticsearch.common.inject.Injector, Key<T>, java.lang.Object, InternalFactory<? extends T>, org.elasticsearch.common.inject.internal.Scoping) ,public V acceptScopingVisitor(BindingScopingVisitor<V>) ,public V acceptVisitor(ElementVisitor<V>) ,public org.elasticsearch.common.inject.Injector getInjector() ,public InternalFactory<? extends T> getInternalFactory() ,public Key<T> getKey() ,public Provider<T> getProvider() ,public org.elasticsearch.common.inject.internal.Scoping getScoping() ,public java.lang.Object getSource() ,public boolean isConstant() ,public java.lang.String toString() <variables>private final non-sealed org.elasticsearch.common.inject.Injector injector,private final non-sealed InternalFactory<? extends T> internalFactory,private final non-sealed Key<T> key,private volatile Provider<T> provider,private final non-sealed org.elasticsearch.common.inject.internal.Scoping scoping,private final non-sealed java.lang.Object source
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/InternalContext.java
InternalContext
getConstructionContext
class InternalContext { private Map<Object, ConstructionContext<?>> constructionContexts = new HashMap<>(); private Dependency dependency; @SuppressWarnings("unchecked") public <T> ConstructionContext<T> getConstructionContext(Object key) {<FILL_FUNCTION_BODY>} public Dependency getDependency() { return dependency; } public void setDependency(Dependency dependency) { this.dependency = dependency; } }
ConstructionContext<T> constructionContext = (ConstructionContext<T>) constructionContexts.get(key); if (constructionContext == null) { constructionContext = new ConstructionContext<>(); constructionContexts.put(key, constructionContext); } return constructionContext;
124
74
198
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/Nullability.java
Nullability
allowsNull
class Nullability { private Nullability() { } public static boolean allowsNull(Annotation[] annotations) {<FILL_FUNCTION_BODY>} }
for (Annotation a : annotations) { if ("Nullable".equals(a.annotationType().getSimpleName())) { return true; } } return false;
44
48
92
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/PrivateElementsImpl.java
PrivateElementsImpl
getElements
class PrivateElementsImpl implements PrivateElements { /* * This class acts as both a value object and as a builder. When getElements() is called, an * immutable collection of elements is constructed and the original mutable list is nulled out. * Similarly, the exposed keys are made immutable on access. */ private final Object source; private List<Element> elementsMutable = new ArrayList<>(); private List<ExposureBuilder<?>> exposureBuilders = new ArrayList<>(); /** * lazily instantiated */ private List<Element> elements; /** * lazily instantiated */ private Map<Key<?>, Object> exposedKeysToSources; private Injector injector; public PrivateElementsImpl(Object source) { this.source = Objects.requireNonNull(source, "source"); } @Override public Object getSource() { return source; } @Override public List<Element> getElements() {<FILL_FUNCTION_BODY>} @Override public Injector getInjector() { return injector; } public void initInjector(Injector injector) { if (this.injector != null) { throw new IllegalStateException("injector already initialized"); } this.injector = Objects.requireNonNull(injector, "injector"); } @Override public Set<Key<?>> getExposedKeys() { if (exposedKeysToSources == null) { Map<Key<?>, Object> exposedKeysToSourcesMutable = new LinkedHashMap<>(); for (ExposureBuilder<?> exposureBuilder : exposureBuilders) { exposedKeysToSourcesMutable.put(exposureBuilder.getKey(), exposureBuilder.getSource()); } exposedKeysToSources = unmodifiableMap(exposedKeysToSourcesMutable); exposureBuilders = null; } return exposedKeysToSources.keySet(); } @Override public <T> T acceptVisitor(ElementVisitor<T> visitor) { return visitor.visit(this); } public List<Element> getElementsMutable() { return elementsMutable; } public void addExposureBuilder(ExposureBuilder<?> exposureBuilder) { exposureBuilders.add(exposureBuilder); } @Override public void applyTo(Binder binder) { PrivateBinder privateBinder = binder.withSource(source).newPrivateBinder(); for (Element element : getElements()) { element.applyTo(privateBinder); } getExposedKeys(); // ensure exposedKeysToSources is populated for (Map.Entry<Key<?>, Object> entry : exposedKeysToSources.entrySet()) { privateBinder.withSource(entry.getValue()).expose(entry.getKey()); } } @Override public Object getExposedSource(Key<?> key) { getExposedKeys(); // ensure exposedKeysToSources is populated Object source = exposedKeysToSources.get(key); if (source == null) { throw new IllegalArgumentException(key + " not exposed by " + "."); } return source; } @Override public String toString() { return new ToStringBuilder(PrivateElements.class) .add("exposedKeys", getExposedKeys()) .add("source", getSource()) .toString(); } }
if (elements == null) { elements = Collections.unmodifiableList(elementsMutable); elementsMutable = null; } return elements;
913
45
958
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/StackTraceElements.java
StackTraceElements
forMember
class StackTraceElements { public static Object forMember(Member member) {<FILL_FUNCTION_BODY>} public static Object forType(Class<?> implementation) { String fileName = null; int lineNumber = -1; return new StackTraceElement(implementation.getName(), "class", fileName, lineNumber); } }
if (member == null) { return SourceProvider.UNKNOWN_SOURCE; } Class declaringClass = member.getDeclaringClass(); String fileName = null; int lineNumber = -1; Class<? extends Member> memberType = MoreTypes.memberType(member); String memberName = memberType == Constructor.class ? "<init>" : member.getName(); return new StackTraceElement(declaringClass.getName(), memberName, fileName, lineNumber);
92
129
221
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/Stopwatch.java
Stopwatch
reset
class Stopwatch { private static final Logger LOGGER = Logger.getLogger(Stopwatch.class.getName()); private static final long NSEC_PER_MSEC = 1000000L; private long startNS = System.nanoTime(); /** * Resets and returns elapsed time in milliseconds. */ public long reset() {<FILL_FUNCTION_BODY>} /** * Resets and logs elapsed time in milliseconds. */ public void resetAndLog(String label) { LOGGER.fine(label + ": " + reset() + "ms"); } }
long nowNS = System.nanoTime(); long deltaNS = nowNS - startNS; try { return deltaNS / NSEC_PER_MSEC; } finally { startNS = nowNS; }
168
63
231
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/internal/UniqueAnnotations.java
UniqueAnnotations
toString
class UniqueAnnotations { private UniqueAnnotations() { } private static final AtomicInteger NEXT_UNIQUE_VALUE = new AtomicInteger(1); /** * Returns an annotation instance that is not equal to any other annotation * instances, for use in creating distinct {@link org.elasticsearch.common.inject.Key}s. */ public static Annotation create() { return create(NEXT_UNIQUE_VALUE.getAndIncrement()); } static Annotation create(final int value) { return new Internal() { @Override public int value() { return value; } @Override public Class<? extends Annotation> annotationType() { return Internal.class; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { return o instanceof Internal && ((Internal) o).value() == value(); } @Override public int hashCode() { return (127 * "value".hashCode()) ^ value; } }; } @Retention(RUNTIME) @BindingAnnotation @interface Internal { int value(); } }
return "@" + Internal.class.getName() + "(value=" + value + ")";
326
27
353
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/matcher/AbstractMatcher.java
AndMatcher
toString
class AndMatcher<T> extends AbstractMatcher<T> { private final Matcher<? super T> a; private final Matcher<? super T> b; AndMatcher(Matcher<? super T> a, Matcher<? super T> b) { this.a = a; this.b = b; } @Override public boolean matches(T t) { return a.matches(t) && b.matches(t); } @Override public boolean equals(Object other) { return other instanceof AndMatcher && ((AndMatcher<?>) other).a.equals(a) && ((AndMatcher<?>) other).b.equals(b); } @Override public int hashCode() { return 41 * (a.hashCode() ^ b.hashCode()); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "and(" + a + ", " + b + ")";
250
19
269
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/name/Names.java
Names
bindProperties
class Names { private Names() { } /** * Creates a {@link Named} annotation with {@code name} as the value. */ public static Named named(String name) { return new NamedImpl(name); } /** * Creates a constant binding to {@code @Named(key)} for each entry in * {@code properties}. */ public static void bindProperties(Binder binder, Map<String, String> properties) { binder = binder.skipSources(Names.class); for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); binder.bind(Key.get(String.class, new NamedImpl(key))).toInstance(value); } } /** * Creates a constant binding to {@code @Named(key)} for each property. This * method binds all properties including those inherited from * {@link Properties#defaults defaults}. */ public static void bindProperties(Binder binder, Properties properties) {<FILL_FUNCTION_BODY>} }
binder = binder.skipSources(Names.class); // use enumeration to include the default properties for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) { String propertyName = (String) e.nextElement(); String value = properties.getProperty(propertyName); binder.bind(Key.get(String.class, new NamedImpl(propertyName))).toInstance(value); }
293
115
408
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/spi/Dependency.java
Dependency
equals
class Dependency<T> { private final InjectionPoint injectionPoint; private final Key<T> key; private final boolean nullable; private final int parameterIndex; Dependency(InjectionPoint injectionPoint, Key<T> key, boolean nullable, int parameterIndex) { this.injectionPoint = injectionPoint; this.key = key; this.nullable = nullable; this.parameterIndex = parameterIndex; } /** * Returns a new dependency that is not attached to an injection point. The returned dependency is * nullable. */ public static <T> Dependency<T> get(Key<T> key) { return new Dependency<>(null, key, true, -1); } /** * Returns the dependencies from the given injection points. */ public static Set<Dependency<?>> forInjectionPoints(Set<InjectionPoint> injectionPoints) { Set<Dependency<?>> dependencies = new HashSet<>(); for (InjectionPoint injectionPoint : injectionPoints) { dependencies.addAll(injectionPoint.getDependencies()); } return unmodifiableSet(dependencies); } /** * Returns the key to the binding that satisfies this dependency. */ public Key<T> getKey() { return this.key; } /** * Returns true if null is a legal value for this dependency. */ public boolean isNullable() { return nullable; } /** * Returns the injection point to which this dependency belongs, or null if this dependency isn't * attached to a particular injection point. */ public InjectionPoint getInjectionPoint() { return injectionPoint; } /** * Returns the index of this dependency in the injection point's parameter list, or {@code -1} if * this dependency does not belong to a parameter list. Only method and constructor dependencies * are elements in a parameter list. */ public int getParameterIndex() { return parameterIndex; } @Override public int hashCode() { return Objects.hash(injectionPoint, parameterIndex, key); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(key); if (injectionPoint != null) { builder.append("@").append(injectionPoint); if (parameterIndex != -1) { builder.append("[").append(parameterIndex).append("]"); } } return builder.toString(); } }
if (o instanceof Dependency) { Dependency dependency = (Dependency) o; return Objects.equals(injectionPoint, dependency.injectionPoint) && Objects.equals(parameterIndex, dependency.parameterIndex) && Objects.equals(key, dependency.key); } else { return false; }
680
87
767
<no_super_class>
crate_crate
crate/libs/guice/src/main/java/org/elasticsearch/common/inject/util/Providers.java
Providers
of
class Providers { private Providers() { } /** * Returns a provider which always provides {@code instance}. This should not * be necessary to use in your application, but is helpful for several types * of unit tests. * * @param instance the instance that should always be provided. This is also * permitted to be null, to enable aggressive testing, although in real * life a Guice-supplied Provider will never return null. */ public static <T> Provider<T> of(final T instance) {<FILL_FUNCTION_BODY>} }
return new Provider<T>() { @Override public T get() { return instance; } @Override public String toString() { return "of(" + instance + ")"; } };
153
63
216
<no_super_class>
crate_crate
crate/libs/pgwire/src/main/java/io/crate/protocols/postgres/parser/PgArrayParser.java
PgArrayParser
invokeParser
class PgArrayParser { private static final BaseErrorListener ERROR_LISTENER = new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException e) { throw new PgArrayParsingException(message, e, line, charPositionInLine); } }; public static Object parse(String s, Function<byte[], Object> convert) { return invokeParser(CharStreams.fromString(s), convert); } public static Object parse(byte[] bytes, Function<byte[], Object> convert) { try { return invokeParser(CharStreams.fromStream(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8), convert); } catch (IOException e) { return new IllegalArgumentException(e); } } private static Object invokeParser(CharStream input, Function<byte[], Object> convert) {<FILL_FUNCTION_BODY>} }
try { var lexer = new PgArrayLexer(input); var tokenStream = new CommonTokenStream(lexer); var parser = new io.crate.protocols.postgres.antlr.PgArrayParser(tokenStream); lexer.removeErrorListeners(); lexer.addErrorListener(ERROR_LISTENER); parser.removeErrorListeners(); parser.addErrorListener(ERROR_LISTENER); ParserRuleContext tree; try { // first, try parsing with potentially faster SLL mode parser.getInterpreter().setPredictionMode(PredictionMode.SLL); tree = parser.array(); } catch (ParseCancellationException ex) { // if we fail, parse with LL mode tokenStream.seek(0); // rewind input stream parser.reset(); parser.getInterpreter().setPredictionMode(PredictionMode.LL); tree = parser.array(); } return tree.accept(new PgArrayASTVisitor(convert)); } catch (StackOverflowError e) { throw new PgArrayParsingException("stack overflow while parsing: " + e.getLocalizedMessage()); }
270
311
581
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/Booleans.java
Booleans
parseBoolean
class Booleans { private Booleans() { throw new AssertionError("No instances intended"); } /** * Parses a char[] representation of a boolean value to <code>boolean</code>. * * @return <code>true</code> iff the sequence of chars is "true", <code>false</code> iff the sequence of chars is "false" or the * provided default value iff either text is <code>null</code> or length == 0. * @throws IllegalArgumentException if the string cannot be parsed to boolean. */ public static boolean parseBoolean(char[] text, int offset, int length, boolean defaultValue) {<FILL_FUNCTION_BODY>} /** * returns true iff the sequence of chars is one of "true","false". * * @param text sequence to check * @param offset offset to start * @param length length to check */ public static boolean isBoolean(char[] text, int offset, int length) { if (text == null || length == 0) { return false; } return isBoolean(new String(text, offset, length)); } public static boolean isBoolean(String value) { return isFalse(value) || isTrue(value); } /** * Parses a string representation of a boolean value to <code>boolean</code>. * * @return <code>true</code> iff the provided value is "true". <code>false</code> iff the provided value is "false". * @throws IllegalArgumentException if the string cannot be parsed to boolean. */ public static boolean parseBoolean(String value) { if (isFalse(value)) { return false; } if (isTrue(value)) { return true; } throw new IllegalArgumentException("Failed to parse value [" + value + "] as only [true] or [false] are allowed."); } private static boolean hasText(CharSequence str) { if (str == null || str.length() == 0) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * * @param value text to parse. * @param defaultValue The default value to return if the provided value is <code>null</code>. * @return see {@link #parseBoolean(String)} */ public static boolean parseBoolean(String value, boolean defaultValue) { if (hasText(value)) { return parseBoolean(value); } return defaultValue; } public static Boolean parseBoolean(String value, Boolean defaultValue) { if (hasText(value)) { return parseBoolean(value); } return defaultValue; } /** * @return {@code true} iff the value is "false", otherwise {@code false}. */ public static boolean isFalse(String value) { return "false".equals(value); } /** * @return {@code true} iff the value is "true", otherwise {@code false}. */ public static boolean isTrue(String value) { return "true".equals(value); } /** * Converts a list of {@code Boolean} instances into a new array of primitive {@code boolean} * values. * * @param input a list of {@code Boolean} objects * @return an array containing the same values as {@code input}, in the same order, converted * to primitives * @throws NullPointerException if {@code input} or any of its elements is null */ public static boolean[] toArray(List<Boolean> input) { int len = input.size(); boolean[] array = new boolean[len]; for (int i = 0; i < len; i++) { array[i] = Objects.requireNonNull(input.get(i)); } return array; } }
if (text == null || length == 0) { return defaultValue; } else { return parseBoolean(new String(text, offset, length)); }
1,051
45
1,096
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/Glob.java
Glob
globMatch
class Glob { /** * Match a String against the given pattern, supporting the following simple * pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches (with an * arbitrary number of pattern parts), as well as direct equality. * * @param pattern the pattern to match against * @param str the String to match * @return whether the String matches the given pattern */ public static boolean globMatch(String pattern, String str) {<FILL_FUNCTION_BODY>} }
if (pattern == null || str == null) { return false; } int firstIndex = pattern.indexOf('*'); if (firstIndex == -1) { return pattern.equals(str); } if (firstIndex == 0) { if (pattern.length() == 1) { return true; } int nextIndex = pattern.indexOf('*', firstIndex + 1); if (nextIndex == -1) { return str.endsWith(pattern.substring(1)); } else if (nextIndex == 1) { // Double wildcard "**" - skipping the first "*" return globMatch(pattern.substring(1), str); } String part = pattern.substring(1, nextIndex); int partIndex = str.indexOf(part); while (partIndex != -1) { if (globMatch(pattern.substring(nextIndex), str.substring(partIndex + part.length()))) { return true; } partIndex = str.indexOf(part, partIndex + 1); } return false; } return (str.length() >= firstIndex && pattern.substring(0, firstIndex).equals(str.substring(0, firstIndex)) && globMatch(pattern.substring(firstIndex), str.substring(firstIndex)));
138
339
477
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/Octal.java
Octal
decode
class Octal { private Octal() { } /** * Converts an array of bytes into a String where unprintable characters are represented as octal numbers. */ public static String encode(byte[] data) { final StringBuilder sb = new StringBuilder(data.length); for (byte b: data) { if (b == 92) { sb.append("\\\\"); } else if (b < 32 || b > 126) { // unprintable character sb.append('\\'); sb.append((b >> 6) & 0x3); sb.append((b >> 3) & 0x7); sb.append(b & 0x7); } else { sb.append((char) b); } } return sb.toString(); } public static byte[] decode(String octalData) {<FILL_FUNCTION_BODY>} /** * Checks the given character is a number in base 8. */ private static int ensureOctalCharacter(char[] chars, int index) { final int o = Character.digit(chars[index], 8); if (o > 7 || o < 0) { throw new IllegalArgumentException( String.format(Locale.ENGLISH, "Illegal octal character %s at index %d", chars[index], index) ); } return o; } private static void throwOnTruncatedOctalSequence(int index) { throw new IllegalArgumentException( String.format(Locale.ENGLISH, "Invalid escape sequence at index %d:" + " expected 1 or 3 more characters but the end of the string got reached", index) ); } }
final byte[] decodedBytes = new byte[octalData.length()]; final char[] encodedChars = octalData.toCharArray(); int decIndex = 0; for (int encIndex = 0; encIndex < encodedChars.length; encIndex++) { final char c = encodedChars[encIndex]; if (c == '\\') { if (encIndex + 1 >= encodedChars.length) { throwOnTruncatedOctalSequence(encIndex); } if (encodedChars[encIndex + 1] == '\\') { decodedBytes[decIndex++] = '\\'; encIndex++; continue; } if (encIndex + 3 >= encodedChars.length) { throwOnTruncatedOctalSequence(encIndex); } decodedBytes[decIndex++] = (byte) (64 * ensureOctalCharacter(encodedChars, encIndex + 1) + 8 * ensureOctalCharacter(encodedChars, encIndex + 2) + ensureOctalCharacter(encodedChars, encIndex + 3)); encIndex += 3; } else { decodedBytes[decIndex++] = (byte) c; } } if (decIndex == decodedBytes.length) { return decodedBytes; } return Arrays.copyOf(decodedBytes, decIndex);
452
354
806
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/StringUtils.java
StringUtils
isBlank
class StringUtils { private StringUtils() {} public static final ThreadLocal<long[]> PARSE_LONG_BUFFER = ThreadLocal.withInitial(() -> new long[1]); public static List<String> splitToList(char delim, String value) { ArrayList<String> result = new ArrayList<>(); int lastStart = 0; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c == delim) { result.add(value.substring(lastStart, i)); lastStart = i + 1; } } if (lastStart <= value.length()) { result.add(value.substring(lastStart)); } return result; } @Nullable public static String nullOrString(@Nullable Object value) { if (value == null) { return null; } return value.toString(); } /** * Checks if a string is blank within the specified range. * {@code start} index is inclusive, {@code end} is exclusive. * * @return {@code false} if any character within the range is not * an unicode space character, otherwise, {@code false}. */ public static boolean isBlank(String string, int start, int end) {<FILL_FUNCTION_BODY>} public static String camelToSnakeCase(String camelCase) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < camelCase.length(); i++) { char c = camelCase.charAt(i); if (Character.isUpperCase(c)) { if (i > 0) { sb.append('_'); } sb.append(Character.toLowerCase(c)); } else { sb.append(c); } } return sb.toString(); } public static String capitalize(String string) { return string.substring(0,1).toUpperCase(Locale.ENGLISH) + string.substring(1).toLowerCase(Locale.ENGLISH); } public static String padEnd(String s, int minimumLength, char c) { if (s == null) { throw new NullPointerException("s"); } if (s.length() >= minimumLength) { return s; } else { return s + String.valueOf(c).repeat(minimumLength - s.length()); } } public static String trim(String target, char charToTrim) { int start = 0; int len = target.length(); while (start < len && target.charAt(start) == charToTrim) { start++; } while (start < len && target.charAt(len - 1) == charToTrim) { len--; } return target.substring(start, len); } /** * This is a copy of {@link Long#parseLong} but optimized to avoid * creating an exception and filling its stacktrace if the input cannot be parsed. */ public static boolean tryParseLong(String s, long[] out) { boolean negative = false; int radix = 10; int i = 0, len = s.length(); long limit = -Long.MAX_VALUE; if (len > 0) { char firstChar = s.charAt(0); if (firstChar < '0') { // Possible leading "+" or "-" if (firstChar == '-') { negative = true; limit = Long.MIN_VALUE; } else if (firstChar != '+') { return false; } if (len == 1) { // Cannot have lone "+" or "-" return false; } i++; } long multmin = limit / radix; long result = 0; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE int digit = Character.digit(s.charAt(i++),radix); if (digit < 0 || result < multmin) { return false; } result *= radix; if (result < limit + digit) { return false; } result -= digit; } out[0] = negative ? result : -result; return true; } else { return false; } } }
for (int i = start; i < end; i++) { if (!Character.isSpaceChar(string.charAt(i))) { return false; } } return true;
1,148
54
1,202
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/Suppliers.java
ExpiringMemoizingSupplier
get
class ExpiringMemoizingSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; final long durationNanos; transient volatile @Nullable T value; // The special value 0 means "not yet initialized". transient volatile long expirationNanos; ExpiringMemoizingSupplier(Supplier<T> delegate, long duration, TimeUnit unit) { this.delegate = Objects.requireNonNull(delegate); assert (duration > 0) : String.format(Locale.ENGLISH, "duration (%s %s) must be > 0", duration, unit); this.durationNanos = unit.toNanos(duration); } @Override public T get() {<FILL_FUNCTION_BODY>} @Override public String toString() { // This is a little strange if the unit the user provided was not NANOS, // but we don't want to store the unit just for toString return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)"; } private static final long serialVersionUID = 0; }
// Another variant of Double Checked Locking. // // We use two volatile reads. We could reduce this to one by // putting our fields into a holder class, but (at least on x86) // the extra memory consumption and indirection are more // expensive than the extra volatile reads. long nanos = expirationNanos; long now = System.nanoTime(); if (nanos == 0 || now - nanos >= 0) { synchronized (this) { if (nanos == expirationNanos) { // recheck for lost race T t = delegate.get(); value = t; nanos = now + durationNanos; // In the very unlikely event that nanos is 0, set it to 1; // no one will notice 1 ns of tardiness. expirationNanos = (nanos == 0) ? 1 : nanos; return t; } } } return value;
303
247
550
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/collections/LexicographicalOrdering.java
LexicographicalOrdering
compare
class LexicographicalOrdering<T> extends Ordering<Iterable<T>> implements Serializable { final Comparator<? super T> elementOrder; public LexicographicalOrdering(Comparator<? super T> elementOrder) { this.elementOrder = elementOrder; } @Override public int compare(Iterable<T> leftIterable, Iterable<T> rightIterable) {<FILL_FUNCTION_BODY>} @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof LexicographicalOrdering) { LexicographicalOrdering<?> that = (LexicographicalOrdering<?>) object; return this.elementOrder.equals(that.elementOrder); } return false; } @Override public int hashCode() { return elementOrder.hashCode() ^ 2075626741; // meaningless } @Override public String toString() { return elementOrder + ".lexicographical()"; } private static final long serialVersionUID = 0; }
Iterator<T> left = leftIterable.iterator(); Iterator<T> right = rightIterable.iterator(); while (left.hasNext()) { if (!right.hasNext()) { return LEFT_IS_GREATER; // because it's longer } int result = elementOrder.compare(left.next(), right.next()); if (result != 0) { return result; } } if (right.hasNext()) { return RIGHT_IS_GREATER; // because it's longer } return 0;
295
152
447
<methods>public abstract int compare(Iterable<T>, Iterable<T>) ,public static Ordering<T> compound(Iterable<? extends Comparator<? super T>>) <variables>static final int LEFT_IS_GREATER,static final int RIGHT_IS_GREATER
crate_crate
crate/libs/shared/src/main/java/io/crate/common/collections/Lists.java
RotatedList
get
class RotatedList<T> extends AbstractList<T> implements RandomAccess { private final List<T> in; private final int distance; RotatedList(List<T> list, int distance) { if (distance < 0 || distance >= list.size()) { throw new IllegalArgumentException(); } if (!(list instanceof RandomAccess)) { throw new IllegalArgumentException(); } this.in = list; this.distance = distance; } @Override public T get(int index) {<FILL_FUNCTION_BODY>} @Override public int size() { return in.size(); } }
int idx = distance + index; if (idx < 0 || idx >= in.size()) { idx -= in.size(); } return in.get(idx);
170
48
218
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/collections/RefCountedItem.java
RefCountedItem
close
class RefCountedItem<T> implements AutoCloseable { private final Function<String, T> itemFactory; private final Consumer<T> closeItem; private final ArrayList<String> sources = new ArrayList<>(); private int refs = 0; private T item; public RefCountedItem(Function<String, T> itemFactory, Consumer<T> closeItem) { this.itemFactory = itemFactory; this.closeItem = closeItem; } /** * Marks resource as acquired by `source`. * On the first acquisition the item is created. * * <p> * If {@link #itemFactory} raises an error the ref-counter is <b>not</b> incremented. * </p> */ public void markAcquired(String source) { synchronized (sources) { if (item == null) { item = itemFactory.apply(source); } sources.add(source); refs++; } } public T item() { synchronized (sources) { if (item == null) { assert !sources.isEmpty() : "Must call `markAcquired` to be able to access the item"; item = itemFactory.apply(sources.get(sources.size() - 1)); } return item; } } @Override public void close() {<FILL_FUNCTION_BODY>} }
synchronized (sources) { refs--; if (refs == 0) { try { closeItem.accept(item); } finally { item = null; } } }
373
60
433
<no_super_class>
crate_crate
crate/libs/shared/src/main/java/io/crate/common/collections/Sets.java
Sets
difference
class Sets { private Sets() { } public static <T> Set<T> newConcurrentHashSet() { return Collections.newSetFromMap(new ConcurrentHashMap<>()); } public static <T> boolean haveEmptyIntersection(Set<T> left, Set<T> right) { Objects.requireNonNull(left); Objects.requireNonNull(right); return left.stream().noneMatch(right::contains); } @SafeVarargs public static <T> Set<T> concat(Set<T> left, T ... right) { Objects.requireNonNull(left); Objects.requireNonNull(right); var result = new HashSet<T>(left); result.addAll(List.of(right)); return Collections.unmodifiableSet(result); } public static <T> Set<T> union(Set<T> left, Set<T> right) { Objects.requireNonNull(left); Objects.requireNonNull(right); Set<T> union = new HashSet<>(left); union.addAll(right); return union; } public static <T> Set<T> intersection(Set<T> set1, Set<T> set2) { Objects.requireNonNull(set1); Objects.requireNonNull(set2); final Set<T> left; final Set<T> right; if (set1.size() < set2.size()) { left = set1; right = set2; } else { left = set2; right = set1; } return left.stream().filter(right::contains).collect(Collectors.toSet()); } public static <E> Set<E> difference(final Set<E> set1, final Set<?> set2) {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(set1, "set1"); Objects.requireNonNull(set2, "set2"); return new AbstractSet<E>() { @Override public Iterator<E> iterator() { return new AbstractIterator<E>() { final Iterator<E> itr = set1.iterator(); @Override protected E computeNext() { while (itr.hasNext()) { E e = itr.next(); if (!set2.contains(e)) { return e; } } return endOfData(); } }; } @Override public Stream<E> stream() { return set1.stream().filter(e -> !set2.contains(e)); } @Override public Stream<E> parallelStream() { return set1.parallelStream().filter(e -> !set2.contains(e)); } @Override public int size() { int size = 0; for (E e : set1) { if (!set2.contains(e)) { size++; } } return size; } @Override public boolean isEmpty() { return set2.containsAll(set1); } @Override public boolean contains(Object element) { return set1.contains(element) && !set2.contains(element); } };
491
372
863
<no_super_class>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/AlterTableRenameColumn.java
AlterTableRenameColumn
toString
class AlterTableRenameColumn<T> extends Statement { private final Table<T> table; private final Expression column; private final Expression newName; public AlterTableRenameColumn(Table<T> table, Expression column, Expression newName) { this.table = table; this.column = column; this.newName = newName; } public Table<T> table() { return table; } public Expression column() { return column; } public Expression newName() { return newName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlterTableRenameColumn<?> that = (AlterTableRenameColumn<?>) o; return table.equals(that.table) && column.equals(that.column) && newName.equals(that.newName); } @Override public int hashCode() { return Objects.hash(table, column, newName); } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitAlterTableRenameColumnStatement(this, context); } }
return "AlterTableRenameColumn{" + "table=" + table + ", column=" + column + ", newName=" + newName + '}';
371
49
420
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/AlterTableReroute.java
AlterTableReroute
toString
class AlterTableReroute<T> extends Statement { private final Table<T> table; private final RerouteOption rerouteOption; private final boolean blob; public AlterTableReroute(Table<T> table, boolean blob, RerouteOption rerouteOption) { this.table = table; this.blob = blob; this.rerouteOption = rerouteOption; } public Table<T> table() { return table; } public boolean blob() { return blob; } public RerouteOption rerouteOption() { return rerouteOption; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AlterTableReroute<?> that = (AlterTableReroute<?>) o; return blob == that.blob && Objects.equals(table, that.table) && Objects.equals(rerouteOption, that.rerouteOption); } @Override public int hashCode() { return Objects.hash(table, rerouteOption, blob); } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitAlterTableReroute(this, context); } }
return "AlterTableReroute{" + "table=" + table + ", blob=" + blob + ", reroute option=" + rerouteOption + '}';
412
53
465
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/ArithmeticExpression.java
ArithmeticExpression
equals
class ArithmeticExpression extends Expression { public enum Type { ADD("+"), SUBTRACT("-"), MULTIPLY("*"), DIVIDE("/"), MODULUS("%"), POWER("^"); private final String value; Type(String value) { this.value = value; } public String getValue() { return value; } } private final Type type; private final Expression left; private final Expression right; public ArithmeticExpression(Type type, Expression left, Expression right) { this.type = type; this.left = left; this.right = right; } public Type getType() { return type; } public Expression getLeft() { return left; } public Expression getRight() { return right; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitArithmeticExpression(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + left.hashCode(); result = 31 * result + right.hashCode(); return result; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArithmeticExpression that = (ArithmeticExpression) o; if (!left.equals(that.left)) { return false; } if (!right.equals(that.right)) { return false; } if (type != that.type) { return false; } return true;
371
131
502
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public final java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/ArrayComparisonExpression.java
ArrayComparisonExpression
equals
class ArrayComparisonExpression extends ComparisonExpression implements ArrayComparison { private final Quantifier quantifier; public ArrayComparisonExpression(Type type, Quantifier quantifier, Expression expression, Expression arrayExpression) { super(type, expression, arrayExpression); this.quantifier = quantifier; } @Override public Quantifier quantifier() { return quantifier; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitArrayComparisonExpression(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (quantifier != null ? quantifier.hashCode() : 0); return result; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ArrayComparisonExpression that = (ArrayComparisonExpression) o; if (quantifier != that.quantifier) return false; return true;
236
86
322
<methods>public void <init>(io.crate.sql.tree.ComparisonExpression.Type, io.crate.sql.tree.Expression, io.crate.sql.tree.Expression) ,public R accept(AstVisitor<R,C>, C) ,public boolean equals(java.lang.Object) ,public io.crate.sql.tree.Expression getLeft() ,public io.crate.sql.tree.Expression getRight() ,public io.crate.sql.tree.ComparisonExpression.Type getType() ,public int hashCode() <variables>private final non-sealed io.crate.sql.tree.Expression left,private final non-sealed io.crate.sql.tree.Expression right,private final non-sealed io.crate.sql.tree.ComparisonExpression.Type type
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/BitString.java
BitString
ofBitString
class BitString extends Literal implements Comparable<BitString> { public static BitString ofBitString(String bitString) {<FILL_FUNCTION_BODY>} public static BitString ofRawBits(String bits) { return ofRawBits(bits, bits.length()); } public static BitString ofRawBits(String bits, int length) { BitSet bitSet = toBitSet(bits, length); return new BitString(bitSet, length); } private static BitSet toBitSet(String text, int length) { BitSet bitSet = new BitSet(length); for (int i = 0; i < length; i++) { char c = text.charAt(i); boolean value = switch (c) { case '0' -> false; case '1' -> true; default -> throw new IllegalArgumentException( "Bit string must only contain `0` or `1` values. Encountered: " + c); }; bitSet.set(i, value); } return bitSet; } private final BitSet bitSet; private final int length; public BitString(BitSet bitSet, int length) { this.bitSet = bitSet; this.length = length; } public BitSet bitSet() { return bitSet; } public int length() { return length; } /** * Return bits as string with B' prefix. Example: * * <pre> * B'1101' * </pre> */ public String asPrefixedBitString() { var sb = new StringBuilder("B'"); for (int i = 0; i < length; i++) { sb.append(bitSet.get(i) ? '1' : '0'); } sb.append("'"); return sb.toString(); } /** * Return bits as string without B' prefix. Example: * * <pre> * 1101 * </pre> */ public String asRawBitString() { var sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(bitSet.get(i) ? '1' : '0'); } return sb.toString(); } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitBitString(this, context); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + bitSet.hashCode(); result = prime * result + length; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BitString other = (BitString) obj; return bitSet.equals(other.bitSet) && length == other.length; } @Override public int compareTo(BitString o) { // This is basically a lexicographically comparison on the bit string // This matches the PostgreSQL behavior (See `bit_cmp` implementation in PostgreSQL) int smallerLength = Math.min(length, o.length); for (int i = 0; i < smallerLength; i++) { boolean thisSet = bitSet.get(i); boolean otherSet = o.bitSet.get(i); int compare = Boolean.compare(thisSet, otherSet); if (compare == 0) { continue; } return compare; } return Integer.compare(length, o.length); } }
assert bitString.startsWith("B'") : "Bitstring must start with B'"; assert bitString.endsWith("'") : "Bitstrign must end with '"; return ofRawBits(bitString.substring(2, bitString.length() - 1));
998
72
1,070
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public static io.crate.sql.tree.Literal fromObject(java.lang.Object) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/BooleanLiteral.java
BooleanLiteral
equals
class BooleanLiteral extends Literal { public static final BooleanLiteral TRUE_LITERAL = new BooleanLiteral(true); public static final BooleanLiteral FALSE_LITERAL = new BooleanLiteral(false); private final boolean value; private BooleanLiteral(boolean value) { this.value = value; } public boolean getValue() { return value; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitBooleanLiteral(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(value); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BooleanLiteral that = (BooleanLiteral) o; return value == that.value;
196
68
264
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public static io.crate.sql.tree.Literal fromObject(java.lang.Object) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/CharFilters.java
CharFilters
equals
class CharFilters<T> extends AnalyzerElement<T> { private final List<NamedProperties<T>> charFilters; public CharFilters(List<NamedProperties<T>> charFilters) { this.charFilters = charFilters; } public List<NamedProperties<T>> charFilters() { return charFilters; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(charFilters); } @Override public String toString() { return "CharFilters{" + "charFilters=" + charFilters + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitCharFilters(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CharFilters<?> that = (CharFilters<?>) o; return Objects.equals(charFilters, that.charFilters);
241
85
326
<methods>public non-sealed void <init>() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/Close.java
Close
equals
class Close extends Statement { private final String cursorName; /** * @param cursorName name of cursor to close; null implies ALL */ public Close(@Nullable String cursorName) { this.cursorName = cursorName; } @Nullable public String cursorName() { return cursorName; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitClose(this, context); } @Override public int hashCode() { return Objects.hashCode(cursorName); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "Close{cursorName=" + cursorName + "}"; } }
if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Close other = (Close) obj; return Objects.equals(cursorName, other.cursorName);
221
86
307
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/ColumnDefinition.java
ColumnDefinition
validateColumnConstraints
class ColumnDefinition<T> extends TableElement<T> { private final String ident; @Nullable private final ColumnType<T> type; private final List<ColumnConstraint<T>> constraints; public ColumnDefinition(String ident, @Nullable ColumnType<T> type, List<ColumnConstraint<T>> constraints) { this.ident = ident; this.type = type; this.constraints = constraints; validateColumnConstraints(ident, type, constraints); } static <T> void validateColumnConstraints(String ident, @Nullable ColumnType<T> type, List<ColumnConstraint<T>> constraints) {<FILL_FUNCTION_BODY>} public String ident() { return ident; } @Nullable public ColumnType<T> type() { return type; } public List<ColumnConstraint<T>> constraints() { return constraints; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ColumnDefinition<?> that = (ColumnDefinition<?>) o; return Objects.equals(ident, that.ident) && Objects.equals(type, that.type) && Objects.equals(constraints, that.constraints); } @Override public int hashCode() { return Objects.hash(ident, type, constraints); } @Override public String toString() { return "ColumnDefinition{" + "ident='" + ident + '\'' + ", type=" + type + ", constraints=" + constraints + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitColumnDefinition(this, context); } @Override public void visit(Consumer<? super T> consumer) { for (ColumnConstraint<T> constraint : constraints) { constraint.visit(consumer); } } }
var hasConstraint = new boolean[5]; for (ColumnConstraint<T> constraint : constraints) { switch (constraint) { case PrimaryKeyColumnConstraint<T> ignored -> { if (hasConstraint[0]) { throw new IllegalArgumentException("Column [" + ident + "]: multiple primary key constraints found"); } hasConstraint[0] = true; } case IndexColumnConstraint<T> ignored -> { if (hasConstraint[1]) { throw new IllegalArgumentException("Column [" + ident + "]: multiple index constraints found"); } hasConstraint[1] = true; } case DefaultConstraint<T> ignored -> { if (hasConstraint[2]) { throw new IllegalArgumentException("Column [" + ident + "]: multiple default constraints found"); } hasConstraint[2] = true; } case GeneratedExpressionConstraint<T> ignored -> { if (hasConstraint[3]) { throw new IllegalArgumentException("Column [" + ident + "]: multiple generated constraints found"); } hasConstraint[3] = true; } case ColumnStorageDefinition<T> ignored -> { if (hasConstraint[4]) { throw new IllegalArgumentException("Column [" + ident + "]: multiple storage constraints found"); } hasConstraint[4] = true; } case CheckColumnConstraint<T> ignored -> { // ignore } case NotNullColumnConstraint<T> ignored -> { // ignore } case NullColumnConstraint<T> ignored -> { // ignore } } } if (type == null && hasConstraint[3] == false) { throw new IllegalArgumentException("Column [" + ident + "]: data type needs to be provided " + "or column should be defined as a generated expression"); } if (hasConstraint[2] && hasConstraint[3]) { throw new IllegalArgumentException("Column [" + ident + "]: the default and generated expressions " + "are mutually exclusive"); }
553
502
1,055
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public abstract void visit(Consumer<? super T>) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/ColumnStorageDefinition.java
ColumnStorageDefinition
equals
class ColumnStorageDefinition<T> extends ColumnConstraint<T> { private final GenericProperties<T> properties; public ColumnStorageDefinition(GenericProperties<T> properties) { this.properties = properties; } public GenericProperties<T> properties() { return properties; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitColumnStorageDefinition(this, context); } @Override public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { return new ColumnStorageDefinition<>(properties.map(mapper)); } @Override public void visit(Consumer<? super T> consumer) { properties.properties().values().forEach(consumer); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(properties); } @Override public String toString() { return "ColumnStorageDefinition{" + "properties=" + properties + '}'; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ColumnStorageDefinition<?> that = (ColumnStorageDefinition<?>) o; return Objects.equals(properties, that.properties);
305
81
386
<methods>public R accept(AstVisitor<R,C>, C) ,public abstract ColumnConstraint<U> map(Function<? super T,? extends U>) ,public abstract void visit(Consumer<? super T>) <variables>permits CheckColumnConstraint,permits ColumnStorageDefinition,permits DefaultConstraint,permits GeneratedExpressionConstraint,permits IndexColumnConstraint,permits NotNullColumnConstraint,permits NullColumnConstraint,permits PrimaryKeyColumnConstraint
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/ComparisonExpression.java
ComparisonExpression
equals
class ComparisonExpression extends Expression { public enum Type { EQUAL("="), NOT_EQUAL("<>"), LESS_THAN("<"), LESS_THAN_OR_EQUAL("<="), GREATER_THAN(">"), GREATER_THAN_OR_EQUAL(">="), CONTAINED_WITHIN("<<"), IS_DISTINCT_FROM("IS DISTINCT FROM"), REGEX_MATCH("~"), REGEX_NO_MATCH("!~"), REGEX_MATCH_CI("~*"), REGEX_NO_MATCH_CI("!~*"); private final String value; Type(String value) { this.value = value; } public String getValue() { return value; } } private final Type type; private final Expression left; private final Expression right; public ComparisonExpression(Type type, Expression left, Expression right) { this.type = type; this.left = requireNonNull(left, "left is null"); this.right = requireNonNull(right, "right is null"); } public Type getType() { return type; } public Expression getLeft() { return left; } public Expression getRight() { return right; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitComparisonExpression(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(type, left, right); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ComparisonExpression that = (ComparisonExpression) o; return type == that.type && Objects.equals(left, that.left) && Objects.equals(right, that.right);
471
96
567
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public final java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/CreateAnalyzer.java
CreateAnalyzer
equals
class CreateAnalyzer<T> extends Statement { private final String ident; @Nullable private final String extendedAnalyzer; private final List<AnalyzerElement<T>> elements; public CreateAnalyzer(String ident, @Nullable String extendedAnalyzer, List<AnalyzerElement<T>> elements) { this.ident = ident; this.extendedAnalyzer = extendedAnalyzer; this.elements = elements; } public String ident() { return ident; } @Nullable public String extendedAnalyzer() { return extendedAnalyzer; } public boolean isExtending() { return extendedAnalyzer != null; } public List<AnalyzerElement<T>> elements() { return elements; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(ident, extendedAnalyzer, elements); } @Override public String toString() { return "CreateAnalyzer{" + "ident='" + ident + '\'' + ", extends='" + extendedAnalyzer + '\'' + ", elements=" + elements + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitCreateAnalyzer(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateAnalyzer<?> that = (CreateAnalyzer<?>) o; return Objects.equals(ident, that.ident) && Objects.equals(extendedAnalyzer, that.extendedAnalyzer) && Objects.equals(elements, that.elements);
372
115
487
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/CreatePublication.java
CreatePublication
toString
class CreatePublication extends Statement { private final String name; private final boolean forAllTables; private final List<QualifiedName> tables; public CreatePublication(String name, boolean forAllTables, List<QualifiedName> tables) { this.name = name; this.forAllTables = forAllTables; this.tables = tables; } public String name() { return name; } public boolean isForAllTables() { return forAllTables; } public List<QualifiedName> tables() { return tables; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitCreatePublication(this, context); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreatePublication that = (CreatePublication) o; return forAllTables == that.forAllTables && name.equals(that.name) && tables.equals(that.tables); } @Override public int hashCode() { return Objects.hash(name, forAllTables, tables); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "CreatePublication{" + "name='" + name + '\'' + ", forAllTables=" + forAllTables + ", tables=" + tables + '}';
377
53
430
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/CreateSnapshot.java
CreateSnapshot
equals
class CreateSnapshot<T> extends Statement { private final QualifiedName name; private final GenericProperties<T> properties; private final List<Table<T>> tables; public CreateSnapshot(QualifiedName name, GenericProperties<T> properties) { this.name = name; this.properties = properties; this.tables = Collections.emptyList(); } public CreateSnapshot(QualifiedName name, List<Table<T>> tables, GenericProperties<T> properties) { this.name = name; this.tables = tables; this.properties = properties; } public QualifiedName name() { return this.name; } public GenericProperties<T> properties() { return properties; } public List<Table<T>> tables() { return tables; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(name, properties, tables); } @Override public String toString() { return "CreateSnapshot{" + "name=" + name + ", properties=" + properties + ", tables=" + tables + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitCreateSnapshot(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateSnapshot<?> that = (CreateSnapshot<?>) o; return Objects.equals(name, that.name) && Objects.equals(properties, that.properties) && Objects.equals(tables, that.tables);
385
107
492
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/CreateTableAs.java
CreateTableAs
equals
class CreateTableAs<T> extends Statement { private final Table<T> name; private final Query query; public CreateTableAs(Table<T> name, Query query) { this.name = name; this.query = query; } public Table<T> name() { return this.name; } public Query query() { return this.query; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitCreateTableAs(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(name, query); } @Override public String toString() { return "CreateTableAs{" + "name=" + name + ", query=" + query + '}'; } }
if (this == o) { return true; } if (!(o instanceof CreateTableAs)) { return false; } CreateTableAs<?> that = (CreateTableAs<?>) o; return name.equals(that.name) && query.equals(that.query);
259
82
341
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/CreateView.java
CreateView
hashCode
class CreateView extends Statement { private final QualifiedName name; private final Query query; private final boolean replaceExisting; public CreateView(QualifiedName name, Query query, boolean replaceExisting) { this.name = name; this.query = query; this.replaceExisting = replaceExisting; } public QualifiedName name() { return name; } public Query query() { return query; } public boolean replaceExisting() { return replaceExisting; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CreateView that = (CreateView) o; if (replaceExisting != that.replaceExisting) return false; if (!name.equals(that.name)) return false; return query.equals(that.query); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "CreateView{" + "name=" + name + ", query=" + query + ", replaceExisting=" + replaceExisting + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitCreateView(this, context); } }
int result = name.hashCode(); result = 31 * result + query.hashCode(); result = 31 * result + (replaceExisting ? 1 : 0); return result;
383
52
435
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/DiscardStatement.java
DiscardStatement
equals
class DiscardStatement extends Statement { public enum Target { ALL, PLANS, SEQUENCES, TEMPORARY } private final Target target; public DiscardStatement(Target target) { this.target = target; } public Target target() { return target; } @Override public String toString() { return "DISCARD " + target.name().toUpperCase(Locale.ENGLISH); } @Override public int hashCode() { return target.hashCode(); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitDiscard(this, context); } }
return obj instanceof DiscardStatement && ((DiscardStatement) obj).target == this.target;
229
25
254
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/DropFunction.java
DropFunction
equals
class DropFunction extends Statement { private final QualifiedName name; private final boolean exists; private final List<FunctionArgument> arguments; public DropFunction(QualifiedName name, boolean exists, List<FunctionArgument> arguments) { this.name = name; this.exists = exists; this.arguments = arguments; } public QualifiedName name() { return name; } public boolean exists() { return exists; } public List<FunctionArgument> arguments() { return arguments; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitDropFunction(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + (exists ? 1 : 0); result = 31 * result + arguments.hashCode(); return result; } @Override public String toString() { return "DropFunction{" + "name=" + name + ", exists=" + exists + ", arguments=" + arguments + '}'; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DropFunction that = (DropFunction) o; if (exists != that.exists) return false; if (!name.equals(that.name)) return false; return arguments.equals(that.arguments);
336
89
425
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/DropRole.java
DropRole
toString
class DropRole extends Statement { private final String name; private final boolean ifExists; public DropRole(String name, boolean ifExists) { this.name = name; this.ifExists = ifExists; } public String name() { return name; } public boolean ifExists() { return ifExists; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DropRole dropRole = (DropRole) o; return ifExists == dropRole.ifExists && Objects.equals(name, dropRole.name); } @Override public int hashCode() { return Objects.hash(name, ifExists); } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitDropRole(this, context); } }
return "DropRole{" + "name='" + name + '\'' + ", ifExists=" + ifExists + '}';
298
39
337
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/DropView.java
DropView
hashCode
class DropView extends Statement { private final List<QualifiedName> names; private final boolean ifExists; public DropView(List<QualifiedName> names, boolean ifExists) { this.names = names; this.ifExists = ifExists; } public List<QualifiedName> names() { return names; } public boolean ifExists() { return ifExists; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DropView dropView = (DropView) o; if (ifExists != dropView.ifExists) return false; return names.equals(dropView.names); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "DropView{" + "names=" + names + ", ifExists=" + ifExists + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitDropView(this, context); } }
int result = names.hashCode(); result = 31 * result + (ifExists ? 1 : 0); return result;
329
37
366
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/Except.java
Except
equals
class Except extends SetOperation { private final Relation left; private final Relation right; public Except(Relation left, Relation right) { this.left = requireNonNull(left, "relation must not be null"); this.right = requireNonNull(right, "relation must not be null"); } public Relation getLeft() { return left; } public Relation getRight() { return right; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitExcept(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(left, right); } @Override public String toString() { return "Except{" + "left=" + left + ", right=" + right + '}'; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Except except = (Except) o; return Objects.equals(left, except.left) && Objects.equals(right, except.right);
269
87
356
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/Explain.java
Explain
toString
class Explain extends Statement { public enum Option { ANALYZE, COSTS, VERBOSE } private final Statement statement; // Possible values for options is `true`, `false`, `null` private final Map<Option, Boolean> options; public Explain(Statement statement, Map<Option, Boolean> options) { this.statement = requireNonNull(statement, "statement is null"); this.options = options; } public Statement getStatement() { return statement; } public Map<Option, Boolean> options() { return options; } public boolean isOptionActivated(Explain.Option option) { // Option is activated if key is present and value true or null // e.g. explain (analyze true) or explain (analyze) return options.containsKey(option) && (options.get(option) == null || options.get(option) == true); } public boolean isOptionExplicitlyDeactivated(Explain.Option option) { return options.containsKey(option) && options.get(option) == false; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitExplain(this, context); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Explain explain = (Explain) o; return Objects.equals(statement, explain.statement) && Objects.equals(options, explain.options); } @Override public int hashCode() { return Objects.hash(statement, options); } public String toString() {<FILL_FUNCTION_BODY>} }
return "Explain{" + "statement=" + statement + ", options=" + options + '}';
492
34
526
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/FunctionArgument.java
FunctionArgument
equals
class FunctionArgument extends Node { @Nullable private final String name; private final ColumnType<?> type; public FunctionArgument(@Nullable String name, ColumnType<?> type) { this.name = name; this.type = type; } @Nullable public String name() { return name; } public ColumnType<?> type() { return type; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitFunctionArgument(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(name, type); } @Override public String toString() { return "FunctionArgument{" + "name=" + name + ", type=" + type + '}'; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final FunctionArgument that = (FunctionArgument) o; return Objects.equals(this.name, that.name) && Objects.equals(this.type, that.type);
259
81
340
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() ,public abstract java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/GenericProperties.java
GenericProperties
equals
class GenericProperties<T> extends Node { private static final GenericProperties<?> EMPTY = new GenericProperties<>(Map.of()); @SuppressWarnings("unchecked") public static <T> GenericProperties<T> empty() { return (GenericProperties<T>) EMPTY; } private final Map<String, T> properties; public GenericProperties(Map<String, T> map) { this.properties = Collections.unmodifiableMap(map); } public Map<String, T> properties() { return properties; } public T get(String key) { return properties.get(key); } public boolean isEmpty() { return properties.isEmpty(); } public <U> GenericProperties<U> map(Function<? super T, ? extends U> mapper) { if (isEmpty()) { return empty(); } // The new map must support NULL values. Map<String, U> mappedProperties = new HashMap<>(properties.size()); properties.forEach((key, value) -> mappedProperties.put( key, mapper.apply(value) )); return new GenericProperties<>(mappedProperties); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(properties); } @Override public String toString() { return properties.toString(); } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitGenericProperties(this, context); } public int size() { return properties.size(); } public Set<String> keys() { return properties.keySet(); } /** * Raises an {@link IllegalArgumentException} if the properties contain a * setting not contained in the given collection. **/ public GenericProperties<T> ensureContainsOnly(Collection<String> supportedSettings) { for (String key : properties.keySet()) { if (!supportedSettings.contains(key)) { throw new IllegalArgumentException("Setting '" + key + "' is not supported"); } } return this; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GenericProperties<?> that = (GenericProperties<?>) o; return Objects.equals(properties, that.properties);
597
80
677
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() ,public abstract java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/GrantPrivilege.java
GrantPrivilege
toString
class GrantPrivilege extends PrivilegeStatement { public GrantPrivilege(List<String> userNames, String securable, List<QualifiedName> tableOrSchemaNames) { super(userNames, securable, tableOrSchemaNames); } public GrantPrivilege(List<String> userNames, List<String> permissions, String securable, List<QualifiedName> tableOrSchemaNames) { super(userNames, permissions, securable, tableOrSchemaNames); } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitGrantPrivilege(this, context); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "GrantPrivilege{" + "allPrivileges=" + all + "permissions=" + permissions + ", userNames=" + userNames + '}';
215
54
269
<methods>public boolean all() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public List<io.crate.sql.tree.QualifiedName> privilegeIdents() ,public List<java.lang.String> privileges() ,public java.lang.String securable() ,public List<java.lang.String> userNames() <variables>permits DenyPrivilege,permits GrantPrivilege,permits RevokePrivilege,protected final non-sealed boolean all,protected final non-sealed List<java.lang.String> permissions,private final non-sealed java.lang.String securable,private final non-sealed List<io.crate.sql.tree.QualifiedName> tableOrSchemaNames,protected final non-sealed List<java.lang.String> userNames
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/IndexDefinition.java
IndexDefinition
equals
class IndexDefinition<T> extends TableElement<T> { private final String ident; private final String method; private final List<T> columns; private final GenericProperties<T> properties; public IndexDefinition(String ident, String method, List<T> columns, GenericProperties<T> properties) { this.ident = ident; this.method = method; this.columns = columns; this.properties = properties; } public String ident() { return ident; } public String method() { return method; } public List<T> columns() { return columns; } public GenericProperties<T> properties() { return properties; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(ident, method, columns, properties); } @Override public String toString() { return "IndexDefinition{" + "ident='" + ident + '\'' + ", method='" + method + '\'' + ", columns=" + columns + ", properties=" + properties + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitIndexDefinition(this, context); } @Override public void visit(Consumer<? super T> consumer) { columns.forEach(consumer); properties.properties().values().forEach(consumer); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexDefinition<?> that = (IndexDefinition<?>) o; return Objects.equals(ident, that.ident) && Objects.equals(method, that.method) && Objects.equals(columns, that.columns) && Objects.equals(properties, that.properties);
410
121
531
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public abstract void visit(Consumer<? super T>) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/Insert.java
DuplicateKeyContext
toString
class DuplicateKeyContext<T> { private static final DuplicateKeyContext<?> NONE = new DuplicateKeyContext<>(Type.NONE, Collections.emptyList(), Collections.emptyList()); @SuppressWarnings("unchecked") public static <T> DuplicateKeyContext<T> none() { return (DuplicateKeyContext<T>) NONE; } public enum Type { ON_CONFLICT_DO_UPDATE_SET, ON_CONFLICT_DO_NOTHING, NONE } private final Type type; private final List<Assignment<T>> onDuplicateKeyAssignments; private final List<T> constraintColumns; public DuplicateKeyContext(Type type, List<Assignment<T>> onDuplicateKeyAssignments, List<T> constraintColumns) { this.type = type; this.onDuplicateKeyAssignments = onDuplicateKeyAssignments; this.constraintColumns = constraintColumns; } public Type getType() { return type; } public List<Assignment<T>> getAssignments() { return onDuplicateKeyAssignments; } public List<T> getConstraintColumns() { return constraintColumns; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DuplicateKeyContext<?> that = (DuplicateKeyContext<?>) o; return type == that.type && Objects.equals(onDuplicateKeyAssignments, that.onDuplicateKeyAssignments) && Objects.equals(constraintColumns, that.constraintColumns); } @Override public int hashCode() { return Objects.hash(type, onDuplicateKeyAssignments, constraintColumns); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "DuplicateKeyContext{" + "type=" + type + ", onDuplicateKeyAssignments=" + onDuplicateKeyAssignments + ", constraintColumns=" + constraintColumns + '}';
531
59
590
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/IntervalLiteral.java
IntervalLiteral
equals
class IntervalLiteral extends Literal { public enum Sign { PLUS, MINUS } public enum IntervalField { YEAR, MONTH, DAY, HOUR, MINUTE, SECOND } private final String value; private final Sign sign; private final IntervalField startField; @Nullable private final IntervalField endField; public IntervalLiteral(String value, Sign sign, IntervalField startField, @Nullable IntervalField endField) { this.value = value; this.sign = sign; this.startField = startField; this.endField = endField; } public String getValue() { return value; } public Sign getSign() { return sign; } public IntervalField getStartField() { return startField; } @Nullable public IntervalField getEndField() { return endField; } public static String format(IntervalLiteral i) { StringBuilder builder = new StringBuilder("INTERVAL "); if (i.getSign() == IntervalLiteral.Sign.MINUS) { builder.append("- "); } builder.append("'"); builder.append(i.getValue()); builder.append("' ") .append(i.getStartField().name()); IntervalLiteral.IntervalField endField = i.getEndField(); if (endField != null) { builder.append(" TO ").append(endField.name()); } return builder.toString(); } @Override public int hashCode() { return Objects.hash(value, sign, startField, endField); } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitIntervalLiteral(this, context); } }
if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } IntervalLiteral other = (IntervalLiteral) obj; return Objects.equals(this.value, other.value) && Objects.equals(this.sign, other.sign) && Objects.equals(this.startField, other.startField) && Objects.equals(this.endField, other.endField);
522
128
650
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public static io.crate.sql.tree.Literal fromObject(java.lang.Object) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/IsNullPredicate.java
IsNullPredicate
equals
class IsNullPredicate extends Expression { private final Expression value; public IsNullPredicate(Expression value) { this.value = requireNonNull(value, "value is null"); } public Expression getValue() { return value; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitIsNullPredicate(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(value); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IsNullPredicate that = (IsNullPredicate) o; return Objects.equals(value, that.value);
174
77
251
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public final java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/JoinOn.java
JoinOn
equals
class JoinOn extends JoinCriteria { private final Expression expression; public JoinOn(Expression expression) { this.expression = requireNonNull(expression, "expression is null"); } public Expression getExpression() { return expression; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(expression); } @Override public String toString() { return "JoinOn{" + "expression=" + expression + '}'; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JoinOn joinOn = (JoinOn) o; return Objects.equals(expression, joinOn.expression);
160
75
235
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() ,public abstract java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/JoinUsing.java
JoinUsing
equals
class JoinUsing extends JoinCriteria { private static QualifiedName extendQualifiedName(QualifiedName name, String ext) { List<String> parts = new ArrayList<>(name.getParts().size() + 1); parts.addAll(name.getParts()); parts.add(ext); return new QualifiedName(parts); } public static Expression toExpression(QualifiedName left, QualifiedName right, List<String> columns) { if (columns.isEmpty()) { throw new IllegalArgumentException("columns must not be empty"); } List<ComparisonExpression> comp = columns.stream() .map(col -> new ComparisonExpression( ComparisonExpression.Type.EQUAL, new QualifiedNameReference(extendQualifiedName(left, col)), new QualifiedNameReference((extendQualifiedName(right, col))))) .toList(); if (1 == comp.size()) { return comp.get(0); } Expression expr = null; for (int i = comp.size() - 2; i >= 0; i--) { if (null == expr) { expr = new LogicalBinaryExpression( LogicalBinaryExpression.Type.AND, comp.get(i), comp.get(i + 1)); } else { expr = new LogicalBinaryExpression( LogicalBinaryExpression.Type.AND, comp.get(i), expr); } } return expr; } private final List<String> columns; public JoinUsing(List<String> columns) { if (columns.isEmpty()) { throw new IllegalArgumentException("columns must not be empty"); } this.columns = List.copyOf(columns); } public List<String> getColumns() { return columns; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(columns); } @Override public String toString() { return "JoinUsing{" + "columns=" + columns + '}'; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JoinUsing joinUsing = (JoinUsing) o; return Objects.equals(columns, joinUsing.columns);
564
75
639
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() ,public abstract java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/Literal.java
Literal
fromObject
class Literal extends Expression { @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitLiteral(this, context); } public static Literal fromObject(Object value) {<FILL_FUNCTION_BODY>} }
Literal literal = null; if (value == null) { literal = NullLiteral.INSTANCE; } else if (value instanceof Number n) { if (value instanceof Float || value instanceof Double) { literal = new DoubleLiteral(value.toString()); } else if (value instanceof Short || value instanceof Integer) { literal = new IntegerLiteral(n.intValue()); } else if (value instanceof Long l) { literal = new LongLiteral(l); } } else if (value instanceof Boolean b) { literal = b ? BooleanLiteral.TRUE_LITERAL : BooleanLiteral.FALSE_LITERAL; } else if (value instanceof Object[] oArray) { List<Expression> expressions = new ArrayList<>(); for (Object o : oArray) { expressions.add(fromObject(o)); } literal = new ArrayLiteral(expressions); } else if (value instanceof Map) { HashMap<String, Expression> map = new HashMap<>(); @SuppressWarnings("unchecked") Map<String, Object> valueMap = (Map<String, Object>) value; for (Map.Entry<String, Object> entry : valueMap.entrySet()) { map.put(entry.getKey(), fromObject(entry.getValue())); } literal = new ObjectLiteral(map); } else { literal = new StringLiteral(value.toString()); } return literal;
84
355
439
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public final java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/LongLiteral.java
LongLiteral
equals
class LongLiteral extends Literal { private final long value; public LongLiteral(long value) { this.value = value; } public long getValue() { return value; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitLongLiteral(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return (int) (value ^ (value >>> 32)); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LongLiteral that = (LongLiteral) o; return value == that.value;
164
68
232
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public static io.crate.sql.tree.Literal fromObject(java.lang.Object) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/MatchPredicate.java
MatchPredicate
equals
class MatchPredicate extends Expression { private final List<MatchPredicateColumnIdent> idents; private final Expression value; private final GenericProperties<Expression> properties; private final String matchType; public MatchPredicate(List<MatchPredicateColumnIdent> idents, Expression value, @Nullable String matchType, GenericProperties<Expression> properties) { if (idents.isEmpty()) { throw new IllegalArgumentException("at least one ident must be given"); } this.idents = idents; this.value = requireNonNull(value, "query_term is null"); this.matchType = matchType; this.properties = properties; } public List<MatchPredicateColumnIdent> idents() { return idents; } public Expression value() { return value; } @Nullable public String matchType() { return matchType; } public GenericProperties<Expression> properties() { return properties; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(idents, value, properties, matchType); } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitMatchPredicate(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MatchPredicate that = (MatchPredicate) o; return Objects.equals(idents, that.idents) && Objects.equals(value, that.value) && Objects.equals(properties, that.properties) && Objects.equals(matchType, that.matchType);
369
119
488
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public final java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/MultiStatement.java
MultiStatement
equals
class MultiStatement extends Statement { private final List<Statement> statements; public MultiStatement(List<Statement> statements) { this.statements = statements; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((statements == null) ? 0 : statements.hashCode()); return result; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "MultiStatement{statements=" + statements + "}"; } public List<Statement> statements() { return statements; } }
if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MultiStatement other = (MultiStatement) obj; if (statements == null) { if (other.statements != null) { return false; } } else if (!statements.equals(other.statements)) { return false; } return true;
186
133
319
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/NaturalJoin.java
NaturalJoin
equals
class NaturalJoin extends JoinCriteria { @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return 0; } @Override public String toString() { return "NaturalJoin{}"; } }
if (this == obj) { return true; } return (obj != null) && (getClass() == obj.getClass());
85
40
125
<methods>public non-sealed void <init>() ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() ,public abstract java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/NotExpression.java
NotExpression
equals
class NotExpression extends Expression { private final Expression value; public NotExpression(Expression value) { this.value = requireNonNull(value, "value is null"); } public Expression getValue() { return value; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(value); } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitNotExpression(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NotExpression that = (NotExpression) o; return Objects.equals(value, that.value);
168
73
241
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public final java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/NullLiteral.java
NullLiteral
equals
class NullLiteral extends Literal { public static final NullLiteral INSTANCE = new NullLiteral(); private NullLiteral() { } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitNullLiteral(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return 0; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return true;
132
53
185
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public static io.crate.sql.tree.Literal fromObject(java.lang.Object) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/ObjectLiteral.java
ObjectLiteral
equals
class ObjectLiteral extends Literal { private final Map<String, Expression> values; public ObjectLiteral(Map<String, Expression> values) { this.values = values; } public Map<String, Expression> values() { return values; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitObjectLiteral(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return values.hashCode(); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ObjectLiteral that = (ObjectLiteral) o; if (!values.equals(that.values)) return false; return true;
172
70
242
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public static io.crate.sql.tree.Literal fromObject(java.lang.Object) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/OptimizeStatement.java
OptimizeStatement
equals
class OptimizeStatement<T> extends Statement { private final List<Table<T>> tables; private final GenericProperties<T> properties; public OptimizeStatement(List<Table<T>> tables, GenericProperties<T> properties) { this.tables = tables; this.properties = properties; } public List<Table<T>> tables() { return tables; } public GenericProperties<T> properties() { return properties; } public <U> OptimizeStatement<U> map(Function<? super T, ? extends U> mapper) { return new OptimizeStatement<>( Lists.map(tables, x -> x.map(mapper)), properties.map(mapper) ); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(tables, properties); } @Override public String toString() { return "OptimizeStatement{" + "tables=" + tables + ", properties=" + properties + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitOptimizeStatement(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OptimizeStatement<?> that = (OptimizeStatement<?>) o; return Objects.equals(tables, that.tables) && Objects.equals(properties, that.properties);
350
96
446
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/ParameterExpression.java
ParameterExpression
equals
class ParameterExpression extends Expression { private final int position; public ParameterExpression(int position) { this.position = position; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitParameterExpression(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return position; } public int position() { return position; } public int index() { return position - 1; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ParameterExpression that = (ParameterExpression) o; if (position != that.position) return false; return true;
172
70
242
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public final java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/PrivilegeStatement.java
PrivilegeStatement
equals
class PrivilegeStatement extends Statement permits GrantPrivilege, RevokePrivilege, DenyPrivilege { protected final List<String> userNames; protected final List<String> permissions; private final List<QualifiedName> tableOrSchemaNames; private final String securable; protected final boolean all; protected PrivilegeStatement(List<String> userNames, String securable, List<QualifiedName> tableOrSchemaNames) { this.userNames = userNames; permissions = Collections.emptyList(); all = true; this.securable = securable; this.tableOrSchemaNames = tableOrSchemaNames; } protected PrivilegeStatement(List<String> userNames, List<String> permissions, String securable, List<QualifiedName> tableOrSchemaNames) { this.userNames = userNames; this.permissions = permissions; this.all = false; this.securable = securable; this.tableOrSchemaNames = tableOrSchemaNames; } public List<String> privileges() { return permissions; } public List<String> userNames() { return userNames; } public boolean all() { return all; } public List<QualifiedName> privilegeIdents() { return tableOrSchemaNames; } public String securable() { return securable; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(userNames, permissions, all); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PrivilegeStatement that = (PrivilegeStatement) o; return all == that.all && Objects.equals(userNames, that.userNames) && Objects.equals(permissions, that.permissions);
438
93
531
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/QueryUtil.java
QueryUtil
selectList
class QueryUtil { public static Select selectList(Expression... expressions) {<FILL_FUNCTION_BODY>} public static List<Relation> table(QualifiedName name) { return List.of(new Table<>(name)); } }
ArrayList<SelectItem> items = new ArrayList<>(); for (Expression expression : expressions) { items.add(new SingleColumn(expression)); } return new Select(false, items);
68
51
119
<no_super_class>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/RerouteCancelShard.java
RerouteCancelShard
equals
class RerouteCancelShard<T> extends RerouteOption { private final T shardId; private final T nodeIdOrName; private final GenericProperties<T> properties; public RerouteCancelShard(T shardId, T nodeIdOrName, GenericProperties<T> properties) { this.shardId = shardId; this.nodeIdOrName = nodeIdOrName; this.properties = properties; } public T nodeIdOrName() { return nodeIdOrName; } public T shardId() { return shardId; } public GenericProperties<T> properties() { return properties; } public <U> RerouteCancelShard<U> map(Function<? super T, ? extends U> mapper) { return new RerouteCancelShard<>( mapper.apply(shardId), mapper.apply(nodeIdOrName), properties.map(mapper)); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(nodeIdOrName, shardId, properties); } @Override public String toString() { return "RerouteCancelShard{" + "nodeIdOrName=" + nodeIdOrName + ", shardId=" + shardId + ", properties=" + properties + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitRerouteCancelShard(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RerouteCancelShard<?> that = (RerouteCancelShard<?>) o; return Objects.equals(nodeIdOrName, that.nodeIdOrName) && Objects.equals(shardId, that.shardId) && Objects.equals(properties, that.properties);
444
125
569
<methods>public non-sealed void <init>() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/RerouteMoveShard.java
RerouteMoveShard
equals
class RerouteMoveShard<T> extends RerouteOption { private final T shardId; private final T fromNodeIdOrName; private final T toNodeIdOrName; public RerouteMoveShard(T shardId, T fromNodeIdOrName, T toNodeIdOrName) { this.shardId = shardId; this.fromNodeIdOrName = fromNodeIdOrName; this.toNodeIdOrName = toNodeIdOrName; } public T shardId() { return shardId; } public T fromNodeIdOrName() { return fromNodeIdOrName; } public T toNodeIdOrName() { return toNodeIdOrName; } public <U> RerouteMoveShard<U> map(Function<? super T, ? extends U> mapper) { return new RerouteMoveShard<>( mapper.apply(shardId), mapper.apply(fromNodeIdOrName), mapper.apply(toNodeIdOrName)); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(shardId, fromNodeIdOrName, toNodeIdOrName); } @Override public String toString() { return "RerouteMoveShard{" + "shardId=" + shardId + ", fromNodeId=" + fromNodeIdOrName + ", toNodeId=" + toNodeIdOrName + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitRerouteMoveShard(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RerouteMoveShard<?> that = (RerouteMoveShard<?>) o; return Objects.equals(shardId, that.shardId) && Objects.equals(fromNodeIdOrName, that.fromNodeIdOrName) && Objects.equals(toNodeIdOrName, that.toNodeIdOrName);
475
135
610
<methods>public non-sealed void <init>() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/Select.java
Select
equals
class Select extends Node { private final boolean distinct; private final List<SelectItem> selectItems; public Select(boolean distinct, List<SelectItem> selectItems) { this.distinct = distinct; this.selectItems = Collections.unmodifiableList(selectItems); } public boolean isDistinct() { return distinct; } public List<SelectItem> getSelectItems() { return selectItems; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitSelect(this, context); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(distinct, selectItems); } @Override public String toString() { return "Select{" + "distinct=" + distinct + ", selectItems=" + selectItems + '}'; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Select select = (Select) o; return distinct == select.distinct && Objects.equals(selectItems, select.selectItems);
269
82
351
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) ,public abstract boolean equals(java.lang.Object) ,public abstract int hashCode() ,public abstract java.lang.String toString() <variables>
crate_crate
crate/libs/sql-parser/src/main/java/io/crate/sql/tree/SetSessionAuthorizationStatement.java
SetSessionAuthorizationStatement
equals
class SetSessionAuthorizationStatement extends Statement { public enum Scope { SESSION, LOCAL } @Nullable private final String user; private final Scope scope; public SetSessionAuthorizationStatement(Scope scope) { this(null, scope); } public SetSessionAuthorizationStatement(@Nullable String user, Scope scope) { this.scope = scope; this.user = user; } /** * user is null for the following statements:: * <p> * SET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULT * and * RESET SESSION AUTHORIZATION */ @Nullable public String user() { return user; } public Scope scope() { return scope; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(user, scope); } @Override public String toString() { return "SetSessionAuthorizationStatement{" + "user='" + user + '\'' + ", scope=" + scope + '}'; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitSetSessionAuthorizationStatement(this, context); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SetSessionAuthorizationStatement that = (SetSessionAuthorizationStatement) o; return Objects.equals(user, that.user) && scope == that.scope;
367
88
455
<methods>public non-sealed void <init>() ,public R accept(AstVisitor<R,C>, C) <variables>