src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
DremioFutures { public static <T, X extends Exception> T getChecked( Future<T> future, Class<X> exceptionClass, Function<? super Throwable, ? extends X> mapper ) throws X { try { return Futures.getChecked(future, ExecutionException.class); } catch (ExecutionException e) { try { handleException(e, exceptionClass, mapper); throw new AssertionError(); } catch (TimeoutException ex) { throw new AssertionError(); } } } private DremioFutures(); static T getChecked( Future<T> future, Class<X> exceptionClass, Function<? super Throwable, ? extends X> mapper ); static T getChecked( Future<T> future, Class<X> exceptionClass, long timeout, TimeUnit unit, Function<? super Throwable, ? extends X> mapper ); }
@Test public void testBasic() { SettableFuture<Integer> future = SettableFuture.create(); Integer expectedValue = 1234; future.set(expectedValue); try { Integer result = DremioFutures.getChecked(future, TestException.class, TestDremioFutures::testMapper); assertEquals(result, expectedValue); } catch (TestException ignored) { throw new AssertionError(); } } @Test public void testTimeout() { SettableFuture future = SettableFuture.create(); Futures.addCallback(future, new FutureCallback<Integer>() { @Override public void onSuccess(@Nullable Integer result) { try { Thread.sleep(10000); } catch (InterruptedException ignored) { } future.set(result); } @Override public void onFailure(Throwable t) { } }, MoreExecutors.directExecutor()); try { DremioFutures.getChecked(future, TestException.class, 1, TimeUnit.MILLISECONDS, TestDremioFutures::testMapper); throw new AssertionError(); } catch (TimeoutException e) { } catch (Exception e) { throw new AssertionError(); } } @Test public void testMappingCause() { Future future = mock(Future.class); Throwable cause = new TestException("inner exception"); try { when(future.get()).thenThrow(new ExecutionException("outer exception", cause)); } catch (InterruptedException | ExecutionException ignored) { throw new AssertionError(); } try { DremioFutures.getChecked(future, TestException.class, TestDremioFutures::testMapper); throw new AssertionError(); } catch (TestException e) { assertSame(e.getCause(), cause); } catch (Exception e) { throw new AssertionError(); } }
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); }
@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]); }
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); }
@Test public void testBackwardCompatofSchema() throws Exception { Schema schema = DremioArrowSchema.fromJSON(OLD_SCHEMA); String newJson = schema.toJson(); assertFalse(newJson.contains("typeLayout")); }
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(); }
@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); }
AutoCloseables { public static void close(Throwable t, AutoCloseable... autoCloseables) { close(t, Arrays.asList(autoCloseables)); } private AutoCloseables(); static AutoCloseable all(final Collection<? extends AutoCloseable> autoCloseables); static void close(Throwable t, AutoCloseable... autoCloseables); static void close(Throwable t, Iterable<? extends AutoCloseable> autoCloseables); static void close(AutoCloseable... autoCloseables); static void close(Class<E> exceptionClazz, AutoCloseable... autoCloseables); static void close(Iterable<? extends AutoCloseable> ac); @SafeVarargs static void close(Iterable<? extends AutoCloseable>... closeables); static Iterable<AutoCloseable> iter(AutoCloseable... ac); static RollbackCloseable rollbackable(AutoCloseable... closeables); static void closeNoChecked(final AutoCloseable autoCloseable); static AutoCloseable noop(); }
@Test public void testClose() { Resource r1 = new Resource(); Resource r2 = new Resource(); Resource r3 = new Resource(); Resource r4 = new Resource(); try { AutoCloseables.close( () -> r1.closeWithException(new IOException("R1 exception")), () -> r2.closeWithException(null), () -> r3.closeWithException(new RuntimeException("R3 exception")), () -> r4.closeWithException(null) ); fail("Expected exception"); } catch (Exception e) { assertEquals(IOException.class, e.getClass()); } assertTrue(r1.isClosed() && r2.isClosed() && r3.isClosed() && r4.isClosed()); } @Test(expected = IOException.class) public void testCloseWithExpectedException() throws IOException { Resource r1 = new Resource(); Resource r2 = new Resource(); AutoCloseables.close(IOException.class, () -> r1.closeWithException(new IOException("R1 exception")), () -> r2.closeWithException(new RuntimeException("R3 exception")) ); fail("Expected exception"); } @Test(expected = RuntimeException.class) public void testCloseWithExpectedRuntimeException() throws IOException { Resource r1 = new Resource(); Resource r2 = new Resource(); AutoCloseables.close(IOException.class, () -> r1.closeWithException(new RuntimeException("R1 exception")), () -> r2.closeWithException(new IOException("R3 exception")) ); fail("Expected exception"); } @Test(expected = IOException.class) public void testCloseWithExpectedWrappedException() throws IOException { Resource r1 = new Resource(); Resource r2 = new Resource(); AutoCloseables.close(IOException.class, () -> r1.closeWithException(new Exception("R1 exception")), () -> r2.closeWithException(new Exception("R3 exception")) ); fail("Expected exception"); }
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); }
@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()); }
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); }
@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()); }
ContextMigratingExecutorService implements ExecutorService { @Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(decorate(task)); } ContextMigratingExecutorService(E delegate, Tracer tracer); @Override void shutdown(); @Override List<Runnable> shutdownNow(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override Future<T> submit(Callable<T> task); @Override Future<T> submit(Runnable task, T result); @Override Future<?> submit(Runnable task); @Override void execute(Runnable command); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); @Override T invokeAny(Collection<? extends Callable<T>> tasks); @Override T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); E getDelegate(); static final String WORK_OPERATION_NAME; static final String WAITING_OPERATION_NAME; }
@Test public void testRunnableDecoration() throws InterruptedException, ExecutionException { Span[] runnableSpan = new Span[1]; try (Scope s = tracer.activateSpan(testSpan)) { Future<?> future = pool.submit(() -> { runnableSpan[0] = tracer.activeSpan(); }); future.get(); } assertChildSpan(runnableSpan[0]); } @Test public void testContextWithCallable() throws Exception { final String testUser = "testUser1"; Callable<String> callable = () -> RequestContext.current().get(UserContext.CTX_KEY).serialize(); Future<String> future = RequestContext.empty() .with(UserContext.CTX_KEY, new UserContext(testUser)) .call(() -> pool.submit(callable)); Assert.assertEquals(testUser, future.get()); } @Test public void testContextWithRunnable() throws Exception { final String testUser = "testUser2"; final Pointer<String> foundUser = new Pointer<>(); Runnable runnable = () -> foundUser.value = RequestContext.current().get(UserContext.CTX_KEY).serialize(); Future<?> future = RequestContext.empty() .with(UserContext.CTX_KEY, new UserContext(testUser)) .call(() -> pool.submit(runnable)); future.get(); Assert.assertEquals(testUser, foundUser.value); }
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); }
@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()); }
BlackListOutput implements Output { @Override public void writeInt32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeInt32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeInt32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeInt32(1, 9, false); subject.writeInt32(2, 8, false); Mockito.verify(delegate).writeInt32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeUInt32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeUInt32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeUInt32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeUInt32(1, 9, false); subject.writeUInt32(2, 8, false); Mockito.verify(delegate).writeUInt32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
ReplaceRecommender extends Recommender<ReplacePatternRule, Selection> { @Override public List<ReplacePatternRule> getRules(Selection selection, DataType selColType) { Preconditions.checkArgument(selColType == DataType.TEXT, "Cards generation for Replace/Keeponly/Exclude transforms is supported only on TEXT type columns"); List<ReplacePatternRule> rules = new ArrayList<>(); if (selection.getCellText() == null) { rules.add(new ReplacePatternRule(IS_NULL)); } else { final int start = selection.getOffset(); final int end = start + selection.getLength(); final String content = selection.getCellText().substring(start, end); if (content.length() > 0) { rules.addAll(casePermutations(CONTAINS, content)); if (start == 0) { rules.addAll(casePermutations(STARTS_WITH, content)); } if (end == selection.getCellText().length()) { rules.addAll(casePermutations(ENDS_WITH, content)); } List<String> patterns = recommendReplacePattern(selection); for (String pattern : patterns) { rules.add(new ReplacePatternRule(MATCHES).setSelectionPattern(pattern)); } } if (start == 0 && end == selection.getCellText().length()) { rules.addAll(casePermutations(EXACT, content)); } } return rules; } @Override List<ReplacePatternRule> getRules(Selection selection, DataType selColType); TransformRuleWrapper<ReplacePatternRule> wrapRule(ReplacePatternRule rule); static ReplaceMatcher getMatcher(ReplacePatternRule rule); }
@Test public void ruleSuggestionsSelectMiddleText() { Selection selection = new Selection("col", "This is a text", 5, 2); List<ReplacePatternRule> rules = recommender.getRules(selection, TEXT); assertEquals(2, rules.size()); compare(ReplaceSelectionType.CONTAINS, "is", true, rules.get(0)); compare(ReplaceSelectionType.CONTAINS, "is", false, rules.get(1)); } @Test public void ruleSuggestionsSelectMiddleNumber() { Selection selection = new Selection("col", "There are 20 types of people", 10, 2); List<ReplacePatternRule> rules = recommender.getRules(selection, TEXT); assertEquals(2, rules.size()); compare(ReplaceSelectionType.CONTAINS, "20", false, rules.get(0)); compare(ReplaceSelectionType.MATCHES, "\\d+", false, rules.get(1)); } @Test public void ruleSuggestionsSelectBeginningText() { Selection selection = new Selection("col", "There are 20 types of people", 0, 5); List<ReplacePatternRule> rules = recommender.getRules(selection, TEXT); assertEquals(4, rules.size()); compare(ReplaceSelectionType.CONTAINS, "There", true, rules.get(0)); compare(ReplaceSelectionType.CONTAINS, "There", false, rules.get(1)); compare(ReplaceSelectionType.STARTS_WITH, "There", true, rules.get(2)); compare(ReplaceSelectionType.STARTS_WITH, "There", false, rules.get(3)); } @Test public void ruleSuggestionsSelectEndingText() { Selection selection = new Selection("col", "There are 20 types of people", 22, 6); List<ReplacePatternRule> rules = recommender.getRules(selection, TEXT); assertEquals(4, rules.size()); compare(ReplaceSelectionType.CONTAINS, "people", true, rules.get(0)); compare(ReplaceSelectionType.CONTAINS, "people", false, rules.get(1)); compare(ReplaceSelectionType.ENDS_WITH, "people", true, rules.get(2)); compare(ReplaceSelectionType.ENDS_WITH, "people", false, rules.get(3)); } @Test public void ruleSuggestionsSelectAllText() { Selection selection = new Selection("col", "There are 20 types of people", 0, 28); List<ReplacePatternRule> rules = recommender.getRules(selection, TEXT); assertEquals(8, rules.size()); compare(ReplaceSelectionType.CONTAINS, "There are 20 types of people", true, rules.get(0)); compare(ReplaceSelectionType.CONTAINS, "There are 20 types of people", false, rules.get(1)); compare(ReplaceSelectionType.STARTS_WITH, "There are 20 types of people", true, rules.get(2)); compare(ReplaceSelectionType.STARTS_WITH, "There are 20 types of people", false, rules.get(3)); compare(ReplaceSelectionType.ENDS_WITH, "There are 20 types of people", true, rules.get(4)); compare(ReplaceSelectionType.ENDS_WITH, "There are 20 types of people", false, rules.get(5)); compare(ReplaceSelectionType.EXACT, "There are 20 types of people", true, rules.get(6)); compare(ReplaceSelectionType.EXACT, "There are 20 types of people", false, rules.get(7)); } @Test public void ruleSuggestionsSelectNumberAtTheEnd() { Selection selection = new Selection("col", "883 N Shoreline Blvd, Mountain View, CA 94043", 40, 5); List<ReplacePatternRule> rules = recommender.getRules(selection, TEXT); assertEquals(3, rules.size()); compare(ReplaceSelectionType.CONTAINS, "94043", false, rules.get(0)); compare(ReplaceSelectionType.ENDS_WITH, "94043", false, rules.get(1)); compare(ReplaceSelectionType.MATCHES, "\\d+", false, rules.get(2)); } @Test public void ruleSuggestionsSelectNumberAtBeginning() { Selection selection = new Selection("col", "883 N Shoreline Blvd, Mountain View, CA 94043", 0, 3); List<ReplacePatternRule> rules = recommender.getRules(selection, TEXT); assertEquals(3, rules.size()); compare(ReplaceSelectionType.CONTAINS, "883", false, rules.get(0)); compare(ReplaceSelectionType.STARTS_WITH, "883", false, rules.get(1)); compare(ReplaceSelectionType.MATCHES, "\\d+", false, rules.get(2)); }
BlackListOutput implements Output { @Override public void writeSInt32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeSInt32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeSInt32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeSInt32(1, 9, false); subject.writeSInt32(2, 8, false); Mockito.verify(delegate).writeSInt32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeFixed32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeFixed32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeFixed32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeFixed32(1, 9, false); subject.writeFixed32(2, 8, false); Mockito.verify(delegate).writeFixed32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeSFixed32(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeSFixed32(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeSFixed32() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeSFixed32(1, 9, false); subject.writeSFixed32(2, 8, false); Mockito.verify(delegate).writeSFixed32(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeInt64(int fieldNumber, long value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeInt64(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeInt64() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeInt64(1, 9, false); subject.writeInt64(2, 8, false); Mockito.verify(delegate).writeInt64(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeUInt64(int fieldNumber, long value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeUInt64(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeUInt64() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeUInt64(1, 9, false); subject.writeUInt64(2, 8, false); Mockito.verify(delegate).writeUInt64(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeSInt64(int fieldNumber, long value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeSInt64(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeSInt64() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeSInt64(1, 9, false); subject.writeSInt64(2, 8, false); Mockito.verify(delegate).writeSInt64(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeFixed64(int fieldNumber, long value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeFixed64(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeFixed64() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeFixed64(1, 9, false); subject.writeFixed64(2, 8, false); Mockito.verify(delegate).writeFixed64(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeSFixed64(int fieldNumber, long value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeSFixed64(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeSFixed64() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeSFixed64(1, 9, false); subject.writeSFixed64(2, 8, false); Mockito.verify(delegate).writeSFixed64(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeFloat(int fieldNumber, float value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeFloat(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeFloat() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeFloat(1, 9, false); subject.writeFloat(2, 8, false); Mockito.verify(delegate).writeFloat(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeDouble(int fieldNumber, double value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeDouble(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeDouble() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeDouble(1, 9, false); subject.writeDouble(2, 8, false); Mockito.verify(delegate).writeDouble(1,9, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeBool(int fieldNumber, boolean value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeBool(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeBool() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeBool(1, true, false); subject.writeBool(2, false, false); Mockito.verify(delegate).writeBool(1,true, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeEnum(int fieldNumber, int value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeEnum(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeEnum() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeEnum(1, 1, false); subject.writeEnum(2, 2, false); Mockito.verify(delegate).writeEnum(1,1, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeString(int fieldNumber, String value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeString(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeString() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeString(1, "1", false); subject.writeString(2, "2", false); Mockito.verify(delegate).writeString(1,"1", false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeBytes(int fieldNumber, ByteString value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeBytes(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeByteString() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeBytes(1, ByteString.bytesDefaultValue("1"), false); subject.writeBytes(2, ByteString.bytesDefaultValue("2"), false); Mockito.verify(delegate).writeBytes(1,ByteString.bytesDefaultValue("1"), false); Mockito.verifyNoMoreInteractions(delegate); } @Test public void writeByteBuffer() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeBytes(1, ByteBuffer.wrap(new byte[]{1}), false); subject.writeBytes(2, ByteBuffer.wrap(new byte[]{2}), false); Mockito.verify(delegate).writeBytes(1, ByteBuffer.wrap(new byte[]{1}), false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeByteArray(int fieldNumber, byte[] value, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeByteArray(fieldNumber, value, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeByteArray() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeByteArray(1, new byte[]{1}, false); subject.writeByteArray(2, new byte[]{2}, false); Mockito.verify(delegate).writeByteArray(1, new byte[]{1}, false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } delegate.writeByteRange(utf8String, fieldNumber, value, offset, length, repeated); } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeByteRange() throws IOException { Output delegate = Mockito.mock(Output.class); BlackListOutput subject = new BlackListOutput( delegate, Collections.emptyMap(), new int[]{2} ); subject.writeByteRange(false,1, new byte[]{1}, 0, 1, false); subject.writeByteRange(false,2, new byte[]{2}, 0,1,false); Mockito.verify(delegate).writeByteRange(false,1, new byte[]{1}, 0, 1,false); Mockito.verifyNoMoreInteractions(delegate); }
BlackListOutput implements Output { @Override public <T> void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated) throws IOException { if(isBlackListed(fieldNumber)){ return; } int[] parentBlackList = currentBlackList; try { String messageFullName = schema.messageFullName(); currentBlackList = schemaNameToBlackList.getOrDefault(messageFullName, EmptyArray); writeString(fieldNumber * -1, messageFullName, repeated); schema.writeTo(this, value); writeString(fieldNumber * -1, schema.messageName(), repeated); } finally { currentBlackList = parentBlackList; } } @VisibleForTesting BlackListOutput( Output delegate, Map<String, int[]> schemaNameToBlackList, int[] currentBlackList); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); }
@Test public void writeObject() throws IOException { Output delegate = Mockito.mock(Output.class); Object object = new Object(); String schemaName = "Hello Schema"; String shortName = "Hello"; Schema<Object> schema = Mockito.mock(Schema.class); int[] subSet = new int[]{4}; BlackListOutput subject = new BlackListOutput( delegate, ImmutableMap.of( schemaName, subSet ), new int[]{2} ); when(schema.messageFullName()).thenReturn(schemaName); when(schema.messageName()).thenReturn(shortName); Mockito.doAnswer((invocation) -> { Assert.assertEquals(subSet, subject.currentBlackList); return null; }).when(schema).writeTo(delegate, object); subject.writeObject(1, object, schema, false); Mockito.verify(schema).messageFullName(); Mockito.verify(delegate).writeString(-1, schemaName, false); Mockito.verify(schema).writeTo(subject, object); Mockito.verify(delegate).writeString(-1, shortName, false); Mockito.verify(schema).messageName(); Mockito.verifyNoMoreInteractions(schema); }
HasherOutput implements Output { public Hasher getHasher() { return hasher; } HasherOutput(Hasher hasher); HasherOutput(); @Override void writeInt32(int fieldNumber, int value, boolean repeated); @Override void writeUInt32(int fieldNumber, int value, boolean repeated); @Override void writeSInt32(int fieldNumber, int value, boolean repeated); @Override void writeFixed32(int fieldNumber, int value, boolean repeated); @Override void writeSFixed32(int fieldNumber, int value, boolean repeated); @Override void writeInt64(int fieldNumber, long value, boolean repeated); @Override void writeUInt64(int fieldNumber, long value, boolean repeated); @Override void writeSInt64(int fieldNumber, long value, boolean repeated); @Override void writeFixed64(int fieldNumber, long value, boolean repeated); @Override void writeSFixed64(int fieldNumber, long value, boolean repeated); @Override void writeFloat(int fieldNumber, float value, boolean repeated); @Override void writeDouble(int fieldNumber, double value, boolean repeated); @Override void writeBool(int fieldNumber, boolean value, boolean repeated); @Override void writeEnum(int fieldNumber, int value, boolean repeated); @Override void writeString(int fieldNumber, String value, boolean repeated); @Override void writeBytes(int fieldNumber, ByteString value, boolean repeated); @Override void writeByteArray(int fieldNumber, byte[] value, boolean repeated); @Override void writeByteRange(boolean utf8String, int fieldNumber, byte[] value, int offset, int length, boolean repeated); @Override void writeObject(int fieldNumber, T value, Schema<T> schema, boolean repeated); @Override void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated); Hasher getHasher(); }
@Test public void testNoInput() { HasherOutput subject = new HasherOutput(); String result = subject.getHasher().hash().toString(); Assert.assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", result); }
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); }
@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)); }
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; }
@Test public void testIsKeyword() { assertTrue(SqlUtils.isKeyword("USER")); assertTrue(SqlUtils.isKeyword("FiLeS")); assertFalse(SqlUtils.isKeyword("myUSER")); }
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; }
@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")); }
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; }
@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")); }
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(); }
@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); }
OptimisticByteOutput extends ByteOutput { public byte[] toByteArray() { if (payloadSize == 0) { return arrayReference != null ? arrayReference : EMPTY; } Preconditions.checkState(arrayOffset == payloadSize, "Byte payload not fully received."); return arrayReference; } 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(); }
@Test public void testLiteralByteString() throws Exception { ByteString literal = ByteString.copyFrom(smallData); OptimisticByteOutput byteOutput = new OptimisticByteOutput(literal.size()); UnsafeByteOperations.unsafeWriteTo(literal, byteOutput); byte[] array = (byte[]) FieldUtils.readField(literal, "bytes", true); assertArrayEquals(smallData, byteOutput.toByteArray()); assertSame(array, byteOutput.toByteArray()); } @Test public void testRopeByteStringWithZeroOnLeft() throws Exception { ByteString literal = ByteString.copyFrom(smallData); ByteString data = (ByteString) NEW_ROPE_BYTE_STRING_INSTANCE.invoke(null, ByteString.EMPTY, literal); OptimisticByteOutput byteOutput = new OptimisticByteOutput(smallData.length); UnsafeByteOperations.unsafeWriteTo(data, byteOutput); byte[] array = (byte[]) FieldUtils.readField(literal, "bytes", true); assertArrayEquals(smallData, byteOutput.toByteArray()); assertSame(array, byteOutput.toByteArray()); } @Test public void testRopeByteStringWithZeroOnRight() throws Exception { ByteString literal = ByteString.copyFrom(smallData); ByteString data = (ByteString) NEW_ROPE_BYTE_STRING_INSTANCE.invoke(null, literal, ByteString.EMPTY); OptimisticByteOutput byteOutput = new OptimisticByteOutput(smallData.length); UnsafeByteOperations.unsafeWriteTo(data, byteOutput); byte[] array = (byte[]) FieldUtils.readField(literal, "bytes", true); assertArrayEquals(smallData, byteOutput.toByteArray()); assertSame(array, byteOutput.toByteArray()); }
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); }
@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/\""))); }
PathUtils { public static String toDottedPath(Path fsPath) { return constructFullPath(toPathComponents(fsPath)); } 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); }
@Test public void testFSPathToSchemaPath() throws Exception { assertEquals("a.b.c", PathUtils.toDottedPath(Path.of("/a/b/c"))); assertEquals("a.b.c", PathUtils.toDottedPath(Path.of("a/b/c"))); assertEquals("a.b.\"c.json\"", PathUtils.toDottedPath(Path.of("/a/b/c.json"))); assertEquals("\"c.json\"", PathUtils.toDottedPath(Path.of("c.json"))); assertEquals("\"c.json\"", PathUtils.toDottedPath(Path.of("/c.json"))); assertEquals("c", PathUtils.toDottedPath(Path.of("/c"))); } @Test public void toDottedPathWithCommonPrefix() throws Exception { assertEquals("d", PathUtils.toDottedPath(Path.of("/a/b/c"), Path.of("/a/b/c/d"))); assertEquals("b.c.d", PathUtils.toDottedPath(Path.of("/a"), Path.of("/a/b/c/d"))); assertEquals("a.b.c.d", PathUtils.toDottedPath(Path.of("/"), Path.of("/a/b/c/d"))); assertEquals("c.d.\"e.json\"", PathUtils.toDottedPath(Path.of("/a/b/"), Path.of("/a/b/c/d/e.json"))); } @Test public void toDottedPathWithInvalidPrefix() throws Exception { try { PathUtils.toDottedPath(Path.of("/p/q/"), Path.of("/a/b/c/d/e.json")); fail("constructing relative path of child /a/b/c/d/e.json with parent /p/q should fail"); } catch (IOException e) { } }
PathUtils { public static Path toFSPath(final List<String> schemaPath) { if (schemaPath == null || schemaPath.isEmpty()) { return ROOT_PATH; } return ROOT_PATH.resolve(PATH_JOINER.join(schemaPath)); } 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); }
@Test public void testToFSPath() throws Exception { assertEquals(Path.of("/a/b/c"), PathUtils.toFSPath("a.b.c")); assertEquals(Path.of("/a/b"), PathUtils.toFSPath("a.b")); assertEquals(Path.of("/c.txt"), PathUtils.toFSPath("\"c.txt\"")); assertEquals(Path.of("/a/b/c.txt"), PathUtils.toFSPath("a.b.\"c.txt\"")); } @Test public void testHybridSchemaPathToFSPath() throws Exception { assertEquals(Path.of("/dfs/tmp/a/b/c"), PathUtils.toFSPath("dfs.tmp.\"a/b/c")); assertEquals(Path.of("/dfs/tmp/a/b/c.json"), PathUtils.toFSPath("dfs.tmp.\"a/b/c.json")); assertEquals(Path.of("/dfs/tmp/a.txt"), PathUtils.toFSPath("dfs.tmp.\"a.txt")); }
PathUtils { public static Path toFSPathSkipRoot(final List<String> schemaPath, final String root) { if (schemaPath == null || schemaPath.isEmpty()) { return ROOT_PATH; } if (root == null || !root.equals(schemaPath.get(0))) { return toFSPath(schemaPath); } else { return toFSPath(schemaPath.subList(1, schemaPath.size())); } } 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); }
@Test public void testToFSPathSkipRoot() throws Exception { assertEquals(Path.of("/b/c"), PathUtils.toFSPathSkipRoot(Arrays.asList("a", "b", "c"), "a")); assertEquals(Path.of("/a/b/c"), PathUtils.toFSPathSkipRoot(Arrays.asList("a", "b", "c"), "z")); assertEquals(Path.of("/a/b/c"), PathUtils.toFSPathSkipRoot(Arrays.asList("a", "b", "c"), null)); assertEquals(Path.of("/"), PathUtils.toFSPathSkipRoot(null, "a")); assertEquals(Path.of("/"), PathUtils.toFSPathSkipRoot(Collections.<String>emptyList(), "a")); }
PathUtils { public static String relativePath(Path absolutePath, Path basePath) { Preconditions.checkArgument(absolutePath.isAbsolute(), "absolutePath must be an absolute path"); Preconditions.checkArgument(basePath.isAbsolute(), "basePath must be an absolute path"); List<String> absolutePathComponents = Lists.newArrayList(toPathComponents(absolutePath)); List<String> basePathComponents = toPathComponents(basePath); boolean hasCommonPrefix = basePathComponents.isEmpty(); for (String base : basePathComponents) { if (absolutePathComponents.get(0).equals(base)) { absolutePathComponents.remove(0); hasCommonPrefix = true; } else { break; } } if (hasCommonPrefix) { return PATH_JOINER.join(absolutePathComponents); } else { return absolutePath.toString(); } } 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); }
@Test public void testRelativePath() throws Exception { assertEquals("a", PathUtils.relativePath(Path.of("/a"), Path.of("/"))); assertEquals("b", PathUtils.relativePath(Path.of("/a/b"), Path.of("/a"))); assertEquals("b/c.json", PathUtils.relativePath(Path.of("/a/b/c.json"), Path.of("/a"))); assertEquals("c/d/e", PathUtils.relativePath(Path.of("/a/b/c/d/e"), Path.of("/a/b"))); assertEquals("/a/b", PathUtils.relativePath(Path.of("/a/b"), Path.of("/c/d"))); }
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); }
@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(" }
PathUtils { public static void verifyNoAccessOutsideBase(Path basePath, Path givenPath) { if (!checkNoAccessOutsideBase(basePath, givenPath)) { throw UserException.permissionError() .message("Not allowed to access files outside of the source root") .addContext("Source root", Path.withoutSchemeAndAuthority(basePath).toString()) .addContext("Requested to path", Path.withoutSchemeAndAuthority(givenPath).toString()) .build(logger); } } 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); }
@Test public void testVerifyNoAccessOutsideBase() { PathUtils.verifyNoAccessOutsideBase(Path.of("/"), Path.of("/")); PathUtils.verifyNoAccessOutsideBase(Path.of("/"), Path.of("/a")); PathUtils.verifyNoAccessOutsideBase(Path.of("/"), Path.of("/a/b")); PathUtils.verifyNoAccessOutsideBase(Path.of("/a/"), Path.of("/a")); PathUtils.verifyNoAccessOutsideBase(Path.of("/a"), Path.of("/a/")); PathUtils.verifyNoAccessOutsideBase(Path.of("/a/"), Path.of("/a/")); PathUtils.verifyNoAccessOutsideBase(Path.of("/a"), Path.of("/a/b")); PathUtils.verifyNoAccessOutsideBase(Path.of("/a"), Path.of("/a/b/c")); PathUtils.verifyNoAccessOutsideBase(Path.of("/a"), Path.of("/a/b/c")); try { PathUtils.verifyNoAccessOutsideBase(Path.of("/a"), Path.of("/a/../b/c")); fail(); } catch (UserException ex) { } try { PathUtils.verifyNoAccessOutsideBase(Path.of("/a"), Path.of("/a/b/../../c")); fail(); } catch (UserException ex) { } try { PathUtils.verifyNoAccessOutsideBase(Path.of("/a"), Path.of("/ab")); fail(); } catch (UserException ex) { } try { PathUtils.verifyNoAccessOutsideBase(Path.of("/a/"), Path.of("/ab")); fail(); } catch (UserException ex) { } }
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); }
@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) { } }
LocalValue { public void clear() { doSet(null); } LocalValue(); @SuppressWarnings("unchecked") Optional<T> get(); void set(T value); void clear(); static LocalValues save(); static void restore(LocalValues localValues); }
@Test public void testClear() { stringLocalValue.set("value1"); intLocalValue.set(1); stringLocalValue.clear(); intLocalValue.clear(); assertFalse(stringLocalValue.get().isPresent()); assertFalse(intLocalValue.get().isPresent()); }
VM { private static final long maxDirectMemory() { try { return invokeMaxDirectMemory("sun.misc.VM"); } catch (ReflectiveOperationException ignored) { } try { return invokeMaxDirectMemory("jdk.internal.misc.VM"); } catch (ReflectiveOperationException ignored) { } final List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments(); long maxDirectMemory = maxDirectMemory(inputArguments); if (maxDirectMemory != 0) { return maxDirectMemory; } return Runtime.getRuntime().maxMemory(); } private VM(); static boolean isDebugEnabled(); static int availableProcessors(); static long getMaxDirectMemory(); static long getMaxHeapMemory(); static boolean isMacOSHost(); static boolean isWindowsHost(); static final String DREMIO_CPU_AVAILABLE_PROPERTY; }
@Test public void checkMaxDirectMemory() { assertThat(VM.maxDirectMemory(arguments), is(maxDirectMemory)); }
VM { public static boolean isDebugEnabled() { return IS_DEBUG; } private VM(); static boolean isDebugEnabled(); static int availableProcessors(); static long getMaxDirectMemory(); static long getMaxHeapMemory(); static boolean isMacOSHost(); static boolean isWindowsHost(); static final String DREMIO_CPU_AVAILABLE_PROPERTY; }
@Test public void checkDebugEnabled() { assertThat(VM.isDebugEnabled(arguments), is(debugEnabled)); }
TimeMilliAccessor extends AbstractSqlAccessor { @Override public boolean isNull(int index) { return ac.isNull(index); } TimeMilliAccessor(TimeMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Time getTime(int index, Calendar calendar); }
@Test public void testIsNull() throws Exception { assertNotNull(accessor.getObject(0)); assertNotNull(accessor.getTime(0, PST_CALENDAR)); assertNull(accessor.getObject(1)); assertNull(accessor.getTime(1, PST_CALENDAR)); }
TimeMilliAccessor extends AbstractSqlAccessor { @Override public Object getObject(int index) { return getTime(index, defaultTimeZone); } TimeMilliAccessor(TimeMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Time getTime(int index, Calendar calendar); }
@Test public void testGetObject() throws Exception { assertEquals(new TimePrintMillis(NON_NULL_VALUE), accessor.getObject(0)); }
TimeMilliAccessor extends AbstractSqlAccessor { @Override public Time getTime(int index, Calendar calendar) { Preconditions.checkNotNull(calendar, "Invalid calendar used when attempting to retrieve time."); return getTime(index, calendar.getTimeZone()); } TimeMilliAccessor(TimeMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Time getTime(int index, Calendar calendar); }
@Test(expected=NullPointerException.class) public void testNullCalendar() throws InvalidAccessException { accessor.getTime(0, null); } @Test public void testGetTime() throws Exception { assertEquals( new TimePrintMillis(LocalDateTime.of(LocalDate.now(), LocalTime.of(8, 14, 07, (int)TimeUnit.MILLISECONDS.toNanos(234)))), accessor.getTime(0, PST_CALENDAR)); assertEquals(new TimePrintMillis(NON_NULL_VALUE), accessor.getTime(0, UTC_CALENDAR)); }
DateMilliAccessor extends AbstractSqlAccessor { @Override public boolean isNull(int index) { return ac.isNull(index); } DateMilliAccessor(DateMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Date getDate(int index, Calendar calendar); }
@Test public void testIsNull() throws Exception { assertNotNull(accessor.getObject(0)); assertNotNull(accessor.getDate(0, PST_CALENDAR)); assertNull(accessor.getObject(2)); assertNull(accessor.getDate(2, PST_CALENDAR)); }
DateMilliAccessor extends AbstractSqlAccessor { @Override public Object getObject(int index) { return getDate(index, defaultTimeZone); } DateMilliAccessor(DateMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Date getDate(int index, Calendar calendar); }
@Test public void testGetObject() throws Exception { assertEquals(new Date(72, 10, 4), accessor.getObject(0)); }
DateMilliAccessor extends AbstractSqlAccessor { @Override public Date getDate(int index, Calendar calendar) { Preconditions.checkNotNull(calendar, "Invalid calendar used when attempting to retrieve date."); return getDate(index, calendar.getTimeZone()); } DateMilliAccessor(DateMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Date getDate(int index, Calendar calendar); }
@Test(expected=NullPointerException.class) public void testNullCalendar() throws InvalidAccessException { accessor.getDate(0, null); } @Test public void testGetDate() throws Exception { assertEquals(new Date(72, 10, 3), accessor.getDate(0, PST_CALENDAR)); assertEquals(new Date(72, 10, 4), accessor.getDate(0, UTC_CALENDAR)); assertEquals(new Date(119, 4, 27), accessor.getDate(1, PST_CALENDAR)); assertEquals(new Date(119, 4, 27), accessor.getDate(1, UTC_CALENDAR)); }
GenericAccessor extends AbstractSqlAccessor { @Override public boolean isNull(int index) { return v.isNull(index); } GenericAccessor(ValueVector v); @Override Class<?> getObjectClass(); @Override boolean isNull(int index); @Override Object getObject(int index); @Override MajorType getType(); }
@Test public void testIsNull() throws Exception { assertFalse(genericAccessor.isNull(0)); assertTrue(genericAccessor.isNull(1)); }
GenericAccessor extends AbstractSqlAccessor { @Override public Object getObject(int index) throws InvalidAccessException { return v.getObject(index); } GenericAccessor(ValueVector v); @Override Class<?> getObjectClass(); @Override boolean isNull(int index); @Override Object getObject(int index); @Override MajorType getType(); }
@Test public void testGetObject() throws Exception { assertEquals(NON_NULL_VALUE, genericAccessor.getObject(0)); assertNull(genericAccessor.getObject(1)); } @Test(expected=IndexOutOfBoundsException.class) public void testGetObject_indexOutOfBounds() throws Exception { genericAccessor.getObject(2); }
GenericAccessor extends AbstractSqlAccessor { @Override public MajorType getType() { return getMajorTypeForField(v.getField()); } GenericAccessor(ValueVector v); @Override Class<?> getObjectClass(); @Override boolean isNull(int index); @Override Object getObject(int index); @Override MajorType getType(); }
@Test public void testGetType() throws Exception { assertEquals(UserBitShared.SerializedField.getDefaultInstance().getMajorType(), genericAccessor.getType()); }
TimeStampMilliAccessor extends AbstractSqlAccessor { @Override public boolean isNull(int index) { return ac.isNull(index); } TimeStampMilliAccessor(TimeStampMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Timestamp getTimestamp(int index, Calendar calendar); }
@Test public void testIsNull() throws Exception { assertNotNull(accessor.getObject(0)); assertNotNull(accessor.getTimestamp(0, PST_CALENDAR)); assertNull(accessor.getObject(2)); assertNull(accessor.getTimestamp(2, PST_CALENDAR)); }
TimeStampMilliAccessor extends AbstractSqlAccessor { @Override public Object getObject(int index) { return getTimestamp(index, defaultTimeZone); } TimeStampMilliAccessor(TimeStampMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Timestamp getTimestamp(int index, Calendar calendar); }
@Test public void testGetObject() throws Exception { assertEquals( new Timestamp(72, 10, 4, 11, 10, 8, (int)TimeUnit.MILLISECONDS.toNanos(957)), accessor.getObject(0)); }
TimeStampMilliAccessor extends AbstractSqlAccessor { @Override public Timestamp getTimestamp(int index, Calendar calendar) { Preconditions.checkNotNull(calendar, "Invalid calendar used when attempting to retrieve timestamp."); return getTimestamp(index, calendar.getTimeZone()); } TimeStampMilliAccessor(TimeStampMilliVector vector, TimeZone defaultTZ); @Override MajorType getType(); @Override boolean isNull(int index); @Override Class<?> getObjectClass(); @Override Object getObject(int index); @Override Timestamp getTimestamp(int index, Calendar calendar); }
@Test(expected=NullPointerException.class) public void testNullCalendar() throws InvalidAccessException { accessor.getTimestamp(0, null); } @Test public void testGetTimestamp() throws Exception { assertEquals( new Timestamp(72, 10, 4, 3, 10, 8, (int)TimeUnit.MILLISECONDS.toNanos(957)), accessor.getTimestamp(0, PST_CALENDAR)); assertEquals( new Timestamp(72, 10, 4, 11, 10, 8, (int)TimeUnit.MILLISECONDS.toNanos(957)), accessor.getTimestamp(0, UTC_CALENDAR)); assertEquals( new Timestamp(119, 4, 27, 16, 33, 13, (int)TimeUnit.MILLISECONDS.toNanos(123)), accessor.getTimestamp(1, PST_CALENDAR)); assertEquals( new Timestamp(119, 4, 27, 23, 33, 13, (int)TimeUnit.MILLISECONDS.toNanos(123)), accessor.getTimestamp(1, UTC_CALENDAR)); }
ReplaceRecommender extends Recommender<ReplacePatternRule, Selection> { public TransformRuleWrapper<ReplacePatternRule> wrapRule(ReplacePatternRule rule) { return new ReplaceTransformRuleWrapper(rule); } @Override List<ReplacePatternRule> getRules(Selection selection, DataType selColType); TransformRuleWrapper<ReplacePatternRule> wrapRule(ReplacePatternRule rule); static ReplaceMatcher getMatcher(ReplacePatternRule rule); }
@Test public void contains() throws Exception { final File dataFile = temp.newFile("containsTest.json"); try (final PrintWriter printWriter = new PrintWriter(dataFile)) { printWriter.append("{ \"col\" : \"This is an amazing restaurant. Very good food.\" }"); printWriter.append("{ \"col\" : \"This is a worst restaurant. bad food.\" }"); printWriter.append("{ \"col\" : \"Amazing environment. \\nAmazing food.\" }"); printWriter.append("{ \"col\" : \"Not good.\" }"); } ReplacePatternRule rule = new ReplacePatternRule(ReplaceSelectionType.CONTAINS) .setSelectionPattern("amazing"); TransformRuleWrapper<ReplacePatternRule> ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'CONTAINS', 'amazing', false)", "CASE WHEN regexp_like(\"input.expr\", '.*?\\Qamazing\\E.*?') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '.*?\\Qamazing\\E.*?') THEN " + "regexp_replace(\"input.expr\", '\\Qamazing\\E', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '.*?\\Qamazing\\E.*?') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '.*?\\Qamazing\\E.*?')" ); List<Object> outputSelReplace = list( (Object)"This is an AMAZING restaurant. Very good food.", "This is a worst restaurant. bad food.", "Amazing environment. \nAmazing food.", "Not good." ); List<Object> outputCompleteReplace = list( (Object)"AMAZING", "This is a worst restaurant. bad food.", "Amazing environment. \nAmazing food.", "Not good." ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "AMAZING"}, outputSelReplace, asList(true, false, false, false), asList(asList(new CardExamplePosition(11, 7)), null, null, null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "AMAZING"}, outputCompleteReplace, asList(true, false, false, false), asList(asList(new CardExamplePosition(11, 7)), null, null, null) ); rule = rule.setIgnoreCase(true); ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'CONTAINS', 'amazing', true)", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?\\Qamazing\\E.*?') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?\\Qamazing\\E.*?') THEN " + "regexp_replace(\"input.expr\", '(?i)(?u)\\Qamazing\\E', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?\\Qamazing\\E.*?') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '(?i)(?u).*?\\Qamazing\\E.*?')" ); outputSelReplace = list( (Object)"This is an AMAZING restaurant. Very good food.", "This is a worst restaurant. bad food.", "AMAZING environment. \nAMAZING food.", "Not good." ); outputCompleteReplace = list( (Object)"AMAZING", "This is a worst restaurant. bad food.", "AMAZING", "Not good." ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "AMAZING"}, outputSelReplace, asList(true, false, true, false), asList(asList(new CardExamplePosition(11, 7)), null, asList(new CardExamplePosition(0, 7)), null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "AMAZING"}, outputCompleteReplace, asList(true, false, true, false), asList(asList(new CardExamplePosition(11, 7)), null, asList(new CardExamplePosition(0, 7)), null) ); } @Test public void startsWith() throws Exception { final File dataFile = temp.newFile("startsWithTest.json"); try (final PrintWriter printWriter = new PrintWriter(dataFile)) { printWriter.append("{ \"col\" : \"amazing restaurant. Very good food.\" }"); printWriter.append("{ \"col\" : \"This is a worst restaurant. bad food.\" }"); printWriter.append("{ \"col\" : \"Amazing environment. Amazing food.\" }"); printWriter.append("{ \"col\" : \"Not good.\" }"); } ReplacePatternRule rule = new ReplacePatternRule() .setSelectionType(ReplaceSelectionType.STARTS_WITH) .setSelectionPattern("amazing"); TransformRuleWrapper<ReplacePatternRule> ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'STARTS_WITH', 'amazing', false)", "CASE WHEN regexp_like(\"input.expr\", '^\\Qamazing\\E.*?') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '^\\Qamazing\\E.*?') THEN " + "regexp_replace(\"input.expr\", '^\\Qamazing\\E', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '^\\Qamazing\\E.*?') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '^\\Qamazing\\E.*?')" ); List<Object> outputSelReplace = list( (Object)"AMAZING restaurant. Very good food.", "This is a worst restaurant. bad food.", "Amazing environment. Amazing food.", "Not good." ); List<Object> outputCompleteReplace = list( (Object)"AMAZING", "This is a worst restaurant. bad food.", "Amazing environment. Amazing food.", "Not good." ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "AMAZING"}, outputSelReplace, asList(true, false, false, false), asList(asList(new CardExamplePosition(0, 7)), null, null, null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "AMAZING"}, outputCompleteReplace, asList(true, false, false, false), asList(asList(new CardExamplePosition(0, 7)), null, null, null) ); rule = rule.setIgnoreCase(true); ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'STARTS_WITH', 'amazing', true)", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u)^\\Qamazing\\E.*?') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u)^\\Qamazing\\E.*?') THEN " + "regexp_replace(\"input.expr\", '(?i)(?u)^\\Qamazing\\E', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u)^\\Qamazing\\E.*?') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '(?i)(?u)^\\Qamazing\\E.*?')" ); outputSelReplace = list( (Object)"AMAZING restaurant. Very good food.", "This is a worst restaurant. bad food.", "AMAZING environment. Amazing food.", "Not good." ); outputCompleteReplace = list( (Object)"AMAZING", "This is a worst restaurant. bad food.", "AMAZING", "Not good." ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "AMAZING"}, outputSelReplace, asList(true, false, true, false), asList(asList(new CardExamplePosition(0, 7)), null, asList(new CardExamplePosition(0, 7)), null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "AMAZING"}, outputCompleteReplace, asList(true, false, true, false), asList(asList(new CardExamplePosition(0, 7)), null, asList(new CardExamplePosition(0, 7)), null) ); } @Test public void endsWith() throws Exception { final File dataFile = temp.newFile("endsWithTest.json"); try (final PrintWriter printWriter = new PrintWriter(dataFile)) { printWriter.append("{ \"col\" : \"amazing restaurant. Very good food\" }"); printWriter.append("{ \"col\" : \"This is a worst restaurant. bad food\" }"); printWriter.append("{ \"col\" : \"Amazing environment. Amazing Food\" }"); printWriter.append("{ \"col\" : \"Not good\" }"); } ReplacePatternRule rule = new ReplacePatternRule() .setSelectionType(ReplaceSelectionType.ENDS_WITH) .setSelectionPattern("food"); TransformRuleWrapper<ReplacePatternRule> ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'ENDS_WITH', 'food', false)", "CASE WHEN regexp_like(\"input.expr\", '.*?\\Qfood\\E$') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '.*?\\Qfood\\E$') THEN " + "regexp_replace(\"input.expr\", '\\Qfood\\E$', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '.*?\\Qfood\\E$') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '.*?\\Qfood\\E$')" ); List<Object> outputSelReplace = list( (Object)"amazing restaurant. Very good dinner", "This is a worst restaurant. bad dinner", "Amazing environment. Amazing Food", "Not good" ); List<Object> outputCompleteReplace = list( (Object)"dinner", "dinner", "Amazing environment. Amazing Food", "Not good" ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "dinner"}, outputSelReplace, asList(true, true, false, false), asList(asList(new CardExamplePosition(30, 4)), asList(new CardExamplePosition(32, 4)), null, null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "dinner"}, outputCompleteReplace, asList(true, true, false, false), asList(asList(new CardExamplePosition(30, 4)), asList(new CardExamplePosition(32, 4)), null, null) ); rule = rule.setIgnoreCase(true); ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'ENDS_WITH', 'food', true)", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?\\Qfood\\E$') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?\\Qfood\\E$') THEN " + "regexp_replace(\"input.expr\", '(?i)(?u)\\Qfood\\E$', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?\\Qfood\\E$') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '(?i)(?u).*?\\Qfood\\E$')" ); outputSelReplace = list( (Object)"amazing restaurant. Very good dinner", "This is a worst restaurant. bad dinner", "Amazing environment. Amazing dinner", "Not good" ); outputCompleteReplace = list( (Object)"dinner", "dinner", "dinner", "Not good" ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "dinner"}, outputSelReplace, asList(true, true, true, false), asList(asList(new CardExamplePosition(30, 4)), asList(new CardExamplePosition(32, 4)), asList(new CardExamplePosition(29, 4)), null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "dinner"}, outputCompleteReplace, asList(true, true, true, false), asList(asList(new CardExamplePosition(30, 4)), asList(new CardExamplePosition(32, 4)), asList(new CardExamplePosition(29, 4)), null) ); } @Test public void exact() throws Exception { final File dataFile = temp.newFile("exact.json"); try (final PrintWriter printWriter = new PrintWriter(dataFile)) { printWriter.append("{ \"col\" : \"Los Angeles\" }"); printWriter.append("{ \"col\" : \"LOS ANGELES\" }"); printWriter.append("{ \"col\" : \"LOS ANGELES, CA\" }"); printWriter.append("{ \"col\" : null }"); } ReplacePatternRule rule = new ReplacePatternRule() .setSelectionType(ReplaceSelectionType.EXACT) .setSelectionPattern("Los Angeles"); TransformRuleWrapper<ReplacePatternRule> ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'EXACT', 'Los Angeles', false)", "CASE WHEN \"input.expr\" = 'Los Angeles' THEN NULL ELSE \"input.expr\" END", "CASE WHEN \"input.expr\" = 'Los Angeles' THEN " + "'new''''value' ELSE \"input.expr\" END", "CASE WHEN \"input.expr\" = 'Los Angeles' THEN 'new value' ELSE \"input.expr\" END", "\"user\".\"col.with.dots\" = 'Los Angeles'" ); List<Object> outputSelReplace = list( (Object)"LOS ANGELES", "LOS ANGELES", "LOS ANGELES, CA", null ); List<Object> outputCompleteReplace = list( (Object)"LOS ANGELES", "LOS ANGELES", "LOS ANGELES, CA", null ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "LOS ANGELES"}, outputSelReplace, asList(true, false, false, false), asList(asList(new CardExamplePosition(0, 11)), null, null, null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "LOS ANGELES"}, outputCompleteReplace, asList(true, false, false, false), asList(asList(new CardExamplePosition(0, 11)), null, null, null) ); rule = rule.setIgnoreCase(true); ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'EXACT', 'Los Angeles', true)", "CASE WHEN lower(\"input.expr\") = lower('Los Angeles') THEN NULL ELSE \"input.expr\" END", "CASE WHEN lower(\"input.expr\") = lower('Los Angeles') THEN " + "'new''''value' ELSE \"input.expr\" END", "CASE WHEN lower(\"input.expr\") = lower('Los Angeles') THEN 'new value' ELSE \"input.expr\" END", "lower(\"user\".\"col.with.dots\") = lower('Los Angeles')" ); outputSelReplace = list( (Object)"LosAngeles", "LosAngeles", "LOS ANGELES, CA", null ); outputCompleteReplace = list( (Object)"LosAngeles", "LosAngeles", "LOS ANGELES, CA", null ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "LosAngeles"}, outputSelReplace, asList(true, true, false, false), asList(asList(new CardExamplePosition(0, 11)), asList(new CardExamplePosition(0, 11)), null, null) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "LosAngeles"}, outputCompleteReplace, asList(true, true, false, false), asList(asList(new CardExamplePosition(0, 11)), asList(new CardExamplePosition(0, 11)), null, null) ); } @Test public void matches() throws Exception { final File dataFile = temp.newFile("matches.json"); try (final PrintWriter printWriter = new PrintWriter(dataFile)) { printWriter.append("{ \"col\" : \"Los Angeles\" }"); printWriter.append("{ \"col\" : \"LOS Angeles\" }"); printWriter.append("{ \"col\" : \"LOSANGELES\" }"); printWriter.append("{ \"col\" : \"LosAngeles, CA\" }"); } ReplacePatternRule rule = new ReplacePatternRule() .setSelectionType(ReplaceSelectionType.MATCHES) .setSelectionPattern("Los.*Angeles"); TransformRuleWrapper<ReplacePatternRule> ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'MATCHES', 'Los.*Angeles', false)", "CASE WHEN regexp_like(\"input.expr\", '.*?Los.*Angeles.*?') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '.*?Los.*Angeles.*?') THEN " + "regexp_replace(\"input.expr\", 'Los.*Angeles', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '.*?Los.*Angeles.*?') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '.*?Los.*Angeles.*?')" ); List<Object> outputSelReplace = list( (Object)"LOS ANGELES", "LOS Angeles", "LOSANGELES", "LOS ANGELES, CA" ); List<Object> outputCompleteReplace = list( (Object)"LOS ANGELES", "LOS Angeles", "LOSANGELES", "LOS ANGELES" ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "LOS ANGELES"}, outputSelReplace, asList(true, false, false, true), asList(asList(new CardExamplePosition(0, 11)), null, null, asList(new CardExamplePosition(0, 10))) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "LOS ANGELES"}, outputCompleteReplace, asList(true, false, false, true), asList(asList(new CardExamplePosition(0, 11)), null, null, asList(new CardExamplePosition(0, 10))) ); rule = rule.setIgnoreCase(true); ruleWrapper = recommender.wrapRule(rule); validateExpressions( ruleWrapper, "match_pattern_example(\"table.with.dots\".col, 'MATCHES', 'Los.*Angeles', true)", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?Los.*Angeles.*?') THEN NULL ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?Los.*Angeles.*?') THEN " + "regexp_replace(\"input.expr\", '(?i)(?u)Los.*Angeles', 'new''''value') ELSE \"input.expr\" END", "CASE WHEN regexp_like(\"input.expr\", '(?i)(?u).*?Los.*Angeles.*?') THEN 'new value' ELSE \"input.expr\" END", "regexp_like(\"user\".\"col.with.dots\", '(?i)(?u).*?Los.*Angeles.*?')" ); outputSelReplace = list( (Object)"LOS ANGELES", "LOS ANGELES", "LOS ANGELES", "LOS ANGELES, CA" ); outputCompleteReplace = list( (Object)"LOS ANGELES", "LOS ANGELES", "LOS ANGELES", "LOS ANGELES" ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "LOS ANGELES"}, outputSelReplace, asList(true, true, true, true), asList(asList(new CardExamplePosition(0, 11)), asList(new CardExamplePosition(0, 11)), asList(new CardExamplePosition(0, 10)), asList(new CardExamplePosition(0, 10))) ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "LOS ANGELES"}, outputCompleteReplace, asList(true, true, true, true), asList(asList(new CardExamplePosition(0, 11)), asList(new CardExamplePosition(0, 11)), asList(new CardExamplePosition(0, 10)), asList(new CardExamplePosition(0, 10))) ); } @Test public void isNull() throws Exception { final File dataFile = temp.newFile("nullTest.json"); try (final PrintWriter printWriter = new PrintWriter(dataFile)) { printWriter.append("{ \"col\" : \"Los Angeles\" }"); printWriter.append("{ \"col\" : null }"); } ReplacePatternRule rule = new ReplacePatternRule() .setSelectionType(ReplaceSelectionType.IS_NULL); TransformRuleWrapper<ReplacePatternRule> ruleWrapper = recommender.wrapRule(rule); assertEquals("CASE WHEN \"input.expr\" IS NULL THEN 'new''''value' ELSE \"input.expr\" END", ruleWrapper.getFunctionExpr("\"input.expr\"", ReplaceType.SELECTION, "new''value")); assertEquals("CASE WHEN \"input.expr\" IS NULL THEN 'new value' ELSE \"input.expr\" END", ruleWrapper.getFunctionExpr("\"input.expr\"", ReplaceType.VALUE, "new value")); assertEquals("\"user\".\"col.with.dots\" IS NULL", ruleWrapper.getMatchFunctionExpr("\"user\".\"col.with.dots\"")); List<Object> output = list( (Object)"Los Angeles", "Los Angeles" ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.SELECTION, "Los Angeles"}, output, asList(false, true), null ); validate(dataFile.getAbsolutePath(), ruleWrapper, new Object[] { ReplaceType.VALUE, "Los Angeles"}, output, asList(false, true), null ); }
TypeConvertingSqlAccessor implements SqlAccessor { @Override public byte getByte( int rowOffset ) throws InvalidAccessException { final byte result; switch ( getType().getMinorType() ) { case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case SMALLINT: result = getByteValueOrThrow( innerAccessor.getShort( rowOffset ), "Java short / SQL SMALLINT" ); break; case INT: result = getByteValueOrThrow( innerAccessor.getInt( rowOffset ), "Java int / SQL INTEGER" ); break; case BIGINT: result = getByteValueOrThrow( innerAccessor.getLong( rowOffset ), "Java long / SQL BIGINT" ); break; case FLOAT4: result = getByteValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getByteValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; case DECIMAL: result = getByteValueOrThrow( innerAccessor.getBigDecimal( rowOffset ).doubleValue(), "Java decimal / SQL DECIMAL PRECISION" ); break; default: result = innerAccessor.getByte( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset, Calendar calendar ); @Override Time getTime( int rowOffset, Calendar calendar ); @Override Timestamp getTimestamp( int rowOffset, Calendar calendar ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); }
@Test public void test_getByte_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getByte( 0 ), equalTo( (byte) 127 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getByte( 0 ), equalTo( (byte) -128 ) ); } @Test public void test_getByte_on_SMALLINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 127 ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) 127 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_SMALLINT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 128 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "128" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "short" ), containsString( "SMALLINT" ) ) ); throw e; } } @Test public void test_getByte_on_INTEGER_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -128 ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) -128 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_INTEGER_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -129 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-129" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "int" ), containsString( "INTEGER" ) ) ); throw e; } } @Test public void test_getByte_on_BIGINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( -128 ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) -128 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_BIGINT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 129 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "129" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "long" ), containsString( "BIGINT" ) ) ); throw e; } } @Test public void test_getByte_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -128.0f ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) -128 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -130f ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-130" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } } @Test public void test_getByte_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 127.0d ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) 127) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -130 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-130" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), anyOf( containsString( "DOUBLE PRECISION" ), containsString( "FLOAT(" ) ) ) ); throw e; } }
TypeConvertingSqlAccessor implements SqlAccessor { @Override public short getShort( int rowOffset ) throws InvalidAccessException { final short result; switch ( getType().getMinorType() ) { case SMALLINT: result = innerAccessor.getShort( rowOffset ); break; case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case INT: result = getShortValueOrThrow( innerAccessor.getInt( rowOffset ), "Java int / SQL INTEGER" ); break; case BIGINT: result = getShortValueOrThrow( innerAccessor.getLong( rowOffset ), "Java long / SQL BIGINT" ); break; case FLOAT4: result = getShortValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getShortValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; case DECIMAL: result = getShortValueOrThrow( innerAccessor.getBigDecimal( rowOffset ).doubleValue(), "Java decimal / SQL DECIMAL PRECISION" ); break; default: result = innerAccessor.getByte( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset, Calendar calendar ); @Override Time getTime( int rowOffset, Calendar calendar ); @Override Timestamp getTimestamp( int rowOffset, Calendar calendar ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); }
@Test public void test_getShort_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getShort( 0 ), equalTo( (short) 127 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getShort( 0 ), equalTo( (short) -128 ) ); } @Test public void test_getShort_on_SMALLINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 32767 ) ); assertThat( uut1.getShort( 0 ), equalTo( (short) 32767 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) -32768 ) ); assertThat( uut2.getShort( 0 ), equalTo( (short) -32768 ) ); } @Test public void test_getShort_on_INTEGER_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( 32767 ) ); assertThat( uut1.getShort( 0 ), equalTo( (short) 32767 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -32768 ) ); assertThat( uut2.getShort( 0 ), equalTo( (short) -32768 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_INTEGER_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -32769 ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-32769" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "int" ), containsString( "INTEGER" ) ) ); throw e; } } @Test public void test_getShort_BIGINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( -32678 ) ); assertThat( uut.getShort( 0 ), equalTo( (short) -32678 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_BIGINT_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 65535 ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "65535" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "long" ), containsString( "BIGINT" ) ) ); throw e; } } @Test public void test_getShort_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -32768f ) ); assertThat( uut.getShort( 0 ), equalTo( (short) -32768 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -32769f ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-32769" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } } @Test public void test_getShort_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 32767d ) ); assertThat( uut.getShort( 0 ), equalTo( (short) 32767) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 32768 ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "32768" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), anyOf( containsString( "DOUBLE PRECISION" ), containsString( "FLOAT" ) ) ) ); throw e; } }
TypeConvertingSqlAccessor implements SqlAccessor { @Override public int getInt( int rowOffset ) throws InvalidAccessException { final int result; switch ( getType().getMinorType() ) { case INT: result = innerAccessor.getInt( rowOffset ); break; case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case SMALLINT: result = innerAccessor.getShort( rowOffset ); break; case BIGINT: result = getIntValueOrThrow( innerAccessor.getLong( rowOffset ), "Java long / SQL BIGINT" ); break; case FLOAT4: result = getIntValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getIntValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; case DECIMAL: result = getIntValueOrThrow( innerAccessor.getBigDecimal( rowOffset ).doubleValue(), "Java decimal / SQL DECIMAL PRECISION" ); break; default: result = innerAccessor.getInt( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset, Calendar calendar ); @Override Time getTime( int rowOffset, Calendar calendar ); @Override Timestamp getTimestamp( int rowOffset, Calendar calendar ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); }
@Test public void test_getInt_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getInt( 0 ), equalTo( 127 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getInt( 0 ), equalTo( -128 ) ); } @Test public void test_getInt_on_SMALLINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 32767 ) ); assertThat( uut1.getInt( 0 ), equalTo( 32767 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) -32768 ) ); assertThat( uut2.getInt( 0 ), equalTo( -32768 ) ); } @Test public void test_getInt_on_INTEGER_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( 2147483647 ) ); assertThat( uut1.getInt( 0 ), equalTo( 2147483647 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -2147483648 ) ); assertThat( uut2.getInt( 0 ), equalTo( -2147483648 ) ); } @Test public void test_getInt_on_BIGINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 2147483647 ) ); assertThat( uut.getInt( 0 ), equalTo( 2147483647 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getInt_on_BIGINT_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 2147483648L ) ); try { uut.getInt( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "2147483648" ) ); assertThat( e.getMessage(), containsString( "getInt" ) ); assertThat( e.getMessage(), allOf( containsString( "long" ), containsString( "BIGINT" ) ) ); throw e; } } @Test public void test_getInt_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1e9f ) ); assertThat( uut.getInt( 0 ), equalTo( 1_000_000_000 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getInt_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1e10f ) ); try { uut.getInt( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.0E10" ) ); assertThat( e.getMessage(), containsString( "getInt" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } } @Test public void test_getInt_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -2147483648.0d ) ); assertThat( uut.getInt( 0 ), equalTo( -2147483648 ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getInt_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -2147483649.0d ) ); try { uut.getInt( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-2.147483649E9" ) ); assertThat( e.getMessage(), containsString( "getInt" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), containsString( "DOUBLE PRECISION" ) ) ); throw e; } }
TypeConvertingSqlAccessor implements SqlAccessor { @Override public long getLong( int rowOffset ) throws InvalidAccessException { final long result; switch ( getType().getMinorType() ) { case BIGINT: result = innerAccessor.getLong( rowOffset ); break; case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case SMALLINT: result = innerAccessor.getShort( rowOffset ); break; case INT: result = innerAccessor.getInt( rowOffset ); break; case FLOAT4: result = getLongValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getLongValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; case DECIMAL: result = getLongValueOrThrow( innerAccessor.getBigDecimal( rowOffset ).doubleValue(), "Java decimal / SQL DECIMAL PRECISION" ); break; default: result = innerAccessor.getLong( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset, Calendar calendar ); @Override Time getTime( int rowOffset, Calendar calendar ); @Override Timestamp getTimestamp( int rowOffset, Calendar calendar ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); }
@Test public void test_getLong_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getLong( 0 ), equalTo( 127L ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getLong( 0 ), equalTo( -128L ) ); } @Test public void test_getLong_on_SMALLINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 32767 ) ); assertThat( uut1.getLong( 0 ), equalTo( 32767L ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) -32768 ) ); assertThat( uut2.getLong( 0 ), equalTo( -32768L ) ); } @Test public void test_getLong_on_INTEGER_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( 2147483647 ) ); assertThat( uut1.getLong( 0 ), equalTo( 2147483647L ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -2147483648 ) ); assertThat( uut2.getLong( 0 ), equalTo( -2147483648L ) ); } @Test public void test_getLong_on_BIGINT_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 2147483648L ) ); assertThat( uut.getLong( 0 ), equalTo( 2147483648L ) ); } @Test public void test_getLong_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 9223372036854775807L * 1.0f ) ); assertThat( uut.getLong( 0 ), equalTo( 9223372036854775807L ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getLong_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1.5e20f ) ); try { uut.getLong( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.5000" ) ); assertThat( e.getMessage(), containsString( "getLong" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } } @Test public void test_getLong_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 9223372036854775807L * 1.0d ) ); assertThat( uut.getLong( 0 ), equalTo( 9223372036854775807L ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getLong_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 1e20 ) ); try { uut.getLong( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.0E20" ) ); assertThat( e.getMessage(), containsString( "getLong" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), containsString( "DOUBLE PRECISION" ) ) ); throw e; } }
Upgrade { @VisibleForTesting public void validateUpgrade(final LegacyKVStoreProvider storeProvider, final String curEdition) throws Exception { if (!getDACConfig().isMigrationEnabled()) { final ConfigurationStore configurationStore = new ConfigurationStore(storeProvider); final ConfigurationEntry entry = configurationStore.get(SupportService.DREMIO_EDITION); if (entry != null && entry.getValue() != null) { final String prevEdition = new String(entry.getValue().toByteArray()); if (!Strings.isNullOrEmpty(prevEdition) && !prevEdition.equals(curEdition)) { throw new Exception(String.format("Illegal upgrade from %s to %s", prevEdition, curEdition)); } } } } Upgrade(DACConfig dacConfig, ScanResult classPathScan, boolean verbose); void run(); void run(boolean noDBOpenRetry); @VisibleForTesting void validateUpgrade(final LegacyKVStoreProvider storeProvider, final String curEdition); void run(final LegacyKVStoreProvider storeProvider); static void main(String[] args); static final Comparator<Version> UPGRADE_VERSION_ORDERING; }
@Test public void testIllegalUpgrade() throws Exception { thrown.expect(Exception.class); thrown.expectMessage("Illegal upgrade from OSS to EE"); final ByteString prevEdition = ByteString.copyFrom("OSS".getBytes()); final ConfigurationEntry configurationEntry = new ConfigurationEntry(); configurationEntry.setValue(prevEdition); final LegacyKVStoreProvider kvStoreProvider = LegacyKVStoreProviderAdapter.inMemory(CLASSPATH_SCAN_RESULT); kvStoreProvider.start(); final ConfigurationStore configurationStore = new ConfigurationStore(kvStoreProvider); configurationStore.put(SupportService.DREMIO_EDITION, configurationEntry); new Upgrade(DACConfig.newConfig(), CLASSPATH_SCAN_RESULT, false).validateUpgrade(kvStoreProvider, "EE"); } @Test public void testLegalUpgrade() throws Exception { final ByteString prevEdition = ByteString.copyFrom("OSS".getBytes()); final ConfigurationEntry configurationEntry = new ConfigurationEntry(); configurationEntry.setValue(prevEdition); final LegacyKVStoreProvider kvStoreProvider = LegacyKVStoreProviderAdapter.inMemory(CLASSPATH_SCAN_RESULT); kvStoreProvider.start(); final ConfigurationStore configurationStore = new ConfigurationStore(kvStoreProvider); new Upgrade(DACConfig.newConfig(), CLASSPATH_SCAN_RESULT, false).validateUpgrade(kvStoreProvider, "OSS"); configurationStore.put(SupportService.DREMIO_EDITION, configurationEntry); new Upgrade(DACConfig.newConfig(), CLASSPATH_SCAN_RESULT, false).validateUpgrade(kvStoreProvider, "OSS"); }
TypeConvertingSqlAccessor implements SqlAccessor { @Override public float getFloat( int rowOffset ) throws InvalidAccessException { final float result; switch ( getType().getMinorType() ) { case FLOAT4: result = innerAccessor.getFloat( rowOffset ); break; case INT: result = innerAccessor.getInt( rowOffset ); break; case BIGINT: result = innerAccessor.getLong( rowOffset ); break; case FLOAT8: final double value = innerAccessor.getDouble( rowOffset ); if ( Float.MIN_VALUE <= value && value <= Float.MAX_VALUE ) { result = (float) value; } else { throw newOverflowException( "getFloat(...)", "Java double / SQL DOUBLE PRECISION", value ); } break; case DECIMAL: final BigDecimal decimalValue = innerAccessor.getBigDecimal( rowOffset ); final float tempFloat = decimalValue.floatValue(); if ( Float.NEGATIVE_INFINITY == tempFloat || Float.POSITIVE_INFINITY == tempFloat) { throw newOverflowException( "getFloat(...)", "Java decimal / SQL DECIMAL PRECISION", tempFloat ); } else { result = tempFloat; } break; default: result = innerAccessor.getInt( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset, Calendar calendar ); @Override Time getTime( int rowOffset, Calendar calendar ); @Override Timestamp getTimestamp( int rowOffset, Calendar calendar ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); }
@Test public void test_getFloat_on_FLOAT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1.23f ) ); assertThat( uut1.getFloat( 0 ), equalTo( 1.23f ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MAX_VALUE ) ); assertThat( uut2.getFloat( 0 ), equalTo( Float.MAX_VALUE ) ); final SqlAccessor uut3 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MIN_VALUE ) ); assertThat( uut3.getFloat( 0 ), equalTo( Float.MIN_VALUE ) ); } @Test public void test_getFloat_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 1.125 ) ); assertThat( uut1.getFloat( 0 ), equalTo( 1.125f ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( Float.MAX_VALUE ) ); assertThat( uut2.getFloat( 0 ), equalTo( Float.MAX_VALUE ) ); } @Test( expected = SQLConversionOverflowException.class ) public void test_getFloat_on_DOUBLE_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 1e100 ) ); try { uut.getFloat( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.0E100" ) ); assertThat( e.getMessage(), containsString( "getFloat" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), anyOf ( containsString( "DOUBLE PRECISION" ), containsString( "FLOAT" ) ) ) ); throw e; } }
TypeConvertingSqlAccessor implements SqlAccessor { @Override public double getDouble( int rowOffset ) throws InvalidAccessException { final double result; switch ( getType().getMinorType() ) { case FLOAT8: result = innerAccessor.getDouble( rowOffset ); break; case INT: result = innerAccessor.getInt( rowOffset ); break; case BIGINT: result = innerAccessor.getLong( rowOffset ); break; case FLOAT4: result = innerAccessor.getFloat( rowOffset ); break; case DECIMAL: result = innerAccessor.getBigDecimal( rowOffset ).doubleValue(); break; default: result = innerAccessor.getLong( rowOffset ); } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset, Calendar calendar ); @Override Time getTime( int rowOffset, Calendar calendar ); @Override Timestamp getTimestamp( int rowOffset, Calendar calendar ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); }
@Test public void test_getDouble_on_FLOAT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new FloatStubAccessor( 6.02e23f ) ); assertThat( uut1.getDouble( 0 ), equalTo( (double) 6.02e23f ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MAX_VALUE ) ); assertThat( uut2.getDouble( 0 ), equalTo( (double) Float.MAX_VALUE ) ); final SqlAccessor uut3 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MIN_VALUE ) ); assertThat( uut3.getDouble( 0 ), equalTo( (double) Float.MIN_VALUE ) ); } @Test public void test_getDouble_on_DOUBLE_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -1e100 ) ); assertThat( uut1.getDouble( 0 ), equalTo( -1e100 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( Double.MAX_VALUE ) ); assertThat( uut2.getDouble( 0 ), equalTo( Double.MAX_VALUE ) ); final SqlAccessor uut3 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( Double.MIN_VALUE ) ); assertThat( uut3.getDouble( 0 ), equalTo( Double.MIN_VALUE ) ); }
DictionaryBuilder { public Iterable<T> build() { Preconditions.checkArgument(!isBuilt, "build can only be called once"); isBuilt = true; if (valueAccumulator.isEmpty()) { return Collections.emptyList(); } final T[] values = ObjectArrays.newArray(clazzType, valueAccumulator.size()); for (ObjectIntCursor<T> entry : valueAccumulator) { values[entry.value] = entry.key; } return Arrays.asList(values); } DictionaryBuilder(final Class<T> clazzType); int getOrCreateSubscript(final T value); Iterable<T> build(); }
@Test public void testEmpty() { DictionaryBuilder<String> builder = new DictionaryBuilder<>(String.class); Iterator<String> iterator = builder.build().iterator(); assertFalse(iterator.hasNext()); }
HiveReaderProtoUtil { @Deprecated static Map<String, Integer> buildInputFormatLookup(HiveTableXattrOrBuilder tableXattr) { int i = 0; final Map<String, Integer> lookup = Maps.newHashMap(); for (final PartitionXattr partitionXattr : tableXattr.getPartitionXattrsList()) { if (partitionXattr.hasInputFormat() && !lookup.containsKey(partitionXattr.getInputFormat())) { lookup.put(partitionXattr.getInputFormat(), i++); } } if (tableXattr.hasInputFormat() && !lookup.containsKey(tableXattr.getInputFormat())) { lookup.put(tableXattr.getInputFormat(), i); } return lookup; } private HiveReaderProtoUtil(); @Deprecated static void encodePropertiesAsDictionary(HiveTableXattr.Builder tableXattr); static List<Prop> getTableProperties(final HiveTableXattr tableXattr); static Optional<String> getTableInputFormat(final HiveTableXattr tableXattr); static Optional<String> getTableStorageHandler(final HiveTableXattr tableXattr); static Optional<String> getTableSerializationLib(final HiveTableXattr tableXattr); static List<Prop> getPartitionProperties(final HiveTableXattr tableXattr, int partitionIndex); static List<Prop> getPartitionProperties(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static Optional<String> getPartitionInputFormat(final HiveTableXattr tableXattr, int partitionId); static Optional<String> getPartitionInputFormat(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static Optional<String> getPartitionStorageHandler(final HiveTableXattr tableXattr, int partitionId); static Optional<String> getPartitionStorageHandler(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static Optional<String> getPartitionSerializationLib(final HiveTableXattr tableXattr, int partitionId); static String getPartitionSerializationLib(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static PartitionXattr getPartitionXattr(SplitAndPartitionInfo split); static boolean isPreDremioVersion3dot2dot0LegacyFormat(final HiveTableXattr tableXattr); static Map<String, AttributeValue> convertValuesToNonProtoAttributeValues(Map<String, HiveReaderProto.AttributeValue> protoMap); static HiveReaderProto.AttributeValue toProtobuf(AttributeValue attributeValue); static AttributeValue toAttribute(HiveReaderProto.AttributeValue attributeValueProto); static String getTypeName(AttributeValue value); static boolean getBoolean(AttributeValue attributeValue); }
@Test public void buildInputFormatLookup() { { assertTrue(HiveReaderProtoUtil.buildInputFormatLookup(HiveTableXattr.newBuilder().build()).size() == 0); } { HiveTableXattr xattr = HiveTableXattr.newBuilder() .addAllPartitionXattrs( Lists.newArrayList( newPartitionXattrWithInputFormat("a"), newPartitionXattrWithInputFormat("a"), newPartitionXattrWithInputFormat("b"))) .build(); Map<String, Integer> result = HiveReaderProtoUtil.buildInputFormatLookup(xattr); assertTrue(result.size() == 2); assertNotNull(result.get("a")); assertNotNull(result.get("b")); } { HiveTableXattr xattr = HiveTableXattr.newBuilder() .addAllPartitionXattrs( Lists.newArrayList( newPartitionXattrWithInputFormat("a"), newPartitionXattrWithInputFormat("b"))) .setInputFormat("c") .build(); Map<String, Integer> result = HiveReaderProtoUtil.buildInputFormatLookup(xattr); assertTrue(result.size() == 3); assertNotNull(result.get("a")); assertNotNull(result.get("b")); assertNotNull(result.get("c")); } { HiveTableXattr xattr = HiveTableXattr.newBuilder() .addAllPartitionXattrs( Lists.newArrayList( newPartitionXattrWithInputFormat("a"), newPartitionXattrWithInputFormat("b"))) .setInputFormat("a") .build(); Map<String, Integer> result = HiveReaderProtoUtil.buildInputFormatLookup(xattr); assertTrue(result.size() == 2); assertNotNull(result.get("a")); assertNotNull(result.get("b")); } }
HiveReaderProtoUtil { @Deprecated static Map<Prop, Integer> buildPropLookup(HiveTableXattrOrBuilder tableXattr) { int i = 0; final Map<Prop, Integer> lookup = Maps.newHashMap(); for (final PartitionXattr partitionXattr : tableXattr.getPartitionXattrsList()) { for (final Prop prop : partitionXattr.getPartitionPropertyList()) { if (!lookup.containsKey(prop)) { lookup.put(prop, i++); } } } for (final Prop tableProp : tableXattr.getTablePropertyList()) { if (!lookup.containsKey(tableProp)) { lookup.put(tableProp, i++); } } return lookup; } private HiveReaderProtoUtil(); @Deprecated static void encodePropertiesAsDictionary(HiveTableXattr.Builder tableXattr); static List<Prop> getTableProperties(final HiveTableXattr tableXattr); static Optional<String> getTableInputFormat(final HiveTableXattr tableXattr); static Optional<String> getTableStorageHandler(final HiveTableXattr tableXattr); static Optional<String> getTableSerializationLib(final HiveTableXattr tableXattr); static List<Prop> getPartitionProperties(final HiveTableXattr tableXattr, int partitionIndex); static List<Prop> getPartitionProperties(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static Optional<String> getPartitionInputFormat(final HiveTableXattr tableXattr, int partitionId); static Optional<String> getPartitionInputFormat(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static Optional<String> getPartitionStorageHandler(final HiveTableXattr tableXattr, int partitionId); static Optional<String> getPartitionStorageHandler(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static Optional<String> getPartitionSerializationLib(final HiveTableXattr tableXattr, int partitionId); static String getPartitionSerializationLib(final HiveTableXattr tableXattr, final PartitionXattr partitionXattr); static PartitionXattr getPartitionXattr(SplitAndPartitionInfo split); static boolean isPreDremioVersion3dot2dot0LegacyFormat(final HiveTableXattr tableXattr); static Map<String, AttributeValue> convertValuesToNonProtoAttributeValues(Map<String, HiveReaderProto.AttributeValue> protoMap); static HiveReaderProto.AttributeValue toProtobuf(AttributeValue attributeValue); static AttributeValue toAttribute(HiveReaderProto.AttributeValue attributeValueProto); static String getTypeName(AttributeValue value); static boolean getBoolean(AttributeValue attributeValue); }
@Test public void buildPropLookup() { { assertTrue(HiveReaderProtoUtil.buildPropLookup(HiveTableXattr.newBuilder().build()).size() == 0); } { HiveTableXattr.Builder xattr = HiveTableXattr.newBuilder() .addAllPartitionXattrs( Lists.newArrayList( newPartitionXattrWithProps(newProp("a", "b")), newPartitionXattrWithProps(newProp("c", "d"), newProp("a", "b")))); Map<Prop, Integer> lookup = HiveReaderProtoUtil.buildPropLookup(xattr); assertTrue(lookup.size() == 2); assertNotNull(lookup.get(newProp("a", "b"))); assertNotNull(lookup.get(newProp("c", "d"))); } { HiveTableXattr.Builder xattr = HiveTableXattr.newBuilder() .addAllPartitionXattrs( Lists.newArrayList( newPartitionXattrWithProps(newProp("a", "b"), newProp("c", "d")))) .addAllTableProperty( Lists.newArrayList( newProp("a", "c"))); Map<Prop, Integer> lookup = HiveReaderProtoUtil.buildPropLookup(xattr); assertTrue(lookup.size() == 3); assertNotNull(lookup.get(newProp("a", "b"))); assertNotNull(lookup.get(newProp("c", "d"))); assertNotNull(lookup.get(newProp("a", "c"))); } { HiveTableXattr.Builder xattr = HiveTableXattr.newBuilder() .addAllPartitionXattrs( Lists.newArrayList( newPartitionXattrWithProps(newProp("a", "b"), newProp("c", "d")), newPartitionXattrWithProps(newProp("c", "d"), newProp("c", "d")), newPartitionXattrWithProps(newProp("c", "d"), newProp("c", "e")), newPartitionXattrWithProps(newProp("c", "d")), newPartitionXattrWithProps(newProp("c", "d")), newPartitionXattrWithProps(newProp("c", "d")))) .addAllTableProperty( Lists.newArrayList( newProp("a", "b"), newProp("a", "b"), newProp("a", "b"), newProp("a", "b"), newProp("a", "c"))); Map<Prop, Integer> lookup = HiveReaderProtoUtil.buildPropLookup(xattr); assertTrue(lookup.size() == 4); assertNotNull(lookup.get(newProp("a", "b"))); assertNotNull(lookup.get(newProp("c", "d"))); assertNotNull(lookup.get(newProp("a", "c"))); assertNotNull(lookup.get(newProp("c", "e"))); } }
DremioFileSystem extends FileSystem { void updateOAuthConfig(Configuration conf, String accountName, String accountNameWithoutSuffix) { final String CLIENT_ID = "dremio.azure.clientId"; final String TOKEN_ENDPOINT = "dremio.azure.tokenEndpoint"; final String CLIENT_SECRET = "dremio.azure.clientSecret"; String refreshToken = getValueForProperty(conf, FS_AZURE_ACCOUNT_OAUTH_CLIENT_ENDPOINT, accountName, accountNameWithoutSuffix, "OAuth Client Endpoint not found."); String clientId = getValueForProperty(conf, FS_AZURE_ACCOUNT_OAUTH_CLIENT_ID, accountName, accountNameWithoutSuffix, "OAuth Client Id not found."); String password = getValueForProperty(conf, FS_AZURE_ACCOUNT_OAUTH_CLIENT_SECRET, accountName, accountNameWithoutSuffix ,"OAuth Client Password not found."); conf.set(CLIENT_ID, clientId); conf.set(TOKEN_ENDPOINT, refreshToken); conf.set(CLIENT_SECRET, password); } @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path path, int i); @Override FSDataOutputStream create(Path path, FsPermission fsPermission, boolean overwrite, int i, short i1, long l, Progressable progressable); @Override FSDataOutputStream append(Path path, int i, Progressable progressable); @Override boolean rename(Path path, Path path1); @Override boolean delete(Path path, boolean recursive); @Override FileStatus[] listStatus(Path path); @Override void setWorkingDirectory(Path path); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path path, FsPermission fsPermission); @Override FileStatus getFileStatus(Path path); boolean supportsAsync(); AsyncByteReader getAsyncByteReader(AsyncByteReader.FileKey fileKey, OperatorStats operatorStats); @Override String getScheme(); }
@Test public void testAzureOauthCopy() { DremioFileSystem fileSystem = new DremioFileSystem(); Configuration conf = new Configuration(); conf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ENDPOINT, ENDPOINT); conf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ID, CLIEN_ID); conf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_SECRET, PASSWORD); fileSystem.updateOAuthConfig(conf, "testAccount.1234", "testAccount"); Assert.assertEquals(ENDPOINT, conf.get("dremio.azure.tokenEndpoint")); Assert.assertEquals(CLIEN_ID, conf.get("dremio.azure.clientId")); Assert.assertEquals(PASSWORD, conf.get("dremio.azure.clientSecret")); } @Test public void testAzureOauthCopyWithAccountProperties() { DremioFileSystem fileSystem = new DremioFileSystem(); Configuration conf = new Configuration(); conf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ENDPOINT + ".testAccount", ENDPOINT); conf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_ID + ".testAccount", CLIEN_ID); conf.set(FS_AZURE_ACCOUNT_OAUTH_CLIENT_SECRET + ".testAccount", PASSWORD); fileSystem.updateOAuthConfig(conf, "testAccount.1234", "testAccount"); Assert.assertEquals(ENDPOINT, conf.get("dremio.azure.tokenEndpoint")); Assert.assertEquals(CLIEN_ID, conf.get("dremio.azure.clientId")); Assert.assertEquals(PASSWORD, conf.get("dremio.azure.clientSecret")); }
HiveScanBatchCreator implements HiveProxiedScanBatchCreator { @VisibleForTesting public UserGroupInformation getUGI(HiveStoragePlugin storagePlugin, HiveProxyingSubScan config) { final String userName = storagePlugin.getUsername(config.getProps().getUserName()); return HiveImpersonationUtil.createProxyUgi(userName); } @Override ProducerOperator create(FragmentExecutionContext fragmentExecContext, OperatorContext context, HiveProxyingSubScan config); @VisibleForTesting UserGroupInformation getUGI(HiveStoragePlugin storagePlugin, HiveProxyingSubScan config); }
@Test public void ensureStoragePluginIsUsedForUsername() throws Exception { final String originalName = "Test"; final String finalName = "Replaced"; final HiveScanBatchCreator creator = new HiveScanBatchCreator(); final HiveStoragePlugin plugin = mock(HiveStoragePlugin.class); when(plugin.getUsername(originalName)).thenReturn(finalName); final FragmentExecutionContext fragmentExecutionContext = mock(FragmentExecutionContext.class); when(fragmentExecutionContext.getStoragePlugin(any())).thenReturn(plugin); final OpProps props = mock(OpProps.class); final HiveProxyingSubScan hiveSubScan = mock(HiveProxyingSubScan.class); when(hiveSubScan.getProps()).thenReturn(props); when(hiveSubScan.getProps().getUserName()).thenReturn(originalName); final UserGroupInformation ugi = creator.getUGI(plugin, hiveSubScan); verify(plugin).getUsername(originalName); assertEquals(finalName, ugi.getUserName()); }
HiveScanBatchCreator implements HiveProxiedScanBatchCreator { boolean allSplitsAreOnS3(List<SplitAndPartitionInfo> splits) { for (SplitAndPartitionInfo split : splits) { try { final HiveReaderProto.HiveSplitXattr splitAttr = HiveReaderProto.HiveSplitXattr.parseFrom(split.getDatasetSplitInfo().getExtendedProperty()); final FileSplit fullFileSplit = (FileSplit) HiveUtilities.deserializeInputSplit(splitAttr.getInputSplit()); if (!AsyncReaderUtils.S3_FILE_SYSTEM.contains(fullFileSplit.getPath().toUri().getScheme().toLowerCase())) { logger.error("Data file {} is not on S3.", fullFileSplit.getPath()); return false; } } catch (IOException | ReflectiveOperationException e) { throw new RuntimeException("Failed to parse dataset split for " + split.getPartitionInfo().getSplitKey(), e); } } return true; } @Override ProducerOperator create(FragmentExecutionContext fragmentExecContext, OperatorContext context, HiveProxyingSubScan config); @VisibleForTesting UserGroupInformation getUGI(HiveStoragePlugin storagePlugin, HiveProxyingSubScan config); }
@Test public void testAllSplitsAreOnS3() { List<SplitAndPartitionInfo> s3Splits = buildSplits("s3"); List<SplitAndPartitionInfo> hdfsplits = buildSplits("hdfs"); HiveScanBatchCreator scanBatchCreator = new HiveScanBatchCreator(); assertTrue(scanBatchCreator.allSplitsAreOnS3(s3Splits)); assertFalse(scanBatchCreator.allSplitsAreOnS3(hdfsplits)); }
HiveStoragePlugin extends BaseHiveStoragePlugin implements StoragePluginCreator.PF4JStoragePlugin, SupportsReadSignature, SupportsListingDatasets, SupportsAlteringDatasetMetadata, SupportsPF4JStoragePlugin { public String getUsername(String name) { if (isStorageImpersonationEnabled()) { return name; } return SystemUser.SYSTEM_USERNAME; } @VisibleForTesting HiveStoragePlugin(HiveConf hiveConf, SabotContext context, String name); HiveStoragePlugin(HiveConf hiveConf, PluginManager pf4jManager, SabotContext context, String name); @Override boolean containerExists(EntityPath key); @Override ViewTable getView(List<String> tableSchemaPath, SchemaConfig schemaConfig); HiveConf getHiveConf(); @Override boolean hasAccessPermission(String user, NamespaceKey key, DatasetConfig datasetConfig); @Override SourceCapabilities getSourceCapabilities(); @Override Class<? extends StoragePluginRulesFactory> getRulesFactoryClass(); @Override MetadataValidity validateMetadata(BytesOutput signature, DatasetHandle datasetHandle, DatasetMetadata metadata, ValidateMetadataOption... options); @Override Optional<DatasetHandle> getDatasetHandle(EntityPath datasetPath, GetDatasetOption... options); @Override DatasetHandleListing listDatasetHandles(GetDatasetOption... options); @Override PartitionChunkListing listPartitionChunks(DatasetHandle datasetHandle, ListPartitionChunkOption... options); @Override DatasetMetadata getDatasetMetadata( DatasetHandle datasetHandle, PartitionChunkListing chunkListing, GetMetadataOption... options ); @Override BytesOutput provideSignature(DatasetHandle datasetHandle, DatasetMetadata metadata); @Override SourceState getState(); @Override void close(); @Override void start(); String getUsername(String name); @Override Class<? extends HiveProxiedSubScan> getSubScanClass(); @Override HiveProxiedScanBatchCreator createScanBatchCreator(); @Override Class<? extends HiveProxiedOrcScanFilter> getOrcScanFilterClass(); @Override DatasetMetadata alterMetadata(final DatasetHandle datasetHandle, final DatasetMetadata oldDatasetMetadata, final Map<String, AttributeValue> attributes, final AlterMetadataOption... options); T getPF4JStoragePlugin(); }
@Test public void impersonationDisabledShouldReturnSystemUser() { final HiveConf hiveConf = new HiveConf(); hiveConf.setBoolVar(HIVE_SERVER2_ENABLE_DOAS, false); final SabotContext context = mock(SabotContext.class); final HiveStoragePlugin plugin = createHiveStoragePlugin(hiveConf, context); final String userName = plugin.getUsername(TEST_USER_NAME); assertEquals(SystemUser.SYSTEM_USERNAME, userName); } @Test public void impersonationEnabledShouldReturnUser() { final HiveConf hiveConf = new HiveConf(); hiveConf.setBoolVar(HIVE_SERVER2_ENABLE_DOAS, true); final SabotContext context = mock(SabotContext.class); final HiveStoragePlugin plugin = new HiveStoragePlugin(hiveConf, context, "foo"); final String userName = plugin.getUsername(TEST_USER_NAME); assertEquals(TEST_USER_NAME, userName); }
S3FileSystem extends ContainerFileSystem implements MayProvideAsyncStream { static software.amazon.awssdk.regions.Region getAwsRegionFromEndpoint(String endpoint) { return Optional.ofNullable(endpoint) .map(e -> e.toLowerCase(Locale.ROOT)) .filter(e -> e.endsWith(S3_ENDPOINT_END) || e.endsWith(S3_CN_ENDPOINT_END)) .flatMap(e -> software.amazon.awssdk.regions.Region.regions() .stream() .filter(region -> e.contains(region.id())) .findFirst()) .orElse(software.amazon.awssdk.regions.Region.US_EAST_1); } S3FileSystem(); @Override RemoteIterator<LocatedFileStatus> listFiles(Path f, boolean recursive); @Override boolean supportsAsync(); @Override AsyncByteReader getAsyncByteReader(Path path, String version); @Override void close(); static final String S3_PERMISSION_ERROR_MSG; }
@Test public void testValidRegionFromEndpoint() { Region r = S3FileSystem.getAwsRegionFromEndpoint("s3-eu-central-1.amazonaws.com"); Assert.assertEquals(Region.EU_CENTRAL_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3-us-gov-west-1.amazonaws.com"); Assert.assertEquals(Region.US_GOV_WEST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3.ap-southeast-1.amazonaws.com"); Assert.assertEquals(Region.AP_SOUTHEAST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3.dualstack.ca-central-1.amazonaws.com"); Assert.assertEquals(Region.CA_CENTRAL_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("dremio.s3-control.cn-north-1.amazonaws.com.cn"); Assert.assertEquals(Region.CN_NORTH_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("accountId.s3-control.dualstack.eu-central-1.amazonaws.com"); Assert.assertEquals(Region.EU_CENTRAL_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3-accesspoint.eu-west-1.amazonaws.com"); Assert.assertEquals(Region.EU_WEST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3-accesspoint.dualstack.sa-east-1.amazonaws.com"); Assert.assertEquals(Region.SA_EAST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3-fips.us-gov-west-1.amazonaws.com"); Assert.assertEquals(Region.US_GOV_WEST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3.dualstack.us-gov-east-1.amazonaws.com"); Assert.assertEquals(Region.US_GOV_EAST_1, r); } @Test public void testInvalidRegionFromEndpoint() { Region r = S3FileSystem.getAwsRegionFromEndpoint("us-west-1"); Assert.assertEquals(Region.US_EAST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("s3-eu-central-1"); Assert.assertEquals(Region.US_EAST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint("abc"); Assert.assertEquals(Region.US_EAST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint(""); Assert.assertEquals(Region.US_EAST_1, r); r = S3FileSystem.getAwsRegionFromEndpoint(null); Assert.assertEquals(Region.US_EAST_1, r); }
S3FileSystem extends ContainerFileSystem implements MayProvideAsyncStream { @Override protected ContainerHolder getUnknownContainer(String containerName) throws IOException { boolean containerFound = false; try { if (s3.doesBucketExistV2(containerName)) { final ListObjectsV2Request req = new ListObjectsV2Request() .withMaxKeys(1) .withRequesterPays(isRequesterPays()) .withEncodingType("url") .withBucketName(containerName); containerFound = s3.listObjectsV2(req).getBucketName().equals(containerName); } } catch (AmazonS3Exception e) { if (e.getMessage().contains("Access Denied")) { throw new ContainerAccessDeniedException("aws-bucket", containerName, e); } throw new ContainerNotFoundException("Error while looking up bucket " + containerName, e); } logger.debug("Unknown container '{}' found ? {}", containerName, containerFound); if (!containerFound) { throw new ContainerNotFoundException("Bucket " + containerName + " not found"); } return new BucketCreator(getConf(), containerName).toContainerHolder(); } S3FileSystem(); @Override RemoteIterator<LocatedFileStatus> listFiles(Path f, boolean recursive); @Override boolean supportsAsync(); @Override AsyncByteReader getAsyncByteReader(Path path, String version); @Override void close(); static final String S3_PERMISSION_ERROR_MSG; }
@Test public void testUnknownContainerExists() { TestExtendedS3FileSystem fs = new TestExtendedS3FileSystem(); AmazonS3 mockedS3Client = mock(AmazonS3.class); when(mockedS3Client.doesBucketExistV2(any(String.class))).thenReturn(true); ListObjectsV2Result result = new ListObjectsV2Result(); result.setBucketName("testunknown"); when(mockedS3Client.listObjectsV2(any(ListObjectsV2Request.class))).thenReturn(result); fs.setCustomClient(mockedS3Client); try { assertNotNull(fs.getUnknownContainer("testunknown")); } catch (IOException e) { fail(e.getMessage()); } } @Test (expected = ContainerNotFoundException.class) public void testUnknownContainerNotExists() throws IOException { TestExtendedS3FileSystem fs = new TestExtendedS3FileSystem(); AmazonS3 mockedS3Client = mock(AmazonS3.class); when(mockedS3Client.doesBucketExistV2(any(String.class))).thenReturn(false); fs.setCustomClient(mockedS3Client); fs.getUnknownContainer("testunknown"); } @Test (expected = ContainerAccessDeniedException.class) public void testUnknownContainerExistsButNoPermissions() throws IOException { TestExtendedS3FileSystem fs = new TestExtendedS3FileSystem(); AmazonS3 mockedS3Client = mock(AmazonS3.class); when(mockedS3Client.doesBucketExistV2(any(String.class))).thenReturn(true); when(mockedS3Client.listObjectsV2(any(ListObjectsV2Request.class))).thenThrow(new AmazonS3Exception("Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: FF025EBC3B2BF017; S3 Extended Request ID: 9cbmmg2cbPG7+3mXBizXNJ1haZ/0FUhztplqsm/dJPJB32okQRAhRWVWyqakJrKjCNVqzT57IZU=), S3 Extended Request ID: 9cbmmg2cbPG7+3mXBizXNJ1haZ/0FUhztplqsm/dJPJB32okQRAhRWVWyqakJrKjCNVqzT57IZU=")); fs.setCustomClient(mockedS3Client); fs.getUnknownContainer("testunknown"); }
SplitRecommender extends Recommender<SplitRule, Selection> { @Override public List<SplitRule> getRules(Selection selection, DataType selColType) { checkArgument(selColType == DataType.TEXT, "Split is supported only on TEXT type columns"); List<SplitRule> rules = new ArrayList<>(); String seltext = selection.getCellText().substring(selection.getOffset(), selection.getOffset() + selection.getLength()); rules.add(new SplitRule(seltext, exact, false)); if (!seltext.toUpperCase().equals(seltext.toLowerCase())) { rules.add(new SplitRule(seltext, exact, true)); } return rules; } @Override List<SplitRule> getRules(Selection selection, DataType selColType); TransformRuleWrapper<SplitRule> wrapRule(SplitRule rule); }
@Test public void ruleSuggestionsAlphabetCharsDelimiter() { Selection selection = new Selection("col", "abbbabbabbaaa", 1, 2); List<SplitRule> rules = recommender.getRules(selection, TEXT); assertEquals(2, rules.size()); compare(MatchType.exact, "bb", false, rules.get(0)); compare(MatchType.exact, "bb", true, rules.get(1)); } @Test public void ruleSuggestionsPipeDelimiter() { Selection selection = new Selection("col", "1|2|3|4|5", 1, 1); List<SplitRule> rules = recommender.getRules(selection, TEXT); assertEquals(1, rules.size()); compare(MatchType.exact, "|", false, rules.get(0)); }
S3FileSystem extends ContainerFileSystem implements MayProvideAsyncStream { protected void verifyCredentials(Configuration conf) throws RuntimeException { AwsCredentialsProvider awsCredentialsProvider = getAsync2Provider(conf); final StsClientBuilder stsClientBuilder = StsClient.builder() .credentialsProvider(awsCredentialsProvider) .region(getAWSRegionFromConfigurationOrDefault(conf)); try (StsClient stsClient = stsClientBuilder.build()) { retryer.call(() -> { GetCallerIdentityRequest request = GetCallerIdentityRequest.builder().build(); stsClient.getCallerIdentity(request); return true; }); } catch (Retryer.OperationFailedAfterRetriesException e) { throw new RuntimeException("Credential Verification failed.", e); } } S3FileSystem(); @Override RemoteIterator<LocatedFileStatus> listFiles(Path f, boolean recursive); @Override boolean supportsAsync(); @Override AsyncByteReader getAsyncByteReader(Path path, String version); @Override void close(); static final String S3_PERMISSION_ERROR_MSG; }
@Test public void testVerifyCredentialsRetry() { PowerMockito.mockStatic(StsClient.class); StsClient mockedClient = mock(StsClient.class); StsClientBuilder mockedClientBuilder = mock(StsClientBuilder.class); when(mockedClientBuilder.credentialsProvider(any(AwsCredentialsProvider.class))).thenReturn(mockedClientBuilder); when(mockedClientBuilder.region(any(Region.class))).thenReturn(mockedClientBuilder); when(mockedClientBuilder.build()).thenReturn(mockedClient); when(StsClient.builder()).thenReturn(mockedClientBuilder); TestExtendedS3FileSystem fs = new TestExtendedS3FileSystem(); AtomicInteger retryAttemptNo = new AtomicInteger(1); when(mockedClient.getCallerIdentity(any(GetCallerIdentityRequest.class))).then(invocationOnMock -> { if (retryAttemptNo.incrementAndGet() < 10) { throw SdkClientException.builder().message("Unable to load credentials from service endpoint.").build(); } return null; }); fs.verifyCredentials(new Configuration()); assertEquals(10, retryAttemptNo.get()); } @Test(expected = RuntimeException.class) public void testVerifyCredentialsNoRetryOnAuthnError() { PowerMockito.mockStatic(StsClient.class); StsClient mockedClient = mock(StsClient.class); StsClientBuilder mockedClientBuilder = mock(StsClientBuilder.class); when(mockedClientBuilder.credentialsProvider(any(AwsCredentialsProvider.class))).thenReturn(mockedClientBuilder); when(mockedClientBuilder.region(any(Region.class))).thenReturn(mockedClientBuilder); when(mockedClientBuilder.build()).thenReturn(mockedClient); when(StsClient.builder()).thenReturn(mockedClientBuilder); TestExtendedS3FileSystem fs = new TestExtendedS3FileSystem(); AtomicInteger retryAttemptNo = new AtomicInteger(0); when(mockedClient.getCallerIdentity(any(GetCallerIdentityRequest.class))).then(invocationOnMock -> { retryAttemptNo.incrementAndGet(); throw StsException.builder().message("The security token included in the request is invalid. (Service: Sts, Status Code: 403, Request ID: a7e2e92e-5ebb-4343-87a1-21e4d64edcd4)").build(); }); fs.verifyCredentials(new Configuration()); assertEquals(1, retryAttemptNo.get()); }
ContainerFileSystem extends FileSystem { @VisibleForTesting static Path transform(Path path, String containerName) { final String relativePath = removeLeadingSlash(Path.getPathWithoutSchemeAndAuthority(path).toString()); final Path containerPath = new Path(Path.SEPARATOR + containerName); return Strings.isNullOrEmpty(relativePath) ? containerPath : new Path(containerPath, new Path(null, null, relativePath)); } protected ContainerFileSystem(String scheme, String containerName, Predicate<CorrectableFileStatus> listFileStatusPredicate); void refreshFileSystems(); List<ContainerFailure> getSubFailures(); @Override final void initialize(URI name, Configuration conf); boolean containerExists(final String containerName); static String getContainerName(Path path); static Path pathWithoutContainer(Path path); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); @Override RemoteIterator<LocatedFileStatus> listFiles(Path f, boolean recursive); @Override FileStatus[] listStatus(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override boolean exists(Path f); @Override FileStatus getFileStatus(Path f); @Override String getScheme(); }
@Test public void transformContainerPathWithColon() { final Path path = new Path("s3a: final String containerName = "qa1.dremio.com"; final Path transformed = ContainerFileSystem.transform(path, containerName); Assert.assertEquals(new Path("/qa1.dremio.com/test:breaks"), transformed); }
AzureAsyncReader extends ExponentialBackoff implements AutoCloseable, AsyncByteReader { @Override public CompletableFuture<Void> readFully(long offset, ByteBuf dst, int dstOffset, int len) { return read(offset, dst, dstOffset, len, 0); } AzureAsyncReader(final String accountName, final Path path, final AzureAuthTokenProvider authProvider, final String version, final boolean isSecure, final AsyncHttpClient asyncHttpClient); @Override CompletableFuture<Void> readFully(long offset, ByteBuf dst, int dstOffset, int len); CompletableFuture<Void> read(long offset, ByteBuf dst, int dstOffset, long len, int retryAttemptNum); @Override void close(); }
@Test public void testAsyncHttpClientClosedError() { AsyncHttpClient client = mock(AsyncHttpClient.class); when(client.isClosed()).thenReturn(true); LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2); AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader( "account", new Path("container/directory/file_00.parquet"), getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()), false, client )); try { azureAsyncReader.readFully(0, Unpooled.buffer(1), 0, 1); fail("Operation shouldn't proceed if client is closed"); } catch (RuntimeException e) { assertEquals("AsyncHttpClient is closed", e.getMessage()); } }
AzureAsyncContainerProvider implements ContainerProvider { @Override public Stream<ContainerFileSystem.ContainerCreator> getContainerCreators() { Iterator<String> containerIterator = new DFSContainerIterator(asyncHttpClient, account, authProvider, isSecure, retryer); return StreamSupport.stream(Spliterators.spliteratorUnknownSize(containerIterator, Spliterator.ORDERED), false) .map(c -> new AzureStorageFileSystem.ContainerCreatorImpl(parent, c)); } AzureAsyncContainerProvider(final AsyncHttpClient asyncHttpClient, final String account, final AzureAuthTokenProvider authProvider, final AzureStorageFileSystem parent, boolean isSecure); @Override Stream<ContainerFileSystem.ContainerCreator> getContainerCreators(); @Override void assertContainerExists(final String containerName); }
@Test public void testListContainers() throws IOException, ExecutionException, InterruptedException { AsyncHttpClient client = mock(AsyncHttpClient.class); Response response = mock(Response.class); when(response.getHeader(any(String.class))).thenReturn(""); HttpResponseStatus status = mock(HttpResponseStatus.class); when(status.getStatusCode()).thenReturn(206); byte[] dfsCoreResponseBodyBytesPage1 = readStaticResponse("dfs-core-container-response-page1.json"); RandomBytesResponseDispatcher dfsCoreResponseDispatcherPage1 = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytesPage1); byte[] dfsCoreResponseBodyBytesPage2 = readStaticResponse("dfs-core-container-response-page2.json"); RandomBytesResponseDispatcher dfsCoreResponseDispatcherPage2 = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytesPage2); byte[] dfsCoreEmptyResponseBytes = readStaticResponse("dfs-core-container-empty.json"); RandomBytesResponseDispatcher dfsCoreEmptyResponseDispatcher = new RandomBytesResponseDispatcher(dfsCoreEmptyResponseBytes); CompletableFuture<Response> future = CompletableFuture.completedFuture(response); ListenableFuture<Response> resFuture = mock(ListenableFuture.class); when(resFuture.toCompletableFuture()).thenReturn(future); when(resFuture.get()).thenReturn(response); when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> { Request req = invocationOnMock.getArgument(0, Request.class); AsyncCompletionHandler handler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class); assertTrue(req.getUrl().startsWith("https: assertNotNull(req.getHeaders().get("Date")); assertNotNull(req.getHeaders().get("x-ms-client-request-id")); assertEquals("2019-07-07", req.getHeaders().get("x-ms-version")); assertEquals("Bearer testtoken", req.getHeaders().get("Authorization")); List<NameValuePair> queryParams = URLEncodedUtils.parse(new URI(req.getUrl()), StandardCharsets.UTF_8); String continuationKey = queryParams.stream() .filter(param -> param.getName().equalsIgnoreCase("continuation")).findAny() .map(NameValuePair::getValue).orElse(""); if ("page1container1".equals(continuationKey)) { when(response.getHeader("x-ms-continuation")).thenReturn("page2container1"); while (dfsCoreResponseDispatcherPage1.isNotFinished()) { handler.onBodyPartReceived(dfsCoreResponseDispatcherPage1.getNextBodyPart()); } } else if ("page2container1".equals(continuationKey)) { when(response.getHeader("x-ms-continuation")).thenReturn(""); while (dfsCoreResponseDispatcherPage2.isNotFinished()) { handler.onBodyPartReceived(dfsCoreResponseDispatcherPage2.getNextBodyPart()); } } else { when(response.getHeader("x-ms-continuation")).thenReturn("page1container1"); while (dfsCoreEmptyResponseDispatcher.isNotFinished()) { handler.onBodyPartReceived(dfsCoreEmptyResponseDispatcher.getNextBodyPart()); } } handler.onStatusReceived(status); handler.onCompleted(response); return resFuture; }); AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class); AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider(); AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider( client, "azurestoragev2hier", authTokenProvider, parentClass, true); List<String> receivedContainers = containerProvider.getContainerCreators() .map(AzureStorageFileSystem.ContainerCreatorImpl.class::cast) .map(AzureStorageFileSystem.ContainerCreatorImpl::getName) .collect(Collectors.toList()); List<String> expectedContainers = Arrays.asList("page1container1", "page1container2", "page1container3", "page2container1", "page2container2", "page2container3"); assertEquals(expectedContainers, receivedContainers); } @Test public void testListContainersWithRetry() throws IOException, ExecutionException, InterruptedException { AsyncHttpClient client = mock(AsyncHttpClient.class); Response response = mock(Response.class); when(response.getHeader(any(String.class))).thenReturn(""); HttpResponseStatus status = mock(HttpResponseStatus.class); when(status.getStatusCode()).thenReturn(206); HttpResponseStatus failedStatus = mock(HttpResponseStatus.class); when(failedStatus.getStatusCode()).thenReturn(500); byte[] dfsCoreResponseBodyBytes = readStaticResponse("dfs-core-container-response-page1.json"); RandomBytesResponseDispatcher dfsCoreResponseDispatcher = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytes); CompletableFuture<Response> future = CompletableFuture.completedFuture(response); ListenableFuture<Response> resFuture = mock(ListenableFuture.class); when(resFuture.toCompletableFuture()).thenReturn(future); when(resFuture.get()).thenReturn(response); AtomicInteger retryAttemptNo = new AtomicInteger(0); when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> { AsyncCompletionHandler handler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class); if (retryAttemptNo.incrementAndGet() < 10) { handler.onStatusReceived(failedStatus); } else { while (dfsCoreResponseDispatcher.isNotFinished()) { handler.onBodyPartReceived(dfsCoreResponseDispatcher.getNextBodyPart()); } handler.onStatusReceived(status); } handler.onCompleted(response); return resFuture; }); AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class); AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider(); AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider( client, "azurestoragev2hier", authTokenProvider, parentClass, true); List<String> receivedContainers = containerProvider.getContainerCreators() .map(AzureStorageFileSystem.ContainerCreatorImpl.class::cast) .map(AzureStorageFileSystem.ContainerCreatorImpl::getName) .collect(Collectors.toList()); List<String> expectedContainers = Arrays.asList("page1container1", "page1container2", "page1container3"); assertEquals(expectedContainers, receivedContainers); }
AzureAsyncContainerProvider implements ContainerProvider { @Override public void assertContainerExists(final String containerName) { logger.debug("Checking for missing azure container " + account + ":" + containerName); final Request req = new RequestBuilder(HttpConstants.Methods.HEAD) .addHeader("x-ms-date", toHttpDateFormat(System.currentTimeMillis())) .addHeader("x-ms-version", XMS_VERSION) .addHeader("Content-Length", 0) .addHeader("x-ms-client-request-id", UUID.randomUUID().toString()) .setUrl(AzureAsyncHttpClientUtils.getBaseEndpointURL(account, true) + "/" + containerName) .addQueryParam("resource", "filesystem") .addQueryParam("timeout", String.valueOf(requestTimeoutSeconds)).build(); req.getHeaders().add("Authorization", authProvider.getAuthzHeaderValue(req)); retryer.call(() -> { Response response = asyncHttpClient.executeRequest(req).get(); int status = response.getStatusCode(); if (status >= 500) { logger.error("Error while checking for azure container " + account + ":" + containerName + " status code " + status); throw new RuntimeException(String.format("Error response %d while checking for existence of container %s", status, containerName)); } if (status == 200) { logger.debug("Azure container is found valid " + account + ":" + containerName); } else if (status == 403) { throw new ContainerAccessDeniedException(String.format("Access to container %s denied - [%d %s]", containerName, status, response.getStatusText())); } else { throw new ContainerNotFoundException(String.format("Unable to find container %s - [%d %s]", containerName, status, response.getStatusText())); } return true; }); } AzureAsyncContainerProvider(final AsyncHttpClient asyncHttpClient, final String account, final AzureAuthTokenProvider authProvider, final AzureStorageFileSystem parent, boolean isSecure); @Override Stream<ContainerFileSystem.ContainerCreator> getContainerCreators(); @Override void assertContainerExists(final String containerName); }
@Test public void testDoesContainerExists() throws ExecutionException, InterruptedException { AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class); AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider(); AsyncHttpClient client = mock(AsyncHttpClient.class); Response response = mock(Response.class); when(response.getHeader(any(String.class))).thenReturn(""); when(response.getStatusCode()).thenReturn(200); ListenableFuture<Response> future = mock(ListenableFuture.class); when(future.get()).thenReturn(response); when(client.executeRequest(any(Request.class))).thenReturn(future); AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider( client, "azurestoragev2hier", authTokenProvider, parentClass, true); containerProvider.assertContainerExists("container"); } @Test public void testDoesContainerExistsNotFound() throws ExecutionException, InterruptedException { AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class); AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider(); AsyncHttpClient client = mock(AsyncHttpClient.class); Response response = mock(Response.class); when(response.getHeader(any(String.class))).thenReturn(""); when(response.getStatusCode()).thenReturn(404); when(response.getStatusText()).thenReturn("The specified filesystem does not exist."); ListenableFuture<Response> future = mock(ListenableFuture.class); when(future.get()).thenReturn(response); when(client.executeRequest(any(Request.class))).thenReturn(future); AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider( client, "azurestoragev2hier", authTokenProvider, parentClass, true); try { containerProvider.assertContainerExists("container"); fail("Expecting exception"); } catch (Retryer.OperationFailedAfterRetriesException e) { assertEquals(ContainerNotFoundException.class, e.getCause().getClass()); assertEquals("Unable to find container container - [404 The specified filesystem does not exist.]", e.getCause().getMessage()); } verify(client, times(1)).executeRequest(any(Request.class)); } @Test public void testDoesContainerExistsAccessDenied() throws ExecutionException, InterruptedException { AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class); AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider(); AsyncHttpClient client = mock(AsyncHttpClient.class); Response response = mock(Response.class); when(response.getHeader(any(String.class))).thenReturn(""); when(response.getStatusCode()).thenReturn(403); when(response.getStatusText()).thenReturn("Forbidden, InsufficientAccountPermissions, \"The account being accessed does not have sufficient permissions to execute this operation.\""); ListenableFuture<Response> future = mock(ListenableFuture.class); when(future.get()).thenReturn(response); when(client.executeRequest(any(Request.class))).thenReturn(future); AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider( client, "azurestoragev2hier", authTokenProvider, parentClass, true); try { containerProvider.assertContainerExists("container"); fail("Expecting exception"); } catch (Retryer.OperationFailedAfterRetriesException e) { assertTrue(e.getCause() instanceof ContainerAccessDeniedException); assertEquals("Access to container container denied - [403 Forbidden, InsufficientAccountPermissions, \"The account being accessed does not have sufficient permissions to execute this operation.\"]", e.getCause().getMessage()); } verify(client, times(1)).executeRequest(any(Request.class)); }
AsyncHttpClientProvider { public static AsyncHttpClient getInstance(){ return SingletonHelper.INSTANCE; } static AsyncHttpClient getInstance(); static final int DEFAULT_REQUEST_TIMEOUT; }
@Test public void testSameInstance() throws InterruptedException { ExecutorService ex = Executors.newFixedThreadPool(10); final Set<Integer> objectIdentities = new ConcurrentSkipListSet<>(); CountDownLatch latch = new CountDownLatch(100); for (int i=0; i<100; i++) { ex.execute(() -> { objectIdentities.add(System.identityHashCode(AsyncHttpClientProvider.getInstance())); latch.countDown(); }); } latch.await(5, TimeUnit.MINUTES); assertEquals(1, objectIdentities.size()); ex.shutdownNow(); }
AzureSharedKeyAuthTokenProvider implements AzureAuthTokenProvider { @Override public String getAuthzHeaderValue(final Request req) { try { final URL url = new URL(req.getUrl()); final Map<String, String> headersMap = new HashMap<>(); req.getHeaders().forEach(header -> headersMap.put(header.getKey(), header.getValue())); return this.storageSharedKeyCredential.generateAuthorizationHeader(url, req.getMethod(), headersMap); } catch (MalformedURLException e) { throw new IllegalStateException("The request URL is invalid ", e); } } AzureSharedKeyAuthTokenProvider(final String accountName, final String key); @Override boolean checkAndUpdateToken(); @Override String getAuthzHeaderValue(final Request req); @Override boolean isCloseToExpiry(); }
@Test public void testGetAuthzHeaderValue() { String authzHeaderValue = authTokenProvider.getAuthzHeaderValue(prepareTestRequest()); assertEquals("SharedKey mock-account:ZwovG4J+nCDc3w58WPei6fvJBQsO96YojteJncy0wwI=", authzHeaderValue); }
AzureSharedKeyAuthTokenProvider implements AzureAuthTokenProvider { @Override public boolean checkAndUpdateToken() { return false; } AzureSharedKeyAuthTokenProvider(final String accountName, final String key); @Override boolean checkAndUpdateToken(); @Override String getAuthzHeaderValue(final Request req); @Override boolean isCloseToExpiry(); }
@Test public void testCheckAndUpdate() { assertFalse("Shared key token is static. There shouldn't ever be an update required", authTokenProvider.checkAndUpdateToken()); }
AzureSharedKeyAuthTokenProvider implements AzureAuthTokenProvider { @Override public boolean isCloseToExpiry() { return false; } AzureSharedKeyAuthTokenProvider(final String accountName, final String key); @Override boolean checkAndUpdateToken(); @Override String getAuthzHeaderValue(final Request req); @Override boolean isCloseToExpiry(); }
@Test public void testIsCloseToExpiry() { assertFalse("Shared key token never expires", authTokenProvider.isCloseToExpiry()); }
RemoteNodeFileSystem extends FileSystem { static DFS.FileStatus toProtoFileStatus(FileStatus status) throws IOException { DFS.FileStatus.Builder builder = DFS.FileStatus.newBuilder(); builder .setLength(status.getLen()) .setIsDirectory(status.isDirectory()) .setBlockReplication(status.getReplication()) .setBlockSize(status.getBlockSize()) .setModificationTime(status.getModificationTime()) .setAccessTime(status.getAccessTime()); if (status.getPath() != null) { builder = builder.setPath(status.getPath().toUri().getPath()); } if (status.getPermission() != null) { builder = builder.setPermission(status.getPermission().toExtendedShort()); } if (status.getOwner() != null) { builder = builder.setOwner(status.getOwner()); } if (status.getGroup() != null) { builder = builder.setGroup(status.getGroup()); } if (status.isSymlink()) { builder = builder.setSymlink(status.getSymlink().toString()); } return builder.build(); } RemoteNodeFileSystem(FabricCommandRunner runner, BufferAllocator allocator); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); }
@Test public void testToProtobuFileStatus() throws IOException { FileStatus status = TEST_FILE_STATUS; DFS.FileStatus result = RemoteNodeFileSystem.toProtoFileStatus(status); assertEquals(TEST_PATH_STRING, result.getPath()); assertEquals(1024,result.getLength()); assertFalse(result.getIsDirectory()); assertEquals(1, result.getBlockReplication()); assertEquals(4096, result.getBlockSize()); assertEquals(1453325758, result.getAccessTime()); assertEquals(1453325757, result.getModificationTime()); assertEquals(0644, result.getPermission()); assertEquals("testowner", result.getOwner()); assertEquals("testgroup", result.getGroup()); assertFalse(result.hasSymlink()); } @Test public void testToProtobuFileStatusWithDefault() throws IOException { FileStatus status = new FileStatus(); DFS.FileStatus result = RemoteNodeFileSystem.toProtoFileStatus(status); assertFalse(result.hasPath()); assertEquals(0, result.getLength()); assertFalse(result.getIsDirectory()); assertEquals(0, result.getBlockReplication()); assertEquals(0, result.getBlockSize()); assertEquals(0, result.getAccessTime()); assertEquals(0, result.getModificationTime()); assertEquals(FsPermission.getFileDefault().toExtendedShort(), result.getPermission()); assertEquals("", result.getOwner()); assertEquals("", result.getGroup()); assertFalse(result.hasSymlink()); } @Test public void testToProtobuFileStatusWithDirectory() throws IOException { FileStatus status = new FileStatus(0, true, 0, 0, 1, 2, null, null, null, TEST_PATH); DFS.FileStatus result = RemoteNodeFileSystem.toProtoFileStatus(status); assertEquals(TEST_PATH_STRING, result.getPath()); assertEquals(0, result.getLength()); assertTrue(result.getIsDirectory()); assertEquals(0, result.getBlockReplication()); assertEquals(0, result.getBlockSize()); assertEquals(2, result.getAccessTime()); assertEquals(1, result.getModificationTime()); assertEquals(FsPermission.getDirDefault().toExtendedShort(), result.getPermission()); assertEquals("", result.getOwner()); assertEquals("", result.getGroup()); assertFalse(result.hasSymlink()); }
RemoteNodeFileSystem extends FileSystem { @Override public FileStatus getFileStatus(Path f) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); final GetFileStatusCommand command = new GetFileStatusCommand(absolutePath.toUri().getPath()); runner.runCommand(command); RpcFuture<DFS.GetFileStatusResponse> future = command.getFuture(); try { DFS.GetFileStatusResponse response = DremioFutures.getChecked( future, RpcException.class, rpcTimeoutMs, TimeUnit.MILLISECONDS, RpcException::mapException); return fromProtoFileStatus(response.getStatus()); } catch(TimeoutException e) { throw new IOException("Timeout occurred during I/O request for " + uri, e); } catch(RpcException e) { RpcException.propagateIfPossible(e, IOException.class); throw e; } } RemoteNodeFileSystem(FabricCommandRunner runner, BufferAllocator allocator); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); }
@Test public void testGetFileStatusRoot() throws Exception { { DFS.FileStatus status = newFileStatus(1024L, true, 0, 4096L, 37L, 42L, 0755, "root", "wheel", "/"); setupRPC( DFS.RpcType.GET_FILE_STATUS_REQUEST, DFS.GetFileStatusRequest.newBuilder().setPath("/").build(), DFS.RpcType.GET_FILE_STATUS_RESPONSE, DFS.GetFileStatusResponse.newBuilder().setStatus(status).build()); } FileSystem fs = newRemoteNodeFileSystem(); Path root = new Path("/"); FileStatus status = fs.getFileStatus(root); assertEquals(new Path("sabot: assertTrue(status.isDirectory()); assertEquals(0755, status.getPermission().toExtendedShort()); } @Test(expected = FileNotFoundException.class) public void testGetFileStatusWithInvalidPath() throws Exception { { setupRPC( DFS.RpcType.GET_FILE_STATUS_REQUEST, DFS.GetFileStatusRequest.newBuilder().setPath("/foo/bar").build(), DFS.GetFileStatusResponse.class, newRPCException(LOCAL_ENDPOINT, new FileNotFoundException("File not found"))); } FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); fs.getFileStatus(path); } @Test public void testGetFileStatusWithValidPath() throws Exception { { DFS.FileStatus status = newFileStatus(1024, false, 1, 4096, 42, 37, 0644 , "root", "wheel", "/foo/bar"); setupRPC( DFS.RpcType.GET_FILE_STATUS_REQUEST, DFS.GetFileStatusRequest.newBuilder().setPath("/foo/bar").build(), DFS.RpcType.GET_FILE_STATUS_RESPONSE, DFS.GetFileStatusResponse.newBuilder().setStatus(status).build()); } FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); FileStatus status = fs.getFileStatus(path); assertEquals(new Path("sabot: assertFalse(status.isDirectory()); assertEquals(1024, status.getLen()); assertEquals(1, status.getReplication()); assertEquals(4096, status.getBlockSize()); assertEquals(42, status.getAccessTime()); assertEquals(37, status.getModificationTime()); assertEquals("root", status.getOwner()); assertEquals("wheel", status.getGroup()); assertEquals(0644, status.getPermission().toExtendedShort()); }
SplitRecommender extends Recommender<SplitRule, Selection> { public TransformRuleWrapper<SplitRule> wrapRule(SplitRule rule) { return new SplitTransformRuleWrapper(rule); } @Override List<SplitRule> getRules(Selection selection, DataType selColType); TransformRuleWrapper<SplitRule> wrapRule(SplitRule rule); }
@Test public void splitListCardGen() throws Exception { File dataFile = temp.newFile("splitExact.json"); try (PrintWriter writer = new PrintWriter(dataFile)) { writer.append("{ \"col\" : \"aBa\" }"); writer.append("{ \"col\" : \"abaBa\" }"); writer.append("{ \"col\" : null }"); writer.append("{ \"col\" : \"abababa\" }"); writer.append("{ \"col\" : \"aaa\" }"); } { SplitRule rule = new SplitRule("b", MatchType.exact, true); TransformRuleWrapper<SplitRule> wrapper = recommender.wrapRule(rule); assertEquals("regexp_matches(\"tbl name\".col, '(?i)(?u).*\\Qb\\E.*')", wrapper.getMatchFunctionExpr("\"tbl name\".col")); assertEquals("regexp_split(tbl.col, '(?i)(?u)\\Qb\\E', 'ALL', 10)", wrapper.getFunctionExpr("tbl.col", SplitPositionType.ALL, 10)); assertEquals("regexp_split_positions(tbl.\"col name\", '(?i)(?u)\\Qb\\E')", wrapper.getExampleFunctionExpr("tbl.\"col name\"")); assertEquals("Exactly matches \"b\" ignore case", wrapper.describe()); List<List<CardExamplePosition>> highlights = asList( asList(new CardExamplePosition(1, 1)), asList(new CardExamplePosition(1, 1), new CardExamplePosition(3, 1)), null, asList(new CardExamplePosition(1, 1), new CardExamplePosition(3, 1), new CardExamplePosition(5, 1)), null ); validate(dataFile.getAbsolutePath(), wrapper, new Object[] { SplitPositionType.INDEX, 1}, list((Object)list("aBa"), list("aba", "a"), null, list("aba", "aba"), list("aaa")), asList(true, true, false, true, false), highlights ); } { SplitRule rule = new SplitRule("b", MatchType.exact, false); TransformRuleWrapper<SplitRule> wrapper = recommender.wrapRule(rule); assertEquals("regexp_matches(tbl.col, '.*\\Qb\\E.*')", wrapper.getMatchFunctionExpr("tbl.col")); assertEquals("regexp_split(tbl.col, '\\Qb\\E', 'ALL', 10)", wrapper.getFunctionExpr("tbl.col", SplitPositionType.ALL, 10)); assertEquals("regexp_split_positions(tbl.col, '\\Qb\\E')", wrapper.getExampleFunctionExpr("tbl.col")); assertEquals("Exactly matches \"b\"", wrapper.describe()); List<List<CardExamplePosition>> highlights = asList( null, asList(new CardExamplePosition(1, 1)), null, asList(new CardExamplePosition(1, 1), new CardExamplePosition(3, 1), new CardExamplePosition(5, 1)), null ); validate(dataFile.getAbsolutePath(), wrapper, new Object[] {SplitPositionType.LAST, -1 }, list((Object)list("aBa"), list("a", "aBa"), null, list("ababa", "a"), list("aaa")), asList(false, true, false, true, false), highlights ); } } @Test public void splitRegex() throws Exception { File dataFile = temp.newFile("splitRegex.json"); try (PrintWriter writer = new PrintWriter(dataFile)) { writer.append("{ \"col\" : \"aaa111BBB222cc33d\" }"); writer.append("{ \"col\" : \"a1b2c3\" }"); writer.append("{ \"col\" : null }"); writer.append("{ \"col\" : \"abababa\" }"); writer.append("{ \"col\" : \"111\" }"); } { SplitRule rule = new SplitRule("\\d+", MatchType.regex, false); TransformRuleWrapper<SplitRule> wrapper = recommender.wrapRule(rule); assertEquals("regexp_matches(\"tbl name\".col, '.*\\d+.*')", wrapper.getMatchFunctionExpr("\"tbl name\".col")); assertEquals("regexp_split(tbl.col, '\\d+', 'ALL', 10)", wrapper.getFunctionExpr("tbl.col", SplitPositionType.ALL, 10)); assertEquals("regexp_split_positions(tbl.\"col name\", '\\d+')", wrapper.getExampleFunctionExpr("tbl.\"col name\"")); assertEquals("Matches regex \"\\d+\"", wrapper.describe()); List<List<CardExamplePosition>> highlights = asList( asList(new CardExamplePosition(3, 3), new CardExamplePosition(9, 3), new CardExamplePosition(14, 2)), asList(new CardExamplePosition(1, 1), new CardExamplePosition(3, 1), new CardExamplePosition(5, 1)), null, null, asList(new CardExamplePosition(0, 3)) ); validate(dataFile.getAbsolutePath(), wrapper, new Object[] { SplitPositionType.FIRST, -1 }, list((Object)list("aaa", "BBB222cc33d"), list("a", "b2c3"), null, list("abababa"), list("", "")), asList(true, true, false, false, true), highlights ); } { SplitRule rule = new SplitRule("[a-z]+", MatchType.regex, true); TransformRuleWrapper<SplitRule> wrapper = recommender.wrapRule(rule); assertEquals("regexp_matches(tbl.col, '(?i)(?u).*[a-z]+.*')", wrapper.getMatchFunctionExpr("tbl.col")); assertEquals("regexp_split(tbl.col, '(?i)(?u)[a-z]+', 'ALL', 10)", wrapper.getFunctionExpr("tbl.col", SplitPositionType.ALL, 10)); assertEquals("regexp_split_positions(tbl.col, '(?i)(?u)[a-z]+')", wrapper.getExampleFunctionExpr("tbl.col")); assertEquals("Matches regex \"[a-z]+\" ignore case", wrapper.describe()); List<List<CardExamplePosition>> highlights = asList( asList(new CardExamplePosition(0, 3), new CardExamplePosition(6, 3), new CardExamplePosition(12, 2), new CardExamplePosition(16, 1)), asList(new CardExamplePosition(0, 1), new CardExamplePosition(2, 1), new CardExamplePosition(4, 1)), null, asList(new CardExamplePosition(0, 7)), null ); validate(dataFile.getAbsolutePath(), wrapper, new Object[] { SplitPositionType.ALL, 2}, list((Object)list("", "111"), list("", "1"), null, list("", ""), list("111")), asList(true, true, false, true, false), highlights ); } }
RemoteNodeFileSystem extends FileSystem { @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { RemoteIterator<FileStatus> remoteIterator = listStatusIterator(f); List<FileStatus> statuses = new ArrayList<>(); while(remoteIterator.hasNext()) { statuses.add(remoteIterator.next()); } return statuses.toArray(new FileStatus[0]); } RemoteNodeFileSystem(FabricCommandRunner runner, BufferAllocator allocator); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); }
@Test public void testListStatusRoot() throws Exception { { DFS.ListStatusResponse listStatusResponse = DFS.ListStatusResponse.newBuilder() .addStatuses(newFileStatus(42, true, 0, 0, 456, 879, 0755, "root", "wheel", "/foo")) .addStatuses(newFileStatus(1024, false, 1, 4096, 354, 435, 0644, "admin", "admin", "/bar")) .build(); setupRPC( DFS.RpcType.LIST_STATUS_REQUEST, DFS.ListStatusRequest.newBuilder().setPath("/").setLimit(RemoteNodeFileSystem.LIST_STATUS_BATCH_SIZE_DEFAULT).build(), DFS.RpcType.LIST_STATUS_RESPONSE, listStatusResponse); } FileSystem fs = newRemoteNodeFileSystem(); Path root = new Path("/"); FileStatus[] statuses = fs.listStatus(root); assertEquals(ENDPOINTS_LIST.size(), statuses.length); assertEquals(new Path("sabot: assertTrue(statuses[0].isDirectory()); assertEquals(0755, statuses[0].getPermission().toExtendedShort()); assertEquals(new Path("sabot: assertFalse(statuses[1].isDirectory()); assertEquals(0644, statuses[1].getPermission().toExtendedShort()); } @Test public void testListStatusRootOneByOne() throws Exception { { DFS.ListStatusContinuationHandle handle = DFS.ListStatusContinuationHandle.newBuilder().setId("test-handle").build(); DFS.ListStatusResponse listStatusInitialResponse = DFS.ListStatusResponse.newBuilder() .addStatuses(newFileStatus(42, true, 0, 0, 456, 879, 0755, "root", "wheel", "/foo")) .setHandle(handle) .build(); DFS.ListStatusResponse listStatusLastResponse = DFS.ListStatusResponse.newBuilder() .addStatuses(newFileStatus(1024, false, 1, 4096, 354, 435, 0644, "admin", "admin", "/bar")) .build(); setupRPC( DFS.RpcType.LIST_STATUS_REQUEST, Arrays.asList( DFS.ListStatusRequest.newBuilder().setPath("/").setLimit(1).build(), DFS.ListStatusRequest.newBuilder().setPath("/").setHandle(handle).setLimit(1).build()), DFS.RpcType.LIST_STATUS_RESPONSE, Arrays.asList(listStatusInitialResponse, listStatusLastResponse), Arrays.asList((ByteBuf) null, null) ); } final Configuration configuration = new Configuration(false); configuration.setTimeDuration(RemoteNodeFileSystem.RPC_TIMEOUT_KEY, TEST_RPC_TIMEOUT_MS, TimeUnit.MILLISECONDS); configuration.setInt(RemoteNodeFileSystem.LIST_STATUS_BATCH_SIZE_KEY, 1); FileSystem fs = newRemoteNodeFileSystem(configuration); Path root = new Path("/"); FileStatus[] statuses = fs.listStatus(root); assertEquals(ENDPOINTS_LIST.size(), statuses.length); assertEquals(new Path("sabot: assertTrue(statuses[0].isDirectory()); assertEquals(0755, statuses[0].getPermission().toExtendedShort()); assertEquals(new Path("sabot: assertFalse(statuses[1].isDirectory()); assertEquals(0644, statuses[1].getPermission().toExtendedShort()); } @Test public void testListStatusWithValidPath() throws Exception { { DFS.ListStatusResponse listStatusResponse = DFS.ListStatusResponse.newBuilder() .addStatuses(newFileStatus(42, true, 0, 0, 456, 879, 0755, "root", "wheel", "/foo/bar/dir")) .addStatuses(newFileStatus(1024, false, 1, 4096, 354, 435, 0644, "admin", "admin", "/foo/bar/file")) .build(); setupRPC( DFS.RpcType.LIST_STATUS_REQUEST, DFS.ListStatusRequest.newBuilder().setPath("/foo/bar").setLimit(RemoteNodeFileSystem.LIST_STATUS_BATCH_SIZE_DEFAULT).build(), DFS.RpcType.LIST_STATUS_RESPONSE, listStatusResponse); } FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); FileStatus[] statuses = fs.listStatus(path); assertEquals(ENDPOINTS_LIST.size(), statuses.length); assertEquals(new Path("sabot: assertTrue(statuses[0].isDirectory()); assertEquals(0755, statuses[0].getPermission().toExtendedShort()); assertEquals(new Path("sabot: assertFalse(statuses[1].isDirectory()); assertEquals(0644, statuses[1].getPermission().toExtendedShort()); } @Test(expected = FileNotFoundException.class) public void testListStatusWithInvalidPath() throws Exception { setupRPC( DFS.RpcType.LIST_STATUS_REQUEST, DFS.ListStatusRequest.newBuilder().setPath("/foo/bar").setLimit(RemoteNodeFileSystem.LIST_STATUS_BATCH_SIZE_DEFAULT).build(), DFS.ListStatusResponse.class, newRPCException(LOCAL_ENDPOINT, new FileNotFoundException("File not found"))); FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); fs.listStatus(path); }
RemoteNodeFileSystem extends FileSystem { @Override public boolean delete(Path f, boolean recursive) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); final DeleteCommand command = new DeleteCommand(absolutePath.toUri().getPath(), recursive); runner.runCommand(command); RpcFuture<DFS.DeleteResponse> future = command.getFuture(); try { DFS.DeleteResponse response = DremioFutures.getChecked( future, RpcException.class, rpcTimeoutMs, TimeUnit.MILLISECONDS, RpcException::mapException ); return response.getValue(); } catch(TimeoutException e) { throw new IOException("Timeout occurred during I/O request for " + uri, e); } catch (RpcException e) { RpcException.propagateIfPossible(e, IOException.class); throw e; } } RemoteNodeFileSystem(FabricCommandRunner runner, BufferAllocator allocator); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); }
@Test public void testDeleteWithValidPath() throws Exception { setupRPC( DFS.RpcType.DELETE_REQUEST, DFS.DeleteRequest.newBuilder().setPath("/foo/bar").setRecursive(true).build(), DFS.RpcType.DELETE_RESPONSE, DFS.DeleteResponse.newBuilder().setValue(true).build()); FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); boolean result = fs.delete(path, true); assertTrue(result); } @Test public void testDeleteWithValidPathButNotDeleted() throws Exception { setupRPC( DFS.RpcType.DELETE_REQUEST, DFS.DeleteRequest.newBuilder().setPath("/foo/bar").setRecursive(true).build(), DFS.RpcType.DELETE_RESPONSE, DFS.DeleteResponse.newBuilder().setValue(false).build()); FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); boolean result = fs.delete(path, true); assertFalse(result); } @Test public void testDeleteWithInvalidPath() throws Exception { setupRPC( DFS.RpcType.DELETE_REQUEST, DFS.DeleteRequest.newBuilder().setPath("/foo/bar").setRecursive(true).build(), DFS.DeleteResponse.class, newRPCException(LOCAL_ENDPOINT, new FileNotFoundException("File not found"))); FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); try { fs.delete(path, true); fail("Expected fs.delete() to throw FileNotFoundException"); } catch(FileNotFoundException e) { } }
RemoteNodeFileSystem extends FileSystem { @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); final MkdirsCommand command = new MkdirsCommand( absolutePath.toUri().getPath(), permission != null ? (int) permission.toExtendedShort() : null); runner.runCommand(command); RpcFuture<DFS.MkdirsResponse> future = command.getFuture(); try { DFS.MkdirsResponse response = DremioFutures.getChecked( future, RpcException.class, rpcTimeoutMs, TimeUnit.MILLISECONDS, RpcException::mapException ); return response.getValue(); } catch(TimeoutException e) { throw new IOException("Timeout occurred during I/O request for " + uri, e); } catch(RpcException e) { RpcException.propagateIfPossible(e, IOException.class); throw e; } } RemoteNodeFileSystem(FabricCommandRunner runner, BufferAllocator allocator); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); }
@Test public void testMkdirsWithValidPath() throws Exception { setupRPC( DFS.RpcType.MKDIRS_REQUEST, DFS.MkdirsRequest.newBuilder().setPath("/foo/bar").setPermission(0755).build(), DFS.RpcType.MKDIRS_RESPONSE, DFS.MkdirsResponse.newBuilder().setValue(true).build()); FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); boolean result = fs.mkdirs(path, FsPermission.createImmutable((short) 0755)); assertTrue(result); } @Test public void testMkdirsWithValidPathButNotCreated() throws Exception { setupRPC( DFS.RpcType.MKDIRS_REQUEST, DFS.MkdirsRequest.newBuilder().setPath("/foo/bar").setPermission(0755).build(), DFS.RpcType.MKDIRS_RESPONSE, DFS.MkdirsResponse.newBuilder().setValue(false).build()); FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); boolean result = fs.mkdirs(path, FsPermission.createImmutable((short) 0755)); assertFalse(result); } @Test public void testMkdirsWithInvalidPath() throws Exception { setupRPC( DFS.RpcType.MKDIRS_REQUEST, DFS.MkdirsRequest.newBuilder().setPath("/foo/bar").setPermission(0755).build(), DFS.MkdirsResponse.class, newRPCException(LOCAL_ENDPOINT, new FileNotFoundException("File not found"))); FileSystem fs = newRemoteNodeFileSystem(); Path path = new Path("/foo/bar"); try { fs.mkdirs(path, FsPermission.createImmutable((short) 0755)); fail("Expected fs.mkdirs() to throw FileNotFoundException"); } catch(FileNotFoundException e) { } }
RemoteNodeFileSystem extends FileSystem { @Override public boolean rename(Path src, Path dst) throws IOException { Path absoluteSrc = toAbsolutePath(src); Path absoluteDst = toAbsolutePath(dst); checkPath(absoluteSrc); checkPath(absoluteDst); final RenameCommand command = new RenameCommand(absoluteSrc.toUri().getPath(), absoluteDst.toUri().getPath()); runner.runCommand(command); RpcFuture<DFS.RenameResponse> future = command.getFuture(); try { DFS.RenameResponse response = DremioFutures.getChecked( future, RpcException.class, rpcTimeoutMs, TimeUnit.MILLISECONDS, RpcException::mapException ); return response.getValue(); } catch(TimeoutException e) { throw new IOException("Timeout occurred during I/O request for " + uri, e); } catch(RpcException e) { RpcException.propagateIfPossible(e, IOException.class); throw e; } } RemoteNodeFileSystem(FabricCommandRunner runner, BufferAllocator allocator); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); }
@Test public void testRenameWithValidPath() throws Exception { setupRPC( DFS.RpcType.RENAME_REQUEST, DFS.RenameRequest.newBuilder().setOldpath("/foo/bar").setNewpath("/foo/bar2").build(), DFS.RpcType.RENAME_RESPONSE, DFS.RenameResponse.newBuilder().setValue(true).build()); FileSystem fs = newRemoteNodeFileSystem(); Path oldPath = new Path("/foo/bar"); Path newPath = new Path("/foo/bar2"); boolean result = fs.rename(oldPath, newPath); assertTrue(result); } @Test public void testRenameWithButNotRenamed() throws Exception { setupRPC( DFS.RpcType.RENAME_REQUEST, DFS.RenameRequest.newBuilder().setOldpath("/foo/bar").setNewpath("/foo/bar2").build(), DFS.RpcType.RENAME_RESPONSE, DFS.RenameResponse.newBuilder().setValue(false).build()); FileSystem fs = newRemoteNodeFileSystem(); Path oldPath = new Path("/foo/bar"); Path newPath = new Path("/foo/bar2"); boolean result = fs.rename(oldPath, newPath); assertFalse(result); } @Test public void testRenameWithInvalidPath() throws Exception { setupRPC( DFS.RpcType.RENAME_REQUEST, DFS.RenameRequest.newBuilder().setOldpath("/foo/bar").setNewpath("/foo/bar2").build(), DFS.RenameResponse.class, newRPCException(LOCAL_ENDPOINT, new FileNotFoundException("File not found"))); FileSystem fs = newRemoteNodeFileSystem(); Path oldPath = new Path("/foo/bar"); Path newPath = new Path("/foo/bar2"); try { fs.rename(oldPath, newPath); fail("Expected fs.mkdirs() to throw FileNotFoundException"); } catch(FileNotFoundException e) { } }
RemoteNodeFileSystem extends FileSystem { @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); final String path = absolutePath.toUri().getPath(); return new FSDataInputStream(new RemoteNodeInputStream(path, bufferSize)); } RemoteNodeFileSystem(FabricCommandRunner runner, BufferAllocator allocator); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(final Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); }
@Test public void testInputStream() throws Exception { Path filePath = new Path("/foo/bar"); byte[] data = new byte[100]; for (int i = 0; i < 100; ++i) { data[i] = (byte)i; } byte [] readBuf = new byte[1000]; ByteBuf byteBuf = Unpooled.wrappedBuffer(data, 0, 100); setupRPC( DFS.RpcType.GET_FILE_DATA_REQUEST, DFS.GetFileDataRequest.newBuilder().setPath(filePath.toString()).setStart(0).setLength(100).build(), DFS.RpcType.GET_FILE_DATA_RESPONSE, DFS.GetFileDataResponse.newBuilder().setRead(100).build(), byteBuf); FileSystem fs = newRemoteNodeFileSystem(); FSDataInputStream inputStream = fs.open(filePath, 100); int read = inputStream.read(readBuf, 0, 50); assertEquals(50, read); setupRPC( DFS.RpcType.GET_FILE_DATA_REQUEST, DFS.GetFileDataRequest.newBuilder().setPath(filePath.toString()).setStart(100).setLength(100).build(), DFS.RpcType.GET_FILE_DATA_RESPONSE, DFS.GetFileDataResponse.newBuilder().setRead(-1).build()); read = inputStream.read(readBuf, 50, 1000); assertEquals(50, read); for (int i = 0; i < 100; ++i) { assertEquals((byte)i, readBuf[i]); } }
PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public FileStatus getFileStatus(Path f) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); if (!isRemoteFile(absolutePath)) { return new GetFileStatusTask(absolutePath).get(); } try { RemotePath remotePath = getRemotePath(absolutePath); FileSystem delegate = getDelegateFileSystem(remotePath.address); FileStatus status = delegate.getFileStatus(remotePath.path); return fixFileStatus(remotePath.address, status); } catch (IllegalArgumentException e) { throw (FileNotFoundException) (new FileNotFoundException("No file " + absolutePath).initCause(e)); } } PseudoDistributedFileSystem(); @VisibleForTesting PseudoDistributedFileSystem(PDFSConfig config); static synchronized void configure(PDFSConfig config); static String getRemoteFileName(String basename); static RemotePath getRemotePath(Path path); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override String getScheme(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path canonicalizePath(Path p); static final String NAME; }
@Test public void testGetFileStatusRoot() throws IOException { Path root = new Path("/"); FileStatus status = fs.getFileStatus(root); assertEquals(new Path("pdfs:/"), status.getPath()); assertTrue(status.isDirectory()); assertEquals(0555, status.getPermission().toExtendedShort()); } @Test public void testGetFileStatusForInvalidPath() throws IOException { Path path = new Path("/foo/baz"); try { fs.getFileStatus(path); fail("Expected getFileStatus to throw FileNotFoundException"); } catch (FileNotFoundException e) { } } @Test public void testGetFileStatusForValidDirectory() throws IOException { Path path = new Path("/foo/bar"); FileStatus status = fs.getFileStatus(path); assertEquals(new Path("pdfs:/foo/bar"), status.getPath()); assertTrue(status.isDirectory()); assertEquals(69, status.getModificationTime()); assertEquals(90, status.getAccessTime()); } @Test public void testGetFileStatusForUnaccessibleDirectory() throws IOException { doThrow(new AccessControlException()).when(mockRemoteFS).getFileStatus(new Path("/foo/baz")); Path path = new Path("/foo/baz"); try { fs.getFileStatus(path); fail("Expected some IOException"); } catch(AccessControlException e) { } } @Test public void testGetFileStatusWithValidRemotePath() throws IOException { doReturn(new FileStatus(1024, false, 1, 4096, 37, 42, FsPermission.createImmutable((short) 0644), "root", "wheel", new Path("sabot: .when(mockRemoteFS).getFileStatus(new Path("/tmp/file")); Path path = new Path("/tmp/10.0.0.2@file"); FileStatus status = fs.getFileStatus(path); assertEquals(new Path("pdfs:/tmp/10.0.0.2@file"), status.getPath()); assertFalse(status.isDirectory()); assertEquals(1024, status.getLen()); assertEquals(1, status.getReplication()); assertEquals(4096, status.getBlockSize()); assertEquals(42, status.getAccessTime()); assertEquals(37, status.getModificationTime()); assertEquals("root", status.getOwner()); assertEquals("wheel", status.getGroup()); assertEquals(0644, status.getPermission().toExtendedShort()); } @Test public void testGetFileStatusWithValidLocalPath() throws IOException { Path tmpPath = new Path("/tmp/file"); doReturn(new FileStatus(1024, false, 1, 4096, 37, 42, FsPermission.createImmutable((short) 0644), "root", "wheel", tmpPath)).when(mockLocalFS).getFileStatus(tmpPath); Path path = new Path("/tmp/10.0.0.1@file"); FileStatus status = fs.getFileStatus(path); assertEquals(new Path("pdfs:/tmp/10.0.0.1@file"), status.getPath()); assertFalse(status.isDirectory()); assertEquals(1024, status.getLen()); assertEquals(1, status.getReplication()); assertEquals(4096, status.getBlockSize()); assertEquals(42, status.getAccessTime()); assertEquals(37, status.getModificationTime()); assertEquals("root", status.getOwner()); assertEquals("wheel", status.getGroup()); assertEquals(0644, status.getPermission().toExtendedShort()); } @Test public void testGetFileStatusWithLocalPath() throws IOException { try { Path path = new Path("/tmp/file"); @SuppressWarnings("unused") FileStatus status = fs.getFileStatus(path); fail("Expected getFileStatus call to throw an exception"); } catch (IOException e) { } } @Test public void testGetFileStatusWithUnknownRemotePath() throws IOException { Path path = new Path("/tmp/10.0.0.3@file"); try { fs.getFileStatus(path); fail("Expected getFileStatus to throw FileNotFoundException"); } catch (FileNotFoundException e) { } }
DatasetTool { History getHistory(final DatasetPath datasetPath, DatasetVersion currentDataset) throws DatasetVersionNotFoundException { return getHistory(datasetPath, currentDataset, currentDataset); } DatasetTool( DatasetVersionMutator datasetService, JobsService jobsService, QueryExecutor executor, SecurityContext context); InitialPreviewResponse newUntitled( BufferAllocator allocator, FromBase from, DatasetVersion version, List<String> context, Integer limit); static UserException toInvalidQueryException(UserException e, String sql, List<String> context); static UserException toInvalidQueryException(UserException e, String sql, List<String> context, DatasetSummary datasetSummary); InitialPreviewResponse newUntitled( BufferAllocator allocator, FromBase from, DatasetVersion version, List<String> context, DatasetSummary parentSummary, boolean prepare, Integer limit); InitialPreviewResponse newUntitled( BufferAllocator allocator, FromBase from, DatasetVersion version, List<String> context, DatasetSummary parentSummary, boolean prepare, Integer limit, boolean runInSameThread); static VirtualDatasetUI newDatasetBeforeQueryMetadata( DatasetPath datasetPath, DatasetVersion version, From from, List<String> sqlContext, String owner); static void applyQueryMetadata(VirtualDatasetUI dataset, JobInfo jobInfo, QueryMetadata metadata); static void applyQueryMetadata(VirtualDatasetUI dataset, Optional<List<ParentDatasetInfo>> parents, Optional<BatchSchema> batchSchema, Optional<List<FieldOrigin>> fieldOrigins, Optional<List<ParentDataset>> grandParents, QueryMetadata metadata); static final DatasetPath TMP_DATASET_PATH; }
@Test public void testBrokenHistory() throws Exception { DatasetPath datasetPath = new DatasetPath(Arrays.asList("space", "dataset")); DatasetVersion current = new DatasetVersion("123"); DatasetVersion tip = new DatasetVersion("456"); DatasetVersion broken = new DatasetVersion("001"); VirtualDatasetUI tipDataset = new VirtualDatasetUI(); tipDataset.setCreatedAt(0L); tipDataset.setFullPathList(datasetPath.toPathList()); tipDataset.setVersion(tip); tipDataset.setPreviousVersion(new NameDatasetRef() .setDatasetVersion(broken.getVersion()) .setDatasetPath(datasetPath.toString())); Transform transform = new Transform(TransformType.updateSQL); transform.setUpdateSQL(new TransformUpdateSQL("sql")); tipDataset.setLastTransform(transform); DatasetVersionMutator datasetVersionMutator = mock(DatasetVersionMutator.class); when(datasetVersionMutator.getVersion(datasetPath, tip)).thenReturn(tipDataset); when(datasetVersionMutator.get(any())).thenReturn(tipDataset); when(datasetVersionMutator.getVersion(datasetPath, broken)).thenThrow(DatasetNotFoundException.class); JobsService jobsService = mock(JobsService.class); when(jobsService.searchJobs(any())).thenReturn(Collections.emptyList()); QueryExecutor executor = mock(QueryExecutor.class); SecurityContext securityContext = new SecurityContext() { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return "user"; } }; } @Override public boolean isUserInRole(String role) { return false; } @Override public boolean isSecure() { return false; } @Override public String getAuthenticationScheme() { return null; } }; final DatasetTool tool = new DatasetTool(datasetVersionMutator, jobsService, executor, securityContext); History history = tool.getHistory(datasetPath, current, tip); Assert.assertEquals(1, history.getItems().size()); }
PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { final RemoteIterator<FileStatus> remoteIterator = listStatusIterator(f); final List<FileStatus> statuses = Lists.newArrayList(); while (remoteIterator.hasNext()) { statuses.add(remoteIterator.next()); } return statuses.toArray(new FileStatus[0]); } PseudoDistributedFileSystem(); @VisibleForTesting PseudoDistributedFileSystem(PDFSConfig config); static synchronized void configure(PDFSConfig config); static String getRemoteFileName(String basename); static RemotePath getRemotePath(Path path); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override String getScheme(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path canonicalizePath(Path p); static final String NAME; }
@Test public void testListStatusRoot() throws IOException { Path root = new Path("/"); FileStatus[] statuses = fs.listStatus(root); assertEquals(1, statuses.length); assertEquals(new Path("pdfs:/foo"), statuses[0].getPath()); assertTrue(statuses[0].isDirectory()); assertEquals(0755, statuses[0].getPermission().toExtendedShort()); } @Test public void testListStatusWithValidPath() throws IOException { Path path = new Path("/foo/bar"); FileStatus[] statuses = fs.listStatus(path); assertEquals(5, statuses.length); Arrays.sort(statuses); final FileStatus searchKeyStatus = new FileStatus(); searchKeyStatus.setPath(new Path("pdfs:/foo/bar/10.0.0.1@file1")); int testIndex = Arrays.binarySearch(statuses, searchKeyStatus); assertTrue("Status for path " + searchKeyStatus.getPath().toString() + " not found", testIndex >= 0); assertEquals(new Path("pdfs:/foo/bar/10.0.0.1@file1"), statuses[testIndex].getPath()); assertFalse(statuses[testIndex].isDirectory()); assertEquals(1024, statuses[testIndex].getLen()); assertEquals(1, statuses[testIndex].getReplication()); assertEquals(4096, statuses[testIndex].getBlockSize()); assertEquals(42, statuses[testIndex].getAccessTime()); assertEquals(37, statuses[testIndex].getModificationTime()); assertEquals("root", statuses[testIndex].getOwner()); assertEquals("wheel", statuses[testIndex].getGroup()); assertEquals(0644, statuses[testIndex].getPermission().toExtendedShort()); searchKeyStatus.setPath(new Path("pdfs:/foo/bar/10.0.0.1@file2")); testIndex = Arrays.binarySearch(statuses, searchKeyStatus); assertTrue("Status for path " + searchKeyStatus.getPath().toString() + " not found", testIndex >= 0); assertEquals(new Path("pdfs:/foo/bar/10.0.0.1@file2"), statuses[testIndex].getPath()); assertFalse(statuses[1].isDirectory()); assertEquals(2048, statuses[testIndex].getLen()); assertEquals(1, statuses[testIndex].getReplication()); assertEquals(4096, statuses[testIndex].getBlockSize()); assertEquals(42, statuses[testIndex].getAccessTime()); assertEquals(37, statuses[testIndex].getModificationTime()); assertEquals("root", statuses[testIndex].getOwner()); assertEquals("wheel", statuses[testIndex].getGroup()); assertEquals(0644, statuses[testIndex].getPermission().toExtendedShort()); searchKeyStatus.setPath(new Path("pdfs:/foo/bar/10.0.0.2@file1")); testIndex = Arrays.binarySearch(statuses, searchKeyStatus); assertTrue("Status for path " + searchKeyStatus.getPath().toString() + " not found", testIndex >= 0); assertEquals(new Path("pdfs:/foo/bar/10.0.0.2@file1"), statuses[testIndex].getPath()); assertFalse(statuses[testIndex].isDirectory()); assertEquals(1027, statuses[testIndex].getLen()); assertEquals(1, statuses[testIndex].getReplication()); assertEquals(4096, statuses[testIndex].getBlockSize()); assertEquals(42, statuses[testIndex].getAccessTime()); assertEquals(37, statuses[testIndex].getModificationTime()); assertEquals("root", statuses[testIndex].getOwner()); assertEquals("wheel", statuses[testIndex].getGroup()); assertEquals(0644, statuses[testIndex].getPermission().toExtendedShort()); searchKeyStatus.setPath(new Path("pdfs:/foo/bar/10.0.0.2@file3")); testIndex = Arrays.binarySearch(statuses, searchKeyStatus); assertTrue("Status for path " + searchKeyStatus.getPath().toString() + " not found", testIndex >= 0); assertEquals(new Path("pdfs:/foo/bar/10.0.0.2@file3"), statuses[testIndex].getPath()); assertFalse(statuses[testIndex].isDirectory()); assertEquals(2049, statuses[testIndex].getLen()); assertEquals(1, statuses[testIndex].getReplication()); assertEquals(4096, statuses[testIndex].getBlockSize()); assertEquals(42, statuses[testIndex].getAccessTime()); assertEquals(37, statuses[testIndex].getModificationTime()); assertEquals("root", statuses[testIndex].getOwner()); assertEquals("wheel", statuses[testIndex].getGroup()); assertEquals(0644, statuses[testIndex].getPermission().toExtendedShort()); searchKeyStatus.setPath(new Path("pdfs:/foo/bar/dir")); testIndex = Arrays.binarySearch(statuses, searchKeyStatus); assertTrue("Status for path " + searchKeyStatus.getPath().toString() + " not found", testIndex >= 0); assertEquals(new Path("pdfs:/foo/bar/dir"), statuses[testIndex].getPath()); assertTrue(statuses[testIndex].isDirectory()); assertEquals(47, statuses[testIndex].getLen()); assertEquals(0, statuses[testIndex].getReplication()); assertEquals(0, statuses[testIndex].getBlockSize()); assertEquals(3645, statuses[testIndex].getAccessTime()); assertEquals(1234, statuses[testIndex].getModificationTime()); assertEquals("admin", statuses[testIndex].getOwner()); assertEquals("admin", statuses[testIndex].getGroup()); assertEquals(0755, statuses[testIndex].getPermission().toExtendedShort()); } @Test public void testListStatusWithUnknownRemotePath() throws IOException { Path path = new Path("/foo/10.0.0.3@bar"); try { fs.listStatus(path); fail("Expected getFileStatus to throw FileNotFoundException"); } catch (FileNotFoundException e) { } }
PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public RemoteIterator<FileStatus> listStatusIterator(Path f) throws FileNotFoundException, IOException { final Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); if (isRemoteFile(absolutePath)) { return new RemoteIterator<FileStatus>() { private boolean hasNext = true; @Override public boolean hasNext() throws IOException { return hasNext; } @Override public FileStatus next() throws IOException { if (!hasNext) { throw new NoSuchElementException(); } hasNext = false; return getFileStatus(absolutePath); } }; } return new ListStatusIteratorTask(absolutePath).get(); } PseudoDistributedFileSystem(); @VisibleForTesting PseudoDistributedFileSystem(PDFSConfig config); static synchronized void configure(PDFSConfig config); static String getRemoteFileName(String basename); static RemotePath getRemotePath(Path path); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override String getScheme(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path canonicalizePath(Path p); static final String NAME; }
@Test public void testListStatusIteratorPastLastElement() throws IOException { final Path root = new Path("/"); final RemoteIterator<FileStatus> statusIter = fs.listStatusIterator(root); while (statusIter.hasNext()) { statusIter.next(); } try { statusIter.next(); fail("NoSuchElementException should be throw when next() is called when there are no elements remaining."); } catch (NoSuchElementException ex) { } } @Test public void testListStatusIteratorRoot() throws IOException { final Path root = new Path("/"); final RemoteIterator<FileStatus> statusIterator = fs.listStatusIterator(root); assertTrue(statusIterator.hasNext()); final FileStatus onlyStatus = statusIterator.next(); assertEquals(new Path("pdfs:/foo"), onlyStatus.getPath()); assertTrue(onlyStatus.isDirectory()); assertEquals(0755, onlyStatus.getPermission().toExtendedShort()); assertTrue(!statusIterator.hasNext()); }
PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); if (absolutePath.isRoot()) { throw new AccessControlException("Cannot open " + f); } try { RemotePath remotePath = getRemotePath(absolutePath); FileSystem delegate = getDelegateFileSystem(remotePath.address); return delegate.open(remotePath.path, bufferSize); } catch (IllegalArgumentException e) { throw (FileNotFoundException) (new FileNotFoundException("No file " + absolutePath).initCause(e)); } } PseudoDistributedFileSystem(); @VisibleForTesting PseudoDistributedFileSystem(PDFSConfig config); static synchronized void configure(PDFSConfig config); static String getRemoteFileName(String basename); static RemotePath getRemotePath(Path path); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override String getScheme(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path canonicalizePath(Path p); static final String NAME; }
@Test public void testOpenRoot() throws IOException { Path root = new Path("/"); try { fs.open(root); fail("Expected open call to throw an exception"); } catch (AccessControlException e) { } } @Test public void testOpenFile() throws IOException { FSDataInputStream mockFDIS = mock(FSDataInputStream.class); doReturn(mockFDIS).when(mockLocalFS).open(new Path("/foo/bar/file"), 32768); Path root = new Path("/foo/bar/10.0.0.1@file"); FSDataInputStream fdis = fs.open(root, 32768); assertNotNull(fdis); } @Test public void testOpenLocalFile() throws IOException { try { Path path = new Path("/tmp/file"); @SuppressWarnings("unused") FSDataInputStream fdis = fs.open(path, 32768); fail("Expected open call to throw an exception"); } catch (IOException e) { } }
Transformer { public VirtualDatasetUI transformWithExtract(DatasetVersion newVersion, DatasetPath path, VirtualDatasetUI baseDataset, TransformBase transform) throws DatasetNotFoundException, NamespaceException{ final ExtractTransformActor actor = new ExtractTransformActor(baseDataset.getState(), false, username(), executor); final TransformResult result = transform.accept(actor); if (!actor.hasMetadata()) { VirtualDatasetState vss = protectAgainstNull(result, transform); actor.getMetadata(new SqlQuery(SQLGenerator.generateSQL(vss), vss.getContextList(), securityContext)); } VirtualDatasetUI dataset = asDataset(newVersion, path, baseDataset, transform, result, actor); datasetService.putVersion(dataset); return dataset; } Transformer(SabotContext context, JobsService jobsService, NamespaceService namespace, DatasetVersionMutator datasetService, QueryExecutor executor, SecurityContext securityContext); static String describe(TransformBase transform); DatasetAndData editOriginalSql(DatasetVersion newVersion, List<Transform> operations, QueryType queryType, JobStatusListener listener); VirtualDatasetUI transformWithExtract(DatasetVersion newVersion, DatasetPath path, VirtualDatasetUI baseDataset, TransformBase transform); DatasetAndData transformWithExecute( DatasetVersion newVersion, DatasetPath path, VirtualDatasetUI original, TransformBase transform, QueryType queryType); InitialPendingTransformResponse transformPreviewWithExecute( DatasetVersion newVersion, DatasetPath path, VirtualDatasetUI original, TransformBase transform, BufferAllocator allocator, int limit); static final String VALUE_PLACEHOLDER; }
@Test public void testTransformWithExtract() throws Exception { setSpace(); DatasetPath myDatasetPath = new DatasetPath("spacefoo.folderbar.folderbaz.datasetbuzz"); createDatasetFromParentAndSave(myDatasetPath, "cp.\"tpch/supplier.parquet\""); DatasetUI dataset = getDataset(myDatasetPath); Transformer testTransformer = new Transformer(l(SabotContext.class), l(JobsService.class), newNamespaceService(), newDatasetVersionMutator(), null, l(SecurityContext.class)); VirtualDatasetUI vdsui = DatasetsUtil.getHeadVersion(myDatasetPath, newNamespaceService(), newDatasetVersionMutator()); List<ViewFieldType> sqlFields = vdsui.getSqlFieldsList(); boolean isContainOriginal = false; boolean isContainConverted = false; for (ViewFieldType sqlType : sqlFields) { if (sqlType.getName().equalsIgnoreCase("s_address")) { isContainOriginal = true; break; } } assertTrue(isContainOriginal); isContainOriginal = false; VirtualDatasetUI vdsuiTransformed = testTransformer.transformWithExtract(dataset.getDatasetVersion(), myDatasetPath, vdsui, new TransformRename("s_address", "s_addr")); List<ViewFieldType> sqlFieldsTransformed = vdsuiTransformed.getSqlFieldsList(); for (ViewFieldType sqlType : sqlFieldsTransformed) { if (sqlType.getName().equalsIgnoreCase("s_addr")) { isContainConverted = true; } if (sqlType.getName().equalsIgnoreCase("s_address")) { isContainOriginal = true; } } assertTrue(isContainConverted); assertTrue(!isContainOriginal); }