method2testcases
stringlengths
118
6.63k
### Question: ThreadsStatsCollector extends Thread implements AutoCloseable { public Integer getCpuTrailingAverage(long id, int seconds) { return cpuStat.getTrailingAverage(id, seconds); } ThreadsStatsCollector(Set<Long> slicingThreadIds); ThreadsStatsCollector(long collectionIntervalInMilliSeconds, Set<Long> slicingThreadIds); @Override void run(); Integer getCpuTrailingAverage(long id, int seconds); Integer getUserTrailingAverage(long id, int seconds); void close(); }### Answer: @Test public void testOldThreadsArePruned() throws InterruptedException { Thread t = new Thread() { public void run () { try { sleep(400l); } catch (InterruptedException e) { } } }; Thread t1 = new Thread() { public void run () { try { sleep(400l); } catch (InterruptedException e) { } } }; t.start(); t1.start(); ThreadsStatsCollector collector = new ThreadsStatsCollector(50L, Sets.newHashSet(t1.getId())); collector.start(); sleep(200l); Integer stat = collector.getCpuTrailingAverage(t.getId(), 1); Integer statThread2 = collector.getCpuTrailingAverage(t1.getId(), 1); Assert.assertTrue(stat == null); Assert.assertTrue(statThread2 != null); t.join(); t1.join(); stat = collector.getCpuTrailingAverage(t.getId(), 1); Assert.assertTrue(stat == null); }
### Question: MatchBitSet implements AutoCloseable { public void set(final int index) { final int wordNum = index >>> LONG_TO_BITS_SHIFT; final int bit = index & BIT_OFFSET_MUSK; final long bitMask = 1L << bit; final long wordAddr = bufferAddr + wordNum * BYTES_PER_WORD; PlatformDependent.putLong(wordAddr, PlatformDependent.getLong(wordAddr) | bitMask); } MatchBitSet(final int numBits, final BufferAllocator allocator); void set(final int index); boolean get(final int index); int nextUnSetBit(final int index); int cardinality(); @Override void close(); }### Answer: @Test public void randomBits() throws Exception { final int count = 8*1024*1024; BitSet bitSet = new BitSet(count); final Random rand = new Random(); try (MatchBitSet matchBitSet = new MatchBitSet(count, allocator)) { for (int i = 0; i < count; i ++) { int val = rand.nextInt(10); if (val > 3) { bitSet.set(i); matchBitSet.set(i); } } validateBits(matchBitSet, bitSet, count); } } @Test public void fullBits() throws Exception { final int count = 256*1024; BitSet bitSet = new BitSet(count); try (MatchBitSet matchBitSet = new MatchBitSet(count, allocator)) { for (int i = 0; i < count; i++) { bitSet.set(i); matchBitSet.set(i); } validateBits(matchBitSet, bitSet, count); } } @Test public void specifiedBits() throws Exception { final int count = 256*1024 + 13; BitSet bitSet = new BitSet(count); try (MatchBitSet matchBitSet = new MatchBitSet(count, allocator)) { for (int i = 0; i < count; i += WORD_BITS) { if ((i / WORD_BITS) % 3 == 0) { for (int j = 0; j < WORD_BITS; j++) { bitSet.set(i + j); matchBitSet.set(i + j); } } else if ((i / WORD_BITS) % 3 == 1) { for (int j = 0; j < WORD_BITS; j++) { if (j % 3 == 0) { bitSet.set(i + j); matchBitSet.set(i + j); } } } else { } } validateBits(matchBitSet, bitSet, count); } }
### Question: LBlockHashTableEight implements AutoCloseable { public Optional<BloomFilter> prepareBloomFilter(final boolean sizeDynamically) throws Exception { final long bloomFilterSize = sizeDynamically ? Math.min(BloomFilter.getOptimalSize(size()), BLOOMFILTER_MAX_SIZE) : BLOOMFILTER_MAX_SIZE; try (ArrowBuf keyHolder = allocator.buffer(9); RollbackCloseable closeOnErr = new RollbackCloseable()) { final BloomFilter bloomFilter = new BloomFilter(allocator, Thread.currentThread().getName(), bloomFilterSize); closeOnErr.add(bloomFilter); bloomFilter.setup(); for (int chunk = 0; chunk < tableFixedAddresses.length; chunk++) { final long chunkAddr = tableFixedAddresses[chunk]; final long chunkEnd = chunkAddr + (MAX_VALUES_PER_BATCH * BLOCK_WIDTH); for (long blockAddr = chunkAddr; blockAddr < chunkEnd; blockAddr += BLOCK_WIDTH) { final long key = PlatformDependent.getLong(blockAddr); if (key == this.freeValue) { continue; } keyHolder.writerIndex(0); final byte validityByte = (key == NULL_KEY_VALUE) ? (byte)0x00 : (byte)0x01; keyHolder.writeByte(validityByte); keyHolder.writeLong(key); bloomFilter.put(keyHolder, 9); } } closeOnErr.commit(); return Optional.of(bloomFilter); } } LBlockHashTableEight(HashConfig config, BufferAllocator allocator, int initialSize); int insert(long key, int keyHash); int getNull(); int insertNull(); int insertNull(int oldNullKeyOrdinal); int get(long key, int keyHash); @Override int hashCode(); @Override String toString(); @Override boolean equals(Object obj); int size(); int blocks(); int capacity(); @Override void close(); long getRehashTime(TimeUnit unit); int getRehashCount(); Optional<BloomFilter> prepareBloomFilter(final boolean sizeDynamically); static final int KEY_WIDTH; static final int ORDINAL_WIDTH; static final int BLOCK_WIDTH; static final int BITS_IN_CHUNK; static final int MAX_VALUES_PER_BATCH; static final int CHUNK_OFFSET_MASK; static final int POSITIVE_MASK; static final int NO_MATCH; }### Answer: @Test public void testPrepareBloomFilter() throws Exception { List<AutoCloseable> closeables = new ArrayList<>(); try (ArrowBuf keyBuf = testAllocator.buffer(9); LBlockHashTableEight table = new LBlockHashTableEight(HashConfig.getDefault(), testAllocator, 16)) { Set<Long> dataSet = generatedData(10); dataSet.stream().forEach(key -> table.insert(key, (int) HashComputation.computeHash(key))); final Optional<BloomFilter> bloomFilterOptional = table.prepareBloomFilter(false); assertTrue(bloomFilterOptional.isPresent()); closeables.add(bloomFilterOptional.get()); dataSet.stream().forEach(key -> assertTrue(bloomFilterOptional.get().mightContain(writeKey(keyBuf, key), 9))); Set<Long> differentData = generatedData(100); long fpCount = differentData.stream() .filter(key -> !dataSet.contains(key)) .filter(key -> bloomFilterOptional.get().mightContain(writeKey(keyBuf, key), 9)).count(); assertTrue("False positive count is high - " + fpCount, fpCount < 5); BloomFilter bloomFilter = bloomFilterOptional.get(); assertFalse(bloomFilter.mightContain(writeNull(keyBuf), 9)); table.insertNull(); BloomFilter bloomFilter2 = table.prepareBloomFilter(false).get(); closeables.add(bloomFilter2); assertTrue(bloomFilter2.mightContain(writeNull(keyBuf), 9)); } finally { AutoCloseables.close(closeables); } }
### Question: AbstractDataCollector implements DataCollector { @Override public synchronized void close() throws Exception { if(!closed){ final List<AutoCloseable> closeables = new ArrayList<>(); closeables.addAll(Arrays.asList(buffers)); closeables.add(new AutoCloseable() { @Override public void close() throws Exception { for (int i = 0; i < completionMessages.length; i++) { completionMessages[i].informUpstreamIfNecessary(); } } }); closeables.add(new AutoCloseable() { @Override public void close() throws Exception { closed = true; } }); AutoCloseables.close(closeables); } } AbstractDataCollector( SharedResourceGroup resourceGroup, boolean isDiscrete, Collector collector, final int bufferCapacity, BufferAllocator allocator, SabotConfig config, FragmentHandle handle, FragmentWorkQueue workQueue, TunnelProvider tunnelProvider, SpillService spillService, EndpointsIndex endpointsIndex); @Override int getOppositeMajorFragmentId(); @Override RawBatchBuffer[] getBuffers(); @Override void streamCompleted(int minorFragmentId); @Override void batchArrived(int minorFragmentId, RawFragmentBatch batch); @Override int getTotalIncomingFragments(); @Override synchronized void close(); }### Answer: @Test public void testReserveMemory() { SharedResourceGroup resourceGroup = mock(SharedResourceGroup.class); SabotConfig config = mock(SabotConfig.class); FragmentWorkQueue workQueue = mock(FragmentWorkQueue.class); TunnelProvider tunnelProvider = mock(TunnelProvider.class); EndpointsIndex endpointsIndex = new EndpointsIndex( Arrays.asList( NodeEndpoint.newBuilder().setAddress("localhost").setFabricPort(12345).build(), NodeEndpoint.newBuilder().setAddress("localhost").setFabricPort(12345).build() ) ); List<CoordExecRPC.MinorFragmentIndexEndpoint> list = Arrays.asList( MinorFragmentIndexEndpoint.newBuilder().setEndpointIndex(0).setMinorFragmentId(0).build(), MinorFragmentIndexEndpoint.newBuilder().setEndpointIndex(0).setMinorFragmentId(0).build() ); CoordExecRPC.Collector collector = CoordExecRPC.Collector.newBuilder() .setIsSpooling(true) .setOppositeMajorFragmentId(3) .setSupportsOutOfOrder(true) .addAllIncomingMinorFragmentIndex(list) .build(); ExecProtos.FragmentHandle handle = ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(2323).setMinorFragmentId(234234).build(); BufferAllocator allocator = allocatorRule.newAllocator("test-abstract-data-collector", 0, 2000000); boolean outOfMemory = false; final SchedulerService schedulerService = Mockito.mock(SchedulerService.class); final SpillService spillService = new SpillServiceImpl(DremioConfig.create(null, config), new DefaultSpillServiceOptions(), new Provider<SchedulerService>() { @Override public SchedulerService get() { return schedulerService; } }); try { AbstractDataCollector dataCollector = new AbstractDataCollector(resourceGroup, true, collector, 10240, allocator, config, handle, workQueue, tunnelProvider, spillService, endpointsIndex) { @Override protected RawBatchBuffer getBuffer(int minorFragmentId) { return null; } }; } catch (OutOfMemoryException e) { assertEquals(allocator.getPeakMemoryAllocation(), 1024*1024); outOfMemory = true; } assertTrue(outOfMemory); allocator.close(); }
### Question: BoundedPivots { public static int pivot(PivotDef pivot, int start, int count, FixedBlockVector fixedBlock, VariableBlockVector variable) { if (pivot.getVariableCount() > 0) { int updatedCount = pivotVariableLengths(pivot.getVariablePivots(), fixedBlock, variable, start, count); Preconditions.checkState(updatedCount <= count); count = updatedCount; } for(VectorPivotDef def : pivot.getFixedPivots()){ switch(def.getType()){ case BIT: pivotBit(def, fixedBlock, start, count); break; case FOUR_BYTE: pivot4Bytes(def, fixedBlock, start, count); break; case EIGHT_BYTE: pivot8Bytes(def, fixedBlock, start, count); break; case SIXTEEN_BYTE: pivot16Bytes(def, fixedBlock, start, count); break; case VARIABLE: default: throw new UnsupportedOperationException("Pivot: unknown type: " + Describer.describe(def.getIncomingVector().getField())); } } return count; } static int pivot(PivotDef pivot, int start, int count, FixedBlockVector fixedBlock, VariableBlockVector variable); }### Answer: @Test public void boolNullEveryOther() throws Exception { final int count = 1024; try ( BitVector in = new BitVector("in", allocator); BitVector out = new BitVector("out", allocator); ) { in.allocateNew(count); ArrowBuf tempBuf = allocator.buffer(1024); for (int i = 0; i < count; i ++) { if (i % 2 == 0) { in.set(i, 1); } } in.setValueCount(count); final PivotDef pivot = PivotBuilder.getBlockDefinition(new FieldVectorPair(in, out)); try ( final FixedBlockVector fbv = new FixedBlockVector(allocator, pivot.getBlockWidth()); final VariableBlockVector vbv = new VariableBlockVector(allocator, pivot.getVariableCount()); ) { fbv.ensureAvailableBlocks(count); Pivots.pivot(pivot, count, fbv, vbv); Unpivots.unpivot(pivot, fbv, vbv, 0, count); for (int i = 0; i < count; i++) { assertEquals(in.getObject(i), out.getObject(i)); } } tempBuf.release(); } }
### Question: ScanOperator implements ProducerOperator { @Override public void workOnOOB(OutOfBandMessage message) { final ArrowBuf msgBuf = message.getBuffer(); final String senderInfo = String.format("Frag %d:%d, OpId %d", message.getSendingMajorFragmentId(), message.getSendingMinorFragmentId(), message.getSendingOperatorId()); if (msgBuf==null || msgBuf.capacity()==0) { logger.warn("Empty runtime filter received from {}", senderInfo); return; } msgBuf.retain(); logger.info("Filter received from {}", senderInfo); try(RollbackCloseable closeOnErr = new RollbackCloseable()) { closeOnErr.add(msgBuf); final BloomFilter bloomFilter = BloomFilter.prepareFrom(msgBuf); final ExecProtos.RuntimeFilter protoFilter = message.getPayload(ExecProtos.RuntimeFilter.parser()); final RuntimeFilter filter = RuntimeFilter.getInstance(protoFilter, bloomFilter, senderInfo); boolean isAlreadyPresent = this.runtimeFilters.stream().anyMatch(r -> r.isOnSameColumns(filter)); if (protoFilter.getPartitionColumnFilter().getSizeBytes() != bloomFilter.getSizeInBytes()) { logger.error("Invalid incoming runtime filter size. Expected size {}, actual size {}, filter {}", protoFilter.getPartitionColumnFilter().getSizeBytes(), bloomFilter.getSizeInBytes(), bloomFilter.toString()); AutoCloseables.close(filter); } else if (isAlreadyPresent) { logger.debug("Skipping enforcement because filter is already present {}", filter); AutoCloseables.close(filter); } else { logger.debug("Adding filter to the record readers {}, current reader {}, FPP {}.", filter, this.currentReader.getClass().getName(), bloomFilter.getExpectedFPP()); this.runtimeFilters.add(filter); this.currentReader.addRuntimeFilter(filter); } closeOnErr.commit(); } catch (Exception e) { logger.warn("Error while merging runtime filter piece from " + message.getSendingMajorFragmentId() + ":" + message.getSendingMinorFragmentId(), e); } } ScanOperator(SubScan config, OperatorContext context, Iterator<RecordReader> readers); ScanOperator(SubScan config, OperatorContext context, Iterator<RecordReader> readers, GlobalDictionaries globalDictionaries, CoordinationProtos.NodeEndpoint foremanEndpoint, CoordExecRPC.QueryContextInformation queryContextInformation); @Override VectorAccessible setup(); @Override State getState(); @Override int outputData(); @Override void workOnOOB(OutOfBandMessage message); @Override OUT accept(OperatorVisitor<OUT, IN, EXCEP> visitor, IN value); @Override void close(); }### Answer: @Test public void testWorkOnOOBRuntimeFilterInvalidFilterSize() { int buildMinorFragment1 = 2; int buildMajorFragment1 = 1; try (ArrowBuf oobMessageBuf = testAllocator.buffer(128)) { RuntimeFilter filter1 = newRuntimeFilter(32, "col1", "col2"); OutOfBandMessage msg1 = newOOBMessage(filter1, oobMessageBuf, buildMajorFragment1, buildMinorFragment1); RecordReader mockReader = mock(RecordReader.class); ScanOperator scanOp = new ScanOperator(mock(SubScan.class), getMockContext(), Lists.newArrayList(mockReader).iterator(), null, null, null); scanOp.workOnOOB(msg1); msg1.getBuffer().release(); verify(mockReader, never()).addRuntimeFilter(any(com.dremio.exec.store.RuntimeFilter.class)); } }
### Question: RpcCompatibilityEncoder extends MessageToMessageEncoder<OutboundRpcMessage> { @Override protected void encode(ChannelHandlerContext context, OutboundRpcMessage message, List<Object> out) throws Exception { if (message.mode != RpcMode.RESPONSE_FAILURE) { out.add(message); return; } final MessageLite pBody = message.pBody; if (!(pBody instanceof DremioPBError)) { out.add(message); return; } DremioPBError error = (DremioPBError) pBody; DremioPBError newError = ErrorCompatibility.convertIfNecessary(error); out.add(new OutboundRpcMessage(message.mode, message.rpcType, message.coordinationId, newError, message.dBodies)); } }### Answer: @Test public void testIgnoreOtherMessages() throws Exception { RpcCompatibilityEncoder encoder = new RpcCompatibilityEncoder(); ChannelHandlerContext context = mock(ChannelHandlerContext.class); OutboundRpcMessage message = new OutboundRpcMessage(RpcMode.PING, 0, 0, Acks.OK); List<Object> out = new ArrayList<>(); encoder.encode(context, message, out); assertEquals(1, out.size()); assertSame(message, out.get(0)); } @Test public void testIgnoreNonDremioPBErrorMessage() throws Exception { RpcCompatibilityEncoder encoder = new RpcCompatibilityEncoder(); ChannelHandlerContext context = mock(ChannelHandlerContext.class); OutboundRpcMessage message = new OutboundRpcMessage(RpcMode.RESPONSE_FAILURE, 0, 0, Acks.OK); List<Object> out = new ArrayList<>(); encoder.encode(context, message, out); assertEquals(1, out.size()); assertSame(message, out.get(0)); } @Test public void testUpdateErrorType() throws Exception { RpcCompatibilityEncoder encoder = new RpcCompatibilityEncoder(); ChannelHandlerContext context = mock(ChannelHandlerContext.class); DremioPBError error = DremioPBError.newBuilder() .setErrorType(ErrorType.IO_EXCEPTION) .setMessage("test message") .build(); OutboundRpcMessage message = new OutboundRpcMessage(RpcMode.RESPONSE_FAILURE, RpcType.RESP_QUERY_PROFILE, 12, error); List<Object> out = new ArrayList<>(); encoder.encode(context, message, out); assertEquals(1, out.size()); OutboundRpcMessage received = (OutboundRpcMessage) out.get(0); assertEquals(RpcMode.RESPONSE_FAILURE, received.mode); assertEquals(12, received.coordinationId); DremioPBError newError = (DremioPBError) received.pBody; assertEquals(ErrorType.RESOURCE, newError.getErrorType()); assertEquals("test message", newError.getMessage()); }
### Question: FragmentTracker implements AutoCloseable { public void populate(List<PlanFragmentFull> fragments, ResourceSchedulingDecisionInfo decisionInfo) { for (PlanFragmentFull fragment : fragments) { final NodeEndpoint assignment = fragment.getMinor().getAssignment(); pendingNodes.add(assignment); } executorSet = executorSetService.getExecutorSet(decisionInfo.getEngineId(), decisionInfo.getSubEngineId()); executorSet.addNodeStatusListener(nodeStatusListener); validateEndpoints(); checkAndNotifyCompletionListener(); } FragmentTracker( QueryId queryId, CompletionListener completionListener, Runnable queryCloser, ExecutorServiceClientFactory executorServiceClientFactory, ExecutorSetService executorSetService ); QueryId getQueryId(); void populate(List<PlanFragmentFull> fragments, ResourceSchedulingDecisionInfo decisionInfo); void nodeMarkFirstError(NodeQueryFirstError firstError); void nodeCompleted(NodeQueryCompletion completion); void screenCompleted(); @Override void close(); }### Answer: @Test public void testEmptyFragmentList() { InOrder inOrder = Mockito.inOrder(completionListener, queryCloser); FragmentTracker fragmentTracker = new FragmentTracker(queryId, completionListener, queryCloser, null, new LocalExecutorSetService(DirectProvider.wrap(coordinator), DirectProvider.wrap(optionManager))); fragmentTracker.populate(Collections.emptyList(), new ResourceSchedulingDecisionInfo()); inOrder.verify(completionListener).succeeded(); inOrder.verify(queryCloser).run(); }
### Question: RexToExpr { public static LogicalExpression toExpr(ParseContext context, RelDataType rowType, RexBuilder rexBuilder, RexNode expr) { return toExpr(context, rowType, rexBuilder, expr, true); } static LogicalExpression toExpr(ParseContext context, RelDataType rowType, RexBuilder rexBuilder, RexNode expr); static LogicalExpression toExpr(ParseContext context, RelDataType rowType, RexBuilder rexBuilder, RexNode expr, boolean throwUserException); static LogicalExpression toExpr(ParseContext context, RelDataType rowType, RexBuilder rexBuilder, RexNode expr, boolean throwUserException, IntFunction<Optional<Integer>> inputFunction); static List<NamedExpression> projectToExpr(ParseContext context, List<Pair<RexNode, String>> projects, RelNode input); static List<NamedExpression> groupSetToExpr(RelNode input, ImmutableBitSet groupSet); static List<NamedExpression> aggsToExpr( RelDataType rowType, RelNode input, ImmutableBitSet groupSet, List<AggregateCall> aggCalls); static boolean isLiteralNull(RexLiteral literal); static final String UNSUPPORTED_REX_NODE_ERROR; }### Answer: @Test public void testUnsupportedRexNode() { try { RelDataTypeFactory relFactory = SqlTypeFactoryImpl.INSTANCE; RexBuilder rex = new DremioRexBuilder(relFactory); RelDataType anyType = relFactory.createSqlType(SqlTypeName.ANY); List<RexNode> emptyList = new LinkedList<>(); ImmutableList<RexFieldCollation> e = ImmutableList.copyOf(new RexFieldCollation[0]); RexNode window = rex.makeOver(anyType, SqlStdOperatorTable.AVG, emptyList, emptyList, e, null, null, true, false, false, false); RexToExpr.toExpr(null, null, null, window); } catch (UserException e) { if (e.getMessage().contains(RexToExpr.UNSUPPORTED_REX_NODE_ERROR)) { return; } Assert.fail("Hit exception with unexpected error message"); } Assert.fail("Failed to raise the expected exception"); }
### Question: EndpointsIndex { public MinorFragmentEndpoint getFragmentEndpoint(MinorFragmentIndexEndpoint ep) { return fragmentsEndpointMap.computeIfAbsent(ep, k -> new MinorFragmentEndpoint(k.getMinorFragmentId(), endpoints.get(k.getEndpointIndex()))); } EndpointsIndex(List<NodeEndpoint> endpoints); EndpointsIndex(); NodeEndpoint getNodeEndpoint(int idx); MinorFragmentEndpoint getFragmentEndpoint(MinorFragmentIndexEndpoint ep); List<MinorFragmentEndpoint> getFragmentEndpoints(List<MinorFragmentIndexEndpoint> eps); }### Answer: @Test public void indexEndpointSingle() { EndpointsIndex.Builder indexBuilder = new EndpointsIndex.Builder(); NodeEndpoint ep = NodeEndpoint.newBuilder() .setAddress("localhost") .setFabricPort(1700) .build(); MinorFragmentEndpoint expected = new MinorFragmentEndpoint(16, ep); MinorFragmentIndexEndpoint indexEndpoint = indexBuilder.addFragmentEndpoint(16, ep); EndpointsIndex index = new EndpointsIndex(indexBuilder.getAllEndpoints()); MinorFragmentEndpoint out = index.getFragmentEndpoint(indexEndpoint); assertEquals(expected, out); }
### Question: MinorDataReader { public ByteString readProtoEntry(OpProps props, String key) throws Exception { return attrsMap.getAttrValue(props, key); } MinorDataReader( FragmentHandle handle, MinorDataSerDe serDe, PlanFragmentsIndex index, MinorAttrsMap attrsMap); FragmentHandle getHandle(); MinorFragmentIndexEndpoint readMinorFragmentIndexEndpoint(OpProps props, String key); List<MinorFragmentIndexEndpoint> readMinorFragmentIndexEndpoints(OpProps props, String key); ByteString readProtoEntry(OpProps props, String key); NormalizedPartitionInfo readSplitPartition(OpProps props, String key); T readJsonEntry(OpProps props, String key, Class<T> clazz); }### Answer: @Test public void multiAttrsInSamePOP() throws Exception { PlanFragmentsIndex.Builder indexBuilder = new PlanFragmentsIndex.Builder(); MinorDataSerDe serDe = new MinorDataSerDe(null, null); MinorDataWriter writer = new MinorDataWriter(null, dummyEndpoint, serDe, indexBuilder); MockStorePOP pop = new MockStorePOP(OpProps.prototype(1), null); List<HBaseSubScanSpec> specList = new ArrayList<>(); for (int i = 0; i < 4; ++i) { HBaseSubScanSpec spec = HBaseSubScanSpec .newBuilder() .setTableName("testTable" + i) .build(); specList.add(spec); writer.writeProtoEntry(pop.getProps(), "testKey" + i, spec); } MinorAttrsMap minorAttrsMap = MinorAttrsMap.create(writer.getAllAttrs()); MinorDataReader reader = new MinorDataReader(null, serDe, null, minorAttrsMap); for (int i = 0; i < 4; ++i) { HBaseSubScanSpec spec = HBaseSubScanSpec.parseFrom(reader.readProtoEntry(pop.getProps(), "testKey" + i)); assertEquals(spec, specList.get(i)); } } @Test public void sameKeyMultiPOPs() throws Exception { PlanFragmentsIndex.Builder indexBuilder = new PlanFragmentsIndex.Builder(); MinorDataSerDe serDe = new MinorDataSerDe(null, null); MinorDataWriter writer = new MinorDataWriter(null, dummyEndpoint, serDe, indexBuilder); MockStorePOP pop1 = new MockStorePOP(OpProps.prototype(1), null); MockStorePOP pop2 = new MockStorePOP(OpProps.prototype(2), null); List<HBaseSubScanSpec> specList = new ArrayList<>(); for (int i = 0; i < 2; ++i) { HBaseSubScanSpec spec = HBaseSubScanSpec .newBuilder() .setTableName("testTable" + i) .build(); specList.add(spec); writer.writeProtoEntry(i == 0 ? pop1.getProps() : pop2.getProps(), "testKey", spec); } MinorAttrsMap minorAttrsMap = MinorAttrsMap.create(writer.getAllAttrs()); MinorDataReader reader = new MinorDataReader(null, serDe, null, minorAttrsMap); HBaseSubScanSpec spec1 = HBaseSubScanSpec.parseFrom(reader.readProtoEntry(pop1.getProps(), "testKey")); assertEquals(spec1, specList.get(0)); HBaseSubScanSpec spec2 = HBaseSubScanSpec.parseFrom(reader.readProtoEntry(pop2.getProps(), "testKey")); assertEquals(spec2, specList.get(1)); }
### Question: MaterializationList implements MaterializationProvider { @VisibleForTesting protected List<DremioMaterialization> build(final MaterializationDescriptorProvider provider) { final Set<String> exclusions = Sets.newHashSet(session.getSubstitutionSettings().getExclusions()); final Set<String> inclusions = Sets.newHashSet(session.getSubstitutionSettings().getInclusions()); final boolean hasInclusions = !inclusions.isEmpty(); final List<DremioMaterialization> materializations = Lists.newArrayList(); for (final MaterializationDescriptor descriptor : provider.get()) { if( (hasInclusions && !inclusions.contains(descriptor.getLayoutId())) || exclusions.contains(descriptor.getLayoutId()) ) { continue; } try { final DremioMaterialization materialization = descriptor.getMaterializationFor(converter); if (materialization == null) { continue; } mapping.put(TablePath.of(descriptor.getPath()), descriptor); materializations.add(materialization); } catch (Throwable e) { logger.warn("failed to expand materialization {}", descriptor.getMaterializationId(), e); } } return materializations; } MaterializationList(final SqlConverter converter, final UserSession session, final MaterializationDescriptorProvider provider); @Override List<DremioMaterialization> getMaterializations(); @Override java.util.Optional<DremioMaterialization> getDefaultRawMaterialization(NamespaceKey path, List<String> vdsFields); Optional<MaterializationDescriptor> getDescriptor(final List<String> path); Optional<MaterializationDescriptor> getDescriptor(final TablePath path); }### Answer: @Test public void testListDiscardsGivenExclusions() { when(excluded.getMaterializationFor(converter)).thenReturn(relOptMat1); when(excluded.getLayoutId()).thenReturn("rid-1"); when(included.getMaterializationFor(converter)).thenReturn(relOptMat2); when(included.getLayoutId()).thenReturn("rid-2"); SubstitutionSettings materializationSettings = new SubstitutionSettings(ImmutableList.of("rid-1")); when(session.getSubstitutionSettings()).thenReturn(materializationSettings); when(provider.get()).thenReturn(ImmutableList.of(excluded, included)); final MaterializationList materializations = new MaterializationList(converter, session, provider); materializations.build(provider); verify(excluded, never()).getMaterializationFor(any(SqlConverter.class)); verify(included, atLeastOnce()).getMaterializationFor(converter); }
### Question: JSONElementLocator { public static JsonPath parsePath(String path) { if (path.startsWith(VALUE_PLACEHOLDER)) { return new JsonPath(path.substring(VALUE_PLACEHOLDER.length())); } throw new IllegalArgumentException(path + " must start with 'value'"); } JSONElementLocator(String text); static JsonPath parsePath(String path); Interval locatePath(JsonPath searchedPath); JsonSelection locate(int selectionStart, int selectionEnd); }### Answer: @Test public void testParseJsonPath() throws Exception { JsonPath p = JSONElementLocator.parsePath("value.a"); assertEquals(p.toString(), 1, p.size()); assertEquals(p.toString(), "a", p.last().asObject().getField()); } @Test public void testParseJsonPath2() throws Exception { JsonPath p = JSONElementLocator.parsePath("value.a.b.c"); assertEquals(p.toString(), 3, p.size()); assertEquals(new JsonPath(new ObjectJsonPathElement("a"), new ObjectJsonPathElement("b"), new ObjectJsonPathElement("c")), p); } @Test public void testParseJsonPath3() throws Exception { JsonPath p = JSONElementLocator.parsePath("value[0][1][2]"); assertEquals(p.toString(), 3, p.size()); assertEquals(new JsonPath(new ArrayJsonPathElement(0), new ArrayJsonPathElement(1), new ArrayJsonPathElement(2)), p); } @Test public void testParseJsonPath4() throws Exception { JsonPath p = JSONElementLocator.parsePath("value[0].a[1]"); assertEquals(p.toString(), 3, p.size()); assertEquals(new JsonPath(new ArrayJsonPathElement(0), new ObjectJsonPathElement("a"), new ArrayJsonPathElement(1)), p); } @Test public void testParseJsonPath5() throws Exception { JsonPath p = JSONElementLocator.parsePath("value.a[0].b"); assertEquals(p.toString(), 3, p.size()); assertEquals(new JsonPath(new ObjectJsonPathElement("a"), new ArrayJsonPathElement(0), new ObjectJsonPathElement("b")), p); }
### Question: MetadataProviderConditions { public static Predicate<String> getTableTypePredicate(List<String> tableTypeFilter) { return tableTypeFilter.isEmpty() ? ALWAYS_TRUE : ImmutableSet.copyOf(tableTypeFilter)::contains; } private MetadataProviderConditions(); static Predicate<String> getTableTypePredicate(List<String> tableTypeFilter); static Predicate<String> getCatalogNamePredicate(LikeFilter filter); static Optional<SearchQuery> createConjunctiveQuery( LikeFilter schemaNameFilter, LikeFilter tableNameFilter ); }### Answer: @Test public void testTableTypesEmptyList() { assertSame(MetadataProviderConditions.ALWAYS_TRUE, MetadataProviderConditions.getTableTypePredicate(Collections.emptyList())); } @Test public void testTableTypes() { Predicate<String> filter = MetadataProviderConditions.getTableTypePredicate(Arrays.asList("foo", "bar")); assertTrue(filter.test("foo")); assertTrue(filter.test("bar")); assertFalse(filter.test("baz")); assertFalse(filter.test("fooo")); assertFalse(filter.test("ofoo")); assertFalse(filter.test("FOO")); }
### Question: MetadataProviderConditions { public static Predicate<String> getCatalogNamePredicate(LikeFilter filter) { if (filter == null || !filter.hasPattern() || SQL_LIKE_ANY_STRING_PATTERN.equals(filter.getPattern())) { return ALWAYS_TRUE; } final String patternString = RegexpUtil.sqlToRegexLike(filter.getPattern(), filter.hasEscape() ? filter.getEscape().charAt(0) : (char) 0); final Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); return input -> pattern.matcher(input).matches(); } private MetadataProviderConditions(); static Predicate<String> getTableTypePredicate(List<String> tableTypeFilter); static Predicate<String> getCatalogNamePredicate(LikeFilter filter); static Optional<SearchQuery> createConjunctiveQuery( LikeFilter schemaNameFilter, LikeFilter tableNameFilter ); }### Answer: @Test public void testLikeFilterAlwaysTrue() { assertSame(MetadataProviderConditions.ALWAYS_TRUE, MetadataProviderConditions.getCatalogNamePredicate(null)); assertSame(MetadataProviderConditions.ALWAYS_TRUE, MetadataProviderConditions.getCatalogNamePredicate(newLikeFilter(null, "\\"))); assertSame(MetadataProviderConditions.ALWAYS_TRUE, MetadataProviderConditions.getCatalogNamePredicate(newLikeFilter("%", "\\"))); } @Test public void testLikeFilter() { Predicate<String> filter = MetadataProviderConditions.getCatalogNamePredicate(newLikeFilter("abc", "\\")); assertTrue(filter.test("abc")); assertFalse(filter.test("abcd")); assertTrue(filter.test("ABC")); } @Test public void testLikeFilterMixedCase() { Predicate<String> filter = MetadataProviderConditions.getCatalogNamePredicate(newLikeFilter("AbC", "\\")); assertTrue(filter.test("abc")); assertFalse(filter.test("abcd")); assertFalse(filter.test("aabc")); assertTrue(filter.test("ABC")); }
### Question: MetadataProviderConditions { public static Optional<SearchQuery> createConjunctiveQuery( LikeFilter schemaNameFilter, LikeFilter tableNameFilter ) { final Optional<SearchQuery> schemaNameQuery = createLikeQuery(DatasetIndexKeys.UNQUOTED_SCHEMA.getIndexFieldName(), schemaNameFilter); final Optional<SearchQuery> tableNameQuery = createLikeQuery(DatasetIndexKeys.UNQUOTED_NAME.getIndexFieldName(), tableNameFilter); if (!schemaNameQuery.isPresent()) { return tableNameQuery; } if (!tableNameQuery.isPresent()) { return schemaNameQuery; } return Optional.of(SearchQuery.newBuilder() .setAnd(SearchQuery.And.newBuilder() .addClauses(schemaNameQuery.get()) .addClauses(tableNameQuery.get())) .build()); } private MetadataProviderConditions(); static Predicate<String> getTableTypePredicate(List<String> tableTypeFilter); static Predicate<String> getCatalogNamePredicate(LikeFilter filter); static Optional<SearchQuery> createConjunctiveQuery( LikeFilter schemaNameFilter, LikeFilter tableNameFilter ); }### Answer: @Test public void testCreateFilterAlwaysTrue() { assertFalse(MetadataProviderConditions.createConjunctiveQuery(null, null).isPresent()); assertFalse(MetadataProviderConditions.createConjunctiveQuery(null, newLikeFilter("%", null)).isPresent()); assertFalse(MetadataProviderConditions.createConjunctiveQuery(newLikeFilter("%", null), null).isPresent()); assertFalse(MetadataProviderConditions.createConjunctiveQuery(newLikeFilter("%", null), newLikeFilter("%", null)) .isPresent()); }
### Question: SQLAnalyzerFactory { public static SQLAnalyzer createSQLAnalyzer(final String username, final SabotContext sabotContext, final List<String> context, final boolean createForSqlSuggestions, ProjectOptionManager projectOptionManager) { final ViewExpansionContext viewExpansionContext = new ViewExpansionContext(username); final OptionManager optionManager = OptionManagerWrapper.Builder.newBuilder() .withOptionManager(new DefaultOptionManager(sabotContext.getOptionValidatorListing())) .withOptionManager(new EagerCachingOptionManager(projectOptionManager)) .withOptionManager(new QueryOptionManager(sabotContext.getOptionValidatorListing())) .build(); final NamespaceKey defaultSchemaPath = context == null ? null : new NamespaceKey(context); final SchemaConfig newSchemaConfig = SchemaConfig.newBuilder(username) .defaultSchema(defaultSchemaPath) .optionManager(optionManager) .setViewExpansionContext(viewExpansionContext) .build(); Catalog catalog = sabotContext.getCatalogService() .getCatalog(MetadataRequestOptions.of(newSchemaConfig)); JavaTypeFactory typeFactory = JavaTypeFactoryImpl.INSTANCE; DremioCatalogReader catalogReader = new DremioCatalogReader(catalog, typeFactory); FunctionImplementationRegistry functionImplementationRegistry = optionManager.getOption (PlannerSettings.ENABLE_DECIMAL_V2_KEY).getBoolVal() ? sabotContext.getDecimalFunctionImplementationRegistry() : sabotContext.getFunctionImplementationRegistry(); OperatorTable opTable = new OperatorTable(functionImplementationRegistry); SqlOperatorTable chainedOpTable = new ChainedSqlOperatorTable(ImmutableList.<SqlOperatorTable>of(opTable, catalogReader)); SqlValidatorWithHints validator = createForSqlSuggestions ? new SqlAdvisorValidator(chainedOpTable, catalogReader, typeFactory, DremioSqlConformance.INSTANCE) : SqlValidatorUtil.newValidator(chainedOpTable, catalogReader, typeFactory, DremioSqlConformance.INSTANCE); return new SQLAnalyzer(validator); } static SQLAnalyzer createSQLAnalyzer(final String username, final SabotContext sabotContext, final List<String> context, final boolean createForSqlSuggestions, ProjectOptionManager projectOptionManager); }### Answer: @Test public void testCreationOfValidator() { SabotContext sabotContext = mock(SabotContext.class); FunctionImplementationRegistry functionImplementationRegistry = mock(FunctionImplementationRegistry.class); CatalogService catalogService = mock(CatalogService.class); Catalog catalog = mock(Catalog.class); ProjectOptionManager mockOptions = mock(ProjectOptionManager.class); when(mockOptions.getOptionValidatorListing()).thenReturn(mock(OptionValidatorListing.class)); when(sabotContext.getFunctionImplementationRegistry()).thenReturn(functionImplementationRegistry); when(sabotContext.getCatalogService()).thenReturn(catalogService); when(sabotContext.getCatalogService().getCatalog(any(MetadataRequestOptions.class))).thenReturn(catalog); OptionValue value1 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, PlannerSettings.ENABLE_DECIMAL_V2_KEY, false); OptionValue value2 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, UserSession.MAX_METADATA_COUNT.getOptionName(), 0); OptionList optionList = new OptionList(); optionList.add(value1); optionList.add(value2); when(mockOptions.getOption(PlannerSettings.ENABLE_DECIMAL_V2_KEY)).thenReturn(value1); when(mockOptions.getOption(UserSession.MAX_METADATA_COUNT.getOptionName())).thenReturn(value2); when(mockOptions.getNonDefaultOptions()).thenReturn(optionList); SQLAnalyzer sqlAnalyzer = SQLAnalyzerFactory.createSQLAnalyzer(SystemUser.SYSTEM_USERNAME, sabotContext, null, true, mockOptions); SqlValidatorWithHints validator = sqlAnalyzer.validator; assertTrue(validator instanceof SqlAdvisorValidator); sqlAnalyzer = SQLAnalyzerFactory.createSQLAnalyzer(SystemUser.SYSTEM_USERNAME, sabotContext, null, false, mockOptions); validator = sqlAnalyzer.validator; assertTrue(validator instanceof SqlValidatorImpl); }
### Question: SqlConverter { @VisibleForTesting static SqlNode parseSingleStatementImpl(String sql, ParserConfig parserConfig, boolean isInnerQuery) { SqlNodeList list = parseMultipleStatementsImpl(sql, parserConfig, isInnerQuery); if (list.size() > 1) { SqlParserPos pos = list.get(1).getParserPosition(); int col = pos.getColumnNum(); String first = sql.substring(0, col); String second = sql.substring(col-1); UserException.Builder builder = UserException.parseError(); builder.message("Unable to parse multiple queries. First query is %s. Rest of submission is %s", first, second); throw builder.buildSilently(); } SqlNode newNode = list.get(0).accept(STRING_LITERAL_CONVERTER); return newNode; } SqlConverter( final PlannerSettings settings, final SqlOperatorTable operatorTable, final FunctionContext functionContext, final MaterializationDescriptorProvider materializationProvider, final FunctionImplementationRegistry functions, final UserSession session, final AttemptObserver observer, final Catalog catalog, final SubstitutionProviderFactory factory, final SabotConfig config, final ScanResult scanResult ); SqlConverter(SqlConverter parent, DremioCatalogReader catalog); SqlNodeList parseMultipleStatements(String sql); SqlNode parse(String sql); ViewExpansionContext getViewExpansionContext(); UserSession getSession(); SqlNode validate(final SqlNode parsedNode); RelDataType getValidatedRowType(String sql); FunctionImplementationRegistry getFunctionImplementationRegistry(); PlannerSettings getSettings(); RelDataType getOutputType(SqlNode validatedNode); JavaTypeFactory getTypeFactory(); SqlOperatorTable getOpTab(); RelOptCostFactory getCostFactory(); FunctionContext getFunctionContext(); DremioCatalogReader getCatalogReader(); SqlParser.Config getParserConfig(); AttemptObserver getObserver(); MaterializationList getMaterializations(); int getNestingLevel(); RelOptCluster getCluster(); AccelerationAwareSubstitutionProvider getSubstitutionProvider(); RelSerializerFactory getSerializerFactory(); SabotConfig getConfig(); RelRootPlus toConvertibleRelRoot(final SqlNode validatedNode, boolean expand, boolean flatten); static final SqlShuttle STRING_LITERAL_CONVERTER; }### Answer: @Test(expected = UserException.class) public void testFailMultipleQueries() { ParserConfig config = new ParserConfig(ParserConfig.QUOTING, 100); SqlConverter.parseSingleStatementImpl("select * from t1; select * from t2", config, false); } @Test public void testPassSemicolon() { ParserConfig config = new ParserConfig(ParserConfig.QUOTING, 100); SqlNode node = SqlConverter.parseSingleStatementImpl("select * from t1;", config, false); assertEquals("SELECT *\n" + "FROM \"t1\"", node.toSqlString(CalciteSqlDialect.DEFAULT).getSql()); }
### Question: SQLAnalyzer { public List<SqlMoniker> suggest(String sql, int cursorPosition) { SqlAdvisor sqlAdvisor = new SqlAdvisor(validator); String[] replaced = {null}; return sqlAdvisor.getCompletionHints(sql, cursorPosition , replaced); } protected SQLAnalyzer(final SqlValidatorWithHints validator); List<SqlMoniker> suggest(String sql, int cursorPosition); List<SqlAdvisor.ValidateErrorInfo> validate(String sql); }### Answer: @Test public void testSuggestion() { final SqlParserUtil.StringAndPos stringAndPos = SqlParserUtil.findPos(sql); List<SqlMoniker> suggestions = sqlAnalyzer.suggest(stringAndPos.sql, stringAndPos.cursor); assertEquals(expectedSuggestionCount, suggestions.size()); if (checkSuggestions) { assertSuggestions(suggestions); } }
### Question: SQLAnalyzer { public List<SqlAdvisor.ValidateErrorInfo> validate(String sql) { SqlAdvisor sqlAdvisor = new SqlAdvisor(validator); return sqlAdvisor.validate(sql); } protected SQLAnalyzer(final SqlValidatorWithHints validator); List<SqlMoniker> suggest(String sql, int cursorPosition); List<SqlAdvisor.ValidateErrorInfo> validate(String sql); }### Answer: @Test public void testValidation() { List<SqlAdvisor.ValidateErrorInfo> validationErrors = sqlAnalyzer.validate("select * from"); assertEquals(1, validationErrors.size()); assertEquals(10, validationErrors.get(0).getStartColumnNum()); assertEquals(13, validationErrors.get(0).getEndColumnNum()); }
### Question: SimpleLimitExchangeRemover { public static Prel apply(PlannerSettings settings, Prel input){ if(!settings.isTrivialSingularOptimized() || settings.isLeafLimitsEnabled()) { return input; } if(input.accept(new Identifier(), false)){ return input.accept(new AllExchangeRemover(), null); } return input; } static Prel apply(PlannerSettings settings, Prel input); }### Answer: @Test public void simpleSelectNoLimit() { Prel input = newScreen( newProject(exprs(), rowType(), newUnionExchange( newProject(exprs(), rowType(), newSoftScan(rowType()) ) ) ) ); Prel output = SimpleLimitExchangeRemover.apply(plannerSettings, input); verifyOutput(output, "Screen", "Project", "UnionExchange", "Project", "SystemScan"); } @Test public void simpleSelectWithLimitWithSoftScan() { Prel input = newScreen( newLimit(0, 10, newProject(exprs(), rowType(), newUnionExchange( newLimit(0, 10, newProject(exprs(), rowType(), newSoftScan(rowType()) ) ) ) ) ) ); Prel output = SimpleLimitExchangeRemover.apply(plannerSettings, input); verifyOutput(output, "Screen", "Limit", "Project", "Limit", "Project", "SystemScan"); } @Test public void simpleSelectWithLimitWithSoftScanWithLeafLimitsEnabled() { OptionValue optionEnabled = OptionValue.createBoolean(OptionValue.OptionType.QUERY, PlannerSettings.ENABLE_LEAF_LIMITS.getOptionName(), true); when(optionManager.getOption(PlannerSettings.ENABLE_LEAF_LIMITS.getOptionName())).thenReturn(optionEnabled); optionList.remove(PlannerSettings.ENABLE_LEAF_LIMITS.getDefault()); optionList.add(optionEnabled); Prel input = newScreen( newLimit(0, 10, newProject(exprs(), rowType(), newUnionExchange( newLimit(0, 10, newProject(exprs(), rowType(), newSoftScan(rowType()) ) ) ) ) ) ); Prel output = SimpleLimitExchangeRemover.apply(plannerSettings, input); verifyOutput(output, "Screen", "Limit", "Project", "UnionExchange", "Limit", "Project", "SystemScan"); } @Test public void simpleSelectWithLargeLimitWithSoftScan() { Prel input = newScreen( newLimit(0, 200000, newProject(exprs(), rowType(), newUnionExchange( newLimit(0, 200000, newProject(exprs(), rowType(), newSoftScan(rowType()) ) ) ) ) ) ); Prel output = SimpleLimitExchangeRemover.apply(plannerSettings, input); verifyOutput(output, "Screen", "Limit", "Project", "UnionExchange", "Limit", "Project", "SystemScan"); } @Test public void simpleSelectWithLimitWithHardScan() { Prel input = newScreen( newLimit(0, 10, newProject(exprs(), rowType(), newUnionExchange( newLimit(0, 10, newProject(exprs(), rowType(), newHardScan(rowType()) ) ) ) ) ) ); Prel output = SimpleLimitExchangeRemover.apply(plannerSettings, input); verifyOutput(output, "Screen", "Limit", "Project", "UnionExchange", "Limit", "Project", "SystemScan"); } @Test public void joinWithLimitWithSoftScan() { Prel input = newScreen( newLimit(0, 10, newProject(exprs(), rowType(), newUnionExchange( newJoin( newProject(exprs(), rowType(), newSoftScan(rowType()) ), newProject(exprs(), rowType(), newSoftScan(rowType()) ) ) ) ) ) ); Prel output = SimpleLimitExchangeRemover.apply(plannerSettings, input); verifyOutput(output, "Screen", "Limit", "Project", "UnionExchange", "HashJoin", "Project", "SystemScan", "Project", "SystemScan"); }
### Question: PushLimitToPruneableScan extends Prule { @Override public boolean matches(RelOptRuleCall call) { return !((ScanPrelBase) call.rel(1)).hasFilter() && call.rel(1) instanceof PruneableScan; } private PushLimitToPruneableScan(); @Override boolean matches(RelOptRuleCall call); @Override void onMatch(RelOptRuleCall call); static final RelOptRule INSTANCE; }### Answer: @Test public void testRuleNoMatch() throws Exception { final TestScanPrel scan = new TestScanPrel(cluster, TRAITS, table, pluginId, metadata, PROJECTED_COLUMNS, 0, true); final LimitPrel limitNode = new LimitPrel(cluster, TRAITS, scan, REX_BUILDER.makeExactLiteral(BigDecimal.valueOf(offset)), REX_BUILDER.makeExactLiteral(BigDecimal.valueOf(fetch))); final RelOptRuleCall call = newCall(rel -> fail("Unexpected call to transformTo"), limitNode, scan); assertFalse(PushLimitToPruneableScan.INSTANCE.matches(call)); }
### Question: KeyFairSliceCalculator { public int getTotalSize() { return totalSize; } KeyFairSliceCalculator(Map<String, Integer> originalKeySizes, int maxTotalSize); Integer getKeySlice(String key); int getTotalSize(); boolean keysTrimmed(); int numValidityBytes(); }### Answer: @Test public void testUnderflowSize() { KeyFairSliceCalculator keyFairSliceCalculator = new KeyFairSliceCalculator(newHashMap("k1", 4, "k2", 4, "k3", 4), 16); assertEquals("Invalid combined key size", 13, keyFairSliceCalculator.getTotalSize()); }
### Question: GlobalDictionaryBuilder { public static String dictionaryFileName(String columnFullPath) { return format("_%s.%s", columnFullPath, DICTIONARY_FILES_EXTENSION); } static String dictionaryFileName(String columnFullPath); static String dictionaryFileName(ColumnDescriptor columnDescriptor); static Path dictionaryFilePath(Path dictionaryRootDir, String columnFullPath); static Path dictionaryFilePath(Path dictionaryRootDir, ColumnDescriptor columnDescriptor); static String getColumnFullPath(String dictionaryFileName); static long getDictionaryVersion(FileSystem fs, Path tableDir); static String dictionaryRootDirName(long version); static Path getDictionaryVersionedRootPath(FileSystem fs, Path tableDir, long version); static Path createDictionaryVersionedRootPath(FileSystem fs, Path tableDir, long nextVersion, Path tmpDictionaryRootPath); static Path getDictionaryFile(FileSystem fs, Path dictRootDir, String columnFullPath); static Path getDictionaryFile(FileSystem fs, Path dictRootDir, ColumnDescriptor columnDescriptor); static Map<String, Path> listDictionaryFiles(FileSystem fs, Path dictRootDir); static VectorContainer readDictionary(FileSystem fs, Path dictionaryRootDir, String columnFullPath, BufferAllocator bufferAllocator); static VectorContainer readDictionary(FileSystem fs, Path dictionaryRootDir, ColumnDescriptor columnDescriptor, BufferAllocator bufferAllocator); static VectorContainer readDictionary(FileSystem fs, Path dictionaryFile, BufferAllocator bufferAllocator); static GlobalDictionariesInfo updateGlobalDictionaries(CompressionCodecFactory codecFactory, FileSystem fs, Path tableDir, Path partitionDir, BufferAllocator bufferAllocator); static GlobalDictionariesInfo createGlobalDictionaries(CompressionCodecFactory codecFactory, FileSystem fs, Path tableDir, BufferAllocator bufferAllocator); static void writeDictionary(OutputStream out, VectorAccessible input, int recordCount, BufferAllocator bufferAllocator); static void main(String []args); static final String DICTIONARY_TEMP_ROOT_PREFIX; static final String DICTIONARY_ROOT_PREFIX; static final Pattern DICTIONARY_VERSION_PATTERN; static final Predicate<Path> DICTIONARY_ROOT_FILTER; static final String DICTIONARY_FILES_EXTENSION; static final Predicate<Path> DICTIONARY_FILES_FILTER; static final Pattern DICTIONARY_FILES_PATTERN; }### Answer: @Test public void testDictionaryFileName() throws Exception { assertEquals("_foo.dict", GlobalDictionaryBuilder.dictionaryFileName("foo")); assertEquals("_a.b.c.dict", GlobalDictionaryBuilder.dictionaryFileName("a.b.c")); assertEquals("_foo.dict", GlobalDictionaryBuilder.dictionaryFileName(new ColumnDescriptor(new String[]{"foo"}, INT64, 0, 1))); assertEquals("_a.b.c.dict", GlobalDictionaryBuilder.dictionaryFileName(new ColumnDescriptor(new String[]{"a", "b", "c"}, INT64, 0, 1))); }
### Question: GlobalDictionaryBuilder { public static String getColumnFullPath(String dictionaryFileName) { final Matcher matcher = DICTIONARY_FILES_PATTERN.matcher(dictionaryFileName); if (matcher.find()) { return matcher.group(1); } return null; } static String dictionaryFileName(String columnFullPath); static String dictionaryFileName(ColumnDescriptor columnDescriptor); static Path dictionaryFilePath(Path dictionaryRootDir, String columnFullPath); static Path dictionaryFilePath(Path dictionaryRootDir, ColumnDescriptor columnDescriptor); static String getColumnFullPath(String dictionaryFileName); static long getDictionaryVersion(FileSystem fs, Path tableDir); static String dictionaryRootDirName(long version); static Path getDictionaryVersionedRootPath(FileSystem fs, Path tableDir, long version); static Path createDictionaryVersionedRootPath(FileSystem fs, Path tableDir, long nextVersion, Path tmpDictionaryRootPath); static Path getDictionaryFile(FileSystem fs, Path dictRootDir, String columnFullPath); static Path getDictionaryFile(FileSystem fs, Path dictRootDir, ColumnDescriptor columnDescriptor); static Map<String, Path> listDictionaryFiles(FileSystem fs, Path dictRootDir); static VectorContainer readDictionary(FileSystem fs, Path dictionaryRootDir, String columnFullPath, BufferAllocator bufferAllocator); static VectorContainer readDictionary(FileSystem fs, Path dictionaryRootDir, ColumnDescriptor columnDescriptor, BufferAllocator bufferAllocator); static VectorContainer readDictionary(FileSystem fs, Path dictionaryFile, BufferAllocator bufferAllocator); static GlobalDictionariesInfo updateGlobalDictionaries(CompressionCodecFactory codecFactory, FileSystem fs, Path tableDir, Path partitionDir, BufferAllocator bufferAllocator); static GlobalDictionariesInfo createGlobalDictionaries(CompressionCodecFactory codecFactory, FileSystem fs, Path tableDir, BufferAllocator bufferAllocator); static void writeDictionary(OutputStream out, VectorAccessible input, int recordCount, BufferAllocator bufferAllocator); static void main(String []args); static final String DICTIONARY_TEMP_ROOT_PREFIX; static final String DICTIONARY_ROOT_PREFIX; static final Pattern DICTIONARY_VERSION_PATTERN; static final Predicate<Path> DICTIONARY_ROOT_FILTER; static final String DICTIONARY_FILES_EXTENSION; static final Predicate<Path> DICTIONARY_FILES_FILTER; static final Pattern DICTIONARY_FILES_PATTERN; }### Answer: @Test public void testExtractColumnName() throws Exception { assertEquals("foo", GlobalDictionaryBuilder.getColumnFullPath("_foo.dict")); assertEquals("a.b.c", GlobalDictionaryBuilder.getColumnFullPath("_a.b.c.dict")); }
### Question: RuntimeFilterProbeTarget { public static List<RuntimeFilterProbeTarget> getProbeTargets(RuntimeFilterInfo runtimeFilterInfo) { final List<RuntimeFilterProbeTarget> targets = new ArrayList<>(); try { if (runtimeFilterInfo==null) { return targets; } for (RuntimeFilterEntry entry : runtimeFilterInfo.getPartitionJoinColumns()) { RuntimeFilterProbeTarget probeTarget = findOrCreateNew(targets, entry); probeTarget.addPartitionKey(entry.getBuildFieldName(), entry.getProbeFieldName()); } for (RuntimeFilterEntry entry : runtimeFilterInfo.getNonPartitionJoinColumns()) { RuntimeFilterProbeTarget probeTarget = findOrCreateNew(targets, entry); probeTarget.addNonPartitionKey(entry.getBuildFieldName(), entry.getProbeFieldName()); } } catch (RuntimeException e) { logger.error("Error while establishing probe scan targets from RuntimeFilterInfo", e); } return targets; } RuntimeFilterProbeTarget(int probeScanMajorFragmentId, int probeScanOperatorId); boolean isSameProbeCoordinate(int majorFragmentId, int operatorId); List<String> getPartitionBuildTableKeys(); List<String> getPartitionProbeTableKeys(); List<String> getNonPartitionBuildTableKeys(); List<String> getNonPartitionProbeTableKeys(); int getProbeScanMajorFragmentId(); int getProbeScanOperatorId(); @Override String toString(); String toTargetIdString(); static List<RuntimeFilterProbeTarget> getProbeTargets(RuntimeFilterInfo runtimeFilterInfo); }### Answer: @Test public void testNullRuntimeFilterInfoObj() { List<RuntimeFilterProbeTarget> probeTargets = RuntimeFilterProbeTarget.getProbeTargets(null); assertTrue(probeTargets.isEmpty()); }
### Question: BloomFilter implements AutoCloseable { public void setup() { checkNotNull(this.allocator, "Setup not required for deserialized objects."); this.dataBuffer = this.allocator.buffer(this.sizeInBytes + META_BYTES_CNT); setup(dataBuffer); dataBuffer.writerIndex(0); for (int i = 0; i < sizeInBytes; i += 8) { dataBuffer.writeLong(0l); } byte[] metaBytes = new byte[24]; byte[] nameBytesAll = name.getBytes(StandardCharsets.UTF_8); System.arraycopy(name.getBytes(StandardCharsets.UTF_8), Math.max(0, nameBytesAll.length - 24), metaBytes, 0, Math.min(24, nameBytesAll.length)); this.name = new String(metaBytes, StandardCharsets.UTF_8); this.dataBuffer.writeBytes(metaBytes); this.dataBuffer.writeLong(0L); this.dataBuffer.readerIndex(0); this.numBitsSetLoc = dataBuffer.memoryAddress() + sizeInBytes + META_BYTES_CNT - 8; logger.debug("Bloomfilter {} set up completed.", this.name); } BloomFilter(BufferAllocator bufferAllocator, String name, long minSizeBytes); private BloomFilter(ArrowBuf dataBuffer); void setup(); String getName(); long getSizeInBytes(); static BloomFilter prepareFrom(ArrowBuf dataBuffer); ArrowBuf getDataBuffer(); boolean mightContain(ArrowBuf bloomFilterKey, int length); boolean put(ArrowBuf bloomFilterKey, int length); double getExpectedFPP(); boolean isCrossingMaxFPP(); long getOptimalInsertions(); static long getOptimalSize(long expectedInsertions); void merge(BloomFilter that); @VisibleForTesting long getNumBitsSet(); @Override String toString(); @Override void close(); }### Answer: @Test public void testSetup() { try (final BloomFilter bloomFilter = new BloomFilter(bfTestAllocator, TEST_NAME, 40)) { bloomFilter.setup(); assertEquals(bloomFilter.getDataBuffer().capacity(), bloomFilter.getSizeInBytes()); String expectedName = TEST_NAME.substring(TEST_NAME.length() - 24); assertEquals("BoomFilter.getName() is incorrect", expectedName, bloomFilter.getName()); byte[] nameBytes = new byte[24]; bloomFilter.getDataBuffer().getBytes(bloomFilter.getSizeInBytes() - 32, nameBytes); assertEquals("Name in meta bytes not set correctly.", expectedName, new String(nameBytes, StandardCharsets.UTF_8)); assertEquals("Reader index not set correctly", 0, bloomFilter.getDataBuffer().readerIndex()); assertEquals("Writer index not set correctly", bloomFilter.getSizeInBytes(), bloomFilter.getDataBuffer().writerIndex()); for (long i = 0; i < bloomFilter.getSizeInBytes() - 32; i += 8) { long block = bloomFilter.getDataBuffer().getLong(i); assertEquals("Found unclean buffer state", 0L, block); } } }
### Question: BloomFilter implements AutoCloseable { public boolean isCrossingMaxFPP() { return getExpectedFPP() > (5 * FPP); } BloomFilter(BufferAllocator bufferAllocator, String name, long minSizeBytes); private BloomFilter(ArrowBuf dataBuffer); void setup(); String getName(); long getSizeInBytes(); static BloomFilter prepareFrom(ArrowBuf dataBuffer); ArrowBuf getDataBuffer(); boolean mightContain(ArrowBuf bloomFilterKey, int length); boolean put(ArrowBuf bloomFilterKey, int length); double getExpectedFPP(); boolean isCrossingMaxFPP(); long getOptimalInsertions(); static long getOptimalSize(long expectedInsertions); void merge(BloomFilter that); @VisibleForTesting long getNumBitsSet(); @Override String toString(); @Override void close(); }### Answer: @Test public void testIsCrossingMaxFpp() { try (final BloomFilter bloomFilter = new BloomFilter(bfTestAllocator, TEST_NAME, 64); final ArrowBuf keyBuf = bfTestAllocator.buffer(36)) { bloomFilter.setup(); for (int i = 0; i < 1_000_000; i++) { bloomFilter.put(writeKey(keyBuf, UUID.randomUUID().toString()), 36); if (bloomFilter.getExpectedFPP() > 0.05) { break; } } assertTrue(bloomFilter.isCrossingMaxFPP()); } }
### Question: BloomFilter implements AutoCloseable { public static long getOptimalSize(long expectedInsertions) { checkArgument(expectedInsertions > 0); long optimalSize = (long) (-expectedInsertions * Math.log(FPP) / (Math.log(2) * Math.log(2))) / 8; optimalSize = ((optimalSize + 8) / 8) * 8; return optimalSize + META_BYTES_CNT; } BloomFilter(BufferAllocator bufferAllocator, String name, long minSizeBytes); private BloomFilter(ArrowBuf dataBuffer); void setup(); String getName(); long getSizeInBytes(); static BloomFilter prepareFrom(ArrowBuf dataBuffer); ArrowBuf getDataBuffer(); boolean mightContain(ArrowBuf bloomFilterKey, int length); boolean put(ArrowBuf bloomFilterKey, int length); double getExpectedFPP(); boolean isCrossingMaxFPP(); long getOptimalInsertions(); static long getOptimalSize(long expectedInsertions); void merge(BloomFilter that); @VisibleForTesting long getNumBitsSet(); @Override String toString(); @Override void close(); }### Answer: @Test public void testGetOptimalSize() { assertEquals(40, BloomFilter.getOptimalSize(1)); assertEquals(40, BloomFilter.getOptimalSize(4)); assertEquals(152, BloomFilter.getOptimalSize(100)); assertEquals(1_232, BloomFilter.getOptimalSize(1_000)); assertEquals(1_198_168, BloomFilter.getOptimalSize(1_000_000)); assertEquals(1_198_132_336, BloomFilter.getOptimalSize(1_000_000_000)); }
### Question: BloomFilter implements AutoCloseable { @Override public void close() { logger.debug("Closing bloomfilter {}'s data buffer. RefCount {}", this.name, dataBuffer.refCnt()); try { dataBuffer.close(); } catch (Exception e) { logger.error("Error while closing bloomfilter " + this.name, e); } } BloomFilter(BufferAllocator bufferAllocator, String name, long minSizeBytes); private BloomFilter(ArrowBuf dataBuffer); void setup(); String getName(); long getSizeInBytes(); static BloomFilter prepareFrom(ArrowBuf dataBuffer); ArrowBuf getDataBuffer(); boolean mightContain(ArrowBuf bloomFilterKey, int length); boolean put(ArrowBuf bloomFilterKey, int length); double getExpectedFPP(); boolean isCrossingMaxFPP(); long getOptimalInsertions(); static long getOptimalSize(long expectedInsertions); void merge(BloomFilter that); @VisibleForTesting long getNumBitsSet(); @Override String toString(); @Override void close(); }### Answer: @Test public void testClose() { try (final BloomFilter f1 = new BloomFilter(bfTestAllocator, TEST_NAME, 64)) { f1.setup(); f1.getDataBuffer().retain(); assertEquals(2, f1.getDataBuffer().refCnt()); f1.close(); assertEquals(1, f1.getDataBuffer().refCnt()); } }
### Question: StringFunctionUtil { public static int copyUtf8(ByteBuf in, final int start, final int end, ArrowBuf out) { int i = 0; int errBytes = 0; while (start + i < end) { byte b = in.getByte(start + i); if (b >= 0) { out.setByte(i - errBytes, b); i++; continue; } int seqLen = utf8CharLenNoThrow(in, start + i); if (seqLen == 0 || (start + i + seqLen) > end || !GuavaUtf8.isUtf8(in, start + i, start + i + seqLen)) { errBytes++; i++; } else { for (int j = i; j < i + seqLen; j++) { out.setByte(j - errBytes, in.getByte(start + j)); } i += seqLen; } } return end - start - errBytes; } static int getUTF8CharLength(ByteBuf buffer, int start, int end, final FunctionErrorContext errCtx); static int getUTF8CharPosition(ByteBuf buffer, int start, int end, int charLength, final FunctionErrorContext errCtx); static Pattern compilePattern(String regex, FunctionErrorContext errCtx); static Pattern compilePattern(String regex, int flags, FunctionErrorContext errCtx); static int stringLeftMatchUTF8(ByteBuf str, int strStart, int strEnd, ByteBuf substr, int subStart, int subEnd); static int stringLeftMatchUTF8(ByteBuf str, int strStart, int strEnd, ByteBuf substr, int subStart, int subEnd, int offset); static int parseBinaryStringNoFormat(ByteBuf str, int strStart, int strEnd, ByteBuf out, FunctionErrorContext errCtx); static int utf8CharLen(ByteBuf buffer, int idx, final FunctionErrorContext errCtx); static int copyUtf8(ByteBuf in, final int start, final int end, ArrowBuf out); static int copyReplaceUtf8(ByteBuf in, final int start, final int end, ByteBuf out, byte replacement); }### Answer: @Test public void testCopyUtf8() throws Exception { testCopyUtf8Helper(new byte[] {'g', 'o', 'o', 'd', 'v', 'a', 'l'}, "goodval"); testCopyUtf8Helper(new byte[] {'b', 'a', 'd', (byte)0xff, 'v', 'a', 'l'}, "badval"); testCopyUtf8Helper(new byte[] {(byte)0xf9, 'g', 'o', 'o', 'd', ' ', 'p', 'a', 'r', 't'}, "good part"); testCopyUtf8Helper(new byte[] {'t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'o', 'k', (byte)0xfe}, "this is ok"); testCopyUtf8Helper(new byte[] {'f', 'a', 'k', 'e', ' ', (byte) 0xC0, '2', 'B', ' ', 's', 'e', 'q', }, "fake 2B seq"); }
### Question: StringFunctionUtil { public static int copyReplaceUtf8(ByteBuf in, final int start, final int end, ByteBuf out, byte replacement) { int i = 0; while (start + i < end) { byte b = in.getByte(start + i); if (b >= 0) { out.setByte(i, b); i++; continue; } int seqLen = utf8CharLenNoThrow(in, start + i); if (seqLen == 0 || (start + i + seqLen) > end || !GuavaUtf8.isUtf8(in, start + i, start + i + seqLen)) { out.setByte(i, replacement); i++; } else { for (int j = i; j < i + seqLen; j++) { out.setByte(j, in.getByte(start + j)); } i += seqLen; } } return end - start; } static int getUTF8CharLength(ByteBuf buffer, int start, int end, final FunctionErrorContext errCtx); static int getUTF8CharPosition(ByteBuf buffer, int start, int end, int charLength, final FunctionErrorContext errCtx); static Pattern compilePattern(String regex, FunctionErrorContext errCtx); static Pattern compilePattern(String regex, int flags, FunctionErrorContext errCtx); static int stringLeftMatchUTF8(ByteBuf str, int strStart, int strEnd, ByteBuf substr, int subStart, int subEnd); static int stringLeftMatchUTF8(ByteBuf str, int strStart, int strEnd, ByteBuf substr, int subStart, int subEnd, int offset); static int parseBinaryStringNoFormat(ByteBuf str, int strStart, int strEnd, ByteBuf out, FunctionErrorContext errCtx); static int utf8CharLen(ByteBuf buffer, int idx, final FunctionErrorContext errCtx); static int copyUtf8(ByteBuf in, final int start, final int end, ArrowBuf out); static int copyReplaceUtf8(ByteBuf in, final int start, final int end, ByteBuf out, byte replacement); }### Answer: @Test public void testCopyReplaceUtf8() throws Exception { testReplaceUtf8Helper(new byte[] {'g', 'o', 'o', 'd', 'v', 'a', 'l'}, (byte)'?', "goodval"); testReplaceUtf8Helper(new byte[] {'b', 'a', 'd', (byte)0xff, 'v', 'a', 'l'}, (byte)'?', "bad?val"); testReplaceUtf8Helper(new byte[] {(byte)0xf9, 'g', 'o', 'o', 'd', ' ', 'p', 'a', 'r', 't'}, (byte)'X', "Xgood part"); testReplaceUtf8Helper(new byte[] {'t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'o', 'k', (byte)0xfe}, (byte)'|', "this is ok|"); testReplaceUtf8Helper(new byte[] {'f', 'a', 'k', 'e', ' ', (byte) 0xC0, '2', 'B', ' ', 's', 'e', 'q', }, (byte)'?', "fake ?2B seq"); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setInteger(int position, Integer value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testIntSpec() throws Exception{ String columnName = "i"; Integer expectedValue = 12322; PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setInteger(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, Integer.class, expectedValue); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setString(int position, String value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testStringSpec() throws Exception{ String columnName = "data"; String expectedValue = "abc"; PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setString(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, String.class, expectedValue); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setLong(int position, Long value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testLongSpec() throws Exception{ String columnName = "id"; Long expectedValue = 123L; PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setLong(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, Long.class, expectedValue); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setBigDecimal(int position, BigDecimal value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testBigDecimalpec() throws Exception{ String columnName = "dec_9_0"; BigDecimal expectedValue = new BigDecimal(234); PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setBigDecimal(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, BigDecimal.class, expectedValue); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setFloat(int position, Float value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testFloatSpec() throws Exception{ String columnName = "f"; Float expectedValue = 1.23f; PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setFloat(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, Float.class, expectedValue); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setDouble(int position, Double value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testDoubleSpec() throws Exception{ String columnName = "d"; Double expectedValue = Double.valueOf(1.23f); PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setDouble(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, Double.class, expectedValue); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setBoolean(int position, Boolean value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testBooleanSpec() throws Exception{ String columnName = "b"; Boolean expectedValue = true; PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setBoolean(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, Boolean.class, expectedValue); }
### Question: IcebergPartitionData implements StructLike, Serializable { public void setBytes(int position, byte[] value) { set(position, value); } IcebergPartitionData(Types.StructType partitionType); private IcebergPartitionData(IcebergPartitionData toCopy); Type getType(int pos); void clear(); @Override int size(); @Override @SuppressWarnings("unchecked") T get(int pos, Class<T> javaClass); Object get(int pos); @Override void set(int pos, T value); @Override String toString(); IcebergPartitionData copy(); @Override boolean equals(Object o); @Override int hashCode(); static Object[] copyData(Types.StructType type, Object[] data); void setInteger(int position, Integer value); void setLong(int position, Long value); void setFloat(int position, Float value); void setDouble(int position, Double value); void setBoolean(int position, Boolean value); void setString(int position, String value); void setBytes(int position, byte[] value); void setBigDecimal(int position, BigDecimal value); void set(int position, CompleteType type, ValueVector vector, int offset); }### Answer: @Test public void testBinarySpec() throws Exception{ String columnName = "bytes"; byte[] expectedValue = "test".getBytes(); PartitionSpec partitionSpec = PartitionSpec .builderFor(schema) .identity(columnName) .build(); IcebergPartitionData icebergPartitionData = new IcebergPartitionData(partitionSpec.partitionType()); icebergPartitionData.setBytes(0, expectedValue); verifyPartitionValue(partitionSpec, icebergPartitionData, columnName, ByteBuffer.class, expectedValue); }
### Question: IcebergFormatMatcher extends FormatMatcher { @Override public boolean matches(FileSystem fs, FileSelection fileSelection, CompressionCodecFactory codecFactory) throws IOException { Path rootDir = Path.of(fileSelection.getSelectionRoot()); Path metaDir = rootDir.resolve(METADATA_DIR_NAME); if (!fs.isDirectory(rootDir) || !fs.exists(metaDir) || !fs.isDirectory(metaDir)) { return false; } Path versionHintPath = metaDir.resolve(VERSION_HINT_FILE_NAME); if (!fs.exists(versionHintPath) || !fs.isFile(versionHintPath)) { return false; } for (FileAttributes file : fs.list(metaDir)) { if (METADATA_FILE_PATTERN.matcher(file.getPath().getName()).matches()) { return true; } } return false; } IcebergFormatMatcher(FormatPlugin plugin); @Override FormatPlugin getFormatPlugin(); @Override boolean matches(FileSystem fs, FileSelection fileSelection, CompressionCodecFactory codecFactory); static final String METADATA_DIR_NAME; }### Answer: @Test public void match() throws Exception { IcebergFormatMatcher matcher = new IcebergFormatMatcher(null); FileSystem fs = HadoopFileSystem.getLocal(new Configuration()); File root = tempDir.newFolder(); FileSelection fileSelection = FileSelection.create(fs, Path.of(root.toURI())); boolean matched; assertFalse(matcher.matches(fs, fileSelection, null)); File metadata = new File(root, "metadata"); metadata.mkdir(); assertFalse(matcher.matches(fs, fileSelection, null)); File versionHint = new File(metadata, "version-hint.text"); versionHint.createNewFile(); File metadataJsonNoDot = new File(metadata, "v9metadata.json"); metadataJsonNoDot.createNewFile(); assertFalse(matcher.matches(fs, fileSelection, null)); File metadataJson = new File(metadata, "v9.metadata.json"); metadataJson.createNewFile(); matched = matcher.matches(fs, fileSelection, null); assertTrue(matched); }
### Question: SchemaConverter { public BatchSchema fromIceberg(org.apache.iceberg.Schema icebergSchema) { return new BatchSchema(icebergSchema .columns() .stream() .map(SchemaConverter::fromIcebergColumn) .filter(Objects::nonNull) .collect(Collectors.toList())); } SchemaConverter(); BatchSchema fromIceberg(org.apache.iceberg.Schema icebergSchema); static Field fromIcebergColumn(NestedField field); static CompleteType fromIcebergType(Type type); static CompleteType fromIcebergPrimitiveType(PrimitiveType type); org.apache.iceberg.Schema toIceberg(BatchSchema schema); static NestedField toIcebergColumn(Field field); static Schema getChildSchemaForStruct(Schema schema, String structName); static Schema getChildSchemaForList(Schema schema, String listName); }### Answer: @Test public void missingArrowTypes() { org.apache.iceberg.Schema icebergSchema = new org.apache.iceberg.Schema( NestedField.optional(1, "uuid", Types.UUIDType.get()) ); BatchSchema schema = BatchSchema.newBuilder() .addField(new CompleteType(new FixedSizeBinary(16)).toField("uuid")) .build(); BatchSchema result = schemaConverter.fromIceberg(icebergSchema); assertEquals(result, schema); } @Test public void unsupportedIcebergTypes() { org.apache.iceberg.Schema schema = new org.apache.iceberg.Schema( NestedField.optional(1, "timestamp_nozone_field", Types.TimestampType.withoutZone()) ); expectedEx.expect(UserException.class); expectedEx.expectMessage("conversion from iceberg type to arrow type failed for field timestamp_nozone_field"); SchemaConverter convert = new SchemaConverter(); convert.fromIceberg(schema); }
### Question: StoragePluginUtils { public static String generateSourceErrorMessage(final String storagePluginName, String errorMessage) { return String.format("Source '%s' returned error '%s'", storagePluginName, errorMessage); } private StoragePluginUtils(); static String generateSourceErrorMessage(final String storagePluginName, String errorMessage); static String generateSourceErrorMessage(final String storagePluginName, String errorMessage, Object... args); static UserException.Builder message(UserException.Builder builder, String sourceName, String errorMessage, Object... args); }### Answer: @Test public void testGenerateSourceErrorMessage() { final String sourceName = "test-source"; final String errorMessage = "Failed to establish connection"; Assert.assertEquals("Source 'test-source' returned error 'Failed to establish connection'", StoragePluginUtils.generateSourceErrorMessage(sourceName, errorMessage)); } @Test public void testGenerateSourceErrorMessageFromFormatString() { final String sourceName = "test-source"; final String errorFmtString = "Returned status code %s from cluster"; Assert.assertEquals("Source 'test-source' returned error 'Returned status code 500 from cluster'", StoragePluginUtils.generateSourceErrorMessage(sourceName, errorFmtString, "500")); }
### Question: StoragePluginUtils { public static UserException.Builder message(UserException.Builder builder, String sourceName, String errorMessage, Object... args) { return builder.message(generateSourceErrorMessage(sourceName, errorMessage), args) .addContext("plugin", sourceName); } private StoragePluginUtils(); static String generateSourceErrorMessage(final String storagePluginName, String errorMessage); static String generateSourceErrorMessage(final String storagePluginName, String errorMessage, Object... args); static UserException.Builder message(UserException.Builder builder, String sourceName, String errorMessage, Object... args); }### Answer: @Test public void testAddContextAndErrorMessageToUserException() { final UserException.Builder builder = UserException.validationError(); final String errorMessageFormatString = "Invalid username: %s"; final String sourceName = "fictitious-source"; final UserException userException = StoragePluginUtils.message( builder, sourceName, errorMessageFormatString, "invalid-user").buildSilently(); Assert.assertEquals("Source 'fictitious-source' returned error 'Invalid username: invalid-user'", userException.getMessage()); Assert.assertEquals("plugin fictitious-source", userException.getContextStrings().get(0)); }
### Question: ManagedSchemaField { public boolean isTextField() { return isTextFieldType(type); } private ManagedSchemaField(final String name, final String type, final int length, final int scale, final boolean isUnbounded); static ManagedSchemaField newUnboundedLenField(final String name, final String type); static ManagedSchemaField newFixedLenField(final String name, final String type, final int length, final int scale); String getName(); String getType(); int getLength(); int getScale(); boolean isTextField(); boolean isUnbounded(); @Override String toString(); }### Answer: @Test public void testIsTextField() { ManagedSchemaField varcharField = ManagedSchemaField.newFixedLenField("varchar_col", "varchar(20)", 20, 0); assertTrue(varcharField.isTextField()); ManagedSchemaField charField = ManagedSchemaField.newFixedLenField("char_col", "char(20)", 20, 0); assertTrue(charField.isTextField()); ManagedSchemaField stringField = ManagedSchemaField.newFixedLenField("string_col", "String", CompleteType.DEFAULT_VARCHAR_PRECISION, 0); assertTrue(stringField.isTextField()); ManagedSchemaField decimalField = ManagedSchemaField.newUnboundedLenField("decimal_col", "decimal"); assertFalse(decimalField.isTextField()); }
### Question: ImpersonationUtil { public static UserGroupInformation createProxyUgi(String proxyUserName) { try { if (Strings.isNullOrEmpty(proxyUserName)) { throw new IllegalArgumentException("Invalid value for proxy user name"); } if (proxyUserName.equals(getProcessUserName()) || SYSTEM_USERNAME.equals(proxyUserName)) { return getProcessUserUGI(); } return CACHE.get(new Key(proxyUserName, UserGroupInformation.getLoginUser())); } catch (IOException | ExecutionException e) { final String errMsg = "Failed to create proxy user UserGroupInformation object: " + e.getMessage(); logger.error(errMsg, e); throw new RuntimeException(errMsg, e); } } private ImpersonationUtil(); static String resolveUserName(String username); static UserGroupInformation createProxyUgi(String proxyUserName); static String getProcessUserName(); static UserGroupInformation getProcessUserUGI(); static FileSystem createFileSystem(String proxyUserName, Configuration fsConf, Path path); }### Answer: @Test public void testNullUser() throws Exception { thrown.expect(IllegalArgumentException.class); ImpersonationUtil.createProxyUgi(null); } @Test public void testEmptyUser() throws Exception { thrown.expect(IllegalArgumentException.class); ImpersonationUtil.createProxyUgi(""); }
### Question: FormatPluginOptionExtractor { @VisibleForTesting Collection<FormatPluginOptionsDescriptor> getOptions() { return optionsByTypeName.values(); } FormatPluginOptionExtractor(ScanResult scanResult); FormatPluginConfig createConfigForTable(TableInstance t); List<Function> getFunctions(final List<String> tableSchemaPath, final FileSystemPlugin plugin, final SchemaConfig schemaConfig); }### Answer: @Test public void test() { FormatPluginOptionExtractor e = new FormatPluginOptionExtractor(CLASSPATH_SCAN_RESULT); Collection<FormatPluginOptionsDescriptor> options = e.getOptions(); for (FormatPluginOptionsDescriptor d : options) { assertEquals(d.pluginConfigClass.getAnnotation(JsonTypeName.class).value(), d.typeName); switch (d.typeName) { case "text": assertEquals(TextFormatConfig.class, d.pluginConfigClass); assertEquals( "(type: String, lineDelimiter: String, fieldDelimiter: String, quote: String, escape: String, " + "comment: String, skipFirstLine: boolean, extractHeader: boolean, " + "autoGenerateColumnNames: boolean, trimHeader: boolean, outputExtension: String)", d.presentParams() ); break; case "named": assertEquals(NamedFormatPluginConfig.class, d.pluginConfigClass); assertEquals("(type: String, name: String)", d.presentParams()); break; case "json": assertEquals(d.typeName, "(type: String, outputExtension: String, prettyPrint: boolean)", d.presentParams()); break; case "parquet": assertEquals(d.typeName, "(type: String, autoCorrectCorruptDates: boolean, outputExtension: String)", d.presentParams()); break; case "arrow": assertEquals(d.typeName, "(type: String, outputExtension: String)", d.presentParams()); break; case "sequencefile": case "avro": assertEquals(d.typeName, "(type: String)", d.presentParams()); break; case "excel": assertEquals(d.typeName, "(type: String, sheet: String, extractHeader: boolean, hasMergedCells: boolean, xls: boolean)", d.presentParams()); break; case "iceberg": assertEquals(d.typeName, "(type: String, metaStoreType: IcebergMetaStoreType, dataFormatType: FileType, dataFormatConfig: FormatPluginConfig)", d.presentParams()); break; default: fail("add validation for format plugin type " + d.typeName); } } }
### Question: EasyScanOperatorCreator implements ProducerOperator.Creator<EasySubScan> { static boolean selectsAllColumns(final BatchSchema datasetSchema, final List<SchemaPath> projectedColumns) { final Set<String> columnsInTable = FluentIterable.from(datasetSchema) .transform( new Function<Field, String>() { @Override public String apply(Field input) { return input.getName(); }}) .filter( new Predicate<String>() { @Override public boolean apply(String input) { return !input.equals(IncrementalUpdateUtils.UPDATE_COLUMN); }}) .toSet(); final Set<String> selectedColumns = FluentIterable.from(projectedColumns) .transform( new Function<SchemaPath, String>() { @Override public String apply(SchemaPath input) { return input.getAsUnescapedPath(); } }) .toSet(); return columnsInTable.equals(selectedColumns); } @Override ProducerOperator create(FragmentExecutionContext fragmentExecContext, final OperatorContext context, EasySubScan config); }### Answer: @Test public void trueWhenAllColumnsAreSelected() { BatchSchema schema = mock(BatchSchema.class); when(schema.iterator()) .thenReturn(Lists.newArrayList(Field.nullable("a1", new ArrowType.Bool())).iterator()); assertTrue(EasyScanOperatorCreator.selectsAllColumns(schema, Lists.<SchemaPath>newArrayList(SchemaPath.getSimplePath("a1")))); } @Test public void selectionIgnoresIncremental() { BatchSchema schema = mock(BatchSchema.class); when(schema.iterator()) .thenReturn(Lists.newArrayList(Field.nullable("a1", new ArrowType.Bool()), Field.nullable(IncrementalUpdateUtils.UPDATE_COLUMN, new ArrowType.Bool())).iterator()); assertTrue(EasyScanOperatorCreator.selectsAllColumns(schema, Lists.<SchemaPath>newArrayList(SchemaPath.getSimplePath("a1")))); } @Test public void falseWhenAllColumnsAreNotSelected() { BatchSchema schema = mock(BatchSchema.class); when(schema.iterator()) .thenReturn(Lists.newArrayList(Field.nullable("a1", new ArrowType.Bool()), Field.nullable("a2", new ArrowType.Bool())).iterator()); assertFalse(EasyScanOperatorCreator.selectsAllColumns(schema, Lists.<SchemaPath>newArrayList(SchemaPath.getSimplePath("a1")))); } @Test public void falseWhenChildrenAreSelected() { BatchSchema schema = mock(BatchSchema.class); when(schema.iterator()) .thenReturn(Lists.newArrayList( new Field("a1", new FieldType(true, new ArrowType.Struct(), null), Lists.newArrayList(Field.nullable("a2", new ArrowType.Bool()))), Field.nullable("a3", new ArrowType.Bool())).iterator()); assertFalse(EasyScanOperatorCreator.selectsAllColumns(schema, Lists.newArrayList(SchemaPath.getSimplePath("a1"), SchemaPath.getCompoundPath("a1", "a2"), SchemaPath.getSimplePath("a3")))); }
### Question: DremioFileSystemCache { public FileSystem get(URI uri, Configuration conf, List<String> uniqueConnectionProps) throws IOException{ final Key key = new Key(uri, conf, uniqueConnectionProps); FileSystem fs; synchronized (this) { fs = map.get(key); } if (fs != null) { return fs; } final String disableCacheName = String.format("fs.%s.impl.disable.cache", uri.getScheme()); final boolean disableCache = conf.getBoolean(disableCacheName, false); if (disableCache || key.uniqueConnectionPropValues == null || key.uniqueConnectionPropValues.isEmpty()) { return FileSystem.get(uri, conf); } final Configuration cloneConf = new Configuration(conf); cloneConf.set(disableCacheName, "true"); fs = FileSystem.get(uri, cloneConf); cloneConf.setBoolean(disableCacheName, disableCache); synchronized (this) { FileSystem oldfs = map.get(key); if (oldfs != null) { fs.close(); return oldfs; } if (map.isEmpty() && !ShutdownHookManager.get().isShutdownInProgress()) { ShutdownHookManager.get().addShutdownHook(clientFinalizer, SHUTDOWN_HOOK_PRIORITY); } map.put(key, fs); if (conf.getBoolean(FS_AUTOMATIC_CLOSE_KEY, FS_AUTOMATIC_CLOSE_DEFAULT)) { toAutoClose.add(key); } return fs; } } FileSystem get(URI uri, Configuration conf, List<String> uniqueConnectionProps); synchronized void closeAll(boolean onlyAutomatic); }### Answer: @Test public void withUniqueConnProps() throws Exception { final DremioFileSystemCache dfsc = new DremioFileSystemCache(); final URI uri = URI.create("file: final List<String> uniqueProps = ImmutableList.of("prop1", "prop2"); Configuration conf1 = new Configuration(); FileSystem fs1 = dfsc.get(uri, conf1, uniqueProps); Configuration conf2 = new Configuration(conf1); conf2.set("prop1", "prop1Val"); FileSystem fs2 = dfsc.get(uri, conf2, uniqueProps); assertTrue(fs1 != fs2); FileSystem fs3 = dfsc.get(uri, conf2, uniqueProps); assertTrue(fs2 == fs3); FileSystem fs4 = getAs("newUser", dfsc, uri, conf2, uniqueProps); assertTrue(fs2 != fs4); assertTrue(fs1 != fs4); FileSystem fs5 = dfsc.get(uri, conf1, null); assertTrue(fs1 != fs5); FileSystem fs6 = dfsc.get(uri, conf1, null); assertTrue(fs5 == fs6); } @Test public void withoutUniqueConnProps() throws Exception { final DremioFileSystemCache dfsc = new DremioFileSystemCache(); final URI uri = URI.create("file: Configuration conf1 = new Configuration(); FileSystem fs1 = dfsc.get(uri, conf1, null); Configuration conf2 = new Configuration(conf1); conf2.set("blah", "boo"); FileSystem fs2 = dfsc.get(uri, conf2, null); assertTrue(fs1 == fs2); FileSystem fs3 = getAs("newUser", dfsc, uri, conf1, null); assertTrue(fs1 != fs3); } @Test public void withoutUniqueConnPropsWithCacheExplicitlyDisabled() throws Exception { final DremioFileSystemCache dfsc = new DremioFileSystemCache(); final URI uri = URI.create("file: Configuration conf1 = new Configuration(); final String disableCacheName = String.format("fs.%s.impl.disable.cache", uri.getScheme()); conf1.setBoolean(disableCacheName, true); FileSystem fs1 = dfsc.get(uri, conf1, null); Configuration conf2 = new Configuration(conf1); conf2.set("blah", "boo"); FileSystem fs2 = dfsc.get(uri, conf2, null); assertTrue(fs1 != fs2); FileSystem fs3 = getAs("newUser", dfsc, uri, conf1, null); assertTrue(fs1 != fs3); assertTrue(fs1 != fs3); }
### Question: DataJsonOutput { public static final boolean isNumberAsString(DatabindContext context) { Object attr = context.getAttribute(DataJsonOutput.DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_ATTRIBUTE); return attr instanceof Boolean && ((Boolean)attr).booleanValue(); } DataJsonOutput(JsonGenerator gen, boolean convertNumbersToStrings); static final ObjectWriter setNumbersAsStrings(ObjectWriter writer, boolean isEnabled); static final boolean isNumberAsString(DatabindContext context); void writeStartArray(); void writeEndArray(); void writeStartObject(); void writeEndObject(); void writeFieldName(String name); void writeVarChar(String value); void writeBoolean(boolean value); void writeDecimal(FieldReader reader, JsonOutputContext context); void writeTinyInt(FieldReader reader, JsonOutputContext context); void writeSmallInt(FieldReader reader, JsonOutputContext context); void writeInt(FieldReader reader, JsonOutputContext context); void writeBigInt(FieldReader reader, JsonOutputContext context); void writeFloat(FieldReader reader, JsonOutputContext context); void writeDouble(FieldReader reader, JsonOutputContext context); void writeVarChar(FieldReader reader, JsonOutputContext context); void writeVar16Char(FieldReader reader, JsonOutputContext context); void writeVarBinary(FieldReader reader, JsonOutputContext context); void writeBit(FieldReader reader, JsonOutputContext context); void writeDateMilli(FieldReader reader, JsonOutputContext context); void writeDate(FieldReader reader, JsonOutputContext context); void writeTimeMilli(FieldReader reader, JsonOutputContext context); void writeTime(FieldReader reader, JsonOutputContext context); void writeTimeStampMilli(FieldReader reader, JsonOutputContext context); void writeIntervalYear(FieldReader reader, JsonOutputContext context); void writeIntervalDay(FieldReader reader, JsonOutputContext context); void writeNull(JsonOutputContext context); void writeUnion(FieldReader reader, JsonOutputContext context); void writeMap(FieldReader reader, JsonOutputContext context); void writeList(FieldReader reader, JsonOutputContext context); static final DateTimeFormatter FORMAT_DATE; static final DateTimeFormatter FORMAT_TIMESTAMP; static final DateTimeFormatter FORMAT_TIME; static final String DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_ATTRIBUTE; }### Answer: @Test public void test() { Mockito.when(context.getAttribute(DataJsonOutput.DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_ATTRIBUTE)).thenReturn(this.inputValue); assertEquals(this.expectedValue, DataJsonOutput.isNumberAsString(context)); }
### Question: TimedRunnable implements Runnable { @Override public final void run() { long start = System.nanoTime(); threadStart=start; try{ value = runInner(); }catch(Exception e){ this.e = e; }finally{ timeNanos = System.nanoTime() - start; } } @Override final void run(); long getThreadStart(); long getTimeSpentNanos(); final V getValue(); static List<V> run(final String activity, final Logger logger, final List<TimedRunnable<V>> runnables, int parallelism); static List<V> run(final String activity, final Logger logger, final List<TimedRunnable<V>> runnables, int parallelism, long timeout); }### Answer: @Test public void withoutAnyTasksTriggeringTimeout() throws Exception { List<TimedRunnable<Void>> tasks = Lists.newArrayList(); for(int i=0; i<100; i++){ tasks.add(new TestTask(2000)); } TimedRunnable.run("Execution without triggering timeout", logger, tasks, 16); } @Test public void withTasksExceedingTimeout() throws Exception { UserException ex = null; try { List<TimedRunnable<Void>> tasks = Lists.newArrayList(); for (int i = 0; i < 100; i++) { if ((i & (i + 1)) == 0) { tasks.add(new TestTask(2000)); } else { tasks.add(new TestTask(20000)); } } TimedRunnable.run("Execution with some tasks triggering timeout", logger, tasks, 16); } catch (UserException e) { ex = e; } assertNotNull("Expected a UserException", ex); assertThat(ex.getMessage(), containsString("Waited for 93750ms, but tasks for 'Execution with some tasks triggering timeout' are not " + "complete. Total runnable size 100, parallelism 16.")); } @Test public void withManyTasks() throws Exception { List<TimedRunnable<Void>> tasks = Lists.newArrayList(); for (int i = 0; i < 150000; i++) { tasks.add(new TestTask(0)); } TimedRunnable.run("Execution with lots of tasks", logger, tasks, 16); } @Test public void withOverriddenHighTimeout() throws Exception { List<TimedRunnable<Void>> tasks = Lists.newArrayList(); for(int i=0; i<10; i++){ tasks.add(new TestTask(20_000)); } TimedRunnable.run("Execution without triggering timeout", logger, tasks, 2, 150_000); }
### Question: QueryContext implements AutoCloseable, ResourceSchedulingContext, OptimizerRulesContext { public OptionManager getOptions() { return optionManager; } QueryContext( final UserSession session, final SabotContext sabotContext, QueryId queryId ); QueryContext( final UserSession session, final SabotContext sabotContext, QueryId queryId, Optional<Boolean> checkMetadataValidity ); QueryContext( final UserSession session, final SabotContext sabotContext, QueryId queryId, QueryPriority priority, long maxAllocation, Predicate<DatasetConfig> datasetValidityChecker ); private QueryContext( final UserSession session, final SabotContext sabotContext, QueryId queryId, QueryPriority priority, long maxAllocation, Predicate<DatasetConfig> datasetValidityChecker, Optional<Boolean> checkMetadataValidity ); CatalogService getCatalogService(); Catalog getCatalog(); AccelerationManager getAccelerationManager(); SubstitutionProviderFactory getSubstitutionProviderFactory(); RuleSet getInjectedRules(PlannerPhase phase); @Override QueryId getQueryId(); @Override PlannerSettings getPlannerSettings(); UserSession getSession(); @Override BufferAllocator getAllocator(); @Override String getQueryUserName(); OptionManager getOptions(); QueryOptionManager getQueryOptionManager(); SessionOptionManager getSessionOptionManager(); SystemOptionManager getSystemOptionManager(); ExecutionControls getExecutionControls(); @Override NodeEndpoint getCurrentEndpoint(); LogicalPlanPersistence getLpPersistence(); @Override Collection<NodeEndpoint> getActiveEndpoints(); SabotConfig getConfig(); OptionList getNonDefaultOptions(); @Override FunctionImplementationRegistry getFunctionRegistry(); boolean isUserAuthenticationEnabled(); ScanResult getScanResult(); OperatorTable getOperatorTable(); @Override QueryContextInformation getQueryContextInfo(); @Override ContextInformation getContextInformation(); @Override ArrowBuf getManagedBuffer(); @Override PartitionExplorer getPartitionExplorer(); @Override int registerFunctionErrorContext(FunctionErrorContext errorContext); @Override FunctionErrorContext getFunctionErrorContext(int errorContextId); @Override FunctionErrorContext getFunctionErrorContext(); MaterializationDescriptorProvider getMaterializationProvider(); Provider<WorkStats> getWorkStatsProvider(); WorkloadType getWorkloadType(); @Override BufferManager getBufferManager(); @Override ValueHolder getConstantValueHolder(String value, MinorType type, Function<ArrowBuf, ValueHolder> holderInitializer); void setGroupResourceInformation(GroupResourceInformation groupResourceInformation); GroupResourceInformation getGroupResourceInformation(); @Override void close(); @Override CompilationOptions getCompilationOptions(); ExecutorService getExecutorService(); }### Answer: @Test public void testOptionManagerSetup() throws Exception { try (final QueryContext queryContext = new QueryContext(session(), getSabotContext(), UserBitShared.QueryId.getDefaultInstance());) { final OptionManagerWrapper optionManager = (OptionManagerWrapper) queryContext.getOptions(); final List<OptionManager> optionManagerList = optionManager.getOptionManagers(); assertEquals(4, optionManagerList.size()); assertTrue(optionManagerList.get(0) instanceof QueryOptionManager); assertTrue(optionManagerList.get(1) instanceof SessionOptionManager); assertTrue(optionManagerList.get(2) instanceof EagerCachingOptionManager); assertTrue(optionManagerList.get(3) instanceof DefaultOptionManager); } }
### Question: OptionManagerWrapper extends BaseOptionManager { @Override public OptionList getNonDefaultOptions() { final OptionList optionList = new OptionList(); for (OptionManager optionManager : optionManagers) { OptionList nonDefaultOptions = optionManager.getNonDefaultOptions(); optionList.merge(nonDefaultOptions); } return optionList; } OptionManagerWrapper(OptionValidatorListing optionValidatorListing, List<OptionManager> optionManagers); OptionValidatorListing getOptionValidatorListing(); @VisibleForTesting List<OptionManager> getOptionManagers(); @Override boolean setOption(OptionValue value); @Override boolean deleteOption(String name, OptionValue.OptionType type); @Override boolean deleteAllOptions(OptionValue.OptionType type); @Override OptionValue getOption(String name); @Override OptionList getDefaultOptions(); @Override OptionList getNonDefaultOptions(); OptionValidator getValidator(String name); @Override Iterator<OptionValue> iterator(); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); }### Answer: @Test public void testGetNonDefaultOptions() throws Exception { OptionManager optionManager = OptionManagerWrapper.Builder.newBuilder() .withOptionValidatorProvider(optionValidatorListing) .withOptionManager(defaultOptionManager) .withOptionManager(systemOptionManager) .withOptionManager(sessionOptionManager) .withOptionManager(queryOptionManager) .build(); int initialOptionsCount = defaultOptionManager.getNonDefaultOptions().size() + systemOptionManager.getNonDefaultOptions().size() + sessionOptionManager.getNonDefaultOptions().size() + queryOptionManager.getNonDefaultOptions().size(); List<OptionValue> optionValues = Arrays.asList( OptionValue.createLong(OptionValue.OptionType.SYSTEM, SLICE_TARGET, 10), OptionValue.createLong(OptionValue.OptionType.SESSION, SLICE_TARGET, 15), OptionValue.createLong(OptionValue.OptionType.QUERY, SLICE_TARGET, 20), OptionValue.createBoolean(OptionValue.OptionType.SESSION, ENABLE_VERBOSE_ERRORS_KEY, true), OptionValue.createBoolean(OptionValue.OptionType.QUERY, ENABLE_VERBOSE_ERRORS_KEY, true) ); optionValues.forEach(optionManager::setOption); OptionList nonDefaultOptions = optionManager.getNonDefaultOptions(); assertEquals(initialOptionsCount + optionValues.size(), nonDefaultOptions.size()); for (OptionValue optionValue : optionValues) { assertTrue(nonDefaultOptions.contains(optionValue)); } for (OptionValue nonDefaultOption : nonDefaultOptions) { assertNotEquals(nonDefaultOption, defaultOptionManager.getOption(nonDefaultOption.getName())); } }
### Question: OptionManagerWrapper extends BaseOptionManager { @Override public OptionList getDefaultOptions() { final OptionList optionList = new OptionList(); for (OptionManager optionManager : optionManagers) { OptionList defaultOptions = optionManager.getDefaultOptions(); optionList.merge(defaultOptions); } return optionList; } OptionManagerWrapper(OptionValidatorListing optionValidatorListing, List<OptionManager> optionManagers); OptionValidatorListing getOptionValidatorListing(); @VisibleForTesting List<OptionManager> getOptionManagers(); @Override boolean setOption(OptionValue value); @Override boolean deleteOption(String name, OptionValue.OptionType type); @Override boolean deleteAllOptions(OptionValue.OptionType type); @Override OptionValue getOption(String name); @Override OptionList getDefaultOptions(); @Override OptionList getNonDefaultOptions(); OptionValidator getValidator(String name); @Override Iterator<OptionValue> iterator(); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); }### Answer: @Test public void testGetDefaultOptions() throws Exception { OptionManager optionManager = OptionManagerWrapper.Builder.newBuilder() .withOptionValidatorProvider(optionValidatorListing) .withOptionManager(defaultOptionManager) .withOptionManager(systemOptionManager) .withOptionManager(sessionOptionManager) .withOptionManager(queryOptionManager) .build(); OptionList defaultOptions = optionManager.getDefaultOptions(); assertEquals(defaultOptionManager.getDefaultOptions().size(), defaultOptions.size()); for (OptionValue defaultOption : defaultOptions) { assertEquals(defaultOption, optionValidatorListing.getValidator(defaultOption.getName()).getDefault()); } }
### Question: OptionManagerWrapper extends BaseOptionManager { @Override public Iterator<OptionValue> iterator() { final OptionList resultList = new OptionList(); final Map<String, OptionValue> optionsMap = CaseInsensitiveMap.newHashMap(); final OptionList defaultOptions = getDefaultOptions(); defaultOptions.forEach(optionValue -> optionsMap.put(optionValue.getName(), optionValue)); final List<OptionManager> reversedOptionManagers = Lists.reverse(optionManagers); for (OptionManager optionManager : reversedOptionManagers) { OptionList optionList = optionManager.getNonDefaultOptions(); for (OptionValue optionValue : optionList) { if (optionValue.getType() == optionsMap.get(optionValue.getName()).getType()) { optionsMap.put(optionValue.getName(), optionValue); } else { resultList.add(optionValue); } } } resultList.addAll(optionsMap.values()); return resultList.iterator(); } OptionManagerWrapper(OptionValidatorListing optionValidatorListing, List<OptionManager> optionManagers); OptionValidatorListing getOptionValidatorListing(); @VisibleForTesting List<OptionManager> getOptionManagers(); @Override boolean setOption(OptionValue value); @Override boolean deleteOption(String name, OptionValue.OptionType type); @Override boolean deleteAllOptions(OptionValue.OptionType type); @Override OptionValue getOption(String name); @Override OptionList getDefaultOptions(); @Override OptionList getNonDefaultOptions(); OptionValidator getValidator(String name); @Override Iterator<OptionValue> iterator(); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); }### Answer: @Test public void testIterator() throws Exception { OptionManager optionManager = OptionManagerWrapper.Builder.newBuilder() .withOptionValidatorProvider(optionValidatorListing) .withOptionManager(defaultOptionManager) .withOptionManager(systemOptionManager) .withOptionManager(sessionOptionManager) .withOptionManager(queryOptionManager) .build(); int initialSystemOptionCount = systemOptionManager.getNonDefaultOptions().size(); int initialOptionsCount = defaultOptionManager.getNonDefaultOptions().size() + initialSystemOptionCount + sessionOptionManager.getNonDefaultOptions().size() + queryOptionManager.getNonDefaultOptions().size(); int defaultOptionsCount = optionValidatorListing.getValidatorList().size(); List<OptionValue> optionValues = Arrays.asList( OptionValue.createLong(OptionValue.OptionType.SYSTEM, SLICE_TARGET, 10), OptionValue.createLong(OptionValue.OptionType.SESSION, SLICE_TARGET, 15), OptionValue.createLong(OptionValue.OptionType.QUERY, SLICE_TARGET, 20), OptionValue.createBoolean(OptionValue.OptionType.SESSION, ENABLE_VERBOSE_ERRORS_KEY, true), OptionValue.createBoolean(OptionValue.OptionType.QUERY, ENABLE_VERBOSE_ERRORS_KEY, true) ); AtomicInteger systemOptionsCount = new AtomicInteger(initialSystemOptionCount); optionValues.forEach(optionValue -> { optionManager.setOption(optionValue); if (optionValue.getType().equals(OptionValue.OptionType.SYSTEM)) { systemOptionsCount.addAndGet(1); } }); OptionList iteratorResult = new OptionList(); optionManager.iterator().forEachRemaining(iteratorResult::add); assertEquals(initialOptionsCount + defaultOptionsCount + optionValues.size() - systemOptionsCount.get(), iteratorResult.size()); }
### Question: TransformBase { public Transform wrap() { return acceptor.wrap(this); } final T accept(TransformVisitor<T> visitor); Transform wrap(); @Override String toString(); static TransformBase unwrap(Transform t); static Converter<TransformBase, Transform> converter(); static final Acceptor<TransformBase, TransformVisitor<?>, Transform> acceptor; }### Answer: @Test public void testConvert() throws Exception { TransformBase transform = new TransformField("source", "new", false, new FieldConvertCase(LOWER_CASE).wrap()); validate(transform); }
### Question: OptionValueProtoUtils { public static OptionValueProto toOptionValueProto(OptionValue optionValue) { checkArgument(optionValue.getType() == OptionValue.OptionType.SYSTEM, String.format("Invalid OptionType. OptionType must be 'SYSTEM', was given '%s'", optionValue.getType())); final OptionValue.Kind kind = optionValue.getKind(); final OptionValueProto.Builder builder = OptionValueProto.newBuilder() .setName(optionValue.getName()); switch (kind) { case BOOLEAN: builder.setBoolVal(optionValue.getBoolVal()); break; case LONG: builder.setNumVal(optionValue.getNumVal()); break; case STRING: builder.setStringVal(optionValue.getStringVal()); break; case DOUBLE: builder.setFloatVal(optionValue.getFloatVal()); break; default: throw new IllegalArgumentException("Invalid OptionValue kind"); } return builder.build(); } private OptionValueProtoUtils(); static OptionValueProto toOptionValueProto(OptionValue optionValue); static OptionValue toOptionValue(OptionValueProto value); static OptionValueProtoList toOptionValueProtoList(Collection<OptionValueProto> optionValueProtos); }### Answer: @Test public void testBoolOptionToProto() { final OptionValue option = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test.option", true); final OptionValueProto optionProto = OptionValueProtoUtils.toOptionValueProto(option); assertTrue(verifyEquivalent(option, optionProto)); } @Test public void testLongOptionToProto() { final OptionValue option = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test.option", 1234); final OptionValueProto optionProto = OptionValueProtoUtils.toOptionValueProto(option); assertTrue(verifyEquivalent(option, optionProto)); } @Test public void testStringOptionToProto() { final OptionValue option = OptionValue.createString(OptionValue.OptionType.SYSTEM, "test.option", "test-option"); final OptionValueProto optionProto = OptionValueProtoUtils.toOptionValueProto(option); assertTrue(verifyEquivalent(option, optionProto)); } @Test public void testDoubleOptionToProto() { final OptionValue option = OptionValue.createDouble(OptionValue.OptionType.SYSTEM, "test.option", 1234.1234); final OptionValueProto optionProto = OptionValueProtoUtils.toOptionValueProto(option); assertTrue(verifyEquivalent(option, optionProto)); }
### Question: OptionValueProtoUtils { public static OptionValue toOptionValue(OptionValueProto value) { switch (value.getOptionValCase()) { case NUM_VAL: return OptionValue.createLong( OptionValue.OptionType.SYSTEM, value.getName(), value.getNumVal() ); case STRING_VAL: return OptionValue.createString( OptionValue.OptionType.SYSTEM, value.getName(), value.getStringVal() ); case BOOL_VAL: return OptionValue.createBoolean( OptionValue.OptionType.SYSTEM, value.getName(), value.getBoolVal() ); case FLOAT_VAL: return OptionValue.createDouble( OptionValue.OptionType.SYSTEM, value.getName(), value.getFloatVal() ); case OPTIONVAL_NOT_SET: default: throw new IllegalArgumentException("Invalid OptionValue kind"); } } private OptionValueProtoUtils(); static OptionValueProto toOptionValueProto(OptionValue optionValue); static OptionValue toOptionValue(OptionValueProto value); static OptionValueProtoList toOptionValueProtoList(Collection<OptionValueProto> optionValueProtos); }### Answer: @Test public void testBoolOptionFromProto() { final OptionValueProto optionProto = OptionValueProto.newBuilder() .setName("test.option") .setBoolVal(true) .build(); final OptionValue option = OptionValueProtoUtils.toOptionValue(optionProto); assertTrue(verifyEquivalent(option, optionProto)); } @Test public void testLongOptionFromProto() { final OptionValueProto optionProto = OptionValueProto.newBuilder() .setName("test.option") .setNumVal(1234) .build(); final OptionValue option = OptionValueProtoUtils.toOptionValue(optionProto); assertTrue(verifyEquivalent(option, optionProto)); } @Test public void testStringOptionFromProto() { final OptionValueProto optionProto = OptionValueProto.newBuilder() .setName("test.option") .setStringVal("test-option") .build(); final OptionValue option = OptionValueProtoUtils.toOptionValue(optionProto); assertTrue(verifyEquivalent(option, optionProto)); } @Test public void testFloatOptionFromProto() { final OptionValueProto optionProto = OptionValueProto.newBuilder() .setName("test.option") .setFloatVal(1234.1234) .build(); final OptionValue option = OptionValueProtoUtils.toOptionValue(optionProto); assertTrue(verifyEquivalent(option, optionProto)); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public OptionValue getOption(final String name) { final OptionValueProto value = getOptionProto(name); return value == null ? null : OptionValueProtoUtils.toOptionValue(value); } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testGet() { registerTestOption(OptionValue.Kind.LONG, "test-option", "0"); OptionValue optionValue = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option", 123); OptionValueProtoList optionList = OptionValueProtoList.newBuilder() .addAllOptions(Collections.singletonList(OptionValueProtoUtils.toOptionValueProto(optionValue))) .build(); when(kvStore.get(OPTIONS_KEY)).thenReturn(optionList); assertEquals(optionValue, som.getOption(optionValue.getName())); verify(kvStore, times(1)).get(eq(OPTIONS_KEY)); assertNull(som.getOption("not-a-real-option")); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public boolean setOption(final OptionValue value) { checkArgument(value.getType() == OptionType.SYSTEM, "OptionType must be SYSTEM."); final String name = value.getName().toLowerCase(Locale.ROOT); final OptionValidator validator = optionValidatorListing.getValidator(name); validator.validate(value); final Map<String, OptionValueProto> optionMap = new HashMap<>(); getOptionProtoList().forEach(optionProto -> optionMap.put(optionProto.getName(), optionProto)); if (optionMap.containsKey(name) && optionMap.get(name).equals(OptionValueProtoUtils.toOptionValueProto(value))) { return true; } if (value.equals(validator.getDefault())) { if (optionMap.containsKey(value.getName())) { optionMap.remove(value.getName()); } else { return true; } } optionMap.put(name, OptionValueProtoUtils.toOptionValueProto(value)); options.put(OPTIONS_KEY, OptionValueProtoUtils.toOptionValueProtoList(optionMap.values())); notifyListeners(); return true; } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testSet() { registerTestOption(OptionValue.Kind.LONG, "already-added-option", "0"); OptionValue toAddOptionDefault = registerTestOption(OptionValue.Kind.STRING, "to-add-option", "default-value"); OptionValue alreadyAddedOption = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "already-added-option", 123); OptionValue toAddOption = OptionValue.createString(OptionValue.OptionType.SYSTEM, "to-add-option", "some-value"); OptionValueProtoList optionList = OptionValueProtoList.newBuilder() .addAllOptions(Collections.singletonList(OptionValueProtoUtils.toOptionValueProto(alreadyAddedOption))) .build(); when(kvStore.get(OPTIONS_KEY)).thenReturn(optionList); som.setOption(alreadyAddedOption); verify(kvStore, times(0)).put(any(), any()); som.setOption(toAddOptionDefault); verify(kvStore, times(0)).put(any(), any()); som.setOption(toAddOption); ArgumentCaptor<OptionValueProtoList> argument = ArgumentCaptor.forClass(OptionValueProtoList.class); verify(kvStore, times(1)).put(eq(OPTIONS_KEY), argument.capture()); assertThat(argument.getValue().getOptionsList(), containsInAnyOrder(OptionValueProtoUtils.toOptionValueProto(toAddOption), OptionValueProtoUtils.toOptionValueProto(alreadyAddedOption)) ); OptionValue overridingOption = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "already-added-option", 999); som.setOption(overridingOption); verify(kvStore, times(1)).put(OPTIONS_KEY, OptionValueProtoList.newBuilder() .addAllOptions(Collections.singletonList(OptionValueProtoUtils.toOptionValueProto(overridingOption))) .build() ); }
### Question: TransformBase { public final <T> T accept(TransformVisitor<T> visitor) throws VisitorException { return acceptor.accept(visitor, this); } final T accept(TransformVisitor<T> visitor); Transform wrap(); @Override String toString(); static TransformBase unwrap(Transform t); static Converter<TransformBase, Transform> converter(); static final Acceptor<TransformBase, TransformVisitor<?>, Transform> acceptor; }### Answer: @Test public void testVisitor() { TransformBase transform = new TransformExtract("source", "new", DatasetsUtil.pattern("\\d+", 0, IndexType.INDEX), false); String name = transform.accept(new TransformVisitor<String>() { @Override public String visit(TransformLookup lookup) throws Exception { return "lookup"; } @Override public String visit(TransformJoin join) throws Exception { return "join"; } @Override public String visit(TransformSort sort) throws Exception { return "sort"; } @Override public String visit(TransformSorts sortMultiple) throws Exception { return "sortMultiple"; } @Override public String visit(TransformDrop drop) throws Exception { return "drop"; } @Override public String visit(TransformRename rename) throws Exception { return "rename"; } @Override public String visit(TransformConvertCase convertCase) throws Exception { return "convertCase"; } @Override public String visit(TransformTrim trim) throws Exception { return "trim"; } @Override public String visit(TransformExtract extract) throws Exception { return "extract"; } @Override public String visit(TransformAddCalculatedField addCalculatedField) throws Exception { return "addCalculatedField"; } @Override public String visit(TransformUpdateSQL updateSQL) throws Exception { return "updateSQL"; } @Override public String visit(TransformField field) throws Exception { return "field"; } @Override public String visit(TransformConvertToSingleType convertToSingleType) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(TransformSplitByDataType splitByDataType) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(TransformGroupBy groupBy) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(TransformFilter filter) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(TransformCreateFromParent createFromParent) throws Exception { throw new UnsupportedOperationException("NYI"); } }); assertEquals("extract", name); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public boolean deleteOption(final String rawName, OptionType type) { checkArgument(type == OptionType.SYSTEM, "OptionType must be SYSTEM."); final String name = rawName.toLowerCase(Locale.ROOT); optionValidatorListing.getValidator(name); final Pointer<Boolean> needUpdate = new Pointer<>(false); final List<OptionValueProto> newOptionValueProtoList = getOptionProtoList().stream() .filter(optionValueProto -> { if (name.equals(optionValueProto.getName())) { needUpdate.value = true; return false; } return true; }) .collect(Collectors.toList()); if (needUpdate.value) { options.put(OPTIONS_KEY, OptionValueProtoUtils.toOptionValueProtoList(newOptionValueProtoList)); } notifyListeners(); return true; } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testDelete() { registerTestOption(OptionValue.Kind.LONG, "added-option-0", "0"); registerTestOption(OptionValue.Kind.LONG, "added-option-1", "1"); registerTestOption(OptionValue.Kind.STRING, "not-added-option", "default-value"); OptionValue optionValue0 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "added-option-0", 100); OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "added-option-1", 111); OptionValueProtoList optionList = OptionValueProtoList.newBuilder() .addAllOptions(Arrays.asList( OptionValueProtoUtils.toOptionValueProto(optionValue0), OptionValueProtoUtils.toOptionValueProto(optionValue1))) .build(); when(kvStore.get(OPTIONS_KEY)).thenReturn(optionList); som.deleteOption("not-added-option", OptionValue.OptionType.SYSTEM); verify(kvStore, times(0)).put(any(), any()); som.deleteOption("added-option-0", OptionValue.OptionType.SYSTEM); verify(kvStore, times(1)).put(OPTIONS_KEY, OptionValueProtoList.newBuilder() .addAllOptions(Collections.singletonList(OptionValueProtoUtils.toOptionValueProto(optionValue1))) .build() ); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public boolean deleteAllOptions(OptionType type) { checkArgument(type == OptionType.SYSTEM, "OptionType must be SYSTEM."); options.put(OPTIONS_KEY, OptionValueProtoList.newBuilder().build()); notifyListeners(); return true; } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testDeleteAll() { registerTestOption(OptionValue.Kind.LONG, "test-option-0", "0"); registerTestOption(OptionValue.Kind.LONG, "test-option-1", "1"); OptionValue optionValue0 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option-0", 100); OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option-1", 111); OptionValueProtoList optionList = OptionValueProtoList.newBuilder() .addAllOptions(Arrays.asList( OptionValueProtoUtils.toOptionValueProto(optionValue0), OptionValueProtoUtils.toOptionValueProto(optionValue1))) .build(); when(kvStore.get(OPTIONS_KEY)).thenReturn(optionList); som.deleteAllOptions(OptionValue.OptionType.SYSTEM); verify(kvStore, times(1)).put(OPTIONS_KEY, OptionValueProtoList.newBuilder() .addAllOptions(Collections.emptyList()) .build() ); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public OptionList getNonDefaultOptions() { final OptionList nonDefaultOptions = new OptionList(); getOptionProtoList().forEach( entry -> nonDefaultOptions.add(OptionValueProtoUtils.toOptionValue(entry)) ); return nonDefaultOptions; } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testGetNonDefaultOptions() { registerTestOption(OptionValue.Kind.LONG, "test-option-0", "0"); registerTestOption(OptionValue.Kind.LONG, "test-option-1", "1"); OptionValue optionValue0 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option-0", 100); OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option-1", 111); OptionValueProtoList optionList = OptionValueProtoList.newBuilder() .addAllOptions(Arrays.asList( OptionValueProtoUtils.toOptionValueProto(optionValue0), OptionValueProtoUtils.toOptionValueProto(optionValue1))) .build(); when(kvStore.get(OPTIONS_KEY)).thenReturn(optionList); assertThat(som.getNonDefaultOptions(), containsInAnyOrder(optionValue0, optionValue1)); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public Iterator<OptionValue> iterator() { return getOptionProtoList().stream() .map(OptionValueProtoUtils::toOptionValue) .iterator(); } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testIterator() { registerTestOption(OptionValue.Kind.LONG, "test-option-0", "0"); registerTestOption(OptionValue.Kind.LONG, "test-option-1", "1"); OptionValue optionValue0 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option-0", 100); OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option-1", 111); OptionValueProtoList optionList = OptionValueProtoList.newBuilder() .addAllOptions(Arrays.asList( OptionValueProtoUtils.toOptionValueProto(optionValue0), OptionValueProtoUtils.toOptionValueProto(optionValue1))) .build(); when(kvStore.get(OPTIONS_KEY)).thenReturn(optionList); assertThat(Lists.from(som.iterator()), containsInAnyOrder(optionValue0, optionValue1)); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public boolean isSet(String name){ return getOptionProto(name) != null; } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testIsSet() { registerTestOption(OptionValue.Kind.LONG, "set-option", "0"); registerTestOption(OptionValue.Kind.LONG, "not-set-option", "1"); OptionValue optionValue = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "set-option", 123); OptionValueProtoList optionList = OptionValueProtoList.newBuilder() .addAllOptions(Collections.singletonList(OptionValueProtoUtils.toOptionValueProto(optionValue))) .build(); when(kvStore.get(OPTIONS_KEY)).thenReturn(optionList); assertTrue(som.isSet("set-option")); assertFalse(som.isSet("not-set-option")); }
### Question: SystemOptionManager extends BaseOptionManager implements Service, ProjectOptionManager { @Override public boolean isValid(String name){ return optionValidatorListing.isValid(name); } SystemOptionManager(OptionValidatorListing optionValidatorListing, LogicalPlanPersistence lpPersistence, final Provider<LegacyKVStoreProvider> storeProvider, boolean inMemory); @Override void start(); @Override boolean isValid(String name); @Override boolean isSet(String name); @Override Iterator<OptionValue> iterator(); @Override OptionValue getOption(final String name); @Override boolean setOption(final OptionValue value); @Override boolean deleteOption(final String rawName, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override void addOptionChangeListener(OptionChangeListener optionChangeListener); @Override OptionList getNonDefaultOptions(); @Override void close(); }### Answer: @Test public void testIsValid() { registerTestOption(OptionValue.Kind.LONG, "valid-option", "0"); assertTrue(som.isValid("valid-option")); assertFalse(som.isValid("invalid-option")); }
### Question: EagerCachingOptionManager extends InMemoryOptionManager { @Override public double getOption(DoubleValidator validator) { return getOption(validator.getOptionName()).getFloatVal(); } EagerCachingOptionManager(OptionManager delegate); @Override boolean setOption(OptionValue value); @Override boolean deleteOption(String name, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override double getOption(DoubleValidator validator); @Override long getOption(LongValidator validator); @Override String getOption(StringValidator validator); @Override OptionValidatorListing getOptionValidatorListing(); }### Answer: @Test public void testGetOption() { final OptionManager eagerCachingOptionManager = new EagerCachingOptionManager(optionManager); assertEquals(optionValueA, eagerCachingOptionManager.getOption(optionValueA.getName())); verify(optionManager, times(0)).getOption(optionValueA.getName()); }
### Question: EagerCachingOptionManager extends InMemoryOptionManager { @Override public boolean setOption(OptionValue value) { return super.setOption(value) && delegate.setOption(value); } EagerCachingOptionManager(OptionManager delegate); @Override boolean setOption(OptionValue value); @Override boolean deleteOption(String name, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override double getOption(DoubleValidator validator); @Override long getOption(LongValidator validator); @Override String getOption(StringValidator validator); @Override OptionValidatorListing getOptionValidatorListing(); }### Answer: @Test public void testSetOption() { final OptionManager eagerCachingOptionManager = new EagerCachingOptionManager(optionManager); final OptionValue newOption = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "newOption", true); eagerCachingOptionManager.setOption(newOption); verify(optionManager, times(1)).setOption(newOption); }
### Question: EagerCachingOptionManager extends InMemoryOptionManager { @Override public boolean deleteOption(String name, OptionType type) { return super.deleteOption(name, type) && delegate.deleteOption(name, type); } EagerCachingOptionManager(OptionManager delegate); @Override boolean setOption(OptionValue value); @Override boolean deleteOption(String name, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override double getOption(DoubleValidator validator); @Override long getOption(LongValidator validator); @Override String getOption(StringValidator validator); @Override OptionValidatorListing getOptionValidatorListing(); }### Answer: @Test public void testDeleteOption() { final OptionManager eagerCachingOptionManager = new EagerCachingOptionManager(optionManager); eagerCachingOptionManager.deleteOption(optionValueC.getName(), OptionValue.OptionType.SYSTEM); assertNull(eagerCachingOptionManager.getOption(optionValueC.getName())); verify(optionManager, times(1)).deleteOption(optionValueC.getName(), OptionValue.OptionType.SYSTEM); }
### Question: EagerCachingOptionManager extends InMemoryOptionManager { @Override public boolean deleteAllOptions(OptionType type) { return super.deleteAllOptions(type) && delegate.deleteAllOptions(type); } EagerCachingOptionManager(OptionManager delegate); @Override boolean setOption(OptionValue value); @Override boolean deleteOption(String name, OptionType type); @Override boolean deleteAllOptions(OptionType type); @Override double getOption(DoubleValidator validator); @Override long getOption(LongValidator validator); @Override String getOption(StringValidator validator); @Override OptionValidatorListing getOptionValidatorListing(); }### Answer: @Test public void testDeleteAllOptions() { final OptionManager eagerCachingOptionManager = new EagerCachingOptionManager(optionManager); eagerCachingOptionManager.deleteAllOptions(OptionValue.OptionType.SYSTEM); assertNull(eagerCachingOptionManager.getOption(optionValueA.getName())); assertNull(eagerCachingOptionManager.getOption(optionValueB.getName())); assertNull(eagerCachingOptionManager.getOption(optionValueC.getName())); verify(optionManager, times(1)).deleteAllOptions(OptionValue.OptionType.SYSTEM); }
### Question: FieldTransformationBase { public final <T> T accept(FieldTransformationVisitor<T> visitor) throws VisitorException { return acceptor.accept(visitor, this); } final T accept(FieldTransformationVisitor<T> visitor); FieldTransformation wrap(); @Override String toString(); static FieldTransformationBase unwrap(FieldTransformation t); static Converter<FieldTransformationBase, FieldTransformation> converter(); static final Acceptor<FieldTransformationBase, FieldTransformationVisitor<?>, FieldTransformation> acceptor; }### Answer: @Test public void testVisitor() { FieldTransformationBase exp = new FieldConvertToJSON(); String name = exp.accept(new FieldTransformationBase.FieldTransformationVisitor<String>() { @Override public String visit(FieldConvertCase col) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldTrim changeCase) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldExtract extract) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertFloatToInteger trim) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertFloatToDecimal calculatedField) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertDateToText fieldTransformation) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertNumberToDate numberToDate) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertDateToNumber dateToNumber) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertTextToDate textToDate) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertListToText fieldTransformation) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertToJSON fieldTransformation) throws Exception { return "json"; } @Override public String visit(FieldUnnestList unnest) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldReplacePattern replacePattern) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldReplaceCustom replacePattern) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldReplaceValue replacePattern) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldReplaceRange replaceRange) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldExtractMap extract) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldExtractList extract) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldSplit split) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldSimpleConvertToType toType) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertToTypeIfPossible toTypeIfPossible) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertToTypeWithPatternIfPossible toTypeIfPossible) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(FieldConvertFromJSON fromJson) throws Exception { throw new UnsupportedOperationException("NYI"); } }); assertEquals("json", name); }
### Question: FSDataInputStreamWrapper extends FSInputStream { public static FSInputStream of(FSDataInputStream in) throws IOException { if (in.getWrappedStream() instanceof ByteBufferReadable) { return new FSDataInputStreamWrapper(in); } return new ByteArrayFSInputStream(in); } private FSDataInputStreamWrapper(FSDataInputStream in); static FSInputStream of(FSDataInputStream in); @Override int read(); @Override int read(byte[] b); @Override int read(byte[] b, int off, int len); @Override int read(ByteBuffer dst); @Override int read(long position, ByteBuffer dst); @Override long getPosition(); @Override void setPosition(long position); @Override long skip(long n); @Override int available(); @Override void close(); @Override void mark(int readlimit); @Override void reset(); @Override boolean markSupported(); }### Answer: @Test public void test() throws Exception { Class<?> byteBufferPositionedReadableClass = getClass("org.apache.hadoop.fs.ByteBufferPositionedReadable"); assumeNonMaprProfile(); final IOException ioException = new IOException("test io exception"); final FSError fsError = newFSError(ioException); FSDataInputStream fdis = new FSDataInputStream(mock(InputStream.class, withSettings().extraInterfaces(Seekable.class, byteBufferPositionedReadableClass == null ? AutoCloseable.class : byteBufferPositionedReadableClass, PositionedReadable.class, ByteBufferReadable.class).defaultAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { throw fsError; } }))); FSInputStream fdisw = FSDataInputStreamWrapper.of(fdis); Object[] params = getDummyArguments(method); try { method.invoke(fdisw, params); } catch(InvocationTargetException e) { if (byteBufferPositionedReadableClass == null) { assertThat(e.getTargetException(), anyOf(is(instanceOf(IOException.class)), is(instanceOf(UnsupportedOperationException.class)))); } else { assertThat(e.getTargetException(), is(instanceOf(IOException.class))); } if (e.getTargetException() instanceof IOException) { assertThat((IOException) e.getTargetException(), is(sameInstance(ioException))); } } }
### Question: PermissionCheckCache { public boolean hasAccess(final String username, final NamespaceKey namespaceKey, final DatasetConfig config, final MetadataStatsCollector metadataStatsCollector, final SourceConfig sourceConfig) { final Stopwatch permissionCheck = Stopwatch.createStarted(); if (authTtlMs.get() == 0) { boolean hasAccess = checkPlugin(username, namespaceKey, config, sourceConfig); permissionCheck.stop(); metadataStatsCollector.addDatasetStat(namespaceKey.getSchemaPath(), PermissionCheckAccessType.PERMISSION_CACHE_MISS.name(), permissionCheck.elapsed(TimeUnit.MILLISECONDS)); return hasAccess; } final Key key = new Key(username, namespaceKey); final long now = System.currentTimeMillis(); final Callable<Value> loader = () -> { final boolean hasAccess = checkPlugin(username, namespaceKey, config, sourceConfig); if (!hasAccess) { throw NoAccessException.INSTANCE; } return new Value(true, now); }; Value value; try { PermissionCheckAccessType permissionCheckAccessType; value = getFromPermissionsCache(key, loader); if (now == value.createdAt) { permissionCheckAccessType = PermissionCheckAccessType.PERMISSION_CACHE_MISS; } else { permissionCheckAccessType = PermissionCheckAccessType.PERMISSION_CACHE_HIT; } if (now - value.createdAt > authTtlMs.get()) { permissionsCache.invalidate(key); value = getFromPermissionsCache(key, loader); permissionCheckAccessType = PermissionCheckAccessType.PERMISSION_CACHE_EXPIRED; } permissionCheck.stop(); metadataStatsCollector.addDatasetStat(namespaceKey.getSchemaPath(), permissionCheckAccessType.name(), permissionCheck.elapsed(TimeUnit.MILLISECONDS)); return value.hasAccess; } catch (ExecutionException e) { throw new RuntimeException("Permission check loader should not throw a checked exception", e.getCause()); } catch (UncheckedExecutionException e) { final Throwable cause = e.getCause(); if (cause instanceof UserException) { throw (UserException) cause; } throw UserException.permissionError(cause) .message("Access denied reading dataset %s.", namespaceKey.toString()) .build(logger); } } PermissionCheckCache( Provider<StoragePlugin> plugin, Provider<Long> authTtlMs, final long maximumSize); boolean hasAccess(final String username, final NamespaceKey namespaceKey, final DatasetConfig config, final MetadataStatsCollector metadataStatsCollector, final SourceConfig sourceConfig); }### Answer: @Test public void throwsProperly() throws Exception { final String username = "throwsProperly"; final StoragePlugin plugin = mock(StoragePlugin.class); final SourceConfig sourceConfig = new SourceConfig(); final PermissionCheckCache checks = new PermissionCheckCache(DirectProvider.wrap(plugin), DirectProvider.wrap(1000L), 1000); when(plugin.hasAccessPermission(anyString(), any(NamespaceKey.class), any(DatasetConfig.class))) .thenThrow(new RuntimeException("you shall not pass")); try { checks.hasAccess(username, new NamespaceKey(Lists.newArrayList("what")), null, new MetadataStatsCollector(), sourceConfig); fail(); } catch (UserException e) { assertEquals(UserBitShared.DremioPBError.ErrorType.PERMISSION, e.getErrorType()); assertEquals("Access denied reading dataset what.", e.getMessage()); } }
### Question: ExpressionBase { public final <T> T accept(ExpressionVisitor<T> visitor) throws VisitorException { return acceptor.accept(visitor, this); } final T accept(ExpressionVisitor<T> visitor); Expression wrap(); @Override String toString(); static ExpressionBase unwrap(Expression t); static Converter<ExpressionBase, Expression> converter(); static final Acceptor<ExpressionBase, ExpressionVisitor<?>, Expression> acceptor; }### Answer: @Test public void testVisitor() { ExpressionBase exp = new ExpCalculatedField("foo"); String name = exp.accept(new ExpressionBase.ExpressionVisitor<String>() { @Override public String visit(ExpColumnReference col) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(ExpConvertCase changeCase) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(ExpExtract extract) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(ExpTrim trim) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(ExpCalculatedField calculatedField) throws Exception { return "calc"; } @Override public String visit(ExpFieldTransformation fieldTransformation) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(ExpConvertType convertType) throws Exception { throw new UnsupportedOperationException("NYI"); } @Override public String visit(ExpMeasure measure) throws Exception { throw new UnsupportedOperationException("NYI"); } }); assertEquals("calc", name); }
### Question: NamespaceListing implements DatasetHandleListing { @VisibleForTesting Iterator<DatasetHandle> newIterator(Iterator<NamespaceKey> keyIterator) { return new TransformingIterator(keyIterator); } NamespaceListing( NamespaceService namespaceService, NamespaceKey sourceKey, SourceMetadata sourceMetadata, DatasetRetrievalOptions options ); @Override Iterator<? extends DatasetHandle> iterator(); }### Answer: @Test public void emptyIterator() { final NamespaceListing listing = new NamespaceListing(null, null, null, null); try { listing.newIterator(Collections.emptyIterator()).next(); fail(); } catch (NoSuchElementException expected) { } assertFalse(listing.newIterator(Collections.emptyIterator()).hasNext()); }
### Question: DayOfWeekFromSundayDateTimeField extends PreciseDurationDateTimeField { @Override public int get(long instant) { return map(chronology.dayOfWeek().get(instant)); } DayOfWeekFromSundayDateTimeField(Chronology chronology, DurationField days); @Override int get(long instant); @Override String getAsText(int fieldValue, Locale locale); @Override String getAsShortText(int fieldValue, Locale locale); @Override DurationField getRangeDurationField(); @Override int getMinimumValue(); @Override int getMaximumValue(); @Override int getMaximumTextLength(Locale locale); @Override int getMaximumShortTextLength(Locale locale); @Override String toString(); }### Answer: @Test public void get() { assertEquals(instance.get(1526173261000L), 1); assertEquals(instance.get(1526259661000L), 2); assertEquals(instance.get(1526086861000L), 7); }
### Question: DayOfWeekFromSundayDateTimeField extends PreciseDurationDateTimeField { @Override public String getAsText(int fieldValue, Locale locale) { return chronology.dayOfWeek().getAsText(reverse(fieldValue), locale); } DayOfWeekFromSundayDateTimeField(Chronology chronology, DurationField days); @Override int get(long instant); @Override String getAsText(int fieldValue, Locale locale); @Override String getAsShortText(int fieldValue, Locale locale); @Override DurationField getRangeDurationField(); @Override int getMinimumValue(); @Override int getMaximumValue(); @Override int getMaximumTextLength(Locale locale); @Override int getMaximumShortTextLength(Locale locale); @Override String toString(); }### Answer: @Test public void getAsText() { assertTrue("Sunday".equalsIgnoreCase(instance.getAsText(1526173261000L))); assertTrue("Monday".equalsIgnoreCase(instance.getAsText(1526259661000L))); assertTrue("Saturday".equalsIgnoreCase(instance.getAsText(1526086861000L))); } @Test public void getAsTextFieldValue() { assertTrue("Sunday".equalsIgnoreCase(instance.getAsText(1, Locale.getDefault()))); assertTrue("Monday".equalsIgnoreCase(instance.getAsText(2, Locale.getDefault()))); assertTrue("Saturday".equalsIgnoreCase(instance.getAsText(7, Locale.getDefault()))); }
### Question: DayOfWeekFromSundayDateTimeField extends PreciseDurationDateTimeField { @Override public String getAsShortText(int fieldValue, Locale locale) { return chronology.dayOfWeek().getAsShortText(reverse(fieldValue), locale); } DayOfWeekFromSundayDateTimeField(Chronology chronology, DurationField days); @Override int get(long instant); @Override String getAsText(int fieldValue, Locale locale); @Override String getAsShortText(int fieldValue, Locale locale); @Override DurationField getRangeDurationField(); @Override int getMinimumValue(); @Override int getMaximumValue(); @Override int getMaximumTextLength(Locale locale); @Override int getMaximumShortTextLength(Locale locale); @Override String toString(); }### Answer: @Test public void getAsShortText() { assertTrue("Sun".equalsIgnoreCase(instance.getAsShortText(1526173261000L))); assertTrue("Mon".equalsIgnoreCase(instance.getAsShortText(1526259661000L))); assertTrue("Sat".equalsIgnoreCase(instance.getAsShortText(1526086861000L))); } @Test public void getAsShortTextFieldValue() { assertTrue("Sun".equalsIgnoreCase(instance.getAsShortText(1, Locale.getDefault()))); assertTrue("Mon".equalsIgnoreCase(instance.getAsShortText(2, Locale.getDefault()))); assertTrue("Sat".equalsIgnoreCase(instance.getAsShortText(7, Locale.getDefault()))); }
### Question: ExtractListRecommender extends Recommender<ExtractListRule, Selection> { @Override public List<ExtractListRule> getRules(Selection selection, DataType selColType) { checkArgument(selColType == DataType.LIST, "Extract list items is supported only on LIST type columns"); JsonSelection jsonSelection; try { jsonSelection = new JSONElementLocator(selection.getCellText()).locate(selection.getOffset(), selection.getOffset() + selection.getLength()); } catch (IOException e) { throw new ClientErrorException(String.format("invalid JSON: %s", selection.getCellText()), e); } ArrayJsonPathElement start = extractArrayIndex(jsonSelection.getStart()); ArrayJsonPathElement end = extractArrayIndex(jsonSelection.getEnd()); List<ExtractListRule> rules = new ArrayList<>(); if (start == end) { rules.add(new ExtractListRule(single).setSingle(new ExtractRuleSingle(start.getPosition()))); } else { ListSelection[] selections = { new ListSelection(fromTheStart(start), fromTheStart(end)), new ListSelection(fromTheStart(start), fromTheEnd(end)), new ListSelection(fromTheEnd(start), fromTheStart(end)), new ListSelection(fromTheEnd(start), fromTheEnd(end)) }; for (ListSelection listSelection : selections) { rules.add((new ExtractListRule(multiple) .setMultiple( new ExtractRuleMultiple(listSelection) ))); } } return rules; } @Override List<ExtractListRule> getRules(Selection selection, DataType selColType); @Override TransformRuleWrapper<ExtractListRule> wrapRule(ExtractListRule rule); }### Answer: @Test public void ruleSuggestionsSingleElement() throws Exception { List<ExtractListRule> rules = recommender.getRules(new Selection("foo", "[ \"foo\", \"bar\", \"baz\" ]", 3, 3), DataType.LIST); assertEquals(1, rules.size()); assertEquals(ExtractListRuleType.single, rules.get(0).getType()); assertEquals(0, rules.get(0).getSingle().getIndex().intValue()); } @Test public void ruleSuggestionsMultiElement() throws Exception { List<ExtractListRule> rules = recommender.getRules(new Selection("foo", "[ \"foo\", \"bar\", \"baz\" ]", 3, 10), DataType.LIST); assertEquals(4, rules.size()); compare(new Offset(0, FROM_THE_START), new Offset(1, FROM_THE_START), rules.get(0)); compare(new Offset(0, FROM_THE_START), new Offset(1, FROM_THE_END), rules.get(1)); compare(new Offset(2, FROM_THE_END), new Offset(1, FROM_THE_START), rules.get(2)); compare(new Offset(2, FROM_THE_END), new Offset(1, FROM_THE_END), rules.get(3)); }
### Question: MorePosixFilePermissions { public static Set<PosixFilePermission> fromOctalMode(int mode) { Preconditions.checkArgument(0 <= mode && mode <= MAX_MODE, "mode should be between 0 and 0777"); final Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class); int mask = 1 << (PERMISSIONS_LENGTH - 1); for (PosixFilePermission permission: PERMISSIONS) { if ((mode & mask) != 0) { result.add(permission); } mask = mask >> 1; } return result; } private MorePosixFilePermissions(); static Set<PosixFilePermission> fromOctalMode(int mode); static Set<PosixFilePermission> fromOctalMode(String mode); }### Answer: @Test public void testFromOctalModeWithIllegalMode() { assertFails(() -> MorePosixFilePermissions.fromOctalMode(-1)); assertFails(() -> MorePosixFilePermissions.fromOctalMode(512)); assertFails(() -> MorePosixFilePermissions.fromOctalMode(Integer.MIN_VALUE)); assertFails(() -> MorePosixFilePermissions.fromOctalMode(Integer.MAX_VALUE)); assertFails(() -> MorePosixFilePermissions.fromOctalMode("-1")); assertFails(() -> MorePosixFilePermissions.fromOctalMode("8")); assertFails(() -> MorePosixFilePermissions.fromOctalMode("")); assertFails(() -> MorePosixFilePermissions.fromOctalMode("foo")); }
### Question: Path implements Comparable<Path> { public static Path of(URI uri) { return new Path(uri); } private Path(URI uri); static Path of(URI uri); static Path of(String path); static Path mergePaths(Path path1, Path path2); static Path withoutSchemeAndAuthority(Path path); String getName(); Path getParent(); Path resolve(Path path); Path resolve(String path); boolean isAbsolute(); int depth(); URI toURI(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Path that); static URI toURI(String uri); static String toString(Path path); static final String SEPARATOR; static final char SEPARATOR_CHAR; }### Answer: @Test public void testParent() { checkParent(Path.of("/foo/bar"), Path.of("/foo")); checkParent(Path.of("/foo"), Path.of("/")); checkParent(Path.of("/"), null); checkParent(Path.of("foo/bar"), Path.of("foo")); checkParent(Path.of("foo"), Path.of(".")); } @Test public void testResolveOfPath() { checkResolveOfPath(Path.of("hdfs: checkResolveOfPath(Path.of("hdfs: checkResolveOfPath(Path.of("hdfs: checkResolveOfPath(Path.of("hdfs: checkResolveOfPath(Path.of("."), Path.of("foo"), Path.of("foo")); checkResolveOfPath(Path.of("foo"), Path.of("."), Path.of("foo")); checkResolveOfPath(Path.of("/"), Path.of("."), Path.of("/")); } @Test public void testResolveOfString() { checkResolveOfString(Path.of("hdfs: checkResolveOfString(Path.of("hdfs: checkResolveOfString(Path.of("hdfs: checkResolveOfString(Path.of("hdfs: checkResolveOfString(Path.of("."), "foo", Path.of("foo")); checkResolveOfString(Path.of("foo"), ".", Path.of("foo")); checkResolveOfString(Path.of("/foo"), ".", Path.of("/foo")); checkResolveOfString(Path.of("/"), ".", Path.of("/")); }
### Question: Path implements Comparable<Path> { public static Path mergePaths(Path path1, Path path2) { final String path1Path = path1.uri.getPath(); final String path2Path = path2.uri.getPath(); if (path2Path.isEmpty()) { return path1; } final StringBuilder finalPath = new StringBuilder(path1Path.length() + path2Path.length() + 1); finalPath.append(path1Path); if (!path1Path.isEmpty() && path1Path.charAt(path1Path.length() - 1) != SEPARATOR_CHAR) { finalPath.append(SEPARATOR_CHAR); } if (path2Path.charAt(0) != SEPARATOR_CHAR) { finalPath.append(path2Path); } else { finalPath.append(path2Path.substring(1)); } try { return of(new URI(path1.uri.getScheme(), path1.uri.getAuthority(), finalPath.toString(), null, null)); } catch (URISyntaxException e) { throw new IllegalArgumentException(); } } private Path(URI uri); static Path of(URI uri); static Path of(String path); static Path mergePaths(Path path1, Path path2); static Path withoutSchemeAndAuthority(Path path); String getName(); Path getParent(); Path resolve(Path path); Path resolve(String path); boolean isAbsolute(); int depth(); URI toURI(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Path that); static URI toURI(String uri); static String toString(Path path); static final String SEPARATOR; static final char SEPARATOR_CHAR; }### Answer: @Test public void testMergePaths() { checkMergePaths(Path.of("hdfs: checkMergePaths(Path.of("hdfs: checkMergePaths(Path.of("hdfs: checkMergePaths(Path.of("hdfs: checkMergePaths(Path.of("."), Path.of("foo"), Path.of("foo")); checkMergePaths(Path.of("foo"), Path.of("."), Path.of("foo")); checkMergePaths(Path.of("/"), Path.of("."), Path.of("/")); }
### Question: Path implements Comparable<Path> { public String getName() { final String path = uri.getPath(); int index = path.lastIndexOf(SEPARATOR_CHAR); return path.substring(index + 1); } private Path(URI uri); static Path of(URI uri); static Path of(String path); static Path mergePaths(Path path1, Path path2); static Path withoutSchemeAndAuthority(Path path); String getName(); Path getParent(); Path resolve(Path path); Path resolve(String path); boolean isAbsolute(); int depth(); URI toURI(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Path that); static URI toURI(String uri); static String toString(Path path); static final String SEPARATOR; static final char SEPARATOR_CHAR; }### Answer: @Test public void testGetName() { checkGetName(Path.of("/foo/bar"), "bar"); checkGetName(Path.of("/foo/bar baz"), "bar baz"); checkGetName(Path.of(" checkGetName(Path.of("foo/bar"), "bar"); checkGetName(Path.of("hdfs: checkGetName(Path.of("hdfs: checkGetName(Path.of("file:/foo/bar baz"), "bar baz"); checkGetName(Path.of("webhdfs: }
### Question: Path implements Comparable<Path> { public boolean isAbsolute() { return uri.getPath().startsWith(SEPARATOR); } private Path(URI uri); static Path of(URI uri); static Path of(String path); static Path mergePaths(Path path1, Path path2); static Path withoutSchemeAndAuthority(Path path); String getName(); Path getParent(); Path resolve(Path path); Path resolve(String path); boolean isAbsolute(); int depth(); URI toURI(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Path that); static URI toURI(String uri); static String toString(Path path); static final String SEPARATOR; static final char SEPARATOR_CHAR; }### Answer: @Test public void testIsAbsolute() { checkIsAbsolute(Path.of("/"), true); checkIsAbsolute(Path.of("/foo"), true); checkIsAbsolute(Path.of("/foo/bar"), true); checkIsAbsolute(Path.of("foo"), false); checkIsAbsolute(Path.of("foo/bar"), false); checkIsAbsolute(Path.of(URI.create("")), false); checkIsAbsolute(Path.of("."), false); }
### Question: Path implements Comparable<Path> { public int depth() { final String path = uri.getPath(); if (path.charAt(0) == SEPARATOR_CHAR && path.length() == 1) { return 0; } int depth = 0; for (int i = 0 ; i < path.length(); i++) { if (path.charAt(i) == SEPARATOR_CHAR) { depth++; } } return depth; } private Path(URI uri); static Path of(URI uri); static Path of(String path); static Path mergePaths(Path path1, Path path2); static Path withoutSchemeAndAuthority(Path path); String getName(); Path getParent(); Path resolve(Path path); Path resolve(String path); boolean isAbsolute(); int depth(); URI toURI(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Path that); static URI toURI(String uri); static String toString(Path path); static final String SEPARATOR; static final char SEPARATOR_CHAR; }### Answer: @Test public void testDepth() { checkDepth(Path.of("/"), 0); checkDepth(Path.of("/foo"), 1); checkDepth(Path.of("/foo/bar"), 2); checkDepth(Path.of("foo"), 0); }
### Question: ServiceRegistry implements Service { public <T extends Service> T replace(@Nullable T service) { if (service == null) { return null; } final Service toReplace = wrapService(service); for(ListIterator<Service> it = services.listIterator(); it.hasNext(); ) { Service s = it.next(); if (toReplace.equals(s)) { it.remove(); try { s.close(); } catch (Exception e) { logger.warn("Exception when closing service {}", s, e); } it.add(toReplace); return service; } } throw new IllegalArgumentException("Trying to replace an unregistered service"); } ServiceRegistry(); @VisibleForTesting ServiceRegistry(boolean timerEnabled); T register(@Nullable T service); T replace(@Nullable T service); @Override void start(); @Override synchronized void close(); }### Answer: @Test public void testReplace() throws Exception { doTestReplace(false); }
### Question: DremioFutures { public static <T, X extends Exception> T getChecked( Future<T> future, Class<X> exceptionClass, Function<? super Throwable, ? extends X> mapper ) throws X { try { return Futures.getChecked(future, ExecutionException.class); } catch (ExecutionException e) { try { handleException(e, exceptionClass, mapper); throw new AssertionError(); } catch (TimeoutException ex) { throw new AssertionError(); } } } private DremioFutures(); static T getChecked( Future<T> future, Class<X> exceptionClass, Function<? super Throwable, ? extends X> mapper ); static T getChecked( Future<T> future, Class<X> exceptionClass, long timeout, TimeUnit unit, Function<? super Throwable, ? extends X> mapper ); }### Answer: @Test public void testBasic() { SettableFuture<Integer> future = SettableFuture.create(); Integer expectedValue = 1234; future.set(expectedValue); try { Integer result = DremioFutures.getChecked(future, TestException.class, TestDremioFutures::testMapper); assertEquals(result, expectedValue); } catch (TestException ignored) { throw new AssertionError(); } } @Test public void testTimeout() { SettableFuture future = SettableFuture.create(); Futures.addCallback(future, new FutureCallback<Integer>() { @Override public void onSuccess(@Nullable Integer result) { try { Thread.sleep(10000); } catch (InterruptedException ignored) { } future.set(result); } @Override public void onFailure(Throwable t) { } }, MoreExecutors.directExecutor()); try { DremioFutures.getChecked(future, TestException.class, 1, TimeUnit.MILLISECONDS, TestDremioFutures::testMapper); throw new AssertionError(); } catch (TimeoutException e) { } catch (Exception e) { throw new AssertionError(); } } @Test public void testMappingCause() { Future future = mock(Future.class); Throwable cause = new TestException("inner exception"); try { when(future.get()).thenThrow(new ExecutionException("outer exception", cause)); } catch (InterruptedException | ExecutionException ignored) { throw new AssertionError(); } try { DremioFutures.getChecked(future, TestException.class, TestDremioFutures::testMapper); throw new AssertionError(); } catch (TestException e) { assertSame(e.getCause(), cause); } catch (Exception e) { throw new AssertionError(); } }
### Question: DremioVersionUtils { public static Collection<NodeEndpoint> getCompatibleNodeEndpoints(Collection<NodeEndpoint> nodeEndpoints) { List<NodeEndpoint> compatibleNodeEndpoints = new ArrayList<>(); if (nodeEndpoints != null && !nodeEndpoints.isEmpty()) { compatibleNodeEndpoints = nodeEndpoints.stream() .filter(nep -> isCompatibleVersion(nep)) .collect(Collectors.toList()); } return Collections.unmodifiableCollection(compatibleNodeEndpoints); } static boolean isCompatibleVersion(NodeEndpoint endpoint); static boolean isCompatibleVersion(String version); static Collection<NodeEndpoint> getCompatibleNodeEndpoints(Collection<NodeEndpoint> nodeEndpoints); }### Answer: @Test public void testCompatibleNodeEndpoints() { NodeEndpoint nep1 = NodeEndpoint.newBuilder() .setAddress("localhost") .setDremioVersion(DremioVersionInfo.getVersion()) .build(); NodeEndpoint nep2 = NodeEndpoint.newBuilder() .setAddress("localhost") .setDremioVersion("incompatibleVersion") .build(); Collection<NodeEndpoint> nodeEndpoints = DremioVersionUtils.getCompatibleNodeEndpoints(Lists.newArrayList(nep1, nep2)); assertEquals(1, nodeEndpoints.size()); assertSame(nep1, nodeEndpoints.toArray()[0]); }
### Question: BackwardCompatibleSchemaDe extends StdDeserializer<Schema> { public static Schema fromJSON(String json) throws IOException { return mapper.readValue(checkNotNull(json), Schema.class); } protected BackwardCompatibleSchemaDe(); protected BackwardCompatibleSchemaDe(Class<?> vc); static Schema fromJSON(String json); @Override Schema deserialize(JsonParser jsonParser, DeserializationContext deserializationContext); }### Answer: @Test public void testBackwardCompatofSchema() throws Exception { Schema schema = DremioArrowSchema.fromJSON(OLD_SCHEMA); String newJson = schema.toJson(); assertFalse(newJson.contains("typeLayout")); }
### Question: JsonAdditionalExceptionContext implements AdditionalExceptionContext { protected static <T extends AdditionalExceptionContext> T fromUserException(Class<T> clazz, UserException ex) { if (ex.getRawAdditionalExceptionContext() == null) { logger.debug("missing additional context in UserException"); return null; } try { return ProtobufByteStringSerDe.readValue(contextMapper.readerFor(clazz), ex.getRawAdditionalExceptionContext(), ProtobufByteStringSerDe.Codec.NONE, logger); } catch (IOException ignored) { logger.debug("unable to deserialize additional exception context", ignored); return null; } } ByteString toByteString(); }### Answer: @Test public void testSerializeDeserialize() throws Exception { UserException ex = UserException.functionError() .message("test") .setAdditionalExceptionContext(new TestContext(TEST_DATA)) .build(logger); Assert.assertTrue(ex.getRawAdditionalExceptionContext() != null); Assert.assertTrue(TEST_DATA.equals(TestContext.fromUserException(ex).getData())); ex = UserException.functionError() .message("test") .build(logger); Assert.assertTrue(ex.getRawAdditionalExceptionContext() == null); Assert.assertTrue(TestContext.fromUserException(ex) == null); }
### Question: AutoCloseables { public static void close(Throwable t, AutoCloseable... autoCloseables) { close(t, Arrays.asList(autoCloseables)); } private AutoCloseables(); static AutoCloseable all(final Collection<? extends AutoCloseable> autoCloseables); static void close(Throwable t, AutoCloseable... autoCloseables); static void close(Throwable t, Iterable<? extends AutoCloseable> autoCloseables); static void close(AutoCloseable... autoCloseables); static void close(Class<E> exceptionClazz, AutoCloseable... autoCloseables); static void close(Iterable<? extends AutoCloseable> ac); @SafeVarargs static void close(Iterable<? extends AutoCloseable>... closeables); static Iterable<AutoCloseable> iter(AutoCloseable... ac); static RollbackCloseable rollbackable(AutoCloseable... closeables); static void closeNoChecked(final AutoCloseable autoCloseable); static AutoCloseable noop(); }### Answer: @Test public void testClose() { Resource r1 = new Resource(); Resource r2 = new Resource(); Resource r3 = new Resource(); Resource r4 = new Resource(); try { AutoCloseables.close( () -> r1.closeWithException(new IOException("R1 exception")), () -> r2.closeWithException(null), () -> r3.closeWithException(new RuntimeException("R3 exception")), () -> r4.closeWithException(null) ); fail("Expected exception"); } catch (Exception e) { assertEquals(IOException.class, e.getClass()); } assertTrue(r1.isClosed() && r2.isClosed() && r3.isClosed() && r4.isClosed()); } @Test(expected = IOException.class) public void testCloseWithExpectedException() throws IOException { Resource r1 = new Resource(); Resource r2 = new Resource(); AutoCloseables.close(IOException.class, () -> r1.closeWithException(new IOException("R1 exception")), () -> r2.closeWithException(new RuntimeException("R3 exception")) ); fail("Expected exception"); } @Test(expected = RuntimeException.class) public void testCloseWithExpectedRuntimeException() throws IOException { Resource r1 = new Resource(); Resource r2 = new Resource(); AutoCloseables.close(IOException.class, () -> r1.closeWithException(new RuntimeException("R1 exception")), () -> r2.closeWithException(new IOException("R3 exception")) ); fail("Expected exception"); } @Test(expected = IOException.class) public void testCloseWithExpectedWrappedException() throws IOException { Resource r1 = new Resource(); Resource r2 = new Resource(); AutoCloseables.close(IOException.class, () -> r1.closeWithException(new Exception("R1 exception")), () -> r2.closeWithException(new Exception("R3 exception")) ); fail("Expected exception"); }
### Question: ReplaceRecommender extends Recommender<ReplacePatternRule, Selection> { public static ReplaceMatcher getMatcher(ReplacePatternRule rule) { final String pattern = rule.getSelectionPattern(); ReplaceSelectionType selectionType = rule.getSelectionType(); if (rule.getIgnoreCase() != null && rule.getIgnoreCase()) { return new ToLowerReplaceMatcher(getMatcher(pattern.toLowerCase(), selectionType)); } else { return getMatcher(pattern, selectionType); } } @Override List<ReplacePatternRule> getRules(Selection selection, DataType selColType); TransformRuleWrapper<ReplacePatternRule> wrapRule(ReplacePatternRule rule); static ReplaceMatcher getMatcher(ReplacePatternRule rule); }### Answer: @Test public void testMatcher() { ReplaceMatcher matcher = ReplaceRecommender.getMatcher( new ReplacePatternRule(ReplaceSelectionType.MATCHES) .setSelectionPattern("[ac]") .setIgnoreCase(false)); Match match = matcher.matches("abc"); assertNotNull(match); assertEquals("Match(0, 1)", match.toString()); }
### Question: TracingUtils { public static <R> R trace(Function<Span, R> work, Tracer tracer, String operation, String... tags) { Span span = TracingUtils.buildChildSpan(tracer, operation, tags); try (Scope s = tracer.activateSpan(span)) { return work.apply(span); } finally { span.finish(); } } private TracingUtils(); static Tracer.SpanBuilder childSpanBuilder(Tracer tracer, String spanName, String... tags); static Tracer.SpanBuilder childSpanBuilder(Tracer tracer, Span parent, String spanName, String... tags); static Span buildChildSpan(Tracer tracer, String spanName, String... tags); static R trace(Function<Span, R> work, Tracer tracer, String operation, String... tags); static R trace(Supplier<R> work, Tracer tracer, String operation, String... tags); static void trace(Consumer<Span> work, Tracer tracer, String operation, String... tags); static void trace(Runnable work, Tracer tracer, String operation, String... tags); }### Answer: @Test public void testTraceWrapperFunction() { MockSpan parent = tracer.buildSpan("parent").start(); final MockSpan[] child = new MockSpan[1]; final int ret; try(Scope s = tracer.activateSpan(parent)) { ret = TracingUtils.trace( (span) -> { span.log("someRunTimeEvent"); child[0] = ((MockSpan) span); return 42; }, tracer, "child-work", "tag1", "val1", "tag2", "val2"); } assertEquals(42, ret); assertEquals(parent.context().spanId(), child[0].parentId()); assertEquals("child-work",child[0].operationName()); assertEquals(tracer.finishedSpans().get(0), child[0]); final Map<String, Object> expectedTags = new HashMap<>(); expectedTags.put("tag1", "val1"); expectedTags.put("tag2", "val2"); assertEquals(expectedTags, child[0].tags()); assertEquals(1, child[0].logEntries().size()); }
### Question: ContextMigratingExecutorService implements ExecutorService { @Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(decorate(task)); } ContextMigratingExecutorService(E delegate, Tracer tracer); @Override void shutdown(); @Override List<Runnable> shutdownNow(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override Future<T> submit(Callable<T> task); @Override Future<T> submit(Runnable task, T result); @Override Future<?> submit(Runnable task); @Override void execute(Runnable command); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); @Override T invokeAny(Collection<? extends Callable<T>> tasks); @Override T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); E getDelegate(); static final String WORK_OPERATION_NAME; static final String WAITING_OPERATION_NAME; }### Answer: @Test public void testRunnableDecoration() throws InterruptedException, ExecutionException { Span[] runnableSpan = new Span[1]; try (Scope s = tracer.activateSpan(testSpan)) { Future<?> future = pool.submit(() -> { runnableSpan[0] = tracer.activeSpan(); }); future.get(); } assertChildSpan(runnableSpan[0]); } @Test public void testContextWithCallable() throws Exception { final String testUser = "testUser1"; Callable<String> callable = () -> RequestContext.current().get(UserContext.CTX_KEY).serialize(); Future<String> future = RequestContext.empty() .with(UserContext.CTX_KEY, new UserContext(testUser)) .call(() -> pool.submit(callable)); Assert.assertEquals(testUser, future.get()); } @Test public void testContextWithRunnable() throws Exception { final String testUser = "testUser2"; final Pointer<String> foundUser = new Pointer<>(); Runnable runnable = () -> foundUser.value = RequestContext.current().get(UserContext.CTX_KEY).serialize(); Future<?> future = RequestContext.empty() .with(UserContext.CTX_KEY, new UserContext(testUser)) .call(() -> pool.submit(runnable)); future.get(); Assert.assertEquals(testUser, foundUser.value); }
### Question: GuiceServiceModule extends AbstractModule { public void close(Injector injector) throws Exception { serviceList.forEach((clazz) -> { final Object instance = injector.getInstance(clazz); if (instance instanceof Service) { try { logger.debug("stopping {}", instance.getClass().toString()); ((Service) instance).close(); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } } }); } GuiceServiceModule(); void close(Injector injector); }### Answer: @Test public void testMultiBind() throws Exception { final GuiceServiceModule guiceServiceHandler = new GuiceServiceModule(); final Injector injector = Guice.createInjector(guiceServiceHandler, new MultiBindModule()); final MultiImpl bInstance = (MultiImpl) injector.getInstance(B.class); final MultiImpl cInstance = (MultiImpl) injector.getInstance(C.class); assertEquals(bInstance, cInstance); assertEquals(1, bInstance.getStarted()); guiceServiceHandler.close(injector); assertEquals(1, bInstance.getClosed()); }
### Question: BlackListOutput implements Output { @Override public void writeInt32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeInt32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }### Answer: @Test public void writeInt32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeInt32(1, 9, false); subject.writeInt32(2, 8, false); Mockito.verify(delegate).writeInt32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
### Question: BlackListOutput implements Output { @Override public void writeUInt32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeUInt32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }### Answer: @Test public void writeUInt32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeUInt32(1, 9, false); subject.writeUInt32(2, 8, false); Mockito.verify(delegate).writeUInt32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
### Question: BlackListOutput implements Output { @Override public void writeSInt32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeSInt32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }### Answer: @Test public void writeSInt32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeSInt32(1, 9, false); subject.writeSInt32(2, 8, false); Mockito.verify(delegate).writeSInt32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
### Question: BlackListOutput implements Output { @Override public void writeFixed32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeFixed32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }### Answer: @Test public void writeFixed32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeFixed32(1, 9, false); subject.writeFixed32(2, 8, false); Mockito.verify(delegate).writeFixed32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }