method2testcases
stringlengths 118
3.08k
|
---|
### Question:
AttemptsHelper { public Long getQueuedTime() { return getDuration(State.QUEUED); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetQueuedTime() { Preconditions.checkNotNull(attemptsHelper.getQueuedTime()); assertTrue(1L == attemptsHelper.getQueuedTime()); } |
### Question:
AttemptsHelper { public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetExecutionPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getExecutionPlanningTime()); assertTrue(1L == attemptsHelper.getExecutionPlanningTime()); } |
### Question:
AttemptsHelper { public Long getStartingTime() { return getDuration(State.STARTING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetStartingTime() { Preconditions.checkNotNull(attemptsHelper.getStartingTime()); assertTrue(1L == attemptsHelper.getStartingTime()); } |
### Question:
AttemptsHelper { public Long getRunningTime() { return getDuration(State.RUNNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetRunningTime() { Preconditions.checkNotNull(attemptsHelper.getRunningTime()); assertTrue(1L == attemptsHelper.getRunningTime()); } |
### Question:
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMetrics); }### Answer:
@Test public void testCombine() { CoordExecRPC.QueryProgressMetrics metrics1 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(100) .build(); CoordExecRPC.QueryProgressMetrics metrics2 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(120) .build(); assertEquals(0, MetricsCombiner.combine(Stream.empty()).getRowsProcessed()); assertEquals(100, MetricsCombiner.combine(Stream.of(metrics1)).getRowsProcessed()); assertEquals(220, MetricsCombiner.combine(Stream.of(metrics1, metrics2)).getRowsProcessed()); } |
### Question:
KeyPair extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2> KeyPair<K1, K2> of(List<Object> list) { checkArgument(list.size() == 2, "list should be of size 2, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) list.get(1); return new KeyPair<>(value1, value2); } KeyPair(K1 key1, K2 key2); @SuppressWarnings("unchecked") static KeyPair<K1, K2> of(List<Object> list); @Override Object get(int index); @Override int size(); K1 getKey1(); K2 getKey2(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } KeyPair<String, String> keyPair = KeyPair.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values, keyPair); } |
### Question:
KeyUtils { public static String toString(Object key) { if (null == key) { return null; } return (key instanceof byte[] ? Arrays.toString((byte[]) key) : key.toString()); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); }### Answer:
@Test public void testToStringNull() { assertNull(KeyUtils.toString(null)); }
@Test public void testToStringBytes() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString(new byte[]{1, 2, 3, 4})); }
@Test public void testToStringString() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString("[1, 2, 3, 4]")); }
@Test public void testToStringProtoStringBytesKeyPair() { assertEquals("KeyPair{ key1=somestring, key2=[1, 23, 43, 5]}", KeyUtils.toString( new KeyPair<>("somestring", new byte[]{1, 23, 43, 5}))); }
@Test public void testToStringProtoByteKeyPairByteKeyTriple() { assertEquals("KeyTriple{ key1=[123, 127, 9, 0], key2=KeyPair{ key1=somestring, key2=[1, 23, 43, 5]}, key3=[0, 0, 0, 0]}", KeyUtils.toString( new KeyTriple<>( new byte[]{123, 127, 9, 0}, new KeyPair<>("somestring", new byte[]{1, 23, 43, 5}), new byte[]{0, 0, 0, 0}))); } |
### Question:
AdminCommandRunner { static void runCommand(String commandName, Class<?> command, String[] commandArgs) throws Exception { final Method mainMethod = command.getMethod("main", String[].class); Preconditions.checkState(Modifier.isStatic(mainMethod.getModifiers()) && Modifier.isPublic(mainMethod.getModifiers()), "#main(String[]) must have public and static modifiers"); final Object[] objects = new Object[1]; objects[0] = commandArgs; try { mainMethod.invoke(null, objects); } catch (final ReflectiveOperationException e) { final Throwable cause = e.getCause() != null ? e.getCause() : e; Throwables.throwIfUnchecked(cause); throw new RuntimeException(String.format("Failed to run '%s' command", commandName), e); } } static void main(String[] args); }### Answer:
@Test public void runCommand() throws Exception { assertFalse(TestCommand.invokedCorrectly); AdminCommandRunner.runCommand("test-command", TestCommand.class, new String[]{"arg0", "arg1"}); assertTrue(TestCommand.invokedCorrectly); } |
### Question:
KeyUtils { public static int hash(Object... keys) { if (null == keys) { return 0; } int result = 1; for (Object key : keys) { result = 31 * result + hashCode(key); } return result; } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); }### Answer:
@Test public void testHashBytes() { assertEquals(918073283, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6})); }
@Test public void testHashBytesAndString() { assertEquals(214780274, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6}, "test hash string")); }
@Test public void testHashBytesAndStringAndNull() { assertEquals(-1931746098, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6}, "test hash string", null)); }
@Test public void testHashString() { assertEquals(1819279604, KeyUtils.hash("test hash string")); }
@Test public void testHashNull() { assertEquals(0, KeyUtils.hash(null)); } |
### Question:
KeyTriple extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2, K3> KeyTriple<K1, K2, K3> of(List<Object> list) { checkArgument(list.size() == 3, "list should be of size 3, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) list.get(1); final K3 value3 = (K3) list.get(2); return new KeyTriple<>(value1, value2, value3); } KeyTriple(K1 key1, K2 key2, K3 key3); @SuppressWarnings("unchecked") static KeyTriple<K1, K2, K3> of(List<Object> list); @Override Object get(int index); @Override int size(); K1 getKey1(); K2 getKey2(); K3 getKey3(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } final KeyTriple<String, String, String> keyPair = KeyTriple.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values.get(2), keyPair.getKey3()); assertEquals(values, keyPair); } |
### Question:
ReIndexer implements ReplayHandler { @Override public void put(String tableName, byte[] key, byte[] value) { if (!isIndexed(tableName)) { logger.trace("Ignoring put: {} on table '{}'", key, tableName); return; } final KVStoreTuple<?> keyTuple = keyTuple(tableName, key); final Document document = toDoc(tableName, keyTuple, valueTuple(tableName, value)); if (document != null) { indexManager.getIndex(tableName) .update(keyAsTerm(keyTuple), document); metrics(tableName).puts++; } } ReIndexer(IndexManager indexManager, Map<String, StoreWithId<?, ?>> idToStore); @Override void put(String tableName, byte[] key, byte[] value); @Override void delete(String tableName, byte[] key); }### Answer:
@Test public void add() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] added = {false}; doAnswer(invocation -> { added[0] = true; return null; }).when(index).update(any(Term.class), any(Document.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reIndexer.put(storeName, one, two); assertTrue(added[0]); } |
### Question:
ExportProfiles { private static void exportOffline(ExportProfilesOptions options, DACConfig dacConfig) throws Exception { Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("No database found. Profiles are not exported"); return; } try (LocalKVStoreProvider kvStoreProvider = providerOptional.get()) { kvStoreProvider.start(); exportOffline(options, kvStoreProvider.asLegacy()); } } static void main(String[] args); }### Answer:
@Test public void testOffline() throws Exception { final String tmpPath = folder0.newFolder("testOffline").getAbsolutePath(); final LegacyKVStoreProvider localKVStoreProvider = l(LegacyKVStoreProvider.class); final LegacyKVStoreProvider spy = spy(localKVStoreProvider); Mockito.doNothing().when(spy).close(); final String[] args = {"-o", "--output", tmpPath, "--format", "JSON", "--write-mode", "FAIL_IF_EXISTS"}; final ExportProfiles.ExportProfilesOptions options = getExportOptions(args); ExportProfiles.exportOffline(options, spy); verifyResult(tmpPath, queryProfile, String.join(" ", args)); } |
### Question:
ReIndexer implements ReplayHandler { @Override public void delete(String tableName, byte[] key) { if (!isIndexed(tableName)) { logger.trace("Ignoring delete: {} on table '{}'", key, tableName); return; } indexManager.getIndex(tableName) .deleteDocuments(keyAsTerm(keyTuple(tableName, key))); metrics(tableName).deletes++; } ReIndexer(IndexManager indexManager, Map<String, StoreWithId<?, ?>> idToStore); @Override void put(String tableName, byte[] key, byte[] value); @Override void delete(String tableName, byte[] key); }### Answer:
@Test public void delete() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] deleted = {false}; doAnswer(invocation -> { deleted[0] = true; return null; }).when(index).deleteDocuments(any(Term.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reIndexer.delete(storeName, one); assertTrue(deleted[0]); } |
### Question:
TracingKVStore implements KVStore<K, V> { @Override public Document<K, V> get(K key, GetOption... options) { return trace("get", () -> delegate.get(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate); @Override Document<K, V> get(K key, GetOption... options); @Override Iterable<Document<K, V>> get(List<K> keys, GetOption... options); @Override boolean contains(K key, ContainsOption... options); @Override Document<K, V> put(K key, V value, PutOption... options); @Override Iterable<Document<K, V>> find(FindOption... options); @Override Iterable<Document<K, V>> find(FindByRange<K> find, FindOption... options); @Override void delete(K key, DeleteOption... options); @Override KVAdmin getAdmin(); @Override String getName(); static final String METHOD_TAG; static final String TABLE_TAG; static final String OPERATION_NAME; static final String CREATOR_TAG; }### Answer:
@Test public void testTypedReturnMethod() { setupLegitParentSpan(); when(delegate.get("myKey")).thenReturn(new TestDocument("myKey","yourValue")); Document<String, String> ret = underTest.get("myKey"); assertEquals("yourValue", ret.getValue()); assertChildSpanMethod("get"); } |
### Question:
TracingKVStore implements KVStore<K, V> { @Override public void delete(K key, DeleteOption... options) { trace("delete", () -> delegate.delete(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate); @Override Document<K, V> get(K key, GetOption... options); @Override Iterable<Document<K, V>> get(List<K> keys, GetOption... options); @Override boolean contains(K key, ContainsOption... options); @Override Document<K, V> put(K key, V value, PutOption... options); @Override Iterable<Document<K, V>> find(FindOption... options); @Override Iterable<Document<K, V>> find(FindByRange<K> find, FindOption... options); @Override void delete(K key, DeleteOption... options); @Override KVAdmin getAdmin(); @Override String getName(); static final String METHOD_TAG; static final String TABLE_TAG; static final String OPERATION_NAME; static final String CREATOR_TAG; }### Answer:
@Test public void testVoidReturnMethod() { setupLegitParentSpan(); underTest.delete("byebye"); verify(delegate).delete("byebye"); assertChildSpanMethod("delete"); } |
### Question:
ResetCatalogSearch { static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); parse(args); if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Reset catalog search should be run on master node"); } final Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("Failed to complete catalog search reset. No KVStore detected."); return; } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); AdminLogger.log("Resetting catalog search..."); final ConfigurationStore configStore = new ConfigurationStore(provider.asLegacy()); configStore.delete(CONFIG_KEY); AdminLogger.log("Catalog search reset will be completed in 1 minute after Dremio starts."); } } static void main(String[] args); }### Answer:
@Test public void testResetCatalogSearchCommand() throws Exception { getCurrentDremioDaemon().close(); ResetCatalogSearch.go(new String[] {}); final Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(getDACConfig().getConfig()); if (!providerOptional.isPresent()) { throw new Exception("No KVStore detected."); } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); final ConfigurationStore configStore = new ConfigurationStore(provider.asLegacy()); final ConfigurationEntry configurationEntry = configStore.get(CONFIG_KEY); assertEquals(configurationEntry, null); } } |
### Question:
KVStoreOptionUtility { public static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options) { if (null == options || options.length == 0) { return; } for (KVStore.KVStoreOption option : options) { if (option instanceof IndexPutOption) { throw new IllegalArgumentException("IndexPutOption not supported."); } } } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); }### Answer:
@Test public void testIndexPutOptionNotSupportedNull() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(); }
@Test public void testIndexPutOptionNotSupportedEmpty() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{}); }
@Test public void testIndexPutOptionNotSupportedSingleCreate() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption}); }
@Test public void testIndexPutOptionNotSupportedSingleVersion() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{versionOption}); }
@Test public void testIndexPutOptionNotSupportedCreateAndVersion() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testIndexPutOptionNotSupportedIndexPutOptionFound() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{indexPutOption}); }
@Test(expected = IllegalArgumentException.class) public void testIndexPutOptionNotSupportedIndexPutOptionFoundAmongMany() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption, indexPutOption, versionOption}); } |
### Question:
DateUtils { public static long getStartOfLastMonth() { LocalDate now = LocalDate.now(); LocalDate targetDate = now.minusDays(now.getDayOfMonth() - 1).minusMonths(1); Instant instant = targetDate.atStartOfDay().toInstant(ZoneOffset.UTC); return instant.toEpochMilli(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testGetStartOfLastMonth() { LocalDate dateLastMonth = LocalDate.now().minusMonths(1); long startOfLastMonth = DateUtils.getStartOfLastMonth(); LocalDate dateStartOfLastMonth = DateUtils.fromEpochMillis(startOfLastMonth); assertEquals(dateLastMonth.getMonthValue(), dateStartOfLastMonth.getMonthValue()); assertEquals(dateLastMonth.getYear(), dateStartOfLastMonth.getYear()); assertEquals(1, dateStartOfLastMonth.getDayOfMonth()); } |
### Question:
KVStoreOptionUtility { public static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options) { if (null == options) { return null; } return Arrays .stream(options) .filter(option -> !(option instanceof IndexPutOption)) .toArray(KVStore.PutOption[]::new); } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); }### Answer:
@Test public void testRemoveIndexPutOption() { testRemoveIndexPutOptions( new KVStore.PutOption[]{indexPutOption}, new KVStore.PutOption[]{}); } |
### Question:
DateUtils { public static LocalDate getLastSundayDate(final LocalDate dateWithinWeek) { int dayOfWeek = dateWithinWeek.getDayOfWeek().getValue(); dayOfWeek = (dayOfWeek == 7) ? 0 : dayOfWeek; return dateWithinWeek.minusDays(dayOfWeek); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testGetLastSundayDate() { LocalDate testDate1 = LocalDate.parse("2020-03-29"); LocalDate date1LastSunday = DateUtils.getLastSundayDate(testDate1); assertEquals(testDate1, date1LastSunday); LocalDate testDate2 = LocalDate.parse("2020-03-28"); LocalDate date2LastSunday = DateUtils.getLastSundayDate(testDate2); assertEquals(LocalDate.parse("2020-03-22"), date2LastSunday); } |
### Question:
ReflectionGoalChecker { public static boolean checkGoal(ReflectionGoal goal, Materialization materialization) { return Instance.isEqual(goal, materialization.getReflectionGoalVersion()); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, String version); static boolean checkGoal(ReflectionGoal goal, Materialization materialization); static boolean checkGoal(ReflectionGoal goal, ReflectionEntry entry); static final ReflectionGoalChecker Instance; }### Answer:
@Test public void testMatchesTag() { final String testTag = "testTag"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag(testTag); assertTrue(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMatchesVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(Long.valueOf(testTag)); assertTrue(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMismatchNonNullVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(0L); assertFalse(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMismatchNullVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(null); assertFalse(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); } |
### Question:
ReflectionGoalChecker { public boolean checkHash(ReflectionGoal goal, ReflectionEntry entry){ if(null == entry.getReflectionGoalHash()){ return false; } return entry.getReflectionGoalHash().equals(calculateReflectionGoalVersion(goal)); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, String version); static boolean checkGoal(ReflectionGoal goal, Materialization materialization); static boolean checkGoal(ReflectionGoal goal, ReflectionEntry entry); static final ReflectionGoalChecker Instance; }### Answer:
@Test public void testCheckHashAgainstHash(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionEntry entry = new ReflectionEntry() .setReflectionGoalHash(new ReflectionGoalHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); assertTrue(ReflectionGoalChecker.Instance.checkHash(goal, entry)); }
@Test public void testCheckHashAgainstNullHash(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionEntry entry = new ReflectionEntry(); assertFalse(ReflectionGoalChecker.Instance.checkHash(goal, entry)); } |
### Question:
DateUtils { public static LocalDate getMonthStartDate(final LocalDate dateWithinMonth) { int dayOfMonth = dateWithinMonth.getDayOfMonth(); return dateWithinMonth.minusDays((dayOfMonth - 1)); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testGetMonthStartDate() { LocalDate testDate1 = LocalDate.parse("2020-03-01"); LocalDate monthStartDate = DateUtils.getMonthStartDate(testDate1); assertEquals(testDate1, monthStartDate); LocalDate testDate2 = LocalDate.parse("2020-03-31"); LocalDate date2MonthStartDate = DateUtils.getMonthStartDate(testDate2); assertEquals(testDate1, date2MonthStartDate); } |
### Question:
OptionList extends ArrayList<OptionValue> { public void mergeIfNotPresent(OptionList list) { final Set<OptionValue> options = Sets.newTreeSet(this); for (OptionValue optionValue : list) { if (options.add(optionValue)) { this.add(optionValue); } } } void merge(OptionList list); void mergeIfNotPresent(OptionList list); OptionList getSystemOptions(); OptionList getNonSystemOptions(); }### Answer:
@Test public void testMergeOptionLists() { final OptionValue optionValue0 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test-option0", false); final OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option1", 2); final OptionValue optionValue2 = OptionValue.createLong(OptionValue.OptionType.SESSION, "test-option2", 4); final OptionValue optionValue3 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test-option0", true); final OptionValue optionValue4 = OptionValue.createLong(OptionValue.OptionType.SESSION, "test-option1", 2); final OptionList localList = new OptionList(); localList.add(optionValue0); localList.add(optionValue1); localList.add(optionValue2); final OptionList changedList = new OptionList(); changedList.add(optionValue3); changedList.add(optionValue4); final OptionList expectedList = new OptionList(); expectedList.add(optionValue3); expectedList.add(optionValue4); expectedList.add(optionValue1); expectedList.add(optionValue2); changedList.mergeIfNotPresent(localList); assert changedList.equals(expectedList) : String.format("OptionLists merge incorrectly.\n\nexpected: %s \n\n" + "returned: %s", expectedList, changedList); } |
### Question:
DateUtils { public static LocalDate fromEpochMillis(final long epochMillis) { return Instant.ofEpochMilli(epochMillis).atZone(ZoneOffset.UTC).toLocalDate(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testFromEpochMillis() { LocalDate extractedDate = DateUtils.fromEpochMillis(System.currentTimeMillis()); assertEquals(LocalDate.now(), extractedDate); } |
### Question:
PathUtils { public static final String join(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part:parts) { Preconditions.checkNotNull(part, "parts cannot contain null"); if (!Strings.isNullOrEmpty(part)) { sb.append(part).append("/"); } } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } final String path = sb.toString(); return normalize(path); } static final String join(final String... parts); static final String normalize(final String path); }### Answer:
@Test(expected = NullPointerException.class) public void testNullSegmentThrowsNPE() { PathUtils.join("", null, ""); }
@Test public void testJoinPreservesAbsoluteOrRelativePaths() { final String actual = PathUtils.join("/a", "/b", "/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, actual); final String actual2 = PathUtils.join("/a", "b", "c"); final String expected2 = "/a/b/c"; Assert.assertEquals("invalid path", expected2, actual2); final String actual3 = PathUtils.join("a", "b", "c"); final String expected3 = "a/b/c"; Assert.assertEquals("invalid path", expected3, actual3); final String actual4 = PathUtils.join("a", "", "c"); final String expected4 = "a/c"; Assert.assertEquals("invalid path", expected4, actual4); final String actual5 = PathUtils.join("", "", "c"); final String expected5 = "c"; Assert.assertEquals("invalid path", expected5, actual5); final String actual6 = PathUtils.join("", "", ""); final String expected6 = ""; Assert.assertEquals("invalid path", expected6, actual6); final String actual7 = PathUtils.join("", "", "/"); final String expected7 = "/"; Assert.assertEquals("invalid path", expected7, actual7); final String actual8 = PathUtils.join("", "", "c/"); final String expected8 = "c/"; Assert.assertEquals("invalid path", expected8, actual8); } |
### Question:
PathUtils { public static final String normalize(final String path) { if (Strings.isNullOrEmpty(Preconditions.checkNotNull(path))) { return path; } final StringBuilder builder = new StringBuilder(); char last = path.charAt(0); builder.append(last); for (int i=1; i<path.length(); i++) { char cur = path.charAt(i); if (last == '/' && cur == last) { continue; } builder.append(cur); last = cur; } return builder.toString(); } static final String join(final String... parts); static final String normalize(final String path); }### Answer:
@Test public void testNormalizeRemovesRedundantForwardSlashes() { final String actual = PathUtils.normalize("/a/b/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, actual); final String actual2 = PathUtils.normalize(" final String expected2 = "/a/b/c"; Assert.assertEquals("invalid path", expected2, actual2); final String actual3 = PathUtils.normalize(" final String expected3 = "/"; Assert.assertEquals("invalid path", expected3, actual3); final String actual4 = PathUtils.normalize("/a"); final String expected4 = "/a"; Assert.assertEquals("invalid path", expected4, actual4); final String actual5 = PathUtils.normalize(" final String expected5 = "/"; Assert.assertEquals("invalid path", expected5, actual5); final String actual6 = PathUtils.normalize(""); final String expected6 = ""; Assert.assertEquals("invalid path", expected6, actual6); } |
### Question:
QueueProcessor implements AutoCloseable { public QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer) { this.name = name; this.lockSupplier = lockSupplier; this.consumer = consumer; this.queue = new LinkedBlockingQueue<>(); this.workerThread = null; this.isClosed = false; this.completed = true; } QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer); void enqueue(T event); void start(); @VisibleForTesting boolean completed(); void close(); }### Answer:
@Test public void testQueueProcessor() throws Exception { Pointer<Long> counter = new Pointer<>(0L); final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); Lock readLock = rwlock.readLock(); Lock writeLock = rwlock.writeLock(); QueueProcessor<Long> qp = new QueueProcessor<>("queue-processor", () -> new AutoCloseableLock(writeLock).open(), (i) -> counter.value += i); qp.start(); final long totalCount = 100_000; final long numBatches = 10; final long batchCount = totalCount / numBatches; for (long i = 0; i < totalCount; i++) { qp.enqueue(new Long(i)); if (i % batchCount == (batchCount - 1)) { Thread.sleep(1); } } final long timeout = 5_000; long loopCount = 0; long expectedValue = totalCount * (totalCount - 1) / 2; while (getValue(counter, readLock) != expectedValue) { Thread.sleep(1); assertTrue(String.format("Timed out after %d ms", timeout), loopCount++ < timeout); } qp.close(); } |
### Question:
JmxConfigurator extends ReporterConfigurator { @Override public void configureAndStart(String name, MetricRegistry registry, MetricFilter filter) { reporter = JmxReporter.forRegistry(registry).convertRatesTo(rateUnit).convertDurationsTo(durationUnit).filter(filter).build(); reporter.start(); } @JsonCreator JmxConfigurator(
@JsonProperty("rate") TimeUnit rateUnit,
@JsonProperty("duration") TimeUnit durationUnit); @Override void configureAndStart(String name, MetricRegistry registry, MetricFilter filter); @Override int hashCode(); @Override boolean equals(Object other); @Override void close(); }### Answer:
@Test public void testConfigureAndStart() throws IOException, InterruptedException, MalformedObjectNameException { final MetricRegistry metrics = new MetricRegistry(); metrics.counter(NAME, () -> { Counter counter = new Counter(); counter.inc(1234); return counter; }); final JmxConfigurator configurator = new JmxConfigurator(TimeUnit.SECONDS, TimeUnit.MILLISECONDS); configurator.configureAndStart("test", metrics, new MetricFilter() { @Override public boolean matches(String s, Metric metric) { return true; } }); final Set<ObjectInstance> beans = ManagementFactory.getPlatformMBeanServer().queryMBeans(new ObjectName(OBJECT_NAME), null); assertEquals(1, beans.size()); assertEquals(OBJECT_NAME, beans.iterator().next().getObjectName().getCanonicalName()); } |
### Question:
LocalSchedulerService implements SchedulerService { @Override public void close() throws Exception { LOGGER.info("Stopping SchedulerService"); AutoCloseables.close(AutoCloseables.iter(executorService), taskLeaderElectionServiceMap.values()); LOGGER.info("Stopped SchedulerService"); } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting LocalSchedulerService(CloseableSchedulerThreadPool executorService,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting CloseableSchedulerThreadPool getExecutorService(); @Override void close(); @Override void start(); @Override Cancellable schedule(Schedule schedule, Runnable task); }### Answer:
@Test public void close() throws Exception { final CloseableSchedulerThreadPool executorService = mock(CloseableSchedulerThreadPool.class); final LocalSchedulerService service = new LocalSchedulerService(executorService, null, null, false); service.close(); verify(executorService).close(); } |
### Question:
LocalSchedulerService implements SchedulerService { @VisibleForTesting public CloseableSchedulerThreadPool getExecutorService() { return executorService; } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting LocalSchedulerService(CloseableSchedulerThreadPool executorService,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting CloseableSchedulerThreadPool getExecutorService(); @Override void close(); @Override void start(); @Override Cancellable schedule(Schedule schedule, Runnable task); }### Answer:
@Test public void newThread() { LocalSchedulerService service = new LocalSchedulerService(1); final Runnable runnable = mock(Runnable.class); final Thread thread = service.getExecutorService().getThreadFactory().newThread(runnable); assertTrue("thread should be a daemon thread", thread.isDaemon()); assertTrue("thread name should start with scheduler-", thread.getName().startsWith("scheduler-")); } |
### Question:
IncludesExcludesFilter implements MetricFilter { @Override public boolean matches(String name, Metric metric) { if (includes.isEmpty() || matches(name, includes)) { return allowedViaExcludes(name); } return false; } IncludesExcludesFilter(List<String> includes, List<String> excludes); @Override boolean matches(String name, Metric metric); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void onlyExclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList(), Arrays.asList("a.*")); assertFalse(f.matches("alpha", null)); assertTrue(f.matches("beta", null)); }
@Test public void onlyInclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList("a.*"), Arrays.asList()); assertTrue(f.matches("alpha", null)); assertFalse(f.matches("beta", null)); }
@Test public void includeAndExclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList("a.*"), Arrays.asList("a\\.b.*")); assertTrue(f.matches("a.alpha", null)); assertFalse(f.matches("a.beta", null)); }
@Test public void noValues() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList(), Arrays.asList()); assertTrue(f.matches(null, null)); } |
### 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:
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:
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:
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:
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:
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 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:
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:
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:
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:
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 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:
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:
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:
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:
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:
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:
UUIDAdapter { public static byte[] getBytesFromUUID(UUID uuid) { byte[] result = new byte[16]; long msb = uuid.getMostSignificantBits(); long lsb = uuid.getLeastSignificantBits(); for (int i =15;i>=8;i--) { result[i] = (byte) (lsb & 0xFF); lsb >>= 8; } for (int i =7;i>=0;i--) { result[i] = (byte) (msb & 0xFF); msb >>= 8; } return result; } private UUIDAdapter(); static byte[] getBytesFromUUID(UUID uuid); static UUID getUUIDFromBytes(byte[] bytes); }### Answer:
@Test public void testGet16BytesFromUUID() { UUID uuid = UUID.randomUUID(); byte[] result = UUIDAdapter.getBytesFromUUID(uuid); assertEquals("Expected result to be a byte array with 16 elements.", 16, result.length); }
@Test public void testShouldNotGenerateSameUUIDFromBytes() { UUID uuid = UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"); byte[] result = UUIDAdapter.getBytesFromUUID(uuid); UUID newUuid = UUID.nameUUIDFromBytes(result); assertFalse(uuid.equals(newUuid)); } |
### Question:
SqlUtils { public static boolean isKeyword(String id) { Preconditions.checkState(RESERVED_SQL_KEYWORDS != null, "SQL reserved keyword list is not loaded. Please check the logs for error messages."); return RESERVED_SQL_KEYWORDS.contains(id.toUpperCase()); } static String quotedCompound(List<String> strings); static String quoteIdentifier(final String id); static boolean isKeyword(String id); static final String stringLiteral(String value); static List<String> parseSchemaPath(String schemaPath); static final String LEGACY_USE_BACKTICKS; static final char QUOTE; static final String QUOTE_WITH_ESCAPE; static ImmutableSet<String> RESERVED_SQL_KEYWORDS; static Function<String, String> QUOTER; }### Answer:
@Test public void testIsKeyword() { assertTrue(SqlUtils.isKeyword("USER")); assertTrue(SqlUtils.isKeyword("FiLeS")); assertFalse(SqlUtils.isKeyword("myUSER")); } |
### Question:
SqlUtils { public static String quoteIdentifier(final String id) { if (id.isEmpty()) { return id; } if (isKeyword(id)) { return quoteString(id); } if (Character.isAlphabetic(id.charAt(0)) && ALPHANUM_MATCHER.matchesAllOf(id)) { return id; } if (NEWLINE_MATCHER.matchesAnyOf(id)) { return quoteUnicodeString(id); } return quoteString(id); } static String quotedCompound(List<String> strings); static String quoteIdentifier(final String id); static boolean isKeyword(String id); static final String stringLiteral(String value); static List<String> parseSchemaPath(String schemaPath); static final String LEGACY_USE_BACKTICKS; static final char QUOTE; static final String QUOTE_WITH_ESCAPE; static ImmutableSet<String> RESERVED_SQL_KEYWORDS; static Function<String, String> QUOTER; }### Answer:
@Test public void testQuoteIdentifier() { assertEquals("\"window\"", SqlUtils.quoteIdentifier("window")); assertEquals("\"metadata\"", SqlUtils.quoteIdentifier("metadata")); assertEquals("abc", SqlUtils.quoteIdentifier("abc")); assertEquals("abc123", SqlUtils.quoteIdentifier("abc123")); assertEquals("a_bc", SqlUtils.quoteIdentifier("a_bc")); assertEquals("\"a_\"\"bc\"", SqlUtils.quoteIdentifier("a_\"bc")); assertEquals("\"a.\"\"bc\"", SqlUtils.quoteIdentifier("a.\"bc")); assertEquals("\"ab-c\"", SqlUtils.quoteIdentifier("ab-c")); assertEquals("\"ab/c\"", SqlUtils.quoteIdentifier("ab/c")); assertEquals("\"ab.c\"", SqlUtils.quoteIdentifier("ab.c")); assertEquals("\"123\"", SqlUtils.quoteIdentifier("123")); assertEquals("U&\"foo\\000abar\"", SqlUtils.quoteIdentifier("foo\nbar")); } |
### Question:
SqlUtils { public static List<String> parseSchemaPath(String schemaPath) { return new StrTokenizer(schemaPath, '.', SqlUtils.QUOTE) .setIgnoreEmptyTokens(true) .getTokenList(); } static String quotedCompound(List<String> strings); static String quoteIdentifier(final String id); static boolean isKeyword(String id); static final String stringLiteral(String value); static List<String> parseSchemaPath(String schemaPath); static final String LEGACY_USE_BACKTICKS; static final char QUOTE; static final String QUOTE_WITH_ESCAPE; static ImmutableSet<String> RESERVED_SQL_KEYWORDS; static Function<String, String> QUOTER; }### Answer:
@Test public void testParseSchemaPath() { assertEquals(asList("a", "b", "c"), SqlUtils.parseSchemaPath("a.b.c")); assertEquals(asList("a"), SqlUtils.parseSchemaPath("a")); assertEquals(asList("a", "b.c", "d"), SqlUtils.parseSchemaPath("a.\"b.c\".d")); assertEquals(asList("a", "c"), SqlUtils.parseSchemaPath("a..c")); } |
### Question:
OptimisticByteOutput extends ByteOutput { @Override public void write(byte value) { checkArray(); arrayReference[arrayOffset++] = value; } OptimisticByteOutput(int payloadSize); @Override void write(byte value); @Override void write(byte[] value, int offset, int length); @Override void writeLazy(byte[] value, int offset, int length); @Override void write(ByteBuffer value); @Override void writeLazy(ByteBuffer value); byte[] toByteArray(); }### Answer:
@Test public void testWrite() throws IOException { OptimisticByteOutput byteOutput = new OptimisticByteOutput(smallData.length); for (byte b : smallData) { byteOutput.write(b); } byte[] outputData = byteOutput.toByteArray(); assertNotSame(smallData, outputData); assertArrayEquals(smallData, outputData); } |
### Question:
PathUtils { public static List<String> toPathComponents(String fsPath) { if (fsPath == null ) { return EMPTY_SCHEMA_PATHS; } final StrTokenizer tokenizer = new StrTokenizer(fsPath, SLASH_CHAR, SqlUtils.QUOTE).setIgnoreEmptyTokens(true); return tokenizer.getTokenList(); } static Path toFSPath(final List<String> schemaPath); static String toFSPathString(final List<String> schemaPath); static Path toFSPathSkipRoot(final List<String> schemaPath, final String root); static Path toFSPath(String path); static String getQuotedFileName(Path path); static String toDottedPath(Path fsPath); static String toDottedPath(final Path parent, final Path child); static List<String> toPathComponents(String fsPath); static List<String> toPathComponents(Path fsPath); static String constructFullPath(Collection<String> pathComponents); static String encodeURIComponent(String component); static List<String> parseFullPath(final String path); static String removeQuotes(String pathComponent); static Joiner getPathJoiner(); static char getPathDelimiter(); static Joiner getKeyJoiner(); static String slugify(Collection<String> pathComponents); static String relativePath(Path absolutePath, Path basePath); static void verifyNoAccessOutsideBase(Path basePath, Path givenPath); static boolean checkNoAccessOutsideBase(Path basePath, Path givenPath); static String removeLeadingSlash(String path); }### Answer:
@Test public void testPathComponents() throws Exception { assertEquals(ImmutableList.of("a", "b", "c"), PathUtils.toPathComponents(Path.of("/a/b/c"))); assertEquals(ImmutableList.of("a", "b", "c"), PathUtils.toPathComponents(Path.of("a/b/c"))); assertEquals(ImmutableList.of("a", "b", "c/"), PathUtils.toPathComponents(Path.of("a/b/\"c/\""))); } |
### Question:
PathUtils { public static String removeLeadingSlash(String path) { if (path.length() > 0 && path.charAt(0) == '/') { String newPath = path.substring(1); return removeLeadingSlash(newPath); } else { return path; } } static Path toFSPath(final List<String> schemaPath); static String toFSPathString(final List<String> schemaPath); static Path toFSPathSkipRoot(final List<String> schemaPath, final String root); static Path toFSPath(String path); static String getQuotedFileName(Path path); static String toDottedPath(Path fsPath); static String toDottedPath(final Path parent, final Path child); static List<String> toPathComponents(String fsPath); static List<String> toPathComponents(Path fsPath); static String constructFullPath(Collection<String> pathComponents); static String encodeURIComponent(String component); static List<String> parseFullPath(final String path); static String removeQuotes(String pathComponent); static Joiner getPathJoiner(); static char getPathDelimiter(); static Joiner getKeyJoiner(); static String slugify(Collection<String> pathComponents); static String relativePath(Path absolutePath, Path basePath); static void verifyNoAccessOutsideBase(Path basePath, Path givenPath); static boolean checkNoAccessOutsideBase(Path basePath, Path givenPath); static String removeLeadingSlash(String path); }### Answer:
@Test public void testRemoveLeadingSlash() { assertEquals("", PathUtils.removeLeadingSlash("")); assertEquals("", PathUtils.removeLeadingSlash("/")); assertEquals("aaaa", PathUtils.removeLeadingSlash("/aaaa")); assertEquals("aaaa/bbb", PathUtils.removeLeadingSlash("/aaaa/bbb")); assertEquals("aaaa/bbb", PathUtils.removeLeadingSlash(" } |
### Question:
LocalValue { public void set(T value) { Preconditions.checkNotNull(value, "LocalValue cannot be set to null"); doSet(value); } LocalValue(); @SuppressWarnings("unchecked") Optional<T> get(); void set(T value); void clear(); static LocalValues save(); static void restore(LocalValues localValues); }### Answer:
@Test public void testSet() throws Exception { stringLocalValue.set("value1"); intLocalValue.set(1); assertEquals("value1", stringLocalValue.get().get()); assertEquals(new Integer(1), intLocalValue.get().get()); stringLocalValue.set("value2"); intLocalValue.set(2); assertEquals("value2", stringLocalValue.get().get()); assertEquals(new Integer(2), intLocalValue.get().get()); try { intLocalValue.restore(null); fail("Restoring null should fail"); } catch (Exception ignored) { } } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.