src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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; } | @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) { } } |
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; } | @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) { } } |
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; } | @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) { } } |
SQLGenerator { public static String generateSQL(VirtualDatasetState vss){ return new SQLGenerator().innerGenerateSQL(vss); } SQLGenerator(); static String generateSQL(VirtualDatasetState vss); static String getTableAlias(From from); } | @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); } |
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; } | @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())); } |
PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public boolean rename(Path src, Path dst) throws IOException { Path absoluteSrc = toAbsolutePath(src); Path absoluteDst = toAbsolutePath(dst); checkPath(absoluteSrc); checkPath(absoluteDst); if (absoluteSrc.isRoot()) { throw new IOException("Cannot rename " + absoluteSrc); } if (absoluteDst.isRoot()) { throw new IOException("Cannot rename into" + absoluteDst); } boolean isSrcRemote = isRemoteFile(absoluteSrc); boolean isDstRemote = isRemoteFile(absoluteDst); if (isSrcRemote) { RemotePath srcRemotePath = getRemotePath(absoluteSrc); final String srcAddress = srcRemotePath.address; final Path srcPath = srcRemotePath.path; if (isDstRemote) { RemotePath dstRemotePath = getRemotePath(absoluteDst); final String dstAddress = dstRemotePath.address; final Path dstPath = dstRemotePath.path; if (!Objects.equal(srcAddress, dstAddress)) { throw new IOException("Cannot rename across endpoints: from " + absoluteSrc + " to " + absoluteDst); } FileSystem delegateFS = getDelegateFileSystem(dstAddress); return delegateFS.rename(srcPath, dstPath); } boolean isDstDirectory = isDirectory(absoluteDst); if (!isDstDirectory) { throw new IOException("Rename destination " + absoluteDst + " does not exist or is not a directory"); } FileSystem delegateFS = getDelegateFileSystem(srcAddress); try { FileStatus status = delegateFS.getFileStatus(absoluteDst); if (!status.isDirectory()) { throw new IOException("A remote file for path " + absoluteDst + " already exists on endpoint " + srcAddress); } } catch(FileNotFoundException e) { delegateFS.mkdirs(absoluteDst); } return delegateFS.rename(srcPath, absoluteDst); } if (isDstRemote) { throw new IOException("Cannot rename " + absoluteSrc + " to " + absoluteDst); } boolean isSrcDirectory = isDirectory(absoluteSrc); boolean isDstDirectory = isDirectory(absoluteDst); if (!(isSrcDirectory || isDstDirectory)) { throw new IOException("Cannot rename " + absoluteSrc + " to " + absoluteDst); } return new RenameTask(absoluteSrc, absoluteDst).get(); } PseudoDistributedFileSystem(); @VisibleForTesting PseudoDistributedFileSystem(PDFSConfig config); static synchronized void configure(PDFSConfig config); static String getRemoteFileName(String basename); static RemotePath getRemotePath(Path path); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override String getScheme(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize,
short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path canonicalizePath(Path p); static final String NAME; } | @Test public void testRenameFromRoot() throws IOException { Path root = new Path("/"); Path dst = new Path("/foo/baz"); try { fs.rename(root, dst); fail("Expected rename to throw an exception"); } catch(IOException e) { } }
@Test public void testRenameToRoot() throws IOException { Path root = new Path("/"); Path src = new Path("/foo/bar"); try { fs.rename(src, root); fail("Expected rename to throw an exception"); } catch(IOException e) { } }
@Test public void testRenameFileSameEndpoint() throws IOException { doReturn(true).when(mockLocalFS).rename( new Path("/foo/bar/file1"), new Path("/foo/bar/file3")); Path src = new Path("/foo/bar/10.0.0.1@file1"); Path dst = new Path("/foo/bar/10.0.0.1@file3"); assertTrue(fs.rename(src, dst)); }
@Test public void testRenameRemoteFileDifferentEndpoints() throws IOException { Path src = new Path("/foo/bar/10.0.0.1@file1"); Path dst = new Path("/foo/bar/10.0.0.2@file3"); try { fs.rename(src, dst); fail("Expected rename across endpoints to fail"); } catch(IOException e) { } }
@Test public void testRenameDirectories() throws IOException { doReturn(true).when(mockLocalFS).rename( new Path("/foo/bar"), new Path("/foo/baz")); doReturn(true).when(mockRemoteFS).rename( new Path("/foo/bar"), new Path("/foo/baz")); Path src = new Path("/foo/bar"); Path dst = new Path("/foo/baz"); assertTrue(fs.rename(src, dst)); } |
PseudoDistributedFileSystem extends FileSystem implements PathCanonicalizer { @Override public BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len) throws IOException { Preconditions.checkArgument(start >= 0, "start should be positive"); Preconditions.checkArgument(len >= 0, "len should be positive"); if (start >= file.getLen()) { return new BlockLocation[] {}; } try { final RemotePath remotePath = getRemotePath(file.getPath()); final List<NodeEndpoint> endpoints = getEndpoints(remotePath.address); if (endpoints.isEmpty()) { if (localAccessAllowed && localIdentity.getAddress().equals(remotePath.address)) { return new BlockLocation[]{ new BlockLocation( new String[]{format("%s:%d", localIdentity.getAddress(), localIdentity.getFabricPort())}, new String[]{localIdentity.getAddress()}, 0, file.getLen()) }; } return new BlockLocation[]{}; } String address = endpoints.get(0).getAddress(); String[] hosts = new String[] { address }; String[] names = new String[endpoints.size()]; int i = 0; for (NodeEndpoint endpoint : endpoints) { names[i++] = format("%s:%d", address, endpoint.getFabricPort()); } return new BlockLocation[] { new BlockLocation(names, hosts, 0, file.getLen()) }; } catch (IllegalArgumentException e) { throw (FileNotFoundException) (new FileNotFoundException("No file " + file.getPath()).initCause(e)); } } PseudoDistributedFileSystem(); @VisibleForTesting PseudoDistributedFileSystem(PDFSConfig config); static synchronized void configure(PDFSConfig config); static String getRemoteFileName(String basename); static RemotePath getRemotePath(Path path); @Override void initialize(URI name, Configuration conf); @Override URI getUri(); @Override String getScheme(); @Override FSDataInputStream open(Path f, int bufferSize); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize,
short replication, long blockSize, Progressable progress); @Override FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override boolean rename(Path src, Path dst); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<FileStatus> listStatusIterator(Path f); @Override void setWorkingDirectory(Path newDir); @Override Path getWorkingDirectory(); @Override boolean mkdirs(Path f, FsPermission permission); @Override FileStatus getFileStatus(Path f); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path canonicalizePath(Path p); static final String NAME; } | @Test public void testGetFileBlockLocations() throws IOException { Path path = new Path("/foo/10.0.0.1@bar"); BlockLocation[] locations = fs.getFileBlockLocations(new FileStatus(1027, false, 1, 4096, 123456, path), 7, 1024); assertEquals(1, locations.length); BlockLocation location = locations[0]; assertArrayEquals(new String[] { "10.0.0.1:1234", "10.0.0.1:9012" }, location.getNames()); assertArrayEquals(new String[] { "10.0.0.1" }, location.getHosts()); assertEquals(0, location.getOffset()); assertEquals(1027, location.getLength()); }
@Test public void testGetFileBlockLocationsStartGreaterThanLen() throws IOException { Path path = new Path("/foo/10.0.0.1@bar"); assertArrayEquals(new BlockLocation[]{}, fs.getFileBlockLocations(new FileStatus(1024, false, 1,4096, 123456, path), 4096, 8192)); }
@Test public void testGetFileBlockLocationsNegativeStart() throws IOException { Path path = new Path("/foo/10.0.0.1@bar"); try { fs.getFileBlockLocations(new FileStatus(1024, false, 1,4096, 123456, path), -22, 8192); fail("Expected getFileBlockLocation to throw an exception"); } catch (IllegalArgumentException e) { } }
@Test public void testGetFileBlockLocationsNegativeLen() throws IOException { Path path = new Path("/foo/10.0.0.1@bar"); try { fs.getFileBlockLocations(new FileStatus(1024, false, 1,4096, 123456, path), 18, -2); fail("Expected getFileBlockLocation to throw an exception"); } catch (IllegalArgumentException e) { } } |
HistogramGenerator { @VisibleForTesting protected static LocalDateTime roundTime(LocalDateTime tmpValue, TruncEvalEnum trucateTo, boolean isRoundDown) { switch (trucateTo) { case SECOND: if (isRoundDown) { return tmpValue.secondOfMinute().roundFloorCopy(); } else { return tmpValue.secondOfMinute().roundCeilingCopy(); } case MINUTE: if (isRoundDown) { return tmpValue.minuteOfHour().roundFloorCopy(); } else { return tmpValue.minuteOfHour().roundCeilingCopy(); } case HOUR: if (isRoundDown) { return tmpValue.hourOfDay().roundFloorCopy(); } else { return tmpValue.hourOfDay().roundCeilingCopy(); } case DAY: if (isRoundDown) { return tmpValue.dayOfMonth().roundFloorCopy(); } else { return tmpValue.dayOfMonth().roundCeilingCopy(); } case WEEK: if (isRoundDown) { return tmpValue.weekOfWeekyear().roundFloorCopy(); } else { return tmpValue.weekOfWeekyear().roundCeilingCopy(); } case MONTH: if (isRoundDown) { return tmpValue.monthOfYear().roundFloorCopy(); } else { return tmpValue.monthOfYear().roundCeilingCopy(); } case QUARTER: if (isRoundDown) { LocalDateTime roundeddown = tmpValue.monthOfYear().roundFloorCopy(); int month = roundeddown.getMonthOfYear(); int quarter = (month - 1) % 3; return roundeddown.minusMonths(quarter); } else { LocalDateTime roundedUp = tmpValue.monthOfYear().roundCeilingCopy(); int month = roundedUp.getMonthOfYear(); int quarter = 3 - (month - 1) % 3; return roundedUp.plusMonths(quarter); } case YEAR: if (isRoundDown) { return tmpValue.year().roundFloorCopy(); } else { return tmpValue.year().roundCeilingCopy(); } case DECADE: if (isRoundDown) { LocalDateTime roundeddown = tmpValue.year().roundFloorCopy(); int year = roundeddown.getYear(); int roundedDownYear = year % 10; return roundeddown.minusYears(roundedDownYear); } else { LocalDateTime roundedUp = tmpValue.year().roundCeilingCopy(); int year = roundedUp.getYear(); int roundedUpYear = 10 - year % 10; return roundedUp.plusYears(roundedUpYear); } case CENTURY: if (isRoundDown) { LocalDateTime roundeddown = tmpValue.year().roundFloorCopy(); int year = roundeddown.getYear(); int roundedDownYear = year % 100; return roundeddown.minusYears(roundedDownYear); } else { LocalDateTime roundedUp = tmpValue.year().roundCeilingCopy(); int year = roundedUp.getYear(); int roundedUpYear = 100 - year % 100; return roundedUp.plusYears(roundedUpYear); } case MILLENNIUM: if (isRoundDown) { LocalDateTime roundeddown = tmpValue.year().roundFloorCopy(); int year = roundeddown.getYear(); int roundedDownYear = year % 1000; return roundeddown.minusYears(roundedDownYear); } else { LocalDateTime roundedUp = tmpValue.year().roundCeilingCopy(); int year = roundedUp.getYear(); int roundedUpYear = 1000 - year % 1000; return roundedUp.plusYears(roundedUpYear); } default: return tmpValue; } } 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); } | @Test public void testTimeIntervals() throws Exception { HistogramGenerator hg = new HistogramGenerator(null); String myTimeStr = "2016-02-29 13:59:01"; DateTimeFormatter dtf = DateFunctionsUtils.getISOFormatterForFormatString("YYYY-MM-DD HH24:MI:SS"); LocalDateTime myTime = dtf.parseLocalDateTime(myTimeStr); System.out.println("Exact time: " + myTime + ", Month: " + myTime.getMonthOfYear()); for (HistogramGenerator.TruncEvalEnum value : HistogramGenerator.TruncEvalEnum.getSortedAscValues()) { LocalDateTime roundedDown = hg.roundTime(myTime, value, true); LocalDateTime roundedUp = hg.roundTime(myTime, value, false); switch(value) { case SECOND: assertEquals(myTime, roundedDown); assertEquals(myTime, roundedUp); break; case MINUTE: assertEquals(dtf.parseLocalDateTime("2016-02-29 13:59:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2016-02-29 14:00:00"), roundedUp); break; case HOUR: assertEquals(dtf.parseLocalDateTime("2016-02-29 13:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2016-02-29 14:00:00"), roundedUp); break; case DAY: assertEquals(dtf.parseLocalDateTime("2016-02-29 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2016-03-01 00:00:00"), roundedUp); break; case WEEK: assertEquals(dtf.parseLocalDateTime("2016-02-29 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2016-03-07 00:00:00"), roundedUp); break; case MONTH: assertEquals(dtf.parseLocalDateTime("2016-02-01 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2016-03-01 00:00:00"), roundedUp); break; case QUARTER: assertEquals(dtf.parseLocalDateTime("2016-01-01 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2016-04-01 00:00:00"), roundedUp); break; case YEAR: assertEquals(dtf.parseLocalDateTime("2016-01-01 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2017-01-01 00:00:00"), roundedUp); break; case DECADE: assertEquals(dtf.parseLocalDateTime("2010-01-01 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2020-01-01 00:00:00"), roundedUp); break; case CENTURY: assertEquals(dtf.parseLocalDateTime("2000-01-01 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("2100-01-01 00:00:00"), roundedUp); break; case MILLENNIUM: assertEquals(dtf.parseLocalDateTime("2000-01-01 00:00:00"), roundedDown); assertEquals(dtf.parseLocalDateTime("3000-01-01 00:00:00"), roundedUp); break; default: fail(); } } } |
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; } | @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); } |
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(); } | @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); } |
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); } | @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()); } |
NativeLibPluginManager extends DefaultPluginManager { @Override protected Path createPluginsRoot() { final Path pluginsPath = this.isDevelopment() ? Paths.get(PLUGINS_PATH_DEV_MODE) : DremioConfig.getPluginsRootPath().resolve("connectors"); return pluginsPath; } } | @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); } |
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); } | @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); } |
NativeLibPluginClassLoader extends PluginClassLoader { @VisibleForTesting static void validateZipDirectory(Path tempDirectory, final ZipEntry entry) throws IOException { final Path destinationPath = tempDirectory.resolve(entry.getName()).normalize(); if (!destinationPath.startsWith(tempDirectory)) { throw new IOException(String.format("JAR entry %s is outside of the target directory %s. ", entry.getName(), tempDirectory)); } } NativeLibPluginClassLoader(Path pluginPath, PluginManager pluginManager,
PluginDescriptor pluginDescriptor, ClassLoader parent); @Override void close(); } | @Test public void validateZipDirectoryValidNatural() throws IOException { ZipEntry entry = new ZipEntry("somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockTempDir, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirWithTrailingSlash, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirInPrivateMappedDir, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirInPrivateMappedDirWithTrailingSlash, entry); }
@Test public void validateZipDirectoryValidSelfref() throws IOException { ZipEntry entry = new ZipEntry("./somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockTempDir, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirWithTrailingSlash, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirInPrivateMappedDir, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirInPrivateMappedDirWithTrailingSlash, entry); }
@Test public void validateZipDirectoryValidUpdirThenCorrectDir() throws IOException { ZipEntry entry = new ZipEntry("../tmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockTempDir, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirWithTrailingSlash, entry); }
@Test public void validateZipDirectoryValidUpdirMoreTheCorrectDir() throws IOException { ZipEntry entry = new ZipEntry("../../../../../tmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockTempDir, entry); NativeLibPluginClassLoader.validateZipDirectory(mockTempDirWithTrailingSlash, entry); }
@Test public void validateZipDirectoryValidNestedUpdirThenCorrectDir() throws IOException { ZipEntry entry = new ZipEntry("../nestedTmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockNestedTempDir, entry); }
@Test public void validateZipDirectoryValidUpdirMoreThanNestedCorrectDir() throws IOException { ZipEntry entry = new ZipEntry("../../../../baseTmpDir/nestedTmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockNestedTempDir, entry); }
@Test public void validateZipDirectoryZipSlipTestUpdirMoreThanNestedCorrectDir() throws IOException { ZipEntry entry = new ZipEntry("../../../../../baseTmpDir/nestedTmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockNestedTempDir, entry); }
@Test public void validateZipDirectoryZipSlipTestUpdirMoreThanNestedCorrectDir2() throws IOException { ZipEntry entry = new ZipEntry("../../../../../../../../../../../baseTmpDir/nestedTmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockNestedTempDir, entry); }
@Test(expected = IOException.class) public void validateZipDirectoryZipSlipTestUpdirMoreThanNestedCorrectDirFinalDirDifferent() throws IOException { ZipEntry entry = new ZipEntry("../../../../../baseTmpDir/nestedTmpDir2/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockNestedTempDir, entry); }
@Test(expected = IOException.class) public void validateZipDirectoryZipSlipTestNested() throws IOException { ZipEntry entry = new ZipEntry("../tmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockNestedTempDir, entry); }
@Test(expected = IOException.class) public void validateZipDirectoryZipSlipTestNestedUpdirMore() throws IOException { ZipEntry entry = new ZipEntry("../../../../../tmpDir/somedir/somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockNestedTempDir, entry); }
@Test(expected = IOException.class) public void validateZipDirectoryZipSlipTest() throws IOException { ZipEntry entry = new ZipEntry("../somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockTempDir, entry); }
@Test(expected = IOException.class) public void validateZipDirectoryZipSlipTestUpMoreDirs() throws IOException { ZipEntry entry = new ZipEntry("../../../../../somefile"); NativeLibPluginClassLoader.validateZipDirectory(mockTempDir, entry); }
@Test public void validateZipDirectoryZipSlipTestUpDirsMispelledCorrectDir() throws IOException { ZipEntry entry = new ZipEntry("../../../.. NativeLibPluginClassLoader.validateZipDirectory(mockTempDir, entry); } |
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); } | @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()); } |
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); } | @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()); } |
YarnService implements ProvisioningServiceDelegate { @Override public ClusterEnriched startCluster(Cluster cluster) throws YarnProvisioningHandlingException { Preconditions.checkArgument(cluster.getState() != ClusterState.RUNNING); return startClusterAsync(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); } | @Test public void testStartCluster() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); Cluster cluster = new Cluster(); cluster.setState(ClusterState.CREATED); cluster.setStateChangeTime(System.currentTimeMillis()); cluster.setId(new ClusterId(UUID.randomUUID().toString())); ClusterConfig clusterConfig = new ClusterConfig(); clusterConfig.setClusterSpec(new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(4096).setMemoryMBOnHeap(4096).setVirtualCoreCount(2)); List<Property> propertyList = new ArrayList<>(); propertyList.add(new Property(FS_DEFAULT_NAME_KEY, "hdfs: propertyList.add(new Property(RM_HOSTNAME, "resource-manager")); propertyList.add(new Property(DremioConfig.DIST_WRITE_PATH_STRING, "pdfs: clusterConfig.setSubPropertyList(propertyList); cluster.setClusterConfig(clusterConfig); YarnConfiguration yarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(cluster, yarnConfig); assertNotNull(yarnConfig.get(FS_DEFAULT_NAME_KEY)); assertNotNull(yarnConfig.get(RM_HOSTNAME)); assertNotNull(yarnConfig.get(DremioConfig.DIST_WRITE_PATH_STRING)); assertEquals("hdfs: assertEquals("resource-manager", yarnConfig.get(RM_HOSTNAME)); assertEquals("pdfs: TwillController twillController = Mockito.mock(TwillController.class); RunId runId = RunIds.generate(); ResourceReport resourceReport = Mockito.mock(ResourceReport.class); when(controller.startCluster(any(YarnConfiguration.class), any(List.class))) .thenReturn(twillController); when(twillController.getRunId()).thenReturn(runId); when(twillController.getResourceReport()).thenReturn(resourceReport); ClusterEnriched clusterEnriched = yarnService.startCluster(cluster); assertNull(null,clusterEnriched.getRunTimeInfo()); assertEquals(ClusterState.STARTING, cluster.getState()); assertNotNull(cluster.getRunId()); assertEquals(runId.getId(), cluster.getRunId().getId()); }
@Test public void testMemorySplit() throws Exception { assumeNonMaprProfile(); try ( final LegacyKVStoreProvider kvstore = LegacyKVStoreProviderAdapter.inMemory(DremioTest.CLASSPATH_SCAN_RESULT)) { SingletonRegistry registry = new SingletonRegistry(); registry.bind(LegacyKVStoreProvider.class, kvstore); registry.start(); ProvisioningService service = Mockito.spy(new ProvisioningServiceImpl( DremioConfig.create(), registry.provider(LegacyKVStoreProvider.class), Mockito.mock(NodeProvider.class), DremioTest.CLASSPATH_SCAN_RESULT, DirectProvider.wrap(null), DirectProvider.wrap(null))); service.start(); ProvisioningResource resource = new ProvisioningResource(service); List<Property> props = new ArrayList<>(); props.add(new Property(ProvisioningService.YARN_HEAP_SIZE_MB_PROPERTY, "2048")); props.add(new Property(FS_DEFAULT_NAME_KEY, "hdfs: props.add(new Property("yarn.resourcemanager.hostname", "resource-manager")); ClusterCreateRequest createRequest = ClusterCreateRequest.builder() .setClusterType(ClusterType.YARN) .setDynamicConfig(DynamicConfig.builder().setContainerCount(2).build()) .setYarnProps(YarnPropsApi.builder() .setVirtualCoreCount(2) .setMemoryMB(8192) .setSubPropertyList(props) .build()) .build(); doReturn(new ClusterEnriched()).when(service).startCluster(any(ClusterId.class)); try { resource.createCluster(createRequest); } catch (NullPointerException e) { } LegacyKVStore<ClusterId, Cluster> store = registry.provider(LegacyKVStoreProvider.class).get().getStore(ProvisioningServiceImpl.ProvisioningStoreCreator.class); Iterable<Map.Entry<ClusterId, Cluster>> entries = store.find(); assertTrue(entries.iterator().hasNext()); int count = 0; for (Map.Entry<ClusterId, Cluster> entry : entries) { Cluster clusterEntry = entry.getValue(); int offHeap = clusterEntry.getClusterConfig().getClusterSpec().getMemoryMBOffHeap(); assertEquals(8192-2048, offHeap); int onHeap = clusterEntry.getClusterConfig().getClusterSpec().getMemoryMBOnHeap(); assertEquals(2048, onHeap); count++; } assertEquals(1, count); } }
@Test public void testUpdater() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); final TestListener listener = new TestListener(); YarnService yarnService = new YarnService(listener, controller, Mockito.mock(NodeProvider.class)); final Cluster cluster = createCluster(); final TwillController twillController = Mockito.mock(TwillController.class); RunId runId = RunIds.generate(); ResourceReport resourceReport = Mockito.mock(ResourceReport.class); when(controller.startCluster(any(YarnConfiguration.class), any(List.class))) .thenReturn(twillController); when(twillController.getRunId()).thenReturn(runId); when(twillController.getResourceReport()).thenReturn(resourceReport); final Future<? extends ServiceController> futureController1 = Executors.newSingleThreadExecutor() .submit(new Runnable() { @Override public void run() { } }, twillController ); doAnswer(new Answer<Future<? extends ServiceController>>() { @Override public Future<? extends ServiceController> answer(InvocationOnMock invocationOnMock) throws Throwable { return futureController1; } }).when(twillController).terminate(); final YarnService.OnRunningRunnable onRunning = yarnService.new OnRunningRunnable(cluster); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { try { Thread.sleep(100); onRunning.run(); System.out.println("run"); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }).when(twillController).onRunning(any(Runnable.class), any(Executor.class)); final YarnService.OnTerminatingRunnable onTerminating = yarnService.new OnTerminatingRunnable(cluster, twillController); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { try { Thread.sleep(1000); onTerminating.run(); System.out.println("terminate"); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }).when(twillController).onTerminated(any(Runnable.class), any(Executor.class)); cluster.setState(ClusterState.CREATED); cluster.setStateChangeTime(System.currentTimeMillis()); ClusterEnriched clusterEnriched = yarnService.startCluster(cluster); assertEquals(ClusterState.STOPPED, clusterEnriched.getCluster().getState()); assertNull(cluster.getRunId()); assertTrue(yarnService.terminatingThreads.isEmpty()); }
@Test public void testFailedUpdater() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); final TestListener listener = new TestListener(); YarnService yarnService = new YarnService(listener, controller, Mockito.mock(NodeProvider.class)); final Cluster cluster = createCluster(); cluster.setDesiredState(ClusterState.RUNNING); final TwillController twillController = Mockito.mock(TwillController.class); RunId runId = RunIds.generate(); ResourceReport resourceReport = Mockito.mock(ResourceReport.class); when(controller.startCluster(any(YarnConfiguration.class), any(List.class))) .thenReturn(twillController); when(twillController.getRunId()).thenReturn(runId); when(twillController.getResourceReport()).thenReturn(resourceReport); final Future<? extends ServiceController> futureController1 = Executors.newSingleThreadExecutor() .submit(new Runnable() { @Override public void run() { } }, twillController ); doAnswer(new Answer<Future<? extends ServiceController>>() { @Override public Future<? extends ServiceController> answer(InvocationOnMock invocationOnMock) throws Throwable { return futureController1; } }).when(twillController).terminate(); final YarnService.OnRunningRunnable onRunning = yarnService.new OnRunningRunnable(cluster); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { try { Thread.sleep(100); onRunning.run(); System.out.println("run"); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }).when(twillController).onRunning(any(Runnable.class), any(Executor.class)); final YarnService.OnTerminatingRunnable onTerminatingNoOP = yarnService.new OnTerminatingRunnable(cluster, twillController); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { try { Thread.sleep(1000); cluster.setState(ClusterState.FAILED); cluster.setStateChangeTime(System.currentTimeMillis()); cluster.setError("My error"); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }).when(twillController).onTerminated(any(Runnable.class), any(Executor.class)); ClusterEnriched clusterEnriched = yarnService.startCluster(cluster); assertEquals(ClusterState.FAILED, clusterEnriched.getCluster().getState()); assertEquals("My error", clusterEnriched.getCluster().getError()); assertEquals(ClusterState.RUNNING, clusterEnriched.getCluster().getDesiredState()); } |
YarnService implements ProvisioningServiceDelegate { @VisibleForTesting protected String updateYarnConfiguration(Cluster cluster, YarnConfiguration yarnConfiguration) { String rmAddress = null; setYarnDefaults(cluster, yarnConfiguration); List<Property> keyValues = cluster.getClusterConfig().getSubPropertyList(); if ( keyValues != null && !keyValues.isEmpty()) { for (Property property : keyValues) { yarnConfiguration.set(property.getKey(), property.getValue()); if (RM_HOSTNAME.equalsIgnoreCase(property.getKey())) { rmAddress = property.getValue(); } } } String queue = cluster.getClusterConfig().getClusterSpec().getQueue(); if (queue != null && !queue.isEmpty()) { yarnConfiguration.set(DacDaemonYarnApplication.YARN_QUEUE_NAME, queue); } Integer memoryOnHeap = cluster.getClusterConfig().getClusterSpec().getMemoryMBOnHeap(); Integer memoryOffHeap = cluster.getClusterConfig().getClusterSpec().getMemoryMBOffHeap(); Preconditions.checkNotNull(memoryOnHeap, "Heap Memory is not specified"); Preconditions.checkNotNull(memoryOffHeap, "Direct Memory is not specified"); final int totalMemory = memoryOnHeap.intValue() + memoryOffHeap.intValue(); final double heapToDirectMemRatio = (double) (memoryOnHeap.intValue()) / totalMemory; yarnConfiguration.setDouble(HEAP_RESERVED_MIN_RATIO, Math.min(heapToDirectMemRatio, 0.1D)); yarnConfiguration.setInt(DacDaemonYarnApplication.YARN_MEMORY_ON_HEAP, memoryOnHeap.intValue()); yarnConfiguration.setInt(DacDaemonYarnApplication.YARN_MEMORY_OFF_HEAP, memoryOffHeap.intValue()); yarnConfiguration.setInt(JAVA_RESERVED_MEMORY_MB, memoryOffHeap.intValue()); Integer cpu = cluster.getClusterConfig().getClusterSpec().getVirtualCoreCount(); if (cpu != null) { yarnConfiguration.setInt(DacDaemonYarnApplication.YARN_CPU, cpu.intValue()); } Integer containerCount = cluster.getClusterConfig().getClusterSpec().getContainerCount(); if (containerCount != null) { yarnConfiguration.setInt(DacDaemonYarnApplication.YARN_CONTAINER_COUNT, containerCount.intValue()); } String clusterName = cluster.getClusterConfig().getName(); if (clusterName != null) { yarnConfiguration.set(DacDaemonYarnApplication.YARN_APP_NAME, clusterName); } yarnConfiguration.set(YARN_CLUSTER_ID, cluster.getId().getId()); return rmAddress; } 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); } | @Test public void testDistroDefaults() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); Cluster cluster = new Cluster(); cluster.setState(ClusterState.CREATED); cluster.setStateChangeTime(System.currentTimeMillis()); cluster.setId(new ClusterId(UUID.randomUUID().toString())); ClusterConfig clusterConfig = new ClusterConfig(); clusterConfig.setClusterSpec(new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(4096).setMemoryMBOnHeap(4096).setVirtualCoreCount(2)); clusterConfig.setIsSecure(false); clusterConfig.setDistroType(DistroType.MAPR); List<Property> propertyList = new ArrayList<>(); propertyList.add(new Property(FS_DEFAULT_NAME_KEY, "hdfs: propertyList.add(new Property(RM_HOSTNAME, "resource-manager")); propertyList.add(new Property(DremioConfig.DIST_WRITE_PATH_STRING, "pdfs: clusterConfig.setSubPropertyList(propertyList); cluster.setClusterConfig(clusterConfig); YarnConfiguration yarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(cluster, yarnConfig); assertNotNull(yarnConfig.get(FS_DEFAULT_NAME_KEY)); assertNotNull(yarnConfig.get(RM_HOSTNAME)); assertNotNull(yarnConfig.get(DremioConfig.DIST_WRITE_PATH_STRING)); assertEquals("hdfs: assertEquals("resource-manager", yarnConfig.get(RM_HOSTNAME)); assertEquals("pdfs: assertEquals("/opt/mapr/conf/mapr.login.conf", yarnConfig.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertEquals("false", yarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertEquals("Client_simple", yarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertEquals("com.mapr.security.simplesasl.SimpleSaslProvider", yarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"maprfs: .SPILL_PATH)); Cluster myCluster = createCluster(); myCluster.getClusterConfig().setDistroType(DistroType.MAPR).setIsSecure(true); YarnConfiguration myYarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(myCluster, myYarnConfig); assertEquals("/opt/mapr/conf/mapr.login.conf", myYarnConfig.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertEquals("false", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertEquals("Client", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertEquals("com.mapr.security.maprsasl.MaprSaslProvider", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"maprfs: .SPILL_PATH)); }
@Test public void testDistroMapRDefaults() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); properties.clear(MAPR_IMPALA_RA_THROTTLE); properties.clear(MAPR_MAX_RA_STREAMS); Cluster myCluster = createCluster(); myCluster.getClusterConfig().setDistroType(DistroType.MAPR).setIsSecure(true); YarnConfiguration myYarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(myCluster, myYarnConfig); assertEquals("/opt/mapr/conf/mapr.login.conf", myYarnConfig.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertEquals("false", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertEquals("Client", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertEquals("com.mapr.security.maprsasl.MaprSaslProvider", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"maprfs: .SPILL_PATH)); assertEquals("0", myYarnConfig.get(NETTY_MAX_DIRECT_MEMORY)); assertNull(myYarnConfig.get(MAPR_IMPALA_RA_THROTTLE)); assertNull(myYarnConfig.get(MAPR_MAX_RA_STREAMS)); Cluster myClusterOff = createCluster(); myClusterOff.getClusterConfig().setDistroType(DistroType.MAPR).setIsSecure(false); YarnConfiguration myYarnConfigOff = new YarnConfiguration(); yarnService.updateYarnConfiguration(myClusterOff, myYarnConfigOff); assertEquals("/opt/mapr/conf/mapr.login.conf", myYarnConfigOff.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertEquals("false", myYarnConfigOff.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertEquals("Client_simple", myYarnConfigOff.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertEquals("com.mapr.security.simplesasl.SimpleSaslProvider", myYarnConfigOff.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"maprfs: .SPILL_PATH)); assertEquals("0", myYarnConfigOff.get(NETTY_MAX_DIRECT_MEMORY)); assertNull(myYarnConfigOff.get(MAPR_IMPALA_RA_THROTTLE)); assertNull(myYarnConfigOff.get(MAPR_MAX_RA_STREAMS)); }
@Test public void testDistroMapRDefaultsWithMaprRAStreams() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); properties.set("MAPR_IMPALA_RA_THROTTLE", ""); properties.set("MAPR_MAX_RA_STREAMS", "123"); Cluster myCluster = createCluster(); myCluster.getClusterConfig().setDistroType(DistroType.MAPR).setIsSecure(true); YarnConfiguration myYarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(myCluster, myYarnConfig); assertEquals("/opt/mapr/conf/mapr.login.conf", myYarnConfig.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertEquals("false", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertEquals("Client", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertEquals("com.mapr.security.maprsasl.MaprSaslProvider", myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"maprfs: .SPILL_PATH)); assertEquals("0", myYarnConfig.get(NETTY_MAX_DIRECT_MEMORY)); assertEquals("", myYarnConfig.get(MAPR_IMPALA_RA_THROTTLE)); assertEquals("123", myYarnConfig.get(MAPR_MAX_RA_STREAMS)); Cluster myClusterOff = createCluster(); myClusterOff.getClusterConfig().setDistroType(DistroType.MAPR).setIsSecure(false); YarnConfiguration myYarnConfigOff = new YarnConfiguration(); yarnService.updateYarnConfiguration(myClusterOff, myYarnConfigOff); assertEquals("/opt/mapr/conf/mapr.login.conf", myYarnConfigOff.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertEquals("false", myYarnConfigOff.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertEquals("Client_simple", myYarnConfigOff.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertEquals("com.mapr.security.simplesasl.SimpleSaslProvider", myYarnConfigOff.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"maprfs: .SPILL_PATH)); assertEquals("0", myYarnConfigOff.get(NETTY_MAX_DIRECT_MEMORY)); assertEquals("", myYarnConfigOff.get(MAPR_IMPALA_RA_THROTTLE)); assertEquals("123", myYarnConfigOff.get(MAPR_MAX_RA_STREAMS)); }
@Test public void testDistroHDPDefaults() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); Cluster myCluster = createCluster(); myCluster.getClusterConfig().setDistroType(DistroType.HDP).setIsSecure(true); YarnConfiguration myYarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(myCluster, myYarnConfig); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"file: assertEquals("0", myYarnConfig.get(NETTY_MAX_DIRECT_MEMORY)); Cluster myClusterOff = createCluster(); myClusterOff.getClusterConfig().setDistroType(DistroType.MAPR).setIsSecure(false); YarnConfiguration myYarnConfigOff = new YarnConfiguration(); yarnService.updateYarnConfiguration(myClusterOff, myYarnConfigOff); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("[\"file: assertEquals("0", myYarnConfigOff.get(NETTY_MAX_DIRECT_MEMORY)); }
@Test public void testDistroDefaultsOverwrite() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); Cluster myCluster = createCluster(); List<Property> props = myCluster.getClusterConfig().getSubPropertyList(); props.add(new Property(YarnDefaultsConfigurator.SPILL_PATH, "/abc/bcd")); props.add(new Property(YarnDefaultsConfigurator.JAVA_LOGIN, "/abc/bcd/login.conf")); myCluster.getClusterConfig().setDistroType(DistroType.HDP).setIsSecure(true); YarnConfiguration myYarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(myCluster, myYarnConfig); assertEquals("/abc/bcd/login.conf", myYarnConfig.get(YarnDefaultsConfigurator.JAVA_LOGIN)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_CLIENT_CONFIG)); assertNull(myYarnConfig.get(YarnDefaultsConfigurator.ZK_SASL_PROVIDER)); assertEquals("/abc/bcd", myYarnConfig.get(YarnDefaultsConfigurator.SPILL_PATH)); }
@Test public void testMemoryOnOffHeapRatio() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); Cluster cluster = new Cluster(); cluster.setState(ClusterState.CREATED); cluster.setStateChangeTime(System.currentTimeMillis()); cluster.setId(new ClusterId(UUID.randomUUID().toString())); ClusterConfig clusterConfig = new ClusterConfig(); List<Property> propertyList = new ArrayList<>(); propertyList.add(new Property(FS_DEFAULT_NAME_KEY, "hdfs: propertyList.add(new Property(RM_HOSTNAME, "resource-manager")); propertyList.add(new Property(DremioConfig.DIST_WRITE_PATH_STRING, "pdfs: RunId runId = RunIds.generate(); clusterConfig.setSubPropertyList(propertyList); cluster.setClusterConfig(clusterConfig); cluster.setRunId(new com.dremio.provision.RunId(runId.toString())); YarnConfiguration yarnConfig = new YarnConfiguration(); List<ClusterSpec> specs = Lists.asList(new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(96000).setMemoryMBOnHeap(4096).setVirtualCoreCount(2), new ClusterSpec[] {new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(96023).setMemoryMBOnHeap(1234).setVirtualCoreCount(2), new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(8192).setMemoryMBOnHeap(4096).setVirtualCoreCount(2), new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(72000).setMemoryMBOnHeap(8192).setVirtualCoreCount(2)}); for (ClusterSpec spec : specs) { clusterConfig.setClusterSpec(spec); int onHeapMemory = spec.getMemoryMBOnHeap(); int offHeapMemory = spec.getMemoryMBOffHeap(); yarnService.updateYarnConfiguration(cluster, yarnConfig); double ratio = ((double) onHeapMemory) / (offHeapMemory + onHeapMemory); if (ratio < 0.1) { assertEquals(ratio, yarnConfig.getDouble(HEAP_RESERVED_MIN_RATIO, 0), 10e-6); } else { assertEquals(0.1, yarnConfig.getDouble(HEAP_RESERVED_MIN_RATIO, 0), 10e-9); } assertEquals(onHeapMemory, Resources.computeMaxHeapSize(offHeapMemory + onHeapMemory, offHeapMemory, yarnConfig.getDouble(HEAP_RESERVED_MIN_RATIO, 0))); assertEquals(onHeapMemory, yarnConfig.getInt(DacDaemonYarnApplication.YARN_MEMORY_ON_HEAP, 0)); assertEquals(offHeapMemory, yarnConfig.getInt(DacDaemonYarnApplication.YARN_MEMORY_OFF_HEAP, 0)); assertEquals(offHeapMemory, yarnConfig.getInt(JAVA_RESERVED_MEMORY_MB, 0)); } }
@Test public void testTimelineServiceIsDisabledByDefault(){ YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); Cluster cluster = new Cluster(); cluster.setState(ClusterState.CREATED); cluster.setStateChangeTime(System.currentTimeMillis()); cluster.setId(new ClusterId(UUID.randomUUID().toString())); ClusterConfig clusterConfig = new ClusterConfig(); clusterConfig.setClusterSpec(new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(4096).setMemoryMBOnHeap(4096).setVirtualCoreCount(2)); List<Property> propertyList = new ArrayList<>(); clusterConfig.setSubPropertyList(propertyList); RunId runId = RunIds.generate(); cluster.setClusterConfig(clusterConfig); cluster.setRunId(new com.dremio.provision.RunId(runId.toString())); YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true); yarnService.updateYarnConfiguration(cluster, yarnConfig); assertFalse(yarnConfig.getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true)); yarnConfig.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, false); cluster.getClusterConfig().getSubPropertyList().add(new Property(YarnConfiguration.TIMELINE_SERVICE_ENABLED, "true")); yarnService.updateYarnConfiguration(cluster, yarnConfig); assertTrue(yarnConfig.getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, false)); } |
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); } | @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")); } |
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); } | @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()); } |
YarnService implements ProvisioningServiceDelegate { @Override public ClusterEnriched getClusterInfo(final Cluster cluster) throws YarnProvisioningHandlingException { TwillController controller = getTwillControllerHelper(cluster); final ClusterEnriched clusterEnriched = new ClusterEnriched(cluster); if (controller != null) { ResourceReport report = controller.getResourceReport(); if (report == null) { return clusterEnriched; } Collection<TwillRunResources> runResources = report.getRunnableResources(DacDaemonYarnApplication.YARN_RUNNABLE_NAME); Set<String> activeContainerIds = new HashSet<>(); for(NodeEndpoint ep : executionNodeProvider.getNodes()){ if(ep.hasProvisionId()){ activeContainerIds.add(ep.getProvisionId()); } } ImmutableContainers.Builder containers = Containers.builder(); List<Container> runningList = new ArrayList<>(); List<Container> disconnectedList = new ArrayList<>(); for (TwillRunResources runResource : runResources) { Container container = Container.builder() .setContainerId(runResource.getContainerId()) .setContainerPropertyList( ImmutableList.<Property>of( new Property("host", runResource.getHost()), new Property("memoryMB", "" + runResource.getMemoryMB()), new Property("virtualCoreCount", "" + runResource.getVirtualCores()) ) ) .build(); if(activeContainerIds.contains(runResource.getContainerId())) { runningList.add(container); } else { disconnectedList.add(container); } } int yarnDelta = (cluster.getClusterConfig().getClusterSpec().getContainerCount() - runResources.size()); if (yarnDelta > 0) { containers.setPendingCount(yarnDelta); } else if (yarnDelta < 0) { containers.setDecommissioningCount(Math.abs(yarnDelta)); } containers.setProvisioningCount(disconnectedList.size()); containers.setRunningList(runningList); containers.setDisconnectedList(disconnectedList); clusterEnriched.setRunTimeInfo(containers.build()); } return clusterEnriched; } 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); } | @Test public void testGetClusterInfo() throws Exception { assumeNonMaprProfile(); YarnController controller = Mockito.mock(YarnController.class); YarnService yarnService = new YarnService(new TestListener(), controller, Mockito.mock(NodeProvider.class)); Cluster cluster = new Cluster(); cluster.setState(ClusterState.CREATED); cluster.setStateChangeTime(System.currentTimeMillis()); cluster.setId(new ClusterId(UUID.randomUUID().toString())); ClusterConfig clusterConfig = new ClusterConfig(); clusterConfig.setClusterSpec(new ClusterSpec().setContainerCount(2).setMemoryMBOffHeap(4096).setMemoryMBOnHeap(4096).setVirtualCoreCount(2)); List<Property> propertyList = new ArrayList<>(); propertyList.add(new Property(FS_DEFAULT_NAME_KEY, "hdfs: propertyList.add(new Property(RM_HOSTNAME, "resource-manager")); propertyList.add(new Property(DremioConfig.DIST_WRITE_PATH_STRING, "pdfs: RunId runId = RunIds.generate(); clusterConfig.setSubPropertyList(propertyList); cluster.setClusterConfig(clusterConfig); cluster.setRunId(new com.dremio.provision.RunId(runId.toString())); YarnConfiguration yarnConfig = new YarnConfiguration(); yarnService.updateYarnConfiguration(cluster, yarnConfig); TwillController twillController = Mockito.mock(TwillController.class); ResourceReport resourceReport = Mockito.mock(ResourceReport.class); TwillRunnerService twillRunnerService = Mockito.mock(TwillRunnerService.class); List<TwillRunResources> resources = new ArrayList<>(); for (int i = 0; i < 10; i++) { resources.add(createResource(i)); } when(controller.startCluster(any(YarnConfiguration.class), eq(cluster.getClusterConfig().getSubPropertyList()))) .thenReturn(twillController); when(controller.getTwillService(cluster.getId())).thenReturn(twillRunnerService); when(twillController.getRunId()).thenReturn(runId); when(resourceReport.getRunnableResources(DacDaemonYarnApplication.YARN_RUNNABLE_NAME)).thenReturn(resources); when(twillRunnerService.lookup(DacDaemonYarnApplication.YARN_APPLICATION_NAME_DEFAULT, runId)).thenReturn(twillController); when(twillController.getResourceReport()).thenReturn(resourceReport); ClusterEnriched clusterEnriched = yarnService.getClusterInfo(cluster); assertNotNull(clusterEnriched.getRunTimeInfo()); assertEquals(8, clusterEnriched.getRunTimeInfo().getDecommissioningCount()); } |
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; } | @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"))))); } |
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); } | @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); } |
YarnContainerHealthMonitor implements LiveHealthMonitor { @Override public boolean isHealthy() { return isHealthy; } YarnContainerHealthMonitor(); @Override boolean isHealthy(); } | @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()); } |
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); } | @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); } |
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); } | @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); } |
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); } | @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()); } |
QuerySemantics { public static VirtualDatasetState extract(QueryMetadata metadata) { final com.dremio.service.jobs.metadata.proto.VirtualDatasetState pState = metadata.getState(); final VirtualDatasetState state = new VirtualDatasetState(); if (pState.hasFrom()) { state.setFrom(fromBuf(pState.getFrom())); } if (pState.getColumnsCount() > 0) { state.setColumnsList( pState.getColumnsList() .stream() .map((c) -> new Column(c.getName(), fromBuf(c.getExpression()))) .collect(Collectors.toList())); } if (pState.getOrdersCount() > 0) { state.setOrdersList( pState.getOrdersList() .stream() .map((o) -> new Order(o.getName(), OrderDirection.valueOf(o.getDirection().name()))) .collect(Collectors.toList()) ); } state.setReferredTablesList(pState.getReferredTablesList()); state.setContextList(pState.getContextList()); return state; } private QuerySemantics(); static VirtualDatasetState extract(QueryMetadata metadata); static void populateSemanticFields(List<ViewFieldType> viewFieldTypes, VirtualDatasetState state); } | @Test public void testStar() { VirtualDatasetState ds = extract( getQueryFromSQL("select * from " + table)); assertEquals( new VirtualDatasetState() .setFrom(from) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("tpch/supplier.parquet")) .setColumnsList(cols("s_suppkey", "s_name", "s_address", "s_nationkey", "s_phone", "s_acctbal", "s_comment")), ds); }
@Test public void selectConstant() { final String query = "SELECT 1729 AS special"; final VirtualDatasetState ds = extract(getQueryFromSQL(query)); assertEquals(ds, new VirtualDatasetState() .setFrom(new FromSQL(query).setAlias("nested_0").wrap()) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Collections.<String>emptyList()) .setColumnsList(cols("special"))); }
@Test public void selectConstantNested() { final String query = "SELECT * FROM (SELECT 87539319 AS special ORDER BY 1 LIMIT 1)"; final VirtualDatasetState ds = extract(getQueryFromSQL(query)); assertEquals(new VirtualDatasetState() .setFrom(new FromSQL(query).setAlias("nested_0").wrap()) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Collections.<String>emptyList()) .setColumnsList(cols("special")), ds); }
@Test public void testTimestampCloseToZero() throws Exception { VirtualDatasetState ds = extract( getQueryFromSQL( "select TIMESTAMP '1970-01-01 00:00:00.100' from sys.memory")); assertNotNull(ds); ds = extract( getQueryFromSQL( "select TIMESTAMP '1970-01-01 00:00:00.099' from sys.memory")); assertNotNull(ds); ds = extract( getQueryFromSQL( "select TIMESTAMP '1970-01-01 00:00:00.000' from sys.memory")); assertNotNull(ds); ds = extract( getQueryFromSQL( "select TIMESTAMP '1970-01-01 00:00:00.001' from sys.memory")); assertNotNull(ds); ds = extract( getQueryFromSQL( "select TIME '00:00:00.100' from sys.memory")); assertNotNull(ds); ds = extract( getQueryFromSQL( "select TIME '00:00:00.099' from sys.memory")); assertNotNull(ds); ds = extract( getQueryFromSQL( "select TIME '00:00:00.000' from sys.memory")); assertNotNull(ds); ds = extract( getQueryFromSQL( "select TIME '00:00:00.001' from sys.memory")); assertNotNull(ds); }
@Test public void testStarAs() { VirtualDatasetState ds = extract( getQueryFromSQL("select * from " + table + " as foo")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable(table).setAlias("foo").wrap()).setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("tpch/supplier.parquet")) .setColumnsList(cols("s_suppkey", "s_name", "s_address", "s_nationkey", "s_phone", "s_acctbal", "s_comment")), ds); }
@Test public void testFields() { VirtualDatasetState ds = extract( getQueryFromSQL("select s_suppkey, s_name, s_address from " + table)); assertEquals( new VirtualDatasetState() .setFrom(from) .setColumnsList(cols("s_suppkey", "s_name", "s_address")) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("tpch/supplier.parquet")), ds); }
@Test public void testFieldsAs() { VirtualDatasetState ds = extract( getQueryFromSQL("select s_suppkey, s_address as mycol from " + table)); assertEquals( new VirtualDatasetState() .setFrom(from) .setColumnsList(asList( new Column("s_suppkey", new ExpColumnReference("s_suppkey").wrap()), new Column("mycol", new ExpColumnReference("s_address").wrap()))) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("tpch/supplier.parquet")), ds); }
@Test public void testFlatten() { VirtualDatasetState ds = extract(getQueryFromSQL("select flatten(b), a as mycol from cp.\"json/nested.json\"")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable("\"cp\".\"json/nested.json\"").setAlias("json/nested.json").wrap()) .setColumnsList(asList( new Column("EXPR$0", new ExpCalculatedField("FLATTEN(\"json/nested.json\".\"b\")").wrap()), new Column("mycol", new ExpColumnReference("a").wrap()))) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("json/nested.json")), ds); }
@Test public void testCount() { VirtualDatasetState ds = extract(getQueryFromSQL("select count(*) from cp.\"json/nested.json\"")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable("\"cp\".\"json/nested.json\"").setAlias("json/nested.json").wrap()) .setColumnsList(asList( new Column("EXPR$0", new ExpCalculatedField("COUNT(*)").wrap()) )).setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("json/nested.json")), ds); }
@Test public void testFunctionUpper() { VirtualDatasetState ds = extract(getQueryFromSQL("select upper(a) from cp.\"json/convert_case.json\"")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable("\"cp\".\"json/convert_case.json\"").setAlias("json/convert_case.json").wrap()) .setColumnsList(asList( new Column("EXPR$0", new ExpCalculatedField("UPPER(\"json/convert_case.json\".\"a\")").wrap()))) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("json/convert_case.json")), ds); }
@Test public void testOrder() { VirtualDatasetState ds = extract(getQueryFromSQL("select a from cp.\"json/nested.json\" order by a")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable("\"cp\".\"json/nested.json\"").setAlias("json/nested.json").wrap()) .setColumnsList(cols("a")).setOrdersList(asList(new Order("a", ASC))) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("json/nested.json")), ds); }
@Test public void testMultipleOrder() { VirtualDatasetState ds = extract(getQueryFromSQL("select a, b from cp.\"json/nested.json\" order by b desc, a asc")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable("\"cp\".\"json/nested.json\"").setAlias("json/nested.json").wrap()) .setColumnsList(cols("a", "b")) .setOrdersList(asList( new Order("b", DESC), new Order("a", ASC))) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("json/nested.json")), ds); }
@Test public void testOrderAlias() { VirtualDatasetState ds = extract(getQueryFromSQL("select a as b from cp.\"json/nested.json\" order by b")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable("\"cp\".\"json/nested.json\"").setAlias("json/nested.json").wrap()) .setColumnsList(asList(new Column("b", new ExpColumnReference("a").wrap()))) .setOrdersList(asList(new Order("b", ASC))) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("json/nested.json")), ds); }
@Test public void testNestedColRef() { VirtualDatasetState ds = extract(getQueryFromSQL("select t.a.Tuesday as tuesday from cp.\"json/extract_map.json\" as t")); assertEquals( new VirtualDatasetState() .setFrom(new FromTable("\"cp\".\"json/extract_map.json\"").setAlias("t").wrap()) .setColumnsList(asList(new Column("tuesday", new ExpCalculatedField("\"t\".\"a\"['Tuesday']").wrap()))) .setContextList(Collections.<String>emptyList()) .setReferredTablesList(Arrays.asList("json/extract_map.json")), ds); } |
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); } | @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()); } |
SourceResource extends BaseResourceWithAllocator { @RolesAllowed("admin") @DELETE @Produces(MediaType.APPLICATION_JSON) public void deleteSource(@QueryParam("version") String version) throws NamespaceException, SourceNotFoundException { if (version == null) { throw new ClientErrorException("missing version parameter"); } try { SourceConfig config = namespaceService.getSource(new SourcePath(sourceName).toNamespaceKey()); if(!Objects.equals(config.getTag(), version)) { throw new ConcurrentModificationException(String.format("Unable to delete source, expected version %s, received version %s.", config.getTag(), version)); } sourceCatalog.deleteSource(config); } catch (NamespaceNotFoundException nfe) { throw new SourceNotFoundException(sourcePath.getSourceName().getName(), nfe); } } @Inject SourceResource(
NamespaceService namespaceService,
ReflectionAdministrationService.Factory reflectionService,
SourceService sourceService,
@PathParam("sourceName") SourceName sourceName,
QueryExecutor executor,
SecurityContext securityContext,
DatasetsResource datasetsResource,
ConnectionReader cReader,
SourceCatalog sourceCatalog,
FormatTools formatTools,
ContextService context,
BufferAllocatorFactory allocatorFactory
); @GET @Produces(MediaType.APPLICATION_JSON) SourceUI getSource(@QueryParam("includeContents") @DefaultValue("true") boolean includeContents); @RolesAllowed("admin") @DELETE @Produces(MediaType.APPLICATION_JSON) void deleteSource(@QueryParam("version") String version); @GET @Path("/folder/{path: .*}") @Produces(MediaType.APPLICATION_JSON) Folder getFolder(@PathParam("path") String path, @QueryParam("includeContents") @DefaultValue("true") boolean includeContents); @GET @Path("/dataset/{path: .*}") @Produces(MediaType.APPLICATION_JSON) PhysicalDataset getPhysicalDataset(@PathParam("path") String path); @GET @Path("/file/{path: .*}") @Produces(MediaType.APPLICATION_JSON) File getFile(@PathParam("path") String path); @GET @Path("/file_format/{path: .*}") @Produces(MediaType.APPLICATION_JSON) FileFormatUI getFileFormatSettings(@PathParam("path") String path); @PUT @Path("/file_format/{path: .*}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) FileFormatUI saveFormatSettings(FileFormat fileFormat, @PathParam("path") String path); @POST @Path("/file_preview/{path: .*}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) JobDataFragment previewFileFormat(FileFormat format, @PathParam("path") String path); @POST @Path("/folder_preview/{path: .*}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) JobDataFragment previewFolderFormat(FileFormat format, @PathParam("path") String path); @DELETE @Path("/file_format/{path: .*}") void deleteFileFormat(@PathParam("path") String path,
@QueryParam("version") String version); @GET @Path("/folder_format/{path: .*}") @Produces(MediaType.APPLICATION_JSON) FileFormatUI getFolderFormat(@PathParam("path") String path); @PUT @Path("/folder_format/{path: .*}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) FileFormatUI saveFolderFormat(FileFormat fileFormat, @PathParam("path") String path); @DELETE @Path("/folder_format/{path: .*}") @Produces(MediaType.APPLICATION_JSON) void deleteFolderFormat(@PathParam("path") String path,
@QueryParam("version") String version); @POST @Path("new_untitled_from_file/{path: .*}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) InitialPreviewResponse createUntitledFromSourceFile(
@PathParam("path") String path,
@QueryParam("limit") Integer limit); @POST @Path("new_untitled_from_folder/{path: .*}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) InitialPreviewResponse createUntitledFromSourceFolder(
@PathParam("path") String path,
@QueryParam("limit") Integer limit); @POST @Path("new_untitled_from_physical_dataset/{path: .*}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) InitialPreviewResponse createUntitledFromPhysicalDataset(
@PathParam("path") String path,
@QueryParam("limit") Integer limit); } | @Test public void testAddSourceWithAccelerationTTL() throws Exception { final String sourceName = "src"; final long refreshPeriod = TimeUnit.HOURS.toMillis(4); final long gracePeriod = TimeUnit.HOURS.toMillis(12); { final NASConf nas = new NASConf(); nas.path = folder.getRoot().getPath(); SourceUI source = new SourceUI(); source.setName(sourceName); source.setCtime(System.currentTimeMillis()); source.setAccelerationRefreshPeriod(refreshPeriod); source.setAccelerationGracePeriod(gracePeriod); source.setConfig(nas); expectSuccess( getBuilder(getAPIv2().path(String.format("/source/%s", sourceName))) .buildPut(Entity.entity(source, JSON))); final SourceUI result = expectSuccess( getBuilder(getAPIv2().path(String.format("/source/%s", sourceName))).buildGet(), SourceUI.class ); assertEquals(source.getFullPathList(), result.getFullPathList()); assertEquals(source.getAccelerationRefreshPeriod(), result.getAccelerationRefreshPeriod()); assertEquals(source.getAccelerationGracePeriod(), result.getAccelerationGracePeriod()); newNamespaceService().deleteSource(new SourcePath(sourceName).toNamespaceKey(), result.getTag()); } }
@Test public void testSourceHasDefaultTTL() throws Exception { final String sourceName = "src2"; final NASConf nas = new NASConf(); nas.path = folder.getRoot().getPath(); SourceUI source = new SourceUI(); source.setName(sourceName); source.setCtime(System.currentTimeMillis()); source.setConfig(nas); source.setAllowCrossSourceSelection(true); expectSuccess( getBuilder(getAPIv2().path(String.format("/source/%s", sourceName))) .buildPut(Entity.entity(source, JSON))); final SourceUI result = expectSuccess( getBuilder(getAPIv2().path(String.format("/source/%s", sourceName))).buildGet(), SourceUI.class ); assertEquals(source.getFullPathList(), result.getFullPathList()); assertNotNull(result.getAccelerationRefreshPeriod()); assertNotNull(result.getAccelerationGracePeriod()); assertTrue(result.getAllowCrossSourceSelection()); newNamespaceService().deleteSource(new SourcePath(sourceName).toNamespaceKey(), result.getTag()); }
@Test public void testSourceHasDefaultRefreshPolicy() throws Exception { final String sourceName = "src3"; final NASConf nas = new NASConf(); nas.path = folder.getRoot().getPath() ; SourceUI source = new SourceUI(); source.setName(sourceName); source.setCtime(System.currentTimeMillis()); source.setConfig(nas); expectSuccess( getBuilder(getAPIv2().path(String.format("/source/%s", sourceName))) .buildPut(Entity.entity(source, JSON))); final SourceUI result = expectSuccess( getBuilder(getAPIv2().path(String.format("/source/%s", sourceName))).buildGet(), SourceUI.class ); assertEquals(source.getFullPathList(), result.getFullPathList()); assertNotNull(source.getMetadataPolicy()); assertEquals(CatalogService.DEFAULT_AUTHTTLS_MILLIS, result.getMetadataPolicy().getAuthTTLMillis()); assertEquals(CatalogService.DEFAULT_REFRESH_MILLIS, result.getMetadataPolicy().getNamesRefreshMillis()); assertEquals(CatalogService.DEFAULT_REFRESH_MILLIS, result.getMetadataPolicy().getDatasetDefinitionRefreshAfterMillis()); assertEquals(CatalogService.DEFAULT_EXPIRE_MILLIS, result.getMetadataPolicy().getDatasetDefinitionExpireAfterMillis()); newNamespaceService().deleteSource(new SourcePath(sourceName).toNamespaceKey(), result.getTag()); } |
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); } | @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)); } |
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); } | @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()); } |
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(); } | @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")); } |
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(); } | @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]); } } |
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(); } | @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)) )); } |
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); } | @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(); } |
WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/apiapimanagementoauth/**", config); } return new CorsFilter(source); } 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); } | @Test public void testCorsFilterOnApiPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( options("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) .andExpect(header().string(HttpHeaders.VARY, "Origin")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); }
@Test public void testCorsFilterOnOtherPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/test/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); }
@Test public void testCorsFilterDeactivated() throws Exception { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); }
@Test public void testCorsFilterDeactivated2() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } |
SwaggerBasePathRewritingFilter extends SendResponseFilter { @Override public boolean shouldFilter() { return RequestContext.getCurrentContext().getRequest().getRequestURI().endsWith(Swagger2Controller.DEFAULT_URL); } SwaggerBasePathRewritingFilter(); @Override String filterType(); @Override int filterOrder(); @Override boolean shouldFilter(); @Override Object run(); static byte[] gzipData(String content); } | @Test public void shouldFilter_on_default_swagger_url() { MockHttpServletRequest request = new MockHttpServletRequest("GET", DEFAULT_URL); RequestContext.getCurrentContext().setRequest(request); assertTrue(filter.shouldFilter()); }
@Test public void shouldFilter_on_default_swagger_url_with_param() { MockHttpServletRequest request = new MockHttpServletRequest("GET", DEFAULT_URL); request.setParameter("debug", "true"); RequestContext.getCurrentContext().setRequest(request); assertTrue(filter.shouldFilter()); }
@Test public void shouldNotFilter_on_wrong_url() { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/management/info"); RequestContext.getCurrentContext().setRequest(request); assertFalse(filter.shouldFilter()); } |
SwaggerBasePathRewritingFilter extends SendResponseFilter { @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.getResponse().setCharacterEncoding("UTF-8"); String rewrittenResponse = rewriteBasePath(context); if (context.getResponseGZipped()) { try { context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse))); } catch (IOException e) { log.error("Swagger-docs filter error", e); } } else { context.setResponseBody(rewrittenResponse); } return null; } SwaggerBasePathRewritingFilter(); @Override String filterType(); @Override int filterOrder(); @Override boolean shouldFilter(); @Override Object run(); static byte[] gzipData(String content); } | @Test public void run_on_valid_response() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponseGZipped(false); context.setResponse(response); InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8); context.setResponseDataStream(in); filter.run(); assertEquals("UTF-8", response.getCharacterEncoding()); assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody()); } |
Employee { public String getName() { return name; } 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(); } | @Test public void whenStreamMapping_thenGetMap() { Map<Character, List<Integer>> idGroupedByAlphabet = empList.stream().collect( Collectors.groupingBy(e -> new Character(e.getName().charAt(0)), Collectors.mapping(Employee::getId, Collectors.toList()))); assertEquals(idGroupedByAlphabet.get('B').get(0), new Integer(2)); assertEquals(idGroupedByAlphabet.get('J').get(0), new Integer(1)); assertEquals(idGroupedByAlphabet.get('M').get(0), new Integer(3)); }
@Test public void whenStreamGroupingAndReducing_thenGetMap() { Comparator<Employee> byNameLength = Comparator.comparing(Employee::getName); Map<Character, Optional<Employee>> longestNameByAlphabet = empList.stream().collect( Collectors.groupingBy(e -> new Character(e.getName().charAt(0)), Collectors.reducing(BinaryOperator.maxBy(byNameLength)))); assertEquals(longestNameByAlphabet.get('B').get().getName(), "Bill Gates"); assertEquals(longestNameByAlphabet.get('J').get().getName(), "Jeff Bezos"); assertEquals(longestNameByAlphabet.get('M').get().getName(), "Mark Zuckerberg"); }
@Test public void whenSortStream_thenGetSortedStream() { List<Employee> employees = empList.stream() .sorted((e1, e2) -> e1.getName().compareTo(e2.getName())) .collect(Collectors.toList()); assertEquals(employees.get(0).getName(), "Bill Gates"); assertEquals(employees.get(1).getName(), "Jeff Bezos"); assertEquals(employees.get(2).getName(), "Mark Zuckerberg"); }
@Test public void whenStreamGroupingBy_thenGetMap() { Map<Character, List<Employee>> groupByAlphabet = empList.stream().collect( Collectors.groupingBy(e -> new Character(e.getName().charAt(0)))); assertEquals(groupByAlphabet.get('B').get(0).getName(), "Bill Gates"); assertEquals(groupByAlphabet.get('J').get(0).getName(), "Jeff Bezos"); assertEquals(groupByAlphabet.get('M').get(0).getName(), "Mark Zuckerberg"); } |
Employee { public Double getSalary() { return salary; } 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(); } | @Test public void whenStreamReducing_thenGetValue() { Double percentage = 10.0; Double salIncrOverhead = empList.stream().collect(Collectors.reducing( 0.0, e -> e.getSalary() * percentage / 100, (s1, s2) -> s1 + s2)); assertEquals(salIncrOverhead, 60000.0, 0); }
@Test public void whenFilterEmployees_thenGetFilteredStream() { Integer[] empIds = { 1, 2, 3, 4 }; List<Employee> employees = Stream.of(empIds) .map(employeeRepository::findById) .filter(e -> e != null) .filter(e -> e.getSalary() > 200000) .collect(Collectors.toList()); assertEquals(Arrays.asList(arrayOfEmps[2]), employees); }
@Test public void whenFindFirst_thenGetFirstEmployeeInStream() { Integer[] empIds = { 1, 2, 3, 4 }; Employee employee = Stream.of(empIds) .map(employeeRepository::findById) .filter(e -> e != null) .filter(e -> e.getSalary() > 100000) .findFirst() .orElse(null); assertEquals(employee.getSalary(), new Double(200000)); }
@Test public void whenStreamCount_thenGetElementCount() { Long empCount = empList.stream() .filter(e -> e.getSalary() > 200000) .count(); assertEquals(empCount, new Long(1)); }
@Test public void whenFindMax_thenGetMaxElementFromStream() { Employee maxSalEmp = empList.stream() .max(Comparator.comparing(Employee::getSalary)) .orElseThrow(NoSuchElementException::new); assertEquals(maxSalEmp.getSalary(), new Double(300000.0)); } |
TshirtSizeController { @RequestMapping(value ="convertSize", method = RequestMethod.GET) public int convertSize(@RequestParam(value = "label") final String label, @RequestParam(value = "countryCode", required = false) final String countryCode) { return service.convertSize(label, countryCode); } TshirtSizeController(SizeConverterService service); @RequestMapping(value ="convertSize", method = RequestMethod.GET) int convertSize(@RequestParam(value = "label") final String label, @RequestParam(value = "countryCode", required = false) final String countryCode); } | @Test void whenConvertSize_thenOK() { String label = "S"; String countryCode = "fr"; int result = 36; when(service.convertSize(label, countryCode)).thenReturn(result); int actual = tested.convertSize(label, countryCode); assertEquals(actual, result); } |
Order { public Order id(Long id) { this.id = id; return this; } Order id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Order petId(Long petId); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PET_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getPetId(); void setPetId(Long petId); Order quantity(Integer quantity); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_QUANTITY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getQuantity(); void setQuantity(Integer quantity); Order shipDate(OffsetDateTime shipDate); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_SHIP_DATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) OffsetDateTime getShipDate(); void setShipDate(OffsetDateTime shipDate); Order status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "Order Status") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); Order complete(Boolean complete); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_COMPLETE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Boolean getComplete(); void setComplete(Boolean complete); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_PET_ID; static final String JSON_PROPERTY_QUANTITY; static final String JSON_PROPERTY_SHIP_DATE; static final String JSON_PROPERTY_STATUS; static final String JSON_PROPERTY_COMPLETE; } | @Test public void idTest() { } |
Order { public Order petId(Long petId) { this.petId = petId; return this; } Order id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Order petId(Long petId); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PET_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getPetId(); void setPetId(Long petId); Order quantity(Integer quantity); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_QUANTITY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getQuantity(); void setQuantity(Integer quantity); Order shipDate(OffsetDateTime shipDate); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_SHIP_DATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) OffsetDateTime getShipDate(); void setShipDate(OffsetDateTime shipDate); Order status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "Order Status") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); Order complete(Boolean complete); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_COMPLETE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Boolean getComplete(); void setComplete(Boolean complete); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_PET_ID; static final String JSON_PROPERTY_QUANTITY; static final String JSON_PROPERTY_SHIP_DATE; static final String JSON_PROPERTY_STATUS; static final String JSON_PROPERTY_COMPLETE; } | @Test public void petIdTest() { } |
Order { public Order quantity(Integer quantity) { this.quantity = quantity; return this; } Order id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Order petId(Long petId); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PET_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getPetId(); void setPetId(Long petId); Order quantity(Integer quantity); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_QUANTITY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getQuantity(); void setQuantity(Integer quantity); Order shipDate(OffsetDateTime shipDate); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_SHIP_DATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) OffsetDateTime getShipDate(); void setShipDate(OffsetDateTime shipDate); Order status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "Order Status") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); Order complete(Boolean complete); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_COMPLETE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Boolean getComplete(); void setComplete(Boolean complete); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_PET_ID; static final String JSON_PROPERTY_QUANTITY; static final String JSON_PROPERTY_SHIP_DATE; static final String JSON_PROPERTY_STATUS; static final String JSON_PROPERTY_COMPLETE; } | @Test public void quantityTest() { } |
Order { public Order shipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; return this; } Order id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Order petId(Long petId); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PET_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getPetId(); void setPetId(Long petId); Order quantity(Integer quantity); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_QUANTITY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getQuantity(); void setQuantity(Integer quantity); Order shipDate(OffsetDateTime shipDate); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_SHIP_DATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) OffsetDateTime getShipDate(); void setShipDate(OffsetDateTime shipDate); Order status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "Order Status") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); Order complete(Boolean complete); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_COMPLETE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Boolean getComplete(); void setComplete(Boolean complete); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_PET_ID; static final String JSON_PROPERTY_QUANTITY; static final String JSON_PROPERTY_SHIP_DATE; static final String JSON_PROPERTY_STATUS; static final String JSON_PROPERTY_COMPLETE; } | @Test public void shipDateTest() { } |
Order { public Order status(StatusEnum status) { this.status = status; return this; } Order id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Order petId(Long petId); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PET_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getPetId(); void setPetId(Long petId); Order quantity(Integer quantity); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_QUANTITY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getQuantity(); void setQuantity(Integer quantity); Order shipDate(OffsetDateTime shipDate); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_SHIP_DATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) OffsetDateTime getShipDate(); void setShipDate(OffsetDateTime shipDate); Order status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "Order Status") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); Order complete(Boolean complete); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_COMPLETE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Boolean getComplete(); void setComplete(Boolean complete); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_PET_ID; static final String JSON_PROPERTY_QUANTITY; static final String JSON_PROPERTY_SHIP_DATE; static final String JSON_PROPERTY_STATUS; static final String JSON_PROPERTY_COMPLETE; } | @Test public void statusTest() { } |
Order { public Order complete(Boolean complete) { this.complete = complete; return this; } Order id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Order petId(Long petId); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PET_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getPetId(); void setPetId(Long petId); Order quantity(Integer quantity); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_QUANTITY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getQuantity(); void setQuantity(Integer quantity); Order shipDate(OffsetDateTime shipDate); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_SHIP_DATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) OffsetDateTime getShipDate(); void setShipDate(OffsetDateTime shipDate); Order status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "Order Status") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); Order complete(Boolean complete); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_COMPLETE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Boolean getComplete(); void setComplete(Boolean complete); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_PET_ID; static final String JSON_PROPERTY_QUANTITY; static final String JSON_PROPERTY_SHIP_DATE; static final String JSON_PROPERTY_STATUS; static final String JSON_PROPERTY_COMPLETE; } | @Test public void completeTest() { } |
User { public User id(Long id) { this.id = id; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void idTest() { } |
User { public User username(String username) { this.username = username; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void usernameTest() { } |
User { public User firstName(String firstName) { this.firstName = firstName; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void firstNameTest() { } |
User { public User lastName(String lastName) { this.lastName = lastName; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void lastNameTest() { } |
User { public User email(String email) { this.email = email; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void emailTest() { } |
User { public User password(String password) { this.password = password; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void passwordTest() { } |
User { public User phone(String phone) { this.phone = phone; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void phoneTest() { } |
User { public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } User id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); User username(String username); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_USERNAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getUsername(); void setUsername(String username); User firstName(String firstName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_FIRST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getFirstName(); void setFirstName(String firstName); User lastName(String lastName); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LAST_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getLastName(); void setLastName(String lastName); User email(String email); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EMAIL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getEmail(); void setEmail(String email); User password(String password); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PASSWORD) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPassword(); void setPassword(String password); User phone(String phone); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PHONE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getPhone(); void setPhone(String phone); User userStatus(Integer userStatus); @javax.annotation.Nullable @ApiModelProperty(value = "User Status") @JsonProperty(JSON_PROPERTY_USER_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getUserStatus(); void setUserStatus(Integer userStatus); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_USERNAME; static final String JSON_PROPERTY_FIRST_NAME; static final String JSON_PROPERTY_LAST_NAME; static final String JSON_PROPERTY_EMAIL; static final String JSON_PROPERTY_PASSWORD; static final String JSON_PROPERTY_PHONE; static final String JSON_PROPERTY_USER_STATUS; } | @Test public void userStatusTest() { } |
Pet { public Pet id(Long id) { this.id = id; return this; } Pet id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Pet category(Category category); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CATEGORY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Category getCategory(); void setCategory(Category category); Pet name(String name); @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) String getName(); void setName(String name); Pet photoUrls(List<String> photoUrls); Pet addPhotoUrlsItem(String photoUrlsItem); @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_PHOTO_URLS) @JsonInclude(value = JsonInclude.Include.ALWAYS) List<String> getPhotoUrls(); void setPhotoUrls(List<String> photoUrls); Pet tags(List<Tag> tags); Pet addTagsItem(Tag tagsItem); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) List<Tag> getTags(); void setTags(List<Tag> tags); Pet status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "pet status in the store") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_CATEGORY; static final String JSON_PROPERTY_NAME; static final String JSON_PROPERTY_PHOTO_URLS; static final String JSON_PROPERTY_TAGS; static final String JSON_PROPERTY_STATUS; } | @Test public void idTest() { } |
Pet { public Pet category(Category category) { this.category = category; return this; } Pet id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Pet category(Category category); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CATEGORY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Category getCategory(); void setCategory(Category category); Pet name(String name); @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) String getName(); void setName(String name); Pet photoUrls(List<String> photoUrls); Pet addPhotoUrlsItem(String photoUrlsItem); @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_PHOTO_URLS) @JsonInclude(value = JsonInclude.Include.ALWAYS) List<String> getPhotoUrls(); void setPhotoUrls(List<String> photoUrls); Pet tags(List<Tag> tags); Pet addTagsItem(Tag tagsItem); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) List<Tag> getTags(); void setTags(List<Tag> tags); Pet status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "pet status in the store") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_CATEGORY; static final String JSON_PROPERTY_NAME; static final String JSON_PROPERTY_PHOTO_URLS; static final String JSON_PROPERTY_TAGS; static final String JSON_PROPERTY_STATUS; } | @Test public void categoryTest() { } |
Pet { public Pet name(String name) { this.name = name; return this; } Pet id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Pet category(Category category); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CATEGORY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Category getCategory(); void setCategory(Category category); Pet name(String name); @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) String getName(); void setName(String name); Pet photoUrls(List<String> photoUrls); Pet addPhotoUrlsItem(String photoUrlsItem); @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_PHOTO_URLS) @JsonInclude(value = JsonInclude.Include.ALWAYS) List<String> getPhotoUrls(); void setPhotoUrls(List<String> photoUrls); Pet tags(List<Tag> tags); Pet addTagsItem(Tag tagsItem); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) List<Tag> getTags(); void setTags(List<Tag> tags); Pet status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "pet status in the store") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_CATEGORY; static final String JSON_PROPERTY_NAME; static final String JSON_PROPERTY_PHOTO_URLS; static final String JSON_PROPERTY_TAGS; static final String JSON_PROPERTY_STATUS; } | @Test public void nameTest() { } |
Pet { public Pet photoUrls(List<String> photoUrls) { this.photoUrls = photoUrls; return this; } Pet id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Pet category(Category category); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CATEGORY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Category getCategory(); void setCategory(Category category); Pet name(String name); @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) String getName(); void setName(String name); Pet photoUrls(List<String> photoUrls); Pet addPhotoUrlsItem(String photoUrlsItem); @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_PHOTO_URLS) @JsonInclude(value = JsonInclude.Include.ALWAYS) List<String> getPhotoUrls(); void setPhotoUrls(List<String> photoUrls); Pet tags(List<Tag> tags); Pet addTagsItem(Tag tagsItem); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) List<Tag> getTags(); void setTags(List<Tag> tags); Pet status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "pet status in the store") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_CATEGORY; static final String JSON_PROPERTY_NAME; static final String JSON_PROPERTY_PHOTO_URLS; static final String JSON_PROPERTY_TAGS; static final String JSON_PROPERTY_STATUS; } | @Test public void photoUrlsTest() { } |
Pet { public Pet tags(List<Tag> tags) { this.tags = tags; return this; } Pet id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Pet category(Category category); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CATEGORY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Category getCategory(); void setCategory(Category category); Pet name(String name); @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) String getName(); void setName(String name); Pet photoUrls(List<String> photoUrls); Pet addPhotoUrlsItem(String photoUrlsItem); @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_PHOTO_URLS) @JsonInclude(value = JsonInclude.Include.ALWAYS) List<String> getPhotoUrls(); void setPhotoUrls(List<String> photoUrls); Pet tags(List<Tag> tags); Pet addTagsItem(Tag tagsItem); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) List<Tag> getTags(); void setTags(List<Tag> tags); Pet status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "pet status in the store") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_CATEGORY; static final String JSON_PROPERTY_NAME; static final String JSON_PROPERTY_PHOTO_URLS; static final String JSON_PROPERTY_TAGS; static final String JSON_PROPERTY_STATUS; } | @Test public void tagsTest() { } |
Pet { public Pet status(StatusEnum status) { this.status = status; return this; } Pet id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Pet category(Category category); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CATEGORY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Category getCategory(); void setCategory(Category category); Pet name(String name); @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.ALWAYS) String getName(); void setName(String name); Pet photoUrls(List<String> photoUrls); Pet addPhotoUrlsItem(String photoUrlsItem); @ApiModelProperty(required = true, value = "") @JsonProperty(JSON_PROPERTY_PHOTO_URLS) @JsonInclude(value = JsonInclude.Include.ALWAYS) List<String> getPhotoUrls(); void setPhotoUrls(List<String> photoUrls); Pet tags(List<Tag> tags); Pet addTagsItem(Tag tagsItem); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) List<Tag> getTags(); void setTags(List<Tag> tags); Pet status(StatusEnum status); @javax.annotation.Nullable @ApiModelProperty(value = "pet status in the store") @JsonProperty(JSON_PROPERTY_STATUS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) StatusEnum getStatus(); void setStatus(StatusEnum status); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_CATEGORY; static final String JSON_PROPERTY_NAME; static final String JSON_PROPERTY_PHOTO_URLS; static final String JSON_PROPERTY_TAGS; static final String JSON_PROPERTY_STATUS; } | @Test public void statusTest() { } |
Category { public Category id(Long id) { this.id = id; return this; } Category id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Category name(String name); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getName(); void setName(String name); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_NAME; } | @Test public void idTest() { } |
Category { public Category name(String name) { this.name = name; return this; } Category id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Category name(String name); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getName(); void setName(String name); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_NAME; } | @Test public void nameTest() { } |
ModelApiResponse { public ModelApiResponse code(Integer code) { this.code = code; return this; } ModelApiResponse code(Integer code); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CODE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getCode(); void setCode(Integer code); ModelApiResponse type(String type); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getType(); void setType(String type); ModelApiResponse message(String message); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_MESSAGE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getMessage(); void setMessage(String message); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_CODE; static final String JSON_PROPERTY_TYPE; static final String JSON_PROPERTY_MESSAGE; } | @Test public void codeTest() { } |
ModelApiResponse { public ModelApiResponse type(String type) { this.type = type; return this; } ModelApiResponse code(Integer code); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CODE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getCode(); void setCode(Integer code); ModelApiResponse type(String type); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getType(); void setType(String type); ModelApiResponse message(String message); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_MESSAGE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getMessage(); void setMessage(String message); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_CODE; static final String JSON_PROPERTY_TYPE; static final String JSON_PROPERTY_MESSAGE; } | @Test public void typeTest() { } |
ModelApiResponse { public ModelApiResponse message(String message) { this.message = message; return this; } ModelApiResponse code(Integer code); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_CODE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Integer getCode(); void setCode(Integer code); ModelApiResponse type(String type); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getType(); void setType(String type); ModelApiResponse message(String message); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_MESSAGE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getMessage(); void setMessage(String message); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_CODE; static final String JSON_PROPERTY_TYPE; static final String JSON_PROPERTY_MESSAGE; } | @Test public void messageTest() { } |
Tag { public Tag id(Long id) { this.id = id; return this; } Tag id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Tag name(String name); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getName(); void setName(String name); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_NAME; } | @Test public void idTest() { } |
Tag { public Tag name(String name) { this.name = name; return this; } Tag id(Long id); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) Long getId(); void setId(Long id); Tag name(String name); @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) String getName(); void setName(String name); @Override boolean equals(java.lang.Object o); @Override int hashCode(); @Override String toString(); static final String JSON_PROPERTY_ID; static final String JSON_PROPERTY_NAME; } | @Test public void nameTest() { } |
UserApi { public void createUser(User body) throws RestClientException { createUserWithHttpInfo(body); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void createUserTest() { User body = null; api.createUser(body); } |
UserApi { public void createUsersWithArrayInput(List<User> body) throws RestClientException { createUsersWithArrayInputWithHttpInfo(body); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void createUsersWithArrayInputTest() { List<User> body = null; api.createUsersWithArrayInput(body); } |
UserApi { public void createUsersWithListInput(List<User> body) throws RestClientException { createUsersWithListInputWithHttpInfo(body); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void createUsersWithListInputTest() { List<User> body = null; api.createUsersWithListInput(body); } |
UserApi { public void deleteUser(String username) throws RestClientException { deleteUserWithHttpInfo(username); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void deleteUserTest() { String username = null; api.deleteUser(username); } |
UserApi { public User getUserByName(String username) throws RestClientException { return getUserByNameWithHttpInfo(username).getBody(); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void getUserByNameTest() { String username = null; User response = api.getUserByName(username); } |
UserApi { public String loginUser(String username, String password) throws RestClientException { return loginUserWithHttpInfo(username, password).getBody(); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void loginUserTest() { String username = null; String password = null; String response = api.loginUser(username, password); } |
UserApi { public void logoutUser() throws RestClientException { logoutUserWithHttpInfo(); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void logoutUserTest() { api.logoutUser(); } |
UserApi { public void updateUser(String username, User body) throws RestClientException { updateUserWithHttpInfo(username, body); } UserApi(); @Autowired UserApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void createUser(User body); ResponseEntity<Void> createUserWithHttpInfo(User body); void createUsersWithArrayInput(List<User> body); ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body); void createUsersWithListInput(List<User> body); ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body); void deleteUser(String username); ResponseEntity<Void> deleteUserWithHttpInfo(String username); User getUserByName(String username); ResponseEntity<User> getUserByNameWithHttpInfo(String username); String loginUser(String username, String password); ResponseEntity<String> loginUserWithHttpInfo(String username, String password); void logoutUser(); ResponseEntity<Void> logoutUserWithHttpInfo(); void updateUser(String username, User body); ResponseEntity<Void> updateUserWithHttpInfo(String username, User body); } | @Test public void updateUserTest() { String username = null; User body = null; api.updateUser(username, body); } |
StoreApi { public void deleteOrder(Long orderId) throws RestClientException { deleteOrderWithHttpInfo(orderId); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); ResponseEntity<Void> deleteOrderWithHttpInfo(Long orderId); Map<String, Integer> getInventory(); ResponseEntity<Map<String, Integer>> getInventoryWithHttpInfo(); Order getOrderById(Long orderId); ResponseEntity<Order> getOrderByIdWithHttpInfo(Long orderId); Order placeOrder(Order body); ResponseEntity<Order> placeOrderWithHttpInfo(Order body); } | @Test public void deleteOrderTest() { Long orderId = null; api.deleteOrder(orderId); } |
StoreApi { public Map<String, Integer> getInventory() throws RestClientException { return getInventoryWithHttpInfo().getBody(); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); ResponseEntity<Void> deleteOrderWithHttpInfo(Long orderId); Map<String, Integer> getInventory(); ResponseEntity<Map<String, Integer>> getInventoryWithHttpInfo(); Order getOrderById(Long orderId); ResponseEntity<Order> getOrderByIdWithHttpInfo(Long orderId); Order placeOrder(Order body); ResponseEntity<Order> placeOrderWithHttpInfo(Order body); } | @Test public void getInventoryTest() { Map<String, Integer> response = api.getInventory(); } |
StoreApi { public Order getOrderById(Long orderId) throws RestClientException { return getOrderByIdWithHttpInfo(orderId).getBody(); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); ResponseEntity<Void> deleteOrderWithHttpInfo(Long orderId); Map<String, Integer> getInventory(); ResponseEntity<Map<String, Integer>> getInventoryWithHttpInfo(); Order getOrderById(Long orderId); ResponseEntity<Order> getOrderByIdWithHttpInfo(Long orderId); Order placeOrder(Order body); ResponseEntity<Order> placeOrderWithHttpInfo(Order body); } | @Test public void getOrderByIdTest() { Long orderId = null; Order response = api.getOrderById(orderId); } |
StoreApi { public Order placeOrder(Order body) throws RestClientException { return placeOrderWithHttpInfo(body).getBody(); } StoreApi(); @Autowired StoreApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void deleteOrder(Long orderId); ResponseEntity<Void> deleteOrderWithHttpInfo(Long orderId); Map<String, Integer> getInventory(); ResponseEntity<Map<String, Integer>> getInventoryWithHttpInfo(); Order getOrderById(Long orderId); ResponseEntity<Order> getOrderByIdWithHttpInfo(Long orderId); Order placeOrder(Order body); ResponseEntity<Order> placeOrderWithHttpInfo(Order body); } | @Test public void placeOrderTest() { Order body = null; Order response = api.placeOrder(body); } |
PetApi { public void addPet(Pet body) throws RestClientException { addPetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void addPetTest() { Pet body = null; api.addPet(body); } |
PetApi { public void deletePet(Long petId, String apiKey) throws RestClientException { deletePetWithHttpInfo(petId, apiKey); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void deletePetTest() { Long petId = null; String apiKey = null; api.deletePet(petId, apiKey); } |
PetApi { public List<Pet> findPetsByStatus(List<String> status) throws RestClientException { return findPetsByStatusWithHttpInfo(status).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void findPetsByStatusTest() { List<String> status = null; List<Pet> response = api.findPetsByStatus(status); } |
PetApi { @Deprecated public List<Pet> findPetsByTags(List<String> tags) throws RestClientException { return findPetsByTagsWithHttpInfo(tags).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void findPetsByTagsTest() { List<String> tags = null; List<Pet> response = api.findPetsByTags(tags); } |
PetApi { public Pet getPetById(Long petId) throws RestClientException { return getPetByIdWithHttpInfo(petId).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void getPetByIdTest() { Long petId = null; Pet response = api.getPetById(petId); } |
PetApi { public void updatePet(Pet body) throws RestClientException { updatePetWithHttpInfo(body); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void updatePetTest() { Pet body = null; api.updatePet(body); } |
PetApi { public void updatePetWithForm(Long petId, String name, String status) throws RestClientException { updatePetWithFormWithHttpInfo(petId, name, status); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void updatePetWithFormTest() { Long petId = null; String name = null; String status = null; api.updatePetWithForm(petId, name, status); } |
PetApi { public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody(); } PetApi(); @Autowired PetApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); void addPet(Pet body); ResponseEntity<Void> addPetWithHttpInfo(Pet body); void deletePet(Long petId, String apiKey); ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey); List<Pet> findPetsByStatus(List<String> status); ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status); @Deprecated List<Pet> findPetsByTags(List<String> tags); @Deprecated ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags); Pet getPetById(Long petId); ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId); void updatePet(Pet body); ResponseEntity<Void> updatePetWithHttpInfo(Pet body); void updatePetWithForm(Long petId, String name, String status); ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status); ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file); ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file); } | @Test public void uploadFileTest() { Long petId = null; String additionalMetadata = null; File file = null; ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); } |
Formatter { public static String getFormattedDate() { DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } static String getFormattedDate(); } | @Test public void testFormatter() { String dateRegex1 = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$"; String dateString = Formatter.getFormattedDate(); assertTrue(Pattern .matches(dateRegex1, dateString)); } |
WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } 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); } | @Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); }
@Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); } |
WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(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); } | @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"); 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(); }
@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(); } |
WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v2/api-docs", config); } return new CorsFilter(source); } 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); } | @Test public void testCorsFilterOnApiPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( options("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) .andExpect(header().string(HttpHeaders.VARY, "Origin")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); }
@Test public void testCorsFilterOnOtherPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/test/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); }
@Test public void testCorsFilterDeactivated() throws Exception { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); }
@Test public void testCorsFilterDeactivated2() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } |
Employee { public Integer getId() { return id; } 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(); } | @Test public void whenFindMin_thenGetMinElementFromStream() { Employee firstEmp = empList.stream() .min((e1, e2) -> e1.getId() - e2.getId()) .orElseThrow(NoSuchElementException::new); assertEquals(firstEmp.getId(), new Integer(1)); } |
OAuth2AuthenticationService { public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) { try { String username = params.get("username"); String password = params.get("password"); boolean rememberMe = Boolean.valueOf(params.get("rememberMe")); OAuth2AccessToken accessToken = authorizationClient.sendPasswordGrant(username, password); OAuth2Cookies cookies = new OAuth2Cookies(); cookieHelper.createCookies(request, accessToken, rememberMe, cookies); cookies.addCookiesTo(response); if (log.isDebugEnabled()) { log.debug("successfully authenticated user {}", params.get("username")); } return ResponseEntity.ok(accessToken); } catch (HttpClientErrorException ex) { log.error("failed to get OAuth2 tokens from UAA", ex); throw new InvalidPasswordException(); } } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | @Test public void testAuthenticationCookies() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); request.addHeader("Authorization", CLIENT_AUTHORIZATION); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user"); params.put("rememberMe", "true"); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.authenticate(request, response, params); Cookie accessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(ACCESS_TOKEN_VALUE, accessTokenCookie.getValue()); Cookie refreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(REFRESH_TOKEN_VALUE, OAuth2CookieHelper.getRefreshTokenValue(refreshTokenCookie)); Assert.assertTrue(OAuth2CookieHelper.isRememberMe(refreshTokenCookie)); }
@Test public void testAuthenticationNoRememberMe() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user"); params.put("rememberMe", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.authenticate(request, response, params); Cookie accessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(ACCESS_TOKEN_VALUE, accessTokenCookie.getValue()); Cookie refreshTokenCookie = response.getCookie(OAuth2CookieHelper.SESSION_TOKEN_COOKIE); Assert.assertEquals(REFRESH_TOKEN_VALUE, OAuth2CookieHelper.getRefreshTokenValue(refreshTokenCookie)); Assert.assertFalse(OAuth2CookieHelper.isRememberMe(refreshTokenCookie)); }
@Test public void testInvalidPassword() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerName("www.test.com"); Map<String, String> params = new HashMap<>(); params.put("username", "user"); params.put("password", "user2"); params.put("rememberMe", "false"); MockHttpServletResponse response = new MockHttpServletResponse(); expectedException.expect(InvalidPasswordException.class); authenticationService.authenticate(request, response, params); } |
OAuth2AuthenticationService { public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { cookieHelper.clearCookies(httpServletRequest, httpServletResponse); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | @Test public void testLogout() { MockHttpServletRequest request = new MockHttpServletRequest(); Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE); Cookie refreshTokenCookie = new Cookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE, REFRESH_TOKEN_VALUE); request.setCookies(accessTokenCookie, refreshTokenCookie); MockHttpServletResponse response = new MockHttpServletResponse(); authenticationService.logout(request, response); Cookie newAccessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE); Assert.assertEquals(0, newAccessTokenCookie.getMaxAge()); Cookie newRefreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE); Assert.assertEquals(0, newRefreshTokenCookie.getMaxAge()); } |
OAuth2AuthenticationService { public HttpServletRequest stripTokens(HttpServletRequest httpServletRequest) { Cookie[] cookies = cookieHelper.stripCookies(httpServletRequest.getCookies()); return new CookiesHttpServletRequestWrapper(httpServletRequest, cookies); } OAuth2AuthenticationService(OAuth2TokenEndpointClient authorizationClient, OAuth2CookieHelper cookieHelper); ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response,
Map<String, String> params); HttpServletRequest refreshToken(HttpServletRequest request, HttpServletResponse response, Cookie
refreshCookie); void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse); HttpServletRequest stripTokens(HttpServletRequest httpServletRequest); } | @Test public void testStripTokens() { MockHttpServletRequest request = createMockHttpServletRequest(); HttpServletRequest newRequest = authenticationService.stripTokens(request); CookieCollection cookies = new CookieCollection(newRequest.getCookies()); Assert.assertFalse(cookies.contains(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE)); Assert.assertFalse(cookies.contains(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE)); } |
CookieCollection implements Collection<Cookie> { @Override public int size() { return cookieMap.size(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | @Test public void size() throws Exception { CookieCollection cookies = new CookieCollection(); Assert.assertEquals(0, cookies.size()); cookies.add(cookie); Assert.assertEquals(1, cookies.size()); } |
CookieCollection implements Collection<Cookie> { @Override public boolean isEmpty() { return cookieMap.isEmpty(); } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | @Test public void isEmpty() throws Exception { CookieCollection cookies = new CookieCollection(); Assert.assertTrue(cookies.isEmpty()); cookies.add(cookie); Assert.assertFalse(cookies.isEmpty()); } |
CookieCollection implements Collection<Cookie> { @Override public boolean contains(Object o) { if (o instanceof String) { return cookieMap.containsKey(o); } if (o instanceof Cookie) { return cookieMap.containsValue(o); } return false; } CookieCollection(); CookieCollection(Cookie... cookies); CookieCollection(Collection<? extends Cookie> cookies); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<Cookie> iterator(); Cookie[] toArray(); @Override T[] toArray(T[] ts); @Override boolean add(Cookie cookie); @Override boolean remove(Object o); Cookie get(String name); @Override boolean containsAll(Collection<?> collection); @Override boolean addAll(Collection<? extends Cookie> collection); @Override boolean removeAll(Collection<?> collection); @Override boolean retainAll(Collection<?> collection); @Override void clear(); } | @Test public void contains() throws Exception { CookieCollection cookies = new CookieCollection(cookie); Assert.assertTrue(cookies.contains(cookie)); Assert.assertTrue(cookies.contains(COOKIE_NAME)); Assert.assertFalse(cookies.contains("yuck")); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.