method2testcases
stringlengths
118
6.63k
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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(); }### Answer: @Test public void testNoInput() { HasherOutput subject = new HasherOutput(); String result = subject.getHasher().hash().toString(); Assert.assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", result); }
### Question: UUIDAdapter { public static byte[] getBytesFromUUID(UUID uuid) { byte[] result = new byte[16]; long msb = uuid.getMostSignificantBits(); long lsb = uuid.getLeastSignificantBits(); for (int i =15;i>=8;i--) { result[i] = (byte) (lsb & 0xFF); lsb >>= 8; } for (int i =7;i>=0;i--) { result[i] = (byte) (msb & 0xFF); msb >>= 8; } return result; } private UUIDAdapter(); static byte[] getBytesFromUUID(UUID uuid); static UUID getUUIDFromBytes(byte[] bytes); }### Answer: @Test public void testGet16BytesFromUUID() { UUID uuid = UUID.randomUUID(); byte[] result = UUIDAdapter.getBytesFromUUID(uuid); assertEquals("Expected result to be a byte array with 16 elements.", 16, result.length); } @Test public void testShouldNotGenerateSameUUIDFromBytes() { UUID uuid = UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"); byte[] result = UUIDAdapter.getBytesFromUUID(uuid); UUID newUuid = UUID.nameUUIDFromBytes(result); assertFalse(uuid.equals(newUuid)); }
### Question: SqlUtils { public static boolean isKeyword(String id) { Preconditions.checkState(RESERVED_SQL_KEYWORDS != null, "SQL reserved keyword list is not loaded. Please check the logs for error messages."); return RESERVED_SQL_KEYWORDS.contains(id.toUpperCase()); } static String quotedCompound(List<String> strings); static String quoteIdentifier(final String id); static boolean isKeyword(String id); static final String stringLiteral(String value); static List<String> parseSchemaPath(String schemaPath); static final String LEGACY_USE_BACKTICKS; static final char QUOTE; static final String QUOTE_WITH_ESCAPE; static ImmutableSet<String> RESERVED_SQL_KEYWORDS; static Function<String, String> QUOTER; }### Answer: @Test public void testIsKeyword() { assertTrue(SqlUtils.isKeyword("USER")); assertTrue(SqlUtils.isKeyword("FiLeS")); assertFalse(SqlUtils.isKeyword("myUSER")); }
### Question: SqlUtils { public static String quoteIdentifier(final String id) { if (id.isEmpty()) { return id; } if (isKeyword(id)) { return quoteString(id); } if (Character.isAlphabetic(id.charAt(0)) && ALPHANUM_MATCHER.matchesAllOf(id)) { return id; } if (NEWLINE_MATCHER.matchesAnyOf(id)) { return quoteUnicodeString(id); } return quoteString(id); } static String quotedCompound(List<String> strings); static String quoteIdentifier(final String id); static boolean isKeyword(String id); static final String stringLiteral(String value); static List<String> parseSchemaPath(String schemaPath); static final String LEGACY_USE_BACKTICKS; static final char QUOTE; static final String QUOTE_WITH_ESCAPE; static ImmutableSet<String> RESERVED_SQL_KEYWORDS; static Function<String, String> QUOTER; }### Answer: @Test public void testQuoteIdentifier() { assertEquals("\"window\"", SqlUtils.quoteIdentifier("window")); assertEquals("\"metadata\"", SqlUtils.quoteIdentifier("metadata")); assertEquals("abc", SqlUtils.quoteIdentifier("abc")); assertEquals("abc123", SqlUtils.quoteIdentifier("abc123")); assertEquals("a_bc", SqlUtils.quoteIdentifier("a_bc")); assertEquals("\"a_\"\"bc\"", SqlUtils.quoteIdentifier("a_\"bc")); assertEquals("\"a.\"\"bc\"", SqlUtils.quoteIdentifier("a.\"bc")); assertEquals("\"ab-c\"", SqlUtils.quoteIdentifier("ab-c")); assertEquals("\"ab/c\"", SqlUtils.quoteIdentifier("ab/c")); assertEquals("\"ab.c\"", SqlUtils.quoteIdentifier("ab.c")); assertEquals("\"123\"", SqlUtils.quoteIdentifier("123")); assertEquals("U&\"foo\\000abar\"", SqlUtils.quoteIdentifier("foo\nbar")); }
### Question: SqlUtils { public static List<String> parseSchemaPath(String schemaPath) { return new StrTokenizer(schemaPath, '.', SqlUtils.QUOTE) .setIgnoreEmptyTokens(true) .getTokenList(); } static String quotedCompound(List<String> strings); static String quoteIdentifier(final String id); static boolean isKeyword(String id); static final String stringLiteral(String value); static List<String> parseSchemaPath(String schemaPath); static final String LEGACY_USE_BACKTICKS; static final char QUOTE; static final String QUOTE_WITH_ESCAPE; static ImmutableSet<String> RESERVED_SQL_KEYWORDS; static Function<String, String> QUOTER; }### Answer: @Test public void testParseSchemaPath() { assertEquals(asList("a", "b", "c"), SqlUtils.parseSchemaPath("a.b.c")); assertEquals(asList("a"), SqlUtils.parseSchemaPath("a")); assertEquals(asList("a", "b.c", "d"), SqlUtils.parseSchemaPath("a.\"b.c\".d")); assertEquals(asList("a", "c"), SqlUtils.parseSchemaPath("a..c")); }
### Question: OptimisticByteOutput extends ByteOutput { @Override public void write(byte value) { checkArray(); arrayReference[arrayOffset++] = value; } OptimisticByteOutput(int payloadSize); @Override void write(byte value); @Override void write(byte[] value, int offset, int length); @Override void writeLazy(byte[] value, int offset, int length); @Override void write(ByteBuffer value); @Override void writeLazy(ByteBuffer value); byte[] toByteArray(); }### Answer: @Test public void testWrite() throws IOException { OptimisticByteOutput byteOutput = new OptimisticByteOutput(smallData.length); for (byte b : smallData) { byteOutput.write(b); } byte[] outputData = byteOutput.toByteArray(); assertNotSame(smallData, outputData); assertArrayEquals(smallData, outputData); }
### Question: 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(); }### Answer: @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()); }
### Question: PathUtils { public static List<String> toPathComponents(String fsPath) { if (fsPath == null ) { return EMPTY_SCHEMA_PATHS; } final StrTokenizer tokenizer = new StrTokenizer(fsPath, SLASH_CHAR, SqlUtils.QUOTE).setIgnoreEmptyTokens(true); return tokenizer.getTokenList(); } static Path toFSPath(final List<String> schemaPath); static String toFSPathString(final List<String> schemaPath); static Path toFSPathSkipRoot(final List<String> schemaPath, final String root); static Path toFSPath(String path); static String getQuotedFileName(Path path); static String toDottedPath(Path fsPath); static String toDottedPath(final Path parent, final Path child); static List<String> toPathComponents(String fsPath); static List<String> toPathComponents(Path fsPath); static String constructFullPath(Collection<String> pathComponents); static String encodeURIComponent(String component); static List<String> parseFullPath(final String path); static String removeQuotes(String pathComponent); static Joiner getPathJoiner(); static char getPathDelimiter(); static Joiner getKeyJoiner(); static String slugify(Collection<String> pathComponents); static String relativePath(Path absolutePath, Path basePath); static void verifyNoAccessOutsideBase(Path basePath, Path givenPath); static boolean checkNoAccessOutsideBase(Path basePath, Path givenPath); static String removeLeadingSlash(String path); }### Answer: @Test public void testPathComponents() throws Exception { assertEquals(ImmutableList.of("a", "b", "c"), PathUtils.toPathComponents(Path.of("/a/b/c"))); assertEquals(ImmutableList.of("a", "b", "c"), PathUtils.toPathComponents(Path.of("a/b/c"))); assertEquals(ImmutableList.of("a", "b", "c/"), PathUtils.toPathComponents(Path.of("a/b/\"c/\""))); }
### Question: PathUtils { public static String 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); }### Answer: @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) { } }
### Question: 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); }### Answer: @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")); }
### Question: 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); }### Answer: @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")); }
### Question: 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); }### Answer: @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"))); }
### Question: PathUtils { public static String removeLeadingSlash(String path) { if (path.length() > 0 && path.charAt(0) == '/') { String newPath = path.substring(1); return removeLeadingSlash(newPath); } else { return path; } } static Path toFSPath(final List<String> schemaPath); static String toFSPathString(final List<String> schemaPath); static Path toFSPathSkipRoot(final List<String> schemaPath, final String root); static Path toFSPath(String path); static String getQuotedFileName(Path path); static String toDottedPath(Path fsPath); static String toDottedPath(final Path parent, final Path child); static List<String> toPathComponents(String fsPath); static List<String> toPathComponents(Path fsPath); static String constructFullPath(Collection<String> pathComponents); static String encodeURIComponent(String component); static List<String> parseFullPath(final String path); static String removeQuotes(String pathComponent); static Joiner getPathJoiner(); static char getPathDelimiter(); static Joiner getKeyJoiner(); static String slugify(Collection<String> pathComponents); static String relativePath(Path absolutePath, Path basePath); static void verifyNoAccessOutsideBase(Path basePath, Path givenPath); static boolean checkNoAccessOutsideBase(Path basePath, Path givenPath); static String removeLeadingSlash(String path); }### Answer: @Test public void testRemoveLeadingSlash() { assertEquals("", PathUtils.removeLeadingSlash("")); assertEquals("", PathUtils.removeLeadingSlash("/")); assertEquals("aaaa", PathUtils.removeLeadingSlash("/aaaa")); assertEquals("aaaa/bbb", PathUtils.removeLeadingSlash("/aaaa/bbb")); assertEquals("aaaa/bbb", PathUtils.removeLeadingSlash(" }
### Question: 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); }### Answer: @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) { } }
### Question: LocalValue { public void set(T value) { Preconditions.checkNotNull(value, "LocalValue cannot be set to null"); doSet(value); } LocalValue(); @SuppressWarnings("unchecked") Optional<T> get(); void set(T value); void clear(); static LocalValues save(); static void restore(LocalValues localValues); }### Answer: @Test public void testSet() throws Exception { stringLocalValue.set("value1"); intLocalValue.set(1); assertEquals("value1", stringLocalValue.get().get()); assertEquals(new Integer(1), intLocalValue.get().get()); stringLocalValue.set("value2"); intLocalValue.set(2); assertEquals("value2", stringLocalValue.get().get()); assertEquals(new Integer(2), intLocalValue.get().get()); try { intLocalValue.restore(null); fail("Restoring null should fail"); } catch (Exception ignored) { } }
### Question: 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); }### Answer: @Test public void testClear() { stringLocalValue.set("value1"); intLocalValue.set(1); stringLocalValue.clear(); intLocalValue.clear(); assertFalse(stringLocalValue.get().isPresent()); assertFalse(intLocalValue.get().isPresent()); }
### Question: 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; }### Answer: @Test public void checkMaxDirectMemory() { assertThat(VM.maxDirectMemory(arguments), is(maxDirectMemory)); }
### Question: 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; }### Answer: @Test public void checkDebugEnabled() { assertThat(VM.isDebugEnabled(arguments), is(debugEnabled)); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @Test public void testGetObject() throws Exception { assertEquals(new TimePrintMillis(NON_NULL_VALUE), accessor.getObject(0)); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @Test public void testGetObject() throws Exception { assertEquals(new Date(72, 10, 4), accessor.getObject(0)); }
### Question: 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); }### Answer: @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)); }
### Question: 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(); }### Answer: @Test public void testIsNull() throws Exception { assertFalse(genericAccessor.isNull(0)); assertTrue(genericAccessor.isNull(1)); }
### Question: 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(); }### Answer: @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); }
### Question: 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(); }### Answer: @Test public void testGetType() throws Exception { assertEquals(UserBitShared.SerializedField.getDefaultInstance().getMajorType(), genericAccessor.getType()); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @Test public void testGetObject() throws Exception { assertEquals( new Timestamp(72, 10, 4, 11, 10, 8, (int)TimeUnit.MILLISECONDS.toNanos(957)), accessor.getObject(0)); }
### Question: 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); }### Answer: @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)); }
### Question: 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; }### Answer: @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"); }
### Question: 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 ); }### Answer: @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; } }
### Question: 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 ); }### Answer: @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 ) ); }
### Question: 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(); }### Answer: @Test public void testEmpty() { DictionaryBuilder<String> builder = new DictionaryBuilder<>(String.class); Iterator<String> iterator = builder.build().iterator(); assertFalse(iterator.hasNext()); }
### Question: 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); }### Answer: @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")); } }
### Question: 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(); }### Answer: @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")); }
### Question: 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); }### Answer: @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()); }
### Question: 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); }### Answer: @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)); }
### Question: 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(); }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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"); }
### Question: 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); }### Answer: @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)); }
### Question: 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; }### Answer: @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()); }
### Question: 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(); }### Answer: @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); }
### Question: 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(); }### Answer: @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()); } }
### Question: AsyncHttpClientProvider { public static AsyncHttpClient getInstance(){ return SingletonHelper.INSTANCE; } static AsyncHttpClient getInstance(); static final int DEFAULT_REQUEST_TIMEOUT; }### Answer: @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(); }
### Question: 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(); }### Answer: @Test public void testGetAuthzHeaderValue() { String authzHeaderValue = authTokenProvider.getAuthzHeaderValue(prepareTestRequest()); assertEquals("SharedKey mock-account:ZwovG4J+nCDc3w58WPei6fvJBQsO96YojteJncy0wwI=", authzHeaderValue); }
### Question: 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(); }### Answer: @Test public void testCheckAndUpdate() { assertFalse("Shared key token is static. There shouldn't ever be an update required", authTokenProvider.checkAndUpdateToken()); }
### Question: 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(); }### Answer: @Test public void testIsCloseToExpiry() { assertFalse("Shared key token never expires", authTokenProvider.isCloseToExpiry()); }
### Question: 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); }### Answer: @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()); }
### Question: 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); }### Answer: @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) { } }
### Question: 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); }### Answer: @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) { } }
### Question: 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); }### Answer: @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) { } }
### Question: 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); }### Answer: @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]); } }
### Question: 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; }### Answer: @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()); }
### Question: 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; }### Answer: @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()); }
### Question: 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; }### Answer: @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) { } }
### Question: 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; }### Answer: @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); }
### Question: PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { final Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); if (absolutePath.isRoot()) { throw new AccessControlException("Cannot create " + f); } if(!isRemoteFile(f)){ if (isDirectory(absolutePath)) { throw new FileAlreadyExistsException("Directory already exists: " + f); } throw new IOException("Cannot create non-canonical path " + f); } try { RemotePath remotePath = getRemotePath(absolutePath); return getDelegateFileSystem(remotePath.address).create(remotePath.path, permission, overwrite, bufferSize, replication, blockSize, progress); } catch (IllegalArgumentException e) { throw (IOException) (new IOException("Cannot create 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; }### Answer: @Test public void testCreateRoot() throws IOException { Path root = new Path("/"); try { fs.create(root, FsPermission.getFileDefault(), true, 0, (short) 1, 4096, null); fail("Expected create call to throw an exception"); } catch (AccessControlException e) { } } @Test public void testCreateFile() throws IOException { FSDataOutputStream mockFDOS = mock(FSDataOutputStream.class); doReturn(mockFDOS).when(mockLocalFS).create( new Path("/foo/bar/file"), FsPermission.getFileDefault(), true, 0, (short) 1, 4096L,null); Path path = new Path("/foo/bar/10.0.0.1@file"); FSDataOutputStream fdos = fs.create(path, FsPermission.getFileDefault(), true, 0, (short) 1, 4096, null); assertNotNull(fdos); } @Test public void testCreateLocalFile() throws IOException { try { Path path = new Path("foo/bar/file"); @SuppressWarnings("unused") FSDataOutputStream fdos = fs.create(path, FsPermission.getFileDefault(), true, 0, (short) 1, 4096, null); fail("Expected create call to throw an exception"); } catch (IOException e) { } }
### Question: PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); if (absolutePath.isRoot()) { throw new AccessControlException("Cannot open " + f); } if(!isRemoteFile(f)){ if (isDirectory(absolutePath)) { throw new FileAlreadyExistsException("Directory already exists: " + f); } throw new IOException("Cannot create non-canonical path " + f); } try { RemotePath remotePath = getRemotePath(absolutePath); FileSystem delegate = getDelegateFileSystem(remotePath.address); return delegate.append(remotePath.path, bufferSize, progress); } 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; }### Answer: @Test public void testAppendRoot() throws IOException { Path root = new Path("/"); try { fs.append(root, 4096, null); fail("Expected append call to throw an exception"); } catch (AccessControlException e) { } } @Test public void testAppendFile() throws IOException { FSDataOutputStream mockFDOS = mock(FSDataOutputStream.class); doReturn(mockFDOS).when(mockRemoteFS).append( new Path("/foo/bar/file"), 4096, null); Path path = new Path("/foo/bar/10.0.0.2@file"); FSDataOutputStream fdos = fs.append(path, 4096, null); assertNotNull(fdos); } @Test public void testAppendLocalFile() throws IOException { try { Path path = new Path("/foo/bar/file"); @SuppressWarnings("unused") FSDataOutputStream fdos = fs.append(path, 4096, null); fail("Expected append call to throw an exception"); } catch (IOException e) { } }
### Question: PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public boolean delete(Path f, boolean recursive) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); if (absolutePath.isRoot()) { throw new AccessControlException("Cannot delete " + f); } if (!isRemoteFile(f)) { return new DeleteTask(absolutePath, recursive).get(); } try { RemotePath remotePath = getRemotePath(absolutePath); FileSystem delegate = getDelegateFileSystem(remotePath.address); return delegate.delete(remotePath.path, recursive); } 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; }### Answer: @Test public void testDeleteRoot() throws IOException { Path root = new Path("/"); try { fs.delete(root, false); fail("Expected delete call to throw an exception"); } catch (AccessControlException e) { } } @Test public void testDeleteLocalFile() throws IOException { try { Path path = new Path("/foo/bar/file"); fs.delete(path, false); fail("Expected delete call to throw an exception"); } catch (IOException e) { } } @Test public void testDeleteFile() throws IOException { doReturn(true).when(mockRemoteFS).delete( new Path("/foo/bar"), false); Path path = new Path("/foo/10.0.0.2@bar"); assertTrue(fs.delete(path, false)); } @Test public void testDeleteUnknownLocalFile() throws IOException { doThrow(FileNotFoundException.class).when(mockLocalFS).delete( new Path("/foo/unknown"), false); Path path = new Path("/foo/10.0.0.1@unknown"); try{ fs.delete(path, false); fail("Expecting FileNotFoundException"); } catch(FileNotFoundException e) { } } @Test public void testDeleteUnknownRemoteFile() throws IOException { doThrow(FileNotFoundException.class).when(mockRemoteFS).delete( new Path("/foo/unknown"), false); Path path = new Path("/foo/10.0.0.2@unknown"); try{ fs.delete(path, false); fail("Expecting FileNotFoundException"); } catch(FileNotFoundException e) { } }
### Question: SQLGenerator { public static String generateSQL(VirtualDatasetState vss){ return new SQLGenerator().innerGenerateSQL(vss); } SQLGenerator(); static String generateSQL(VirtualDatasetState vss); static String getTableAlias(From from); }### Answer: @Test public void testReplaceInvalidReplacedValues() { boolean exThrown = false; try { VirtualDatasetState state = new VirtualDatasetState() .setFrom(nameDSRef); Expression exp0 = new ExpColumnReference("bar").wrap(); FieldTransformationBase transf1 = new FieldReplaceValue() .setReplacedValuesList(Collections.<String>emptyList()) .setReplacementType(DATE) .setReplaceType(ReplaceType.VALUE) .setReplacementValue("2016-11-05"); Expression exp = new ExpFieldTransformation(transf1.wrap(), exp0).wrap(); SQLGenerator.generateSQL(state.setColumnsList(asList(new Column("foo", exp)))); fail("not expected to reach here"); } catch (UserException e) { exThrown = true; assertEquals("select at least one value to replace", e.getMessage()); } assertTrue("expected a UserException", exThrown); }
### Question: PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { Path absolutePath = toAbsolutePath(f); checkPath(absolutePath); if (absolutePath.isRoot()) { return true; } if (isRemoteFile(absolutePath)) { throw new IOException("Cannot create a directory under file " + f); } return new MkdirsTask(absolutePath, permission).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; }### Answer: @Test public void testMkdirsRoot() throws IOException { Path root = new Path("/"); assertTrue(fs.mkdirs(root, FsPermission.getDirDefault())); } @Test public void testMkdirsRemoteFile() throws IOException { doReturn(true).when(mockLocalFS).mkdirs( new Path("/foo/bar/dir2"), FsPermission.getFileDefault()); doReturn(true).when(mockRemoteFS).mkdirs( new Path("/foo/bar/dir2"), FsPermission.getFileDefault()); Path path = new Path("/foo/bar/dir2"); assertTrue(fs.mkdirs(path, FsPermission.getFileDefault())); }
### Question: PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public Path canonicalizePath(Path p) throws IOException { Path absolutePath = toAbsolutePath(p); checkPath(absolutePath); if (isRemoteFile(absolutePath)) { return absolutePath; } if (isDirectory(absolutePath)) { return absolutePath; } if (localAccessAllowed) { return createRemotePath(localIdentity.getAddress(), absolutePath); } final NodeEndpoint randomDelegate = getRandomDelegate(); return createRemotePath(randomDelegate.getAddress(), absolutePath); } 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; }### Answer: @Test public void testCanonicalizeRemoteFile() throws IOException { Path path = new Path("/foo/bar/10.0.0.2@file"); Path resolvedPath = fs.canonicalizePath(path); assertEquals(new Path("/foo/bar/10.0.0.2@file"), resolvedPath); } @Test public void testCanonicalizeDirectoryFile() throws IOException { Path path = new Path("/foo/bar"); Path resolvedPath = fs.canonicalizePath(path); assertEquals(new Path("/foo/bar"), resolvedPath); } @Test public void testCanonicalizeLocalFile() throws IOException { Path path = new Path("/foo/bar/file"); Path resolvedPath = fs.canonicalizePath(path); assertEquals(new Path("/foo/bar/10.0.0.1@file"), resolvedPath); } @Test public void testCanonicalizeLocalFileIfNoLocalAccess() throws IOException { Provider<Iterable<NodeEndpoint>> endpointsProvider = DirectProvider.<Iterable<NodeEndpoint>>wrap((Arrays.asList(REMOTE_ENDPOINT_1, REMOTE_ENDPOINT_2))); PDFSConfig pdfsConfig = new PDFSConfig(MoreExecutors.newDirectExecutorService(), null, null, endpointsProvider, LOCAL_ENDPOINT, false); PseudoDistributedFileSystem pdfs = newPseudoDistributedFileSystem(pdfsConfig); Path path = new Path("/foo/bar/file"); Path resolvedPath = pdfs.canonicalizePath(path); assertEquals(new Path("/foo/bar/10.0.0.2@file"), resolvedPath); }
### Question: Hive3StoragePlugin extends BaseHiveStoragePlugin implements StoragePluginCreator.PF4JStoragePlugin, SupportsReadSignature, SupportsListingDatasets, SupportsAlteringDatasetMetadata, SupportsPF4JStoragePlugin { public String getUsername(String name) { if (isStorageImpersonationEnabled()) { return name; } return SystemUser.SYSTEM_USERNAME; } @VisibleForTesting Hive3StoragePlugin(HiveConf hiveConf, SabotContext context, String name); Hive3StoragePlugin(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(DatasetHandle datasetHandle, DatasetMetadata oldDatasetMetadata, Map<String, AttributeValue> attributes, AlterMetadataOption... options); T getPF4JStoragePlugin(); }### Answer: @Test public void impersonationDisabledShouldReturnSystemUser() { final HiveConf hiveConf = new HiveConf(); hiveConf.setBoolVar(HIVE_SERVER2_ENABLE_DOAS, false); final SabotContext context = mock(SabotContext.class); final Hive3StoragePlugin 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 Hive3StoragePlugin plugin = new Hive3StoragePlugin(hiveConf, context, "foo"); final String userName = plugin.getUsername(TEST_USER_NAME); assertEquals(TEST_USER_NAME, userName); }
### Question: HiveScanBatchCreator implements HiveProxiedScanBatchCreator { @VisibleForTesting public UserGroupInformation getUGI(Hive3StoragePlugin 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(Hive3StoragePlugin storagePlugin, HiveProxyingSubScan config); }### Answer: @Test public void ensureStoragePluginIsUsedForUsername() throws Exception { final String originalName = "Test"; final String finalName = "Replaced"; final HiveScanBatchCreator creator = new HiveScanBatchCreator(); final Hive3StoragePlugin plugin = mock(Hive3StoragePlugin.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()); }
### Question: NativeLibPluginManager extends DefaultPluginManager { @Override protected Path createPluginsRoot() { final Path pluginsPath = this.isDevelopment() ? Paths.get(PLUGINS_PATH_DEV_MODE) : DremioConfig.getPluginsRootPath().resolve("connectors"); return pluginsPath; } }### Answer: @Test public void testShouldReturnPluginRoot() { properties.set(DremioConfig.PLUGINS_ROOT_PATH_PROPERTY, "/tmp/plugins"); Path expectedPath = Paths.get("/tmp/plugins/connectors"); Path actualPath = nativeLibPluginManager.createPluginsRoot(); Assert.assertEquals(expectedPath, actualPath); }
### Question: HistogramGenerator { @VisibleForTesting static void produceRanges(List<Number> ranges, LocalDateTime min, LocalDateTime max, TruncEvalEnum truncateTo) { long timeValue = toMillis(roundTime(min, truncateTo, true)); long maxTimeValue = toMillis(roundTime(max, truncateTo, false)); ranges.add(timeValue); while ( timeValue <= maxTimeValue) { LocalDateTime tmpValue = new LocalDateTime(timeValue, DateTimeZone.UTC); switch (truncateTo) { case SECOND: timeValue = toMillis(tmpValue.plusSeconds(1)); break; case MINUTE: timeValue = toMillis(tmpValue.plusMinutes(1)); break; case HOUR: timeValue = toMillis(tmpValue.plusHours(1)); break; case DAY: timeValue = toMillis(tmpValue.plusDays(1)); break; case WEEK: timeValue = toMillis(tmpValue.plusWeeks(1)); break; case MONTH: timeValue = toMillis(tmpValue.plusMonths(1)); break; case QUARTER: timeValue = toMillis(tmpValue.plusMonths(3)); break; case YEAR: timeValue = toMillis(tmpValue.plusYears(1)); break; case DECADE: timeValue = toMillis(tmpValue.plusYears(10)); break; case CENTURY: timeValue = toMillis(tmpValue.plusYears(100)); break; case MILLENNIUM: timeValue = toMillis(tmpValue.plusYears(1000)); default: break; } ranges.add(timeValue); if (ranges.size() > 100_000) { throw new AssertionError(String.format("the ranges size should not grow that big: min: %s, max: %s, t: %s", min, max, truncateTo)); } } } HistogramGenerator(QueryExecutor executor); Histogram<HistogramValue> getHistogram(final DatasetPath datasetPath, DatasetVersion version, Selection selection, DataType colType, SqlQuery datasetQuery, BufferAllocator allocator); Histogram<CleanDataHistogramValue> getCleanDataHistogram(final DatasetPath datasetPath, DatasetVersion version, String colName, SqlQuery datasetQuery, BufferAllocator allocator); Map<DataType, Long> getTypeHistogram(final DatasetPath datasetPath, DatasetVersion version, String colName, SqlQuery datasetQuery, BufferAllocator allocator); long getSelectionCount(final DatasetPath datasetPath, final DatasetVersion version, final SqlQuery datasetQuery, final DataType dataType, final String colName, Set<String> selectedValues, BufferAllocator allocator); }### Answer: @Test public void testProduceRanges() { List<Number> ranges = new ArrayList<>(); HistogramGenerator.produceRanges(ranges , new LocalDateTime(1970, 1, 1, 1, 0, 0), new LocalDateTime(1970, 1, 1, 11, 59, 0), TruncEvalEnum.HOUR); List<Number> expected = new ArrayList<>(); for (int i = 0; i < 13; i++) { expected.add((i + 1 ) * 3600_000L); } Assert.assertEquals(expected.size(), ranges.size()); Assert.assertEquals(expected, ranges); }
### Question: ExtractMapRecommender extends Recommender<ExtractMapRule, MapSelection> { @Override public List<ExtractMapRule> getRules(MapSelection selection, DataType selColType) { checkArgument(selColType == DataType.MAP, "Extract map entries is supported only on MAP type columns"); return Collections.singletonList(new ExtractMapRule(Joiner.on(".").join(selection.getMapPathList()))); } @Override List<ExtractMapRule> getRules(MapSelection selection, DataType selColType); @Override TransformRuleWrapper<ExtractMapRule> wrapRule(ExtractMapRule rule); }### Answer: @Test public void testExtractMapRules() throws Exception { List<ExtractMapRule> rules = recommender.getRules(new MapSelection("foo", ImmutableList.of("a")), DataType.MAP); assertEquals(1, rules.size()); assertEquals("a", rules.get(0).getPath()); }
### Question: YarnController { public YarnController() { this(DremioConfig.create()); } YarnController(); YarnController(DremioConfig config); TwillRunnerService getTwillService(ClusterId key); void invalidateTwillService(final ClusterId key); TwillRunnerService startTwillRunner(YarnConfiguration yarnConfiguration); TwillController startCluster(YarnConfiguration yarnConfiguration, List<Property> propertyList); }### Answer: @Test public void testYarnController() throws Exception { assumeNonMaprProfile(); YarnController yarnController = new YarnController(); YarnConfiguration yarnConfiguration = createYarnConfig("resource-manager", "hdfs: String jvmOptions = yarnController.prepareCommandOptions(yarnConfiguration, getProperties()); logger.info("JVMOptions: {}", jvmOptions); assertTrue(jvmOptions.contains(" -Dpaths.dist=pdfs: assertTrue(jvmOptions.contains(" -Xmx4096")); assertTrue(jvmOptions.contains(" -XX:MaxDirectMemorySize=5120m")); assertTrue(jvmOptions.contains(" -Xms4096m")); assertTrue(jvmOptions.contains(" -XX:ThreadStackSize=512")); assertTrue(jvmOptions.contains(" -Dzookeeper.saslprovider=com.mapr.security.maprsasl.MaprSaslProvider")); assertTrue(jvmOptions.contains(" -Dzookeeper.client.sasl=false")); assertTrue(jvmOptions.contains(" -Dzookeeper.sasl.clientconfig=Client")); assertTrue(jvmOptions.contains(" -Djava.security.auth.login.config=/opt/mapr/conf/mapr.login.conf")); assertTrue(jvmOptions.contains(" -Dpaths.spilling=[maprfs: assertFalse(jvmOptions.contains("JAVA_HOME")); assertTrue(jvmOptions.contains(" -DMAPR_IMPALA_RA_THROTTLE")); assertTrue(jvmOptions.contains(" -DMAPR_MAX_RA_STREAMS")); assertTrue(jvmOptions.contains(" -D" + DremioConfig.NETTY_REFLECTIONS_ACCESSIBLE + "=true")); assertTrue(jvmOptions.contains(" -D"+VM.DREMIO_CPU_AVAILABLE_PROPERTY + "=2")); DacDaemonYarnApplication.Environment myEnv = new DacDaemonYarnApplication.Environment() { @Override public String getEnv(String name) { return tempDir.getRoot().toString(); } }; DacDaemonYarnApplication dacDaemonApp = new DacDaemonYarnApplication(yarnController.dremioConfig, yarnConfiguration, myEnv); TwillSpecification twillSpec = dacDaemonApp.configure(); assertEquals(DacDaemonYarnApplication.YARN_APPLICATION_NAME_DEFAULT, twillSpec.getName()); Map<String, RuntimeSpecification> runnables = twillSpec.getRunnables(); assertNotNull(runnables); assertEquals(1, runnables.size()); RuntimeSpecification runnable = runnables.get(DacDaemonYarnApplication.YARN_RUNNABLE_NAME); assertNotNull(runnable); assertEquals(DacDaemonYarnApplication.YARN_RUNNABLE_NAME, runnable.getName()); assertEquals(9216, runnable.getResourceSpecification().getMemorySize()); assertEquals(2, runnable.getResourceSpecification().getVirtualCores()); assertEquals(3, runnable.getResourceSpecification().getInstances()); }
### Question: ExtractMapRecommender extends Recommender<ExtractMapRule, MapSelection> { @Override public TransformRuleWrapper<ExtractMapRule> wrapRule(ExtractMapRule rule) { return new ExtractMapTransformRuleWrapper(rule); } @Override List<ExtractMapRule> getRules(MapSelection selection, DataType selColType); @Override TransformRuleWrapper<ExtractMapRule> wrapRule(ExtractMapRule rule); }### Answer: @Test public void testGenExtractMapRuleWrapper() throws Exception { TransformRuleWrapper<ExtractMapRule> wrapper = recommender.wrapRule(new ExtractMapRule("a")); assertEquals("a", wrapper.getRule().getPath()); assertEquals("extract from map a", wrapper.describe()); assertEquals("tbl.foo.a IS NOT NULL", wrapper.getMatchFunctionExpr("tbl.foo")); assertEquals("tbl.foo.a", wrapper.getFunctionExpr("tbl.foo")); TransformRuleWrapper<ExtractMapRule> wrapper2 = recommender.wrapRule(new ExtractMapRule("c[0].b")); assertEquals("extract from map c[0].b", wrapper2.describe()); assertEquals("tbl.foo.c[0].b IS NOT NULL", wrapper2.getMatchFunctionExpr("tbl.foo")); assertEquals("tbl.foo.c[0].b", wrapper2.getFunctionExpr("tbl.foo")); }
### Question: YarnService implements ProvisioningServiceDelegate { @Override public void stopCluster(Cluster cluster) throws YarnProvisioningHandlingException { stopClusterAsync(cluster); } YarnService(DremioConfig config, ProvisioningStateListener stateListener, NodeProvider executionNodeProvider, OptionManager options, EditionProvider editionProvider); @VisibleForTesting YarnService(ProvisioningStateListener stateListener, YarnController controller, NodeProvider executionNodeProvider); @Override ClusterType getType(); @Override ClusterEnriched startCluster(Cluster cluster); @Override void stopCluster(Cluster cluster); @Override ClusterEnriched resizeCluster(Cluster cluster); @Override ClusterEnriched getClusterInfo(final Cluster cluster); }### Answer: @Test public void testStopCluster() throws Exception { assumeNonMaprProfile(); Cluster myCluster = createCluster(); myCluster.setState(ClusterState.RUNNING); myCluster.setStateChangeTime(System.currentTimeMillis()); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); TwillController twillController = Mockito.mock(TwillController.class); RunId runId = RunIds.generate(); when(controller.startCluster(any(YarnConfiguration.class), eq(myCluster.getClusterConfig().getSubPropertyList()))) .thenReturn(twillController); when(twillController.getRunId()).thenReturn(runId); myCluster.setRunId(new com.dremio.provision.RunId(runId.getId())); yarnService.stopCluster(myCluster); assertEquals(ClusterState.STOPPED, myCluster.getState()); }
### Question: AppBundleGenerator { @VisibleForTesting static Stream<Path> toPathStream(ClassLoader classLoader) { if (classLoader == null) { return Stream.of(); } if (classLoader != ClassLoader.getSystemClassLoader()) { return Stream.concat(toPathStream(classLoader.getParent()), getPaths(classLoader)); } else { return getPaths(classLoader); } } AppBundleGenerator(ClassLoader classLoader, @NotNull List<String> classPathPrefix, @NotNull List<String> classPath, List<String> nativeLibraryPath, Path pluginsPath); static AppBundleGenerator of(DremioConfig config); Path generateBundle(); static final String X_DREMIO_LIBRARY_PATH_MANIFEST_ATTRIBUTE; static final String X_DREMIO_PLUGINS_PATH_MANIFEST_ATTRIBUTE; }### Answer: @Test public void testToPathStream() throws MalformedURLException, IOException { try ( URLClassLoader clA = new URLClassLoader( new URL[] { new URL("file:/foo/bar.jar"), new URL("file:/foo/baz.jar") }, null); URLClassLoader clB = new URLClassLoader( new URL[] { new URL("file:/test/ab.jar"), new URL("file:/test/cd.jar") }, clA)) { Stream<Path> stream = AppBundleGenerator.toPathStream(clB); assertThat(stream.collect(Collectors.toList()), is(equalTo(Arrays.asList(Paths.get("/foo/bar.jar"), Paths.get("/foo/baz.jar"), Paths.get("/test/ab.jar"), Paths.get("/test/cd.jar"))))); } } @Test public void testSkipJDKClassLoaders() throws MalformedURLException, IOException { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); ClassLoader parent = classLoader.getParent(); Assume.assumeNotNull(parent); Assume.assumeTrue(parent instanceof URLClassLoader); URL[] parentURLs = ((URLClassLoader) parent).getURLs(); Stream<Path> stream = AppBundleGenerator.toPathStream(classLoader); assertFalse("Stream contains a jar from the parent classloader", stream.anyMatch(path -> { try { return Arrays.asList(parentURLs).contains(path.toUri().toURL()); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } })); } @Test public void testToPathStreamFromClassPath() throws MalformedURLException, IOException { Path mainFolder = temporaryFolder.newFolder().toPath(); Files.createFile(mainFolder.resolve("a.jar")); Files.createFile(mainFolder.resolve("b.jar")); Files.createFile(mainFolder.resolve("xyz-dremio.jar")); Files.createDirectory(mainFolder.resolve("www-dremio")); Files.createFile(mainFolder.resolve("www-dremio/foo.jar")); assertThat( AppBundleGenerator .toPathStream( Arrays.asList(mainFolder.resolve("a.jar").toString(), mainFolder.resolve(".*-dremio").toString())) .collect(Collectors.toList()), is(equalTo(Arrays.asList(mainFolder.resolve("a.jar"), mainFolder.resolve("www-dremio"))))); }
### Question: CardGenerator { <T> String generateCardGenQuery(String inputColName, String datasetPreviewTable, List<TransformRuleWrapper<T>> evaluators) { StringBuilder queryBuilder = new StringBuilder(); String inputExpr = String.format("%s.%s", quoteIdentifier("dremio_preview_data"), quoteIdentifier(inputColName)); List<String> exprs = Lists.newArrayList(); for(int i=0; i<evaluators.size(); i++) { if (evaluators.get(i).canGenerateExamples()) { final String expr = evaluators.get(i).getExampleFunctionExpr(inputExpr); final String outputColAlias = "example_" + i; exprs.add(String.format("%s AS %s", expr, outputColAlias)); } } exprs.add(String.format("%s AS inputCol", inputExpr)); queryBuilder.append("SELECT\n"); queryBuilder.append(Joiner.on(",\n").join(exprs)); queryBuilder.append(format("\nFROM %s as dremio_preview_data", datasetPreviewTable)); queryBuilder.append(format("\nWHERE %s IS NOT NULL", quoteIdentifier(inputColName))); queryBuilder.append(format("\nLIMIT %d", Card.EXAMPLES_TO_SHOW)); return queryBuilder.toString(); } CardGenerator(final QueryExecutor executor, DatasetPath datasetPath, DatasetVersion version); List<Card<T>> generateCards(SqlQuery datasetSql, String colName, List<TransformRuleWrapper<T>> transformRuleWrappers, Comparator<Card<T>> comparator, BufferAllocator allocator); }### Answer: @Test public void exampleGeneratorQuery() { String outputQuery1 = cardGenerator.generateCardGenQuery("col.with.dots", "TABLE(\"jobstore\".\"path\"(type => 'arrow))", rules); String expQuery1 = "SELECT\n" + "match_pattern_example(dremio_preview_data.\"col.with.dots\", 'CONTAINS', 'test pattern', false) AS example_0,\n" + "match_pattern_example(dremio_preview_data.\"col.with.dots\", 'MATCHES', '.*txt.*', true) AS example_1,\n" + "dremio_preview_data.\"col.with.dots\" AS inputCol\n" + "FROM TABLE(\"jobstore\".\"path\"(type => 'arrow)) as dremio_preview_data\n" + "WHERE \"col.with.dots\" IS NOT NULL\n" + "LIMIT 3"; assertEquals(expQuery1, outputQuery1); String outputQuery2 = cardGenerator.generateCardGenQuery("normalCol", "TABLE(\"jobstore\".\"path\"(type => 'arrow))", rules); String expQuery2 = "SELECT\n" + "match_pattern_example(dremio_preview_data.normalCol, 'CONTAINS', 'test pattern', false) AS example_0,\n" + "match_pattern_example(dremio_preview_data.normalCol, 'MATCHES', '.*txt.*', true) AS example_1,\n" + "dremio_preview_data.normalCol AS inputCol\n" + "FROM TABLE(\"jobstore\".\"path\"(type => 'arrow)) as dremio_preview_data\n" + "WHERE normalCol IS NOT NULL\n" + "LIMIT 3"; assertEquals(expQuery2, outputQuery2); }
### Question: YarnContainerHealthMonitor implements LiveHealthMonitor { @Override public boolean isHealthy() { return isHealthy; } YarnContainerHealthMonitor(); @Override boolean isHealthy(); }### Answer: @Test public void testUnavailableContainer() throws Exception { when(connection.getResponseCode()).thenReturn(HttpStatus.SC_NOT_FOUND); assertNull(healthMonitorThread.getContainerState(connection)); assertFalse(healthMonitorThread.isHealthy()); } @Test public void testHealthyContainer() throws Exception { String containerInfoJson = "{\"container\":{\"user\":\"dremio\",\"state\":\"NEW\"}}"; InputStream targetStream = new ByteArrayInputStream(containerInfoJson.getBytes()); when(connection.getInputStream()).thenReturn(targetStream); assertEquals(ContainerState.NEW.name(), healthMonitorThread.getContainerState(connection)); assertTrue(healthMonitorThread.isHealthy()); } @Test public void testUnhealthyContainer() throws Exception { String containerInfoJson = "{\"container\":{\"state\":\"COMPLETE\",\"user\":\"root\"}}"; InputStream targetStream = new ByteArrayInputStream(containerInfoJson.getBytes()); when(connection.getInputStream()).thenReturn(targetStream); assertEquals(ContainerState.COMPLETE.name(), healthMonitorThread.getContainerState(connection)); assertFalse(healthMonitorThread.isHealthy()); }
### Question: CardGenerator { <T> String generateMatchCountQuery(String inputColName, String datasetPreviewTable, List<TransformRuleWrapper<T>> evaluators) { StringBuilder queryBuilder = new StringBuilder(); String inputExpr = String.format("%s.%s", quoteIdentifier("dremio_preview_data"), quoteIdentifier(inputColName)); List<String> exprs = Lists.newArrayList(); for(int i=0; i<evaluators.size(); i++) { final String expr = evaluators.get(i).getMatchFunctionExpr(inputExpr); final String outputColAlias = "matched_count_" + i; exprs.add(String.format("sum(CASE WHEN %s THEN 1 ELSE 0 END) AS %s", expr, outputColAlias)); } exprs.add("COUNT(1) as total"); queryBuilder.append("SELECT\n"); queryBuilder.append(Joiner.on(",\n").join(exprs)); queryBuilder.append(format("\nFROM %s as dremio_preview_data", datasetPreviewTable)); return queryBuilder.toString(); } CardGenerator(final QueryExecutor executor, DatasetPath datasetPath, DatasetVersion version); List<Card<T>> generateCards(SqlQuery datasetSql, String colName, List<TransformRuleWrapper<T>> transformRuleWrappers, Comparator<Card<T>> comparator, BufferAllocator allocator); }### Answer: @Test public void matchCountGeneratorQuery() { String outputQuery1 = cardGenerator.generateMatchCountQuery("col with spaces", "TABLE(\"jobstore\".\"path\"(type => 'arrow))", rules); String expQuery1 = "SELECT\n" + "sum(CASE WHEN regexp_like(dremio_preview_data.\"col with spaces\", '.*?\\Qtest pattern\\E.*?') THEN 1 ELSE 0 END) AS matched_count_0,\n" + "sum(CASE WHEN regexp_like(dremio_preview_data.\"col with spaces\", '(?i)(?u).*?.*txt.*.*?') THEN 1 ELSE 0 END) AS matched_count_1,\n" + "COUNT(1) as total\n" + "FROM TABLE(\"jobstore\".\"path\"(type => 'arrow)) as dremio_preview_data"; assertEquals(expQuery1, outputQuery1); String outputQuery2 = cardGenerator.generateMatchCountQuery("normalCol", "TABLE(\"jobstore\".\"path\"(type => 'arrow))", rules); String expQuery2 = "SELECT\n" + "sum(CASE WHEN regexp_like(dremio_preview_data.normalCol, '.*?\\Qtest pattern\\E.*?') THEN 1 ELSE 0 END) AS matched_count_0,\n" + "sum(CASE WHEN regexp_like(dremio_preview_data.normalCol, '(?i)(?u).*?.*txt.*.*?') THEN 1 ELSE 0 END) AS matched_count_1,\n" + "COUNT(1) as total\n" + "FROM TABLE(\"jobstore\".\"path\"(type => 'arrow)) as dremio_preview_data"; assertEquals(expQuery2, outputQuery2); }
### Question: ExtractRecommender extends Recommender<ExtractRule, Selection> { @Override public List<ExtractRule> getRules(Selection selection, DataType selColType) { checkArgument(selColType == DataType.TEXT, "Extract text is supported only on TEXT type columns"); if (selection.getLength() <= 0) { throw UserException.validationError() .message("text recommendation requires non-empty text selection") .build(logger); } List<ExtractRule> rules = new ArrayList<>(); rules.addAll(recommendCharacterGroup(selection)); rules.addAll(recommendPosition(selection)); return rules; } @Override List<ExtractRule> getRules(Selection selection, DataType selColType); TransformRuleWrapper<ExtractRule> wrapRule(ExtractRule extractRule); static String describePlacement(Offset start, Offset end); static String describeExtractRulePattern(ExtractRulePattern extractRulePattern); static String describe(ExtractRule rule); }### Answer: @Test public void ruleSuggestionsSelNumberInTheBeginning() { Selection selection = new Selection("col", "883 N Shoreline Blvd., Mountain View, CA 94043", 0, 3); List<ExtractRule> rules = recommender.getRules(selection, TEXT); assertEquals(5, rules.size()); comparePattern("\\d+", 0, INDEX, rules.get(0).getPattern()); comparePattern("\\w+", 0, INDEX, rules.get(1).getPattern()); comparePos(0, true, 2, true, rules.get(2).getPosition()); comparePos(0, true, 43, false, rules.get(3).getPosition()); comparePos(45, false, 43, false, rules.get(4).getPosition()); } @Test public void ruleSuggestionsSelNumberAtTheEnd() { Selection selection = new Selection("col", "883 N Shoreline Blvd., Mountain View, CA 94043", 41, 5); List<ExtractRule> rules = recommender.getRules(selection, TEXT); assertEquals(7, rules.size()); comparePattern("\\d+", 1, INDEX, rules.get(0).getPattern()); comparePattern("\\d+", 0, INDEX_BACKWARDS, rules.get(1).getPattern()); comparePattern("\\w+", 7, INDEX, rules.get(2).getPattern()); comparePattern("\\w+", 0, INDEX_BACKWARDS, rules.get(3).getPattern()); comparePos(41, true, 45, true, rules.get(4).getPosition()); comparePos(41, true, 0, false, rules.get(5).getPosition()); comparePos(4, false, 0, false, rules.get(6).getPosition()); } @Test public void ruleSuggestionsSelStateAtTheEnd() { Selection selection = new Selection("col", "883 N Shoreline Blvd., Mountain View, CA 94043", 38, 2); List<ExtractRule> rules = recommender.getRules(selection, TEXT); assertEquals(4, rules.size()); comparePattern("\\w+", 6, INDEX, rules.get(0).getPattern()); comparePos(38, true, 39, true, rules.get(1).getPosition()); comparePos(38, true, 6, false, rules.get(2).getPosition()); comparePos(7, false, 6, false, rules.get(3).getPosition()); } @Test public void emptySelection() { boolean exThrown = false; try { recommender.getRules(new Selection("col", "883 N Shoreline Blvd.", 5, 0), TEXT); fail("not expected to reach here"); } catch (UserException e) { exThrown = true; assertEquals("text recommendation requires non-empty text selection", e.getMessage()); } assertTrue("expected a UserException", exThrown); }
### Question: ExtractRecommender extends Recommender<ExtractRule, Selection> { List<ExtractRule> recommendCharacterGroup(Selection selection) { List<ExtractRule> rules = new ArrayList<>(); String cellText = selection.getCellText(); int start = selection.getOffset(); int end = start + selection.getLength(); String selected = cellText.substring(start, end); for (CharType charType : PatternMatchUtils.CharType.values()) { boolean startIsCharType = start == 0 ? false : charType.isTypeOf(cellText.charAt(start - 1)); boolean endIsCharType = end == cellText.length() ? false : charType.isTypeOf(cellText.charAt(end)); boolean selectionIsCharType = charType.isTypeOf(selected); if (!startIsCharType && !endIsCharType && selectionIsCharType) { Matcher matcher = charType.matcher(cellText); List<Match> matches = PatternMatchUtils.findMatches(matcher, cellText, INDEX); for (int index = 0; index < matches.size(); index++) { Match match = matches.get(index); if (match.start() == start && match.end() == end) { rules.add(DatasetsUtil.pattern(charType.pattern(), index, INDEX)); if (index == matches.size() - 1) { rules.add(DatasetsUtil.pattern(charType.pattern(), 0, INDEX_BACKWARDS)); } } } } } return rules; } @Override List<ExtractRule> getRules(Selection selection, DataType selColType); TransformRuleWrapper<ExtractRule> wrapRule(ExtractRule extractRule); static String describePlacement(Offset start, Offset end); static String describeExtractRulePattern(ExtractRulePattern extractRulePattern); static String describe(ExtractRule rule); }### Answer: @Test public void testRecommendCharacterGroup() { List<ExtractRule> cards = recommender.recommendCharacterGroup(new Selection("col", "abc def,ghi", 4, 3)); assertEquals(1, cards.size()); assertEquals(pattern, cards.get(0).getType()); ExtractRulePattern pattern = cards.get(0).getPattern(); assertEquals(1, pattern.getIndex().intValue()); assertEquals(WORD.pattern(), pattern.getPattern()); assertEquals(INDEX, pattern.getIndexType()); }
### Question: PowerBIMessageBodyGenerator extends BaseBIToolMessageBodyGenerator { @VisibleForTesting static DSRFile createDSRFile(String hostname, DatasetConfig datasetConfig) { final DSRConnectionInfo connInfo = new DSRConnectionInfo(); connInfo.server = hostname; final DatasetPath dataset = new DatasetPath(datasetConfig.getFullPathList()); connInfo.schema = String.join(".", datasetConfig.getFullPathList().subList(0, datasetConfig.getFullPathList().size() - 1)); connInfo.table = dataset.getLeaf().getName(); final DataSourceReference dsr = new DataSourceReference(connInfo); final Connection conn = new Connection(); conn.dsr = dsr; final DSRFile dsrFile = new DSRFile(); dsrFile.addConnection(conn); return dsrFile; } @Inject PowerBIMessageBodyGenerator(@Context Configuration configuration, CoordinationProtos.NodeEndpoint endpoint); @Override void writeTo(DatasetConfig datasetConfig, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream); }### Answer: @Test public void verifyDSRFile() { final PowerBIMessageBodyGenerator.DSRFile dsrFile = PowerBIMessageBodyGenerator.createDSRFile(server, datasetConfig); assertEquals("0.1", dsrFile.getVersion()); final PowerBIMessageBodyGenerator.Connection connection = dsrFile.getConnections()[0]; assertEquals("DirectQuery", connection.getMode()); final PowerBIMessageBodyGenerator.DataSourceReference details = connection.getDSR(); assertEquals("dremio", details.getProtocol()); final PowerBIMessageBodyGenerator.DSRConnectionInfo address = details.getAddress(); assertEquals(server, address.getServer()); assertEquals(expectedSchema, address.getSchema()); assertEquals(expectedTable, address.getTable()); }
### Question: BaseBIToolResource { @VisibleForTesting Response.ResponseBuilder buildResponseWithHost(Response.ResponseBuilder builder, String host) { if (host == null) { return builder; } final String hostOnly; final int portIndex = host.indexOf(":"); if (portIndex == -1) { hostOnly = host; } else { hostOnly = host.substring(0, portIndex); } return builder.header(WebServer.X_DREMIO_HOSTNAME, hostOnly); } protected BaseBIToolResource(NamespaceService namespace, ProjectOptionManager optionManager, String datasetId); }### Answer: @Test public void verifyHeaders() { final Response response = resource.buildResponseWithHost(Response.ok(), inputHost).build(); if (expectedHost == null) { assertFalse(response.getHeaders().containsKey(WebServer.X_DREMIO_HOSTNAME)); return; } assertEquals(expectedHost, response.getHeaders().get(WebServer.X_DREMIO_HOSTNAME).get(0)); }
### Question: ReflectionResource { @GET @Path("/{id}") public Reflection getReflection(@PathParam("id") String id) { Optional<ReflectionGoal> goal = reflectionServiceHelper.getReflectionById(id); if (!goal.isPresent()) { throw new ReflectionNotFound(id); } String reflectionId = goal.get().getId().getId(); return new Reflection(goal.get(), reflectionServiceHelper.getStatusForReflection(reflectionId), reflectionServiceHelper.getCurrentSize(reflectionId), reflectionServiceHelper.getTotalSize(reflectionId)); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); @GET @Path("/{id}") Reflection getReflection(@PathParam("id") String id); @POST Reflection createReflection(Reflection reflection); @PUT @Path("/{id}") Reflection editReflection(@PathParam("id") String id, Reflection reflection); @DELETE @Path("/{id}") Response deleteReflection(@PathParam("id") String id); }### Answer: @Test public void testGetReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); Reflection response2 = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response.getId())).buildGet(), Reflection.class); assertEquals(response2.getId(), response.getId()); assertEquals(response2.getName(), response.getName()); assertEquals(response2.getType(), response.getType()); assertEquals(response2.getCreatedAt(), response.getCreatedAt()); assertEquals(response2.getUpdatedAt(), response.getUpdatedAt()); assertEquals(response2.getTag(), response.getTag()); assertEquals(response2.getDisplayFields(), response.getDisplayFields()); assertEquals(response2.getDimensionFields(), response.getDimensionFields()); assertEquals(response2.getDistributionFields(), response.getDistributionFields()); assertEquals(response2.getMeasureFields(), response.getMeasureFields()); assertEquals(response2.getPartitionFields(), response.getPartitionFields()); assertEquals(response2.getSortFields(), response.getSortFields()); assertEquals(response2.getPartitionDistributionStrategy(), response.getPartitionDistributionStrategy()); }
### Question: ScorePair { public ScorePair(MatchingConfig mc) { this.mc = mc; vt = new VectorTable(mc); modifiers = new ArrayList<Modifier>(); observed_vectors = new Hashtable<MatchVector, Long>(); } ScorePair(MatchingConfig mc); void addScoreModifier(Modifier sm); MatchResult scorePair(Record rec1, Record rec2); Hashtable<MatchVector, Long> getObservedVectors(); }### Answer: @Test public void scorePair_shouldIndicateAMatchOnPatientsWithMultipleIdentifiersForAnIdentifierType() throws Exception { Record rec1 = new Record(1, "foo"); Record rec2 = new Record(2, "foo"); rec1.addDemographic("(Identifier) Old OpenMRS Identifier", "111,222,333"); rec2.addDemographic("(Identifier) Old OpenMRS Identifier", "222,444,555"); MatchingConfigRow mcr = new MatchingConfigRow("(Identifier) Old OpenMRS Identifier"); mcr.setInclude(true); MatchingConfig mc = new MatchingConfig("bar", new MatchingConfigRow[]{ mcr }); ScorePair sp = new ScorePair(mc); MatchResult mr = sp.scorePair(rec1, rec2); Assert.assertTrue(mr.matchedOn("(Identifier) Old OpenMRS Identifier")); }
### Question: ScorePair { protected List<String[]> getCandidatesFromMultiFieldDemographics(String data1, String data2) { String[] a = data1.split(MatchingConstants.MULTI_FIELD_DELIMITER); String[] b = data2.split(MatchingConstants.MULTI_FIELD_DELIMITER); List<String[]> res = new ArrayList<String[]>(); for (String i : a) { for (String j : b) { res.add(new String[]{i, j}); } } return res; } ScorePair(MatchingConfig mc); void addScoreModifier(Modifier sm); MatchResult scorePair(Record rec1, Record rec2); Hashtable<MatchVector, Long> getObservedVectors(); }### Answer: @Test public void getCandidatesFromMultiFieldDemographics_shouldReturnAListOfAllPossiblePermutations() throws Exception { MatchingConfigRow mcr = new MatchingConfigRow("ack"); mcr.setInclude(true); MatchingConfig mc = new MatchingConfig("foo", new MatchingConfigRow[]{ mcr }); ScorePair sp = new ScorePair(mc); String data1 = "101" + MatchingConstants.MULTI_FIELD_DELIMITER + "202"; String data2 = "303" + MatchingConstants.MULTI_FIELD_DELIMITER + "404" + MatchingConstants.MULTI_FIELD_DELIMITER + "505"; List<String[]> expected = new ArrayList<String[]>(); expected.add(new String[]{ "101", "303"}); expected.add(new String[]{ "101", "404"}); expected.add(new String[]{ "101", "505"}); expected.add(new String[]{ "202", "303"}); expected.add(new String[]{ "202", "404"}); expected.add(new String[]{ "202", "505"}); List<String[]> actual = sp.getCandidatesFromMultiFieldDemographics(data1, data2); for (int i=0; i<6; i++) { Assert.assertEquals("permutation", expected.get(i)[0], actual.get(i)[0]); Assert.assertEquals("permutation", expected.get(i)[1], actual.get(i)[1]); } }
### Question: Employee { public void salaryIncrement(Double percentage) { Double newSalary = salary + percentage * salary / 100; setSalary(newSalary); } Employee(Integer id, String name, Double salary); Integer getId(); void setId(Integer id); String getName(); void setName(String name); Double getSalary(); void setSalary(Double salary); void salaryIncrement(Double percentage); String toString(); }### Answer: @Test public void whenIncrementSalaryForEachEmployee_thenApplyNewSalary() { Employee[] arrayOfEmps = { new Employee(1, "Jeff Bezos", 100000.0), new Employee(2, "Bill Gates", 200000.0), new Employee(3, "Mark Zuckerberg", 300000.0) }; List<Employee> empList = Arrays.asList(arrayOfEmps); empList.stream().forEach(e -> e.salaryIncrement(10.0)); assertThat(empList, contains( hasProperty("salary", equalTo(110000.0)), hasProperty("salary", equalTo(220000.0)), hasProperty("salary", equalTo(330000.0)) )); } @Test public void whenParallelStream_thenPerformOperationsInParallel() { Employee[] arrayOfEmps = { new Employee(1, "Jeff Bezos", 100000.0), new Employee(2, "Bill Gates", 200000.0), new Employee(3, "Mark Zuckerberg", 300000.0) }; List<Employee> empList = Arrays.asList(arrayOfEmps); empList.stream().parallel().forEach(e -> e.salaryIncrement(10.0)); assertThat(empList, contains( hasProperty("salary", equalTo(110000.0)), hasProperty("salary", equalTo(220000.0)), hasProperty("salary", equalTo(330000.0)) )); } @Test public void whenIncrementSalaryUsingPeek_thenApplyNewSalary() { Employee[] arrayOfEmps = { new Employee(1, "Jeff Bezos", 100000.0), new Employee(2, "Bill Gates", 200000.0), new Employee(3, "Mark Zuckerberg", 300000.0) }; List<Employee> empList = Arrays.asList(arrayOfEmps); empList.stream() .peek(e -> e.salaryIncrement(10.0)) .peek(System.out::println) .collect(Collectors.toList()); assertThat(empList, contains( hasProperty("salary", equalTo(110000.0)), hasProperty("salary", equalTo(220000.0)), hasProperty("salary", equalTo(330000.0)) )); }
### Question: WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); setLocationForStaticAssets(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer: @Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); } @Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); } Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); }