target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testAddGridset() throws GeoWebCacheException, IOException { String gridsetName = "EPSG:3005"; GridSet epsg3005 = GridSetFactory.createGridSet( gridsetName, SRS.getSRS(gridsetName), new BoundingBox(35043.6538, 440006.8768, 1885895.3117, 1735643.8497), false, null, new double[] {25000000, 1250000, 500000, 250000}, null, GridSetFactory.DEFAULT_PIXEL_SIZE_METER, null, 256, 256, false); gridSetBroker.addGridSet(epsg3005); assertTrue(gridSetBroker.getNames().contains(gridsetName)); assertEquals(gridSetBroker.get(gridsetName), epsg3005); } | public void addGridSet(GridSet gridSet) { log.debug("Adding " + gridSet.getName()); getConfigurations() .stream() .filter(c -> c.canSave(gridSet)) .findFirst() .orElseThrow( () -> new UnsupportedOperationException( "No Configuration is able to save gridset " + gridSet.getName())) .addGridSet(gridSet); } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public void addGridSet(GridSet gridSet) { log.debug("Adding " + gridSet.getName()); getConfigurations() .stream() .filter(c -> c.canSave(gridSet)) .findFirst() .orElseThrow( () -> new UnsupportedOperationException( "No Configuration is able to save gridset " + gridSet.getName())) .addGridSet(gridSet); } } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public void addGridSet(GridSet gridSet) { log.debug("Adding " + gridSet.getName()); getConfigurations() .stream() .filter(c -> c.canSave(gridSet)) .findFirst() .orElseThrow( () -> new UnsupportedOperationException( "No Configuration is able to save gridset " + gridSet.getName())) .addGridSet(gridSet); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public void addGridSet(GridSet gridSet) { log.debug("Adding " + gridSet.getName()); getConfigurations() .stream() .filter(c -> c.canSave(gridSet)) .findFirst() .orElseThrow( () -> new UnsupportedOperationException( "No Configuration is able to save gridset " + gridSet.getName())) .addGridSet(gridSet); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public void addGridSet(GridSet gridSet) { log.debug("Adding " + gridSet.getName()); getConfigurations() .stream() .filter(c -> c.canSave(gridSet)) .findFirst() .orElseThrow( () -> new UnsupportedOperationException( "No Configuration is able to save gridset " + gridSet.getName())) .addGridSet(gridSet); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); } |
@Test public void testRemoveGridset() throws IOException { String gridsetToRemove = GWCConfigIntegrationTestData.GRIDSET_EPSG2163; gridSetBroker.removeGridSet(gridsetToRemove); assertThat(gridSetBroker.getGridSetNames(), not(hasItem(gridsetToRemove))); assertThat(gridSetBroker.getGridSet(gridsetToRemove), notPresent()); } | public synchronized void removeGridSet(final String gridSetName) { getConfigurations() .stream() .filter(c -> c.getGridSet(gridSetName).isPresent()) .forEach( c -> { c.removeGridSet(gridSetName); }); } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public synchronized void removeGridSet(final String gridSetName) { getConfigurations() .stream() .filter(c -> c.getGridSet(gridSetName).isPresent()) .forEach( c -> { c.removeGridSet(gridSetName); }); } } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public synchronized void removeGridSet(final String gridSetName) { getConfigurations() .stream() .filter(c -> c.getGridSet(gridSetName).isPresent()) .forEach( c -> { c.removeGridSet(gridSetName); }); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public synchronized void removeGridSet(final String gridSetName) { getConfigurations() .stream() .filter(c -> c.getGridSet(gridSetName).isPresent()) .forEach( c -> { c.removeGridSet(gridSetName); }); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); } | GridSetBroker implements ConfigurationAggregator<GridSetConfiguration>,
ApplicationContextAware,
InitializingBean { public synchronized void removeGridSet(final String gridSetName) { getConfigurations() .stream() .filter(c -> c.getGridSet(gridSetName).isPresent()) .forEach( c -> { c.removeGridSet(gridSetName); }); } GridSetBroker(); GridSetBroker(List<GridSetConfiguration> configurations); void afterPropertiesSet(); @Nullable GridSet get(String gridSetId); Set<String> getEmbeddedNames(); Set<String> getNames(); Set<String> getGridSetNames(); Collection<GridSet> getGridSets(); synchronized void put(GridSet gridSet); void addGridSet(GridSet gridSet); synchronized GridSet remove(final String gridSetName); synchronized void removeGridSet(final String gridSetName); DefaultGridsets getDefaults(); GridSet getWorldEpsg4326(); GridSet getWorldEpsg3857(); @SuppressWarnings("unchecked") List<? extends GSC> getConfigurations(
Class<GSC> type); @Override void setApplicationContext(ApplicationContext applicationContext); } |
@Test public void testCreateTileRange() throws IOException, GeoWebCacheException { WMSLayer tl = createWMSLayer(); String gridSet = tl.getGridSubsets().iterator().next(); GridSubset gridSubSet = tl.getGridSubset(gridSet); BoundingBox bounds = new BoundingBox(0d, 0d, 1d, 1d); long[][] result = gridSubSet.getCoverageIntersections(bounds); assertNotNull(result); } | public long[][] getCoverageIntersections(BoundingBox reqBounds) { final int zoomStart = getZoomStart(); final int zoomStop = getZoomStop(); long[][] ret = new long[1 + zoomStop - zoomStart][5]; for (int level = zoomStart; level <= zoomStop; level++) { ret[level - zoomStart] = getCoverageIntersection(level, reqBounds); } return ret; } | GridSubset { public long[][] getCoverageIntersections(BoundingBox reqBounds) { final int zoomStart = getZoomStart(); final int zoomStop = getZoomStop(); long[][] ret = new long[1 + zoomStop - zoomStart][5]; for (int level = zoomStart; level <= zoomStop; level++) { ret[level - zoomStart] = getCoverageIntersection(level, reqBounds); } return ret; } } | GridSubset { public long[][] getCoverageIntersections(BoundingBox reqBounds) { final int zoomStart = getZoomStart(); final int zoomStop = getZoomStop(); long[][] ret = new long[1 + zoomStop - zoomStart][5]; for (int level = zoomStart; level <= zoomStop; level++) { ret[level - zoomStart] = getCoverageIntersection(level, reqBounds); } return ret; } protected GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage); GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage,
Integer minCachedZoom,
Integer maxCachedZoom); GridSubset(GridSubset subSet); } | GridSubset { public long[][] getCoverageIntersections(BoundingBox reqBounds) { final int zoomStart = getZoomStart(); final int zoomStop = getZoomStop(); long[][] ret = new long[1 + zoomStop - zoomStart][5]; for (int level = zoomStart; level <= zoomStop; level++) { ret[level - zoomStart] = getCoverageIntersection(level, reqBounds); } return ret; } protected GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage); GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage,
Integer minCachedZoom,
Integer maxCachedZoom); GridSubset(GridSubset subSet); BoundingBox boundsFromIndex(long[] tileIndex); BoundingBox boundsFromRectangle(long[] rectangleExtent); long[] closestIndex(BoundingBox tileBounds); long[] closestRectangle(BoundingBox rectangleBounds); boolean covers(long[] index); void checkCoverage(long[] index); void checkTileDimensions(int width, int height); long[][] expandToMetaFactors(final long[][] coverages, final int[] metaFactors); long[] getCoverage(int level); long[][] getCoverages(); double getDotsPerInch(); BoundingBox getCoverageBounds(int level); long[] getCoverageBestFit(); BoundingBox getCoverageBestFitBounds(); long[] getCoverageIntersection(long[] reqRectangle); long[][] getCoverageIntersections(BoundingBox reqBounds); long[] getCoverageIntersection(int level, BoundingBox reqBounds); long getGridIndex(String gridId); String[] getGridNames(); GridSet getGridSet(); BoundingBox getGridSetBounds(); long getNumTilesWide(int zoomLevel); long getNumTilesHigh(int zoomLevel); String getName(); BoundingBox getOriginalExtent(); double[] getResolutions(); long[][] getSubGrid(long[] gridLoc); boolean getScaleWarning(); SRS getSRS(); int getTileHeight(); int getTileWidth(); long[][] getWMTSCoverages(); int getZoomStart(); int getZoomStop(); Integer getMinCachedZoom(); Integer getMaxCachedZoom(); boolean fullGridSetCoverage(); boolean shouldCacheAtZoom(long zoom); @Override String toString(); } | GridSubset { public long[][] getCoverageIntersections(BoundingBox reqBounds) { final int zoomStart = getZoomStart(); final int zoomStop = getZoomStop(); long[][] ret = new long[1 + zoomStop - zoomStart][5]; for (int level = zoomStart; level <= zoomStop; level++) { ret[level - zoomStart] = getCoverageIntersection(level, reqBounds); } return ret; } protected GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage); GridSubset(
GridSet gridSet,
Map<Integer, GridCoverage> coverages,
BoundingBox originalExtent,
boolean fullCoverage,
Integer minCachedZoom,
Integer maxCachedZoom); GridSubset(GridSubset subSet); BoundingBox boundsFromIndex(long[] tileIndex); BoundingBox boundsFromRectangle(long[] rectangleExtent); long[] closestIndex(BoundingBox tileBounds); long[] closestRectangle(BoundingBox rectangleBounds); boolean covers(long[] index); void checkCoverage(long[] index); void checkTileDimensions(int width, int height); long[][] expandToMetaFactors(final long[][] coverages, final int[] metaFactors); long[] getCoverage(int level); long[][] getCoverages(); double getDotsPerInch(); BoundingBox getCoverageBounds(int level); long[] getCoverageBestFit(); BoundingBox getCoverageBestFitBounds(); long[] getCoverageIntersection(long[] reqRectangle); long[][] getCoverageIntersections(BoundingBox reqBounds); long[] getCoverageIntersection(int level, BoundingBox reqBounds); long getGridIndex(String gridId); String[] getGridNames(); GridSet getGridSet(); BoundingBox getGridSetBounds(); long getNumTilesWide(int zoomLevel); long getNumTilesHigh(int zoomLevel); String getName(); BoundingBox getOriginalExtent(); double[] getResolutions(); long[][] getSubGrid(long[] gridLoc); boolean getScaleWarning(); SRS getSRS(); int getTileHeight(); int getTileWidth(); long[][] getWMTSCoverages(); int getZoomStart(); int getZoomStop(); Integer getMinCachedZoom(); Integer getMaxCachedZoom(); boolean fullGridSetCoverage(); boolean shouldCacheAtZoom(long zoom); @Override String toString(); } |
@Test public void testBoundsFromIndex() throws Exception { long[] index = {0, 0, 1}; BoundingBox bboxTL = gridSetTL.boundsFromIndex(index); BoundingBox bboxBL = gridSetBL.boundsFromIndex(index); BoundingBox bboxTLswap = gridSetTLswap.boundsFromIndex(index); BoundingBox bboxBLswap = gridSetBLswap.boundsFromIndex(index); BoundingBox solution = new BoundingBox(-180.0, -90.0, -90.0, 0); assertThat(bboxTL, closeTo(solution, 0.00000001)); assertThat(bboxBL, closeTo(solution, 0.00000001)); assertThat(bboxTLswap, closeTo(solution, 0.00000001)); assertThat(bboxBLswap, closeTo(solution, 0.00000001)); } | public BoundingBox boundsFromIndex(long[] tileIndex) { final int tileZ = (int) tileIndex[2]; Grid grid = getGrid(tileZ); final long tileX = tileIndex[0]; final long tileY; if (yBaseToggle) { tileY = tileIndex[1] - grid.getNumTilesHigh(); } else { tileY = tileIndex[1]; } double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); final double[] tileOrigin = tileOrigin(); BoundingBox tileBounds = new BoundingBox( tileOrigin[0] + width * tileX, tileOrigin[1] + height * (tileY), tileOrigin[0] + width * (tileX + 1), tileOrigin[1] + height * (tileY + 1)); return tileBounds; } | GridSet implements Info { public BoundingBox boundsFromIndex(long[] tileIndex) { final int tileZ = (int) tileIndex[2]; Grid grid = getGrid(tileZ); final long tileX = tileIndex[0]; final long tileY; if (yBaseToggle) { tileY = tileIndex[1] - grid.getNumTilesHigh(); } else { tileY = tileIndex[1]; } double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); final double[] tileOrigin = tileOrigin(); BoundingBox tileBounds = new BoundingBox( tileOrigin[0] + width * tileX, tileOrigin[1] + height * (tileY), tileOrigin[0] + width * (tileX + 1), tileOrigin[1] + height * (tileY + 1)); return tileBounds; } } | GridSet implements Info { public BoundingBox boundsFromIndex(long[] tileIndex) { final int tileZ = (int) tileIndex[2]; Grid grid = getGrid(tileZ); final long tileX = tileIndex[0]; final long tileY; if (yBaseToggle) { tileY = tileIndex[1] - grid.getNumTilesHigh(); } else { tileY = tileIndex[1]; } double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); final double[] tileOrigin = tileOrigin(); BoundingBox tileBounds = new BoundingBox( tileOrigin[0] + width * tileX, tileOrigin[1] + height * (tileY), tileOrigin[0] + width * (tileX + 1), tileOrigin[1] + height * (tileY + 1)); return tileBounds; } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { public BoundingBox boundsFromIndex(long[] tileIndex) { final int tileZ = (int) tileIndex[2]; Grid grid = getGrid(tileZ); final long tileX = tileIndex[0]; final long tileY; if (yBaseToggle) { tileY = tileIndex[1] - grid.getNumTilesHigh(); } else { tileY = tileIndex[1]; } double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); final double[] tileOrigin = tileOrigin(); BoundingBox tileBounds = new BoundingBox( tileOrigin[0] + width * tileX, tileOrigin[1] + height * (tileY), tileOrigin[0] + width * (tileX + 1), tileOrigin[1] + height * (tileY + 1)); return tileBounds; } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { public BoundingBox boundsFromIndex(long[] tileIndex) { final int tileZ = (int) tileIndex[2]; Grid grid = getGrid(tileZ); final long tileX = tileIndex[0]; final long tileY; if (yBaseToggle) { tileY = tileIndex[1] - grid.getNumTilesHigh(); } else { tileY = tileIndex[1]; } double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); final double[] tileOrigin = tileOrigin(); BoundingBox tileBounds = new BoundingBox( tileOrigin[0] + width * tileX, tileOrigin[1] + height * (tileY), tileOrigin[0] + width * (tileX + 1), tileOrigin[1] + height * (tileY + 1)); return tileBounds; } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testBounds() throws Exception { BoundingBox bboxTL = gridSetTL.getBounds(); BoundingBox bboxBL = gridSetBL.getBounds(); BoundingBox bboxTLswap = gridSetTLswap.getBounds(); BoundingBox bboxBLswap = gridSetBLswap.getBounds(); BoundingBox solution = new BoundingBox(-180.0, -90.0, 180, 90); assertThat(bboxTL, closeTo(solution, 0.00000001)); assertThat(bboxBL, closeTo(solution, 0.00000001)); assertThat(bboxTLswap, closeTo(solution, 0.00000001)); assertThat(bboxBLswap, closeTo(solution, 0.00000001)); } | public BoundingBox getBounds() { int i; long tilesWide, tilesHigh; for (i = (getNumLevels() - 1); i > 0; i--) { tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); if (tilesWide == 1 && tilesHigh == 0) { break; } } tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); long[] ret = {0, 0, tilesWide - 1, tilesHigh - 1, i}; return boundsFromRectangle(ret); } | GridSet implements Info { public BoundingBox getBounds() { int i; long tilesWide, tilesHigh; for (i = (getNumLevels() - 1); i > 0; i--) { tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); if (tilesWide == 1 && tilesHigh == 0) { break; } } tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); long[] ret = {0, 0, tilesWide - 1, tilesHigh - 1, i}; return boundsFromRectangle(ret); } } | GridSet implements Info { public BoundingBox getBounds() { int i; long tilesWide, tilesHigh; for (i = (getNumLevels() - 1); i > 0; i--) { tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); if (tilesWide == 1 && tilesHigh == 0) { break; } } tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); long[] ret = {0, 0, tilesWide - 1, tilesHigh - 1, i}; return boundsFromRectangle(ret); } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { public BoundingBox getBounds() { int i; long tilesWide, tilesHigh; for (i = (getNumLevels() - 1); i > 0; i--) { tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); if (tilesWide == 1 && tilesHigh == 0) { break; } } tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); long[] ret = {0, 0, tilesWide - 1, tilesHigh - 1, i}; return boundsFromRectangle(ret); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { public BoundingBox getBounds() { int i; long tilesWide, tilesHigh; for (i = (getNumLevels() - 1); i > 0; i--) { tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); if (tilesWide == 1 && tilesHigh == 0) { break; } } tilesWide = getGrid(i).getNumTilesWide(); tilesHigh = getGrid(i).getNumTilesHigh(); long[] ret = {0, 0, tilesWide - 1, tilesHigh - 1, i}; return boundsFromRectangle(ret); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testProxyDefaultWhitelistLimitedWhenSecure() throws Exception { SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); testProxyRequestPrevented(secDisp, layerName, tileLayer, "TROZ"); } | public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); static final String GEOWEBCACHE_WMS_PROXY_REQUEST_WHITELIST; static final String SERVICE_WMS; } |
@Test public void testBoundsFromRectangle() throws Exception { long[] rect = {0, 0, 0, 0, 0}; BoundingBox bboxTL = gridSetTL.boundsFromRectangle(rect); BoundingBox bboxBL = gridSetBL.boundsFromRectangle(rect); BoundingBox bboxTLswap = gridSetTLswap.boundsFromRectangle(rect); BoundingBox bboxBLswap = gridSetBLswap.boundsFromRectangle(rect); BoundingBox solution = new BoundingBox(-180.0, -90.0, 0.0, 90.0); assertThat(bboxTL, equalTo(solution)); assertThat(bboxBL, equalTo(solution)); assertThat(bboxTLswap, equalTo(solution)); assertThat(bboxBLswap, equalTo(solution)); long[] rect2 = {2, 1, 2, 1, 1}; BoundingBox bboxTL2 = gridSetTL.boundsFromRectangle(rect2); BoundingBox bboxBL2 = gridSetBL.boundsFromRectangle(rect2); BoundingBox bboxTLswap2 = gridSetTLswap.boundsFromRectangle(rect2); BoundingBox bboxBLswap2 = gridSetBLswap.boundsFromRectangle(rect2); BoundingBox solution2 = new BoundingBox(0.0, 0.0, 90.0, 90.0); assertThat(bboxTL2, equalTo(solution2)); assertThat(bboxBL2, equalTo(solution2)); assertThat(bboxTLswap2, equalTo(solution2)); assertThat(bboxBLswap2, equalTo(solution2)); } | protected BoundingBox boundsFromRectangle(long[] rectangleExtent) { Grid grid = getGrid((int) rectangleExtent[4]); double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); long bottomY = rectangleExtent[1]; long topY = rectangleExtent[3]; if (yBaseToggle) { bottomY = bottomY - grid.getNumTilesHigh(); topY = topY - grid.getNumTilesHigh(); } double[] tileOrigin = tileOrigin(); double minx = tileOrigin[0] + width * rectangleExtent[0]; double miny = tileOrigin[1] + height * (bottomY); double maxx = tileOrigin[0] + width * (rectangleExtent[2] + 1); double maxy = tileOrigin[1] + height * (topY + 1); BoundingBox rectangleBounds = new BoundingBox(minx, miny, maxx, maxy); return rectangleBounds; } | GridSet implements Info { protected BoundingBox boundsFromRectangle(long[] rectangleExtent) { Grid grid = getGrid((int) rectangleExtent[4]); double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); long bottomY = rectangleExtent[1]; long topY = rectangleExtent[3]; if (yBaseToggle) { bottomY = bottomY - grid.getNumTilesHigh(); topY = topY - grid.getNumTilesHigh(); } double[] tileOrigin = tileOrigin(); double minx = tileOrigin[0] + width * rectangleExtent[0]; double miny = tileOrigin[1] + height * (bottomY); double maxx = tileOrigin[0] + width * (rectangleExtent[2] + 1); double maxy = tileOrigin[1] + height * (topY + 1); BoundingBox rectangleBounds = new BoundingBox(minx, miny, maxx, maxy); return rectangleBounds; } } | GridSet implements Info { protected BoundingBox boundsFromRectangle(long[] rectangleExtent) { Grid grid = getGrid((int) rectangleExtent[4]); double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); long bottomY = rectangleExtent[1]; long topY = rectangleExtent[3]; if (yBaseToggle) { bottomY = bottomY - grid.getNumTilesHigh(); topY = topY - grid.getNumTilesHigh(); } double[] tileOrigin = tileOrigin(); double minx = tileOrigin[0] + width * rectangleExtent[0]; double miny = tileOrigin[1] + height * (bottomY); double maxx = tileOrigin[0] + width * (rectangleExtent[2] + 1); double maxy = tileOrigin[1] + height * (topY + 1); BoundingBox rectangleBounds = new BoundingBox(minx, miny, maxx, maxy); return rectangleBounds; } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { protected BoundingBox boundsFromRectangle(long[] rectangleExtent) { Grid grid = getGrid((int) rectangleExtent[4]); double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); long bottomY = rectangleExtent[1]; long topY = rectangleExtent[3]; if (yBaseToggle) { bottomY = bottomY - grid.getNumTilesHigh(); topY = topY - grid.getNumTilesHigh(); } double[] tileOrigin = tileOrigin(); double minx = tileOrigin[0] + width * rectangleExtent[0]; double miny = tileOrigin[1] + height * (bottomY); double maxx = tileOrigin[0] + width * (rectangleExtent[2] + 1); double maxy = tileOrigin[1] + height * (topY + 1); BoundingBox rectangleBounds = new BoundingBox(minx, miny, maxx, maxy); return rectangleBounds; } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { protected BoundingBox boundsFromRectangle(long[] rectangleExtent) { Grid grid = getGrid((int) rectangleExtent[4]); double width = grid.getResolution() * getTileWidth(); double height = grid.getResolution() * getTileHeight(); long bottomY = rectangleExtent[1]; long topY = rectangleExtent[3]; if (yBaseToggle) { bottomY = bottomY - grid.getNumTilesHigh(); topY = topY - grid.getNumTilesHigh(); } double[] tileOrigin = tileOrigin(); double minx = tileOrigin[0] + width * rectangleExtent[0]; double miny = tileOrigin[1] + height * (bottomY); double maxx = tileOrigin[0] + width * (rectangleExtent[2] + 1); double maxy = tileOrigin[1] + height * (topY + 1); BoundingBox rectangleBounds = new BoundingBox(minx, miny, maxx, maxy); return rectangleBounds; } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testClosestIndex() throws Exception { BoundingBox box = new BoundingBox(-180.0, -90.0, -90.0, 0); long[] idxTL = gridSetTL.closestIndex(box); long[] idxBL = gridSetBL.closestIndex(box); long[] solution = {0, 0, 1}; assertTrue(Arrays.equals(idxTL, solution)); assertTrue(Arrays.equals(idxBL, solution)); } | protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testClosestRectangle() throws Exception { BoundingBox box = new BoundingBox(-180.0, -90.0, 0.0, 0.0); long[] rectTL = gridSetTL.closestRectangle(box); long[] rectBL = gridSetBL.closestRectangle(box); long[] solution = {0, 0, 1, 0, 1}; assertTrue(Arrays.equals(rectTL, solution)); assertTrue(Arrays.equals(rectBL, solution)); } | public long[] closestRectangle(BoundingBox rectangleBounds) { double rectWidth = rectangleBounds.getWidth(); double rectHeight = rectangleBounds.getHeight(); double bestError = Double.MAX_VALUE; int bestLevel = -1; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double countX = rectWidth / (grid.getResolution() * getTileWidth()); double countY = rectHeight / (grid.getResolution() * getTileHeight()); double error = Math.abs(countX - Math.round(countX)) + Math.abs(countY - Math.round(countY)); if (error < bestError) { bestError = error; bestLevel = i; } else if (error >= bestError) { break; } } return closestRectangle(bestLevel, rectangleBounds); } | GridSet implements Info { public long[] closestRectangle(BoundingBox rectangleBounds) { double rectWidth = rectangleBounds.getWidth(); double rectHeight = rectangleBounds.getHeight(); double bestError = Double.MAX_VALUE; int bestLevel = -1; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double countX = rectWidth / (grid.getResolution() * getTileWidth()); double countY = rectHeight / (grid.getResolution() * getTileHeight()); double error = Math.abs(countX - Math.round(countX)) + Math.abs(countY - Math.round(countY)); if (error < bestError) { bestError = error; bestLevel = i; } else if (error >= bestError) { break; } } return closestRectangle(bestLevel, rectangleBounds); } } | GridSet implements Info { public long[] closestRectangle(BoundingBox rectangleBounds) { double rectWidth = rectangleBounds.getWidth(); double rectHeight = rectangleBounds.getHeight(); double bestError = Double.MAX_VALUE; int bestLevel = -1; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double countX = rectWidth / (grid.getResolution() * getTileWidth()); double countY = rectHeight / (grid.getResolution() * getTileHeight()); double error = Math.abs(countX - Math.round(countX)) + Math.abs(countY - Math.round(countY)); if (error < bestError) { bestError = error; bestLevel = i; } else if (error >= bestError) { break; } } return closestRectangle(bestLevel, rectangleBounds); } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { public long[] closestRectangle(BoundingBox rectangleBounds) { double rectWidth = rectangleBounds.getWidth(); double rectHeight = rectangleBounds.getHeight(); double bestError = Double.MAX_VALUE; int bestLevel = -1; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double countX = rectWidth / (grid.getResolution() * getTileWidth()); double countY = rectHeight / (grid.getResolution() * getTileHeight()); double error = Math.abs(countX - Math.round(countX)) + Math.abs(countY - Math.round(countY)); if (error < bestError) { bestError = error; bestLevel = i; } else if (error >= bestError) { break; } } return closestRectangle(bestLevel, rectangleBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { public long[] closestRectangle(BoundingBox rectangleBounds) { double rectWidth = rectangleBounds.getWidth(); double rectHeight = rectangleBounds.getHeight(); double bestError = Double.MAX_VALUE; int bestLevel = -1; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double countX = rectWidth / (grid.getResolution() * getTileWidth()); double countY = rectHeight / (grid.getResolution() * getTileHeight()); double error = Math.abs(countX - Math.round(countX)) + Math.abs(countY - Math.round(countY)); if (error < bestError) { bestError = error; bestLevel = i; } else if (error >= bestError) { break; } } return closestRectangle(bestLevel, rectangleBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testGetLeftTopCorner() throws Exception { double[] tlTL = gridSetTL.getOrderedTopLeftCorner(1); double[] tlBL = gridSetBL.getOrderedTopLeftCorner(1); assertThat(tlBL[1], Matchers.closeTo(90.0, 0.01)); assertThat(tlTL[1], Matchers.closeTo(90.0, 0.01)); } | public double[] getOrderedTopLeftCorner(int gridIndex) { double[] leftTop = new double[2]; if (yBaseToggle) { leftTop[0] = tileOrigin()[0]; leftTop[1] = tileOrigin()[1]; } else { Grid grid = getGrid(gridIndex); double dTileHeight = getTileHeight(); double dGridExtent = grid.getNumTilesHigh(); double top = tileOrigin()[1] + dTileHeight * grid.getResolution() * dGridExtent; if (Math.abs(top - Math.round(top)) < (top / 200)) { top = Math.round(top); } leftTop[0] = tileOrigin()[0]; leftTop[1] = top; } if (isyCoordinateFirst()) { double[] ret = {leftTop[1], leftTop[0]}; return ret; } return leftTop; } | GridSet implements Info { public double[] getOrderedTopLeftCorner(int gridIndex) { double[] leftTop = new double[2]; if (yBaseToggle) { leftTop[0] = tileOrigin()[0]; leftTop[1] = tileOrigin()[1]; } else { Grid grid = getGrid(gridIndex); double dTileHeight = getTileHeight(); double dGridExtent = grid.getNumTilesHigh(); double top = tileOrigin()[1] + dTileHeight * grid.getResolution() * dGridExtent; if (Math.abs(top - Math.round(top)) < (top / 200)) { top = Math.round(top); } leftTop[0] = tileOrigin()[0]; leftTop[1] = top; } if (isyCoordinateFirst()) { double[] ret = {leftTop[1], leftTop[0]}; return ret; } return leftTop; } } | GridSet implements Info { public double[] getOrderedTopLeftCorner(int gridIndex) { double[] leftTop = new double[2]; if (yBaseToggle) { leftTop[0] = tileOrigin()[0]; leftTop[1] = tileOrigin()[1]; } else { Grid grid = getGrid(gridIndex); double dTileHeight = getTileHeight(); double dGridExtent = grid.getNumTilesHigh(); double top = tileOrigin()[1] + dTileHeight * grid.getResolution() * dGridExtent; if (Math.abs(top - Math.round(top)) < (top / 200)) { top = Math.round(top); } leftTop[0] = tileOrigin()[0]; leftTop[1] = top; } if (isyCoordinateFirst()) { double[] ret = {leftTop[1], leftTop[0]}; return ret; } return leftTop; } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { public double[] getOrderedTopLeftCorner(int gridIndex) { double[] leftTop = new double[2]; if (yBaseToggle) { leftTop[0] = tileOrigin()[0]; leftTop[1] = tileOrigin()[1]; } else { Grid grid = getGrid(gridIndex); double dTileHeight = getTileHeight(); double dGridExtent = grid.getNumTilesHigh(); double top = tileOrigin()[1] + dTileHeight * grid.getResolution() * dGridExtent; if (Math.abs(top - Math.round(top)) < (top / 200)) { top = Math.round(top); } leftTop[0] = tileOrigin()[0]; leftTop[1] = top; } if (isyCoordinateFirst()) { double[] ret = {leftTop[1], leftTop[0]}; return ret; } return leftTop; } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { public double[] getOrderedTopLeftCorner(int gridIndex) { double[] leftTop = new double[2]; if (yBaseToggle) { leftTop[0] = tileOrigin()[0]; leftTop[1] = tileOrigin()[1]; } else { Grid grid = getGrid(gridIndex); double dTileHeight = getTileHeight(); double dGridExtent = grid.getNumTilesHigh(); double top = tileOrigin()[1] + dTileHeight * grid.getResolution() * dGridExtent; if (Math.abs(top - Math.round(top)) < (top / 200)) { top = Math.round(top); } leftTop[0] = tileOrigin()[0]; leftTop[1] = top; } if (isyCoordinateFirst()) { double[] ret = {leftTop[1], leftTop[0]}; return ret; } return leftTop; } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testClosestIndexInvalidBounds1() throws Exception { BoundingBox box = new BoundingBox(0, -180, 180.0, 0); exception.expect(GridAlignmentMismatchException.class); gridSetTL.closestIndex(box); } | protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testClosestIndexInvalidBounds2() throws Exception { BoundingBox box = new BoundingBox(0, 0, 180.0, 180); exception.expect(GridAlignmentMismatchException.class); gridSetTL.closestIndex(box); } | protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } | GridSet implements Info { protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchException { double wRes = tileBounds.getWidth() / getTileWidth(); double bestError = Double.MAX_VALUE; int bestLevel = -1; double bestResolution = -1.0; for (int i = 0; i < getNumLevels(); i++) { Grid grid = getGrid(i); double error = Math.abs(wRes - grid.getResolution()); if (error < bestError) { bestError = error; bestResolution = grid.getResolution(); bestLevel = i; } else { break; } } if (Math.abs(wRes - bestResolution) > (0.1 * wRes)) { throw new ResolutionMismatchException(wRes, bestResolution); } return closestIndex(bestLevel, tileBounds); } protected GridSet(); GridSet(GridSet g); BoundingBox getOriginalExtent(); boolean isResolutionsPreserved(); BoundingBox boundsFromIndex(long[] tileIndex); long[] closestRectangle(BoundingBox rectangleBounds); @Override boolean equals(Object obj); @Override int hashCode(); BoundingBox getBounds(); double[] getOrderedTopLeftCorner(int gridIndex); String guessMapUnits(); boolean isTopLeftAligned(); int getNumLevels(); Grid getGrid(final int zLevel); void setGrid(final int zLevel, final Grid grid); double[] tileOrigin(); boolean isyCoordinateFirst(); boolean isScaleWarning(); double getMetersPerUnit(); double getPixelSize(); String getName(); String getDescription(); void setDescription(String description); SRS getSrs(); int getTileWidth(); int getTileHeight(); boolean shouldTruncateIfChanged(final GridSet another); @Override String toString(); } |
@Test public void testAddLayer() throws GeoWebCacheException { String layerName = "newLayer"; WMSLayer layer = new WMSLayer( layerName, new String[] {"http: null, null, null, null, null, null, null, false, null); tileLayerDispatcher.addLayer(layer); assertTrue(tileLayerDispatcher.getLayerNames().contains(layerName)); assertEquals(layer, tileLayerDispatcher.getTileLayer(layerName)); } | public synchronized void addLayer(final TileLayer tl) throws IllegalArgumentException { for (TileLayerConfiguration c : configs) { if (c.canSave(tl)) { c.addLayer(tl); return; } } throw new IllegalArgumentException("No configuration found capable of saving " + tl); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addLayer(final TileLayer tl) throws IllegalArgumentException { for (TileLayerConfiguration c : configs) { if (c.canSave(tl)) { c.addLayer(tl); return; } } throw new IllegalArgumentException("No configuration found capable of saving " + tl); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addLayer(final TileLayer tl) throws IllegalArgumentException { for (TileLayerConfiguration c : configs) { if (c.canSave(tl)) { c.addLayer(tl); return; } } throw new IllegalArgumentException("No configuration found capable of saving " + tl); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addLayer(final TileLayer tl) throws IllegalArgumentException { for (TileLayerConfiguration c : configs) { if (c.canSave(tl)) { c.addLayer(tl); return; } } throw new IllegalArgumentException("No configuration found capable of saving " + tl); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addLayer(final TileLayer tl) throws IllegalArgumentException { for (TileLayerConfiguration c : configs) { if (c.canSave(tl)) { c.addLayer(tl); return; } } throw new IllegalArgumentException("No configuration found capable of saving " + tl); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void testRemoveLayer() { String layerToRemove = GWCConfigIntegrationTestData.LAYER_TOPP_STATES; tileLayerDispatcher.removeLayer(layerToRemove); assertFalse(tileLayerDispatcher.getLayerNames().contains(layerToRemove)); try { tileLayerDispatcher.getTileLayer(layerToRemove); fail("Expected exception when trying to get removed layer"); } catch (GeoWebCacheException e) { } } | public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void testRemoveLayerException() { try { tileLayerDispatcher.removeLayer(null); fail("Expected failure when trying to remove null layer"); } catch (Exception e) { } try { tileLayerDispatcher.removeLayer("nonexistantLayer"); fail("Expected failure when trying to remove nonexistant layer"); } catch (Exception e) { } } | public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeLayer(final String layerName) throws IllegalArgumentException { for (TileLayerConfiguration config : configs) { if (config.containsLayer(layerName)) { config.removeLayer(layerName); return; } } throw new NoSuchElementException("No configuration found containing layer " + layerName); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void testModifyBadLayer() { String layerName = "newLayer"; WMSLayer layer = new WMSLayer( layerName, new String[] {"http: null, null, null, null, null, null, null, false, null); try { tileLayerDispatcher.modify(layer); fail("Expected exception when modifiying nonexistant layer"); } catch (IllegalArgumentException e) { } try { tileLayerDispatcher.modify(null); fail("Expected exception when modifiying null layer"); } catch (IllegalArgumentException e) { } } | public synchronized void modify(final TileLayer tl) throws IllegalArgumentException { TileLayerConfiguration config = getConfiguration(tl); config.modifyLayer(tl); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void modify(final TileLayer tl) throws IllegalArgumentException { TileLayerConfiguration config = getConfiguration(tl); config.modifyLayer(tl); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void modify(final TileLayer tl) throws IllegalArgumentException { TileLayerConfiguration config = getConfiguration(tl); config.modifyLayer(tl); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void modify(final TileLayer tl) throws IllegalArgumentException { TileLayerConfiguration config = getConfiguration(tl); config.modifyLayer(tl); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void modify(final TileLayer tl) throws IllegalArgumentException { TileLayerConfiguration config = getConfiguration(tl); config.modifyLayer(tl); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void testProxyRequestSecuredDefaultAllowGetLegendGraphic() throws Exception { SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); testProxyRequestAllowed(secDisp, layerName, tileLayer, "GetLegendGraphic"); } | public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); static final String GEOWEBCACHE_WMS_PROXY_REQUEST_WHITELIST; static final String SERVICE_WMS; } |
@Test public void testAddGridset() throws GeoWebCacheException, IOException { String gridsetName = "EPSG:3005"; GridSet epsg3005 = GridSetFactory.createGridSet( gridsetName, SRS.getSRS(gridsetName), new BoundingBox(35043.6538, 440006.8768, 1885895.3117, 1735643.8497), false, null, new double[] {25000000, 1250000, 500000, 250000}, null, GridSetFactory.DEFAULT_PIXEL_SIZE_METER, null, 256, 256, false); tileLayerDispatcher.addGridSet(epsg3005); assertTrue(gridSetBroker.getNames().contains(gridsetName)); assertEquals(gridSetBroker.get(gridsetName), epsg3005); } | public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void testAddBadGridset() throws IOException { GridSet existingGridSet = gridSetBroker.get(GWCConfigIntegrationTestData.GRIDSET_EPSG2163); try { tileLayerDispatcher.addGridSet(existingGridSet); fail("Expected exception adding existing gridset"); } catch (IllegalArgumentException e) { } try { tileLayerDispatcher.addGridSet(null); fail("Expected exception adding null gridset"); } catch (NullPointerException e) { } } | public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } saveGridSet(gridSet); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void testRemoveGridset() throws IOException { String gridsetToRemove = GWCConfigIntegrationTestData.GRIDSET_EPSG2163; tileLayerDispatcher.removeLayer(GWCConfigIntegrationTestData.LAYER_TOPP_STATES); tileLayerDispatcher.removeGridSet(gridsetToRemove); assertFalse(gridSetBroker.getNames().contains(gridsetToRemove)); assertNull(gridSetBroker.get(gridsetToRemove)); } | public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void testRemoveGridsetException() throws IOException { String gridsetToRemove = GWCConfigIntegrationTestData.GRIDSET_EPSG2163; try { tileLayerDispatcher.removeGridSet(gridsetToRemove); fail("Expected exception removing a gridset referenced by a layer"); } catch (IllegalStateException e) { } } | public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } | TileLayerDispatcher implements DisposableBean,
InitializingBean,
ApplicationContextAware,
ConfigurationAggregator<TileLayerConfiguration> { public synchronized void removeGridSet(String gridsetToRemove) { if (StreamSupport.stream(getLayerList().spliterator(), true) .anyMatch(g -> Objects.nonNull(g.getGridSubset(gridsetToRemove)))) { throw new IllegalStateException( "Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } TileLayerDispatcher(GridSetBroker gridSetBroker, List<TileLayerConfiguration> configs); TileLayerDispatcher(GridSetBroker gridSetBroker); boolean layerExists(final String layerName); TileLayer getTileLayer(final String layerName); int getLayerCount(); Set<String> getLayerNames(); @SuppressWarnings("unchecked") Iterable<TileLayer> getLayerList(); ServiceInformation getServiceInformation(); void setServiceInformation(ServiceInformation serviceInformation); void destroy(); synchronized void removeLayer(final String layerName); synchronized void addLayer(final TileLayer tl); synchronized void rename(final String oldName, final String newName); synchronized void modify(final TileLayer tl); TileLayerConfiguration getConfiguration(TileLayer tl); TileLayerConfiguration getConfiguration(final String tileLayerName); synchronized void addGridSet(final GridSet gridSet); synchronized void removeGridSet(String gridsetToRemove); synchronized void removeGridSetRecursive(String gridsetToRemove); @SuppressWarnings("unchecked") @Override List<? extends T> getConfigurations(Class<T> clazz); @Override void afterPropertiesSet(); @Override void setApplicationContext(ApplicationContext applicationContext); void reInit(); } |
@Test public void test() { Clock clock = EasyMock.createMock("Clock", Clock.class); EasyMock.expect(clock.millis()).andStubAnswer(() -> time); EasyMock.replay(clock); time = 0; RuntimeStats stats = new RuntimeStats(1, Arrays.asList(60), Arrays.asList("Minutes"), clock); time += 500; stats.getHTMLStats(); EasyMock.verify(clock); } | public String getHTMLStats() { long runningTime = (clock.millis() - startTime) / 1000; StringBuilder str = new StringBuilder(); str.append("<table border=\"0\" cellspacing=\"5\" class=\"stats\">"); synchronized (bytes) { if (runningTime > 0) { str.append("<tbody>"); str.append("<tr><th colspan=\"2\" scope=\"row\">Started:</th><td colspan=\"3\">"); str.append( ServletUtils.formatTimestamp(this.startTime) + " (" + formatTimeDiff(runningTime) + ") "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of requests:</th><td colspan=\"3\">" + totalRequests); str.append(" (" + totalRequests / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of untiled WMS requests:</th><td colspan=\"3\">" + totalWMS); str.append(" (" + totalWMS / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of bytes:</th><td colspan=\"3\">" + totalBytes); str.append(" (" + formatBits((totalBytes * 8.0) / (runningTime)) + ") "); str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); } else { str.append("<tbody>"); str.append( "<tr><th colspan=\"5\">Runtime stats not yet available, try again in a few seconds.</th></tr>"); str.append("<tbody>"); } str.append( "<tr><th colspan=\"2\" scope=\"row\">Cache hit ratio:</th><td colspan=\"3\">"); if (totalHits + totalMisses > 0) { double hitPercentage = (totalHits * 100.0) / (totalHits + totalMisses); int rounded = (int) Math.round(hitPercentage * 100.0); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Blank/KML/HTML:</th><td colspan=\"3\">"); if (totalRequests > 0) { if (totalHits + totalMisses == 0) { str.append("100.0% of requests"); } else { int rounded = (int) Math.round( ((totalRequests - totalHits - totalMisses - totalWMS) * 100.0) / totalRequests); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak request rate:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatRequests((peakRequests * 1.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak bandwidth:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatBits((peakBytes * 8.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th scope=\"col\">Interval</th><th scope=\"col\">Requests</th><th scope=\"col\">Rate</th><th scope=\"col\">Bytes</th><th scope=\"col\">Bandwidth</th></tr>\n"); for (int i = 0; i < intervals.length; i++) { if (runningTime < intervals[i]) { continue; } String[] requests = calculateRequests(intervals[i]); String[] bits = calculateBits(intervals[i]); str.append( "<tr><td>" + intervalDescs[i] + "</td><td>" + requests[0] + "</td><td>" + requests[1] + "</td><td>" + bits[0] + "</td><td>" + bits[1] + "</td><td>" + "</tr>\n"); } str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><td colspan=\"5\">All figures are " + pollInterval + " second(s) delayed and do not include HTTP overhead</td></tr>"); str.append( "<tr><td colspan=\"5\">The cache hit ratio does not account for metatiling</td></tr>"); str.append("</tbody>"); } return str.toString(); } | RuntimeStats { public String getHTMLStats() { long runningTime = (clock.millis() - startTime) / 1000; StringBuilder str = new StringBuilder(); str.append("<table border=\"0\" cellspacing=\"5\" class=\"stats\">"); synchronized (bytes) { if (runningTime > 0) { str.append("<tbody>"); str.append("<tr><th colspan=\"2\" scope=\"row\">Started:</th><td colspan=\"3\">"); str.append( ServletUtils.formatTimestamp(this.startTime) + " (" + formatTimeDiff(runningTime) + ") "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of requests:</th><td colspan=\"3\">" + totalRequests); str.append(" (" + totalRequests / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of untiled WMS requests:</th><td colspan=\"3\">" + totalWMS); str.append(" (" + totalWMS / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of bytes:</th><td colspan=\"3\">" + totalBytes); str.append(" (" + formatBits((totalBytes * 8.0) / (runningTime)) + ") "); str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); } else { str.append("<tbody>"); str.append( "<tr><th colspan=\"5\">Runtime stats not yet available, try again in a few seconds.</th></tr>"); str.append("<tbody>"); } str.append( "<tr><th colspan=\"2\" scope=\"row\">Cache hit ratio:</th><td colspan=\"3\">"); if (totalHits + totalMisses > 0) { double hitPercentage = (totalHits * 100.0) / (totalHits + totalMisses); int rounded = (int) Math.round(hitPercentage * 100.0); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Blank/KML/HTML:</th><td colspan=\"3\">"); if (totalRequests > 0) { if (totalHits + totalMisses == 0) { str.append("100.0% of requests"); } else { int rounded = (int) Math.round( ((totalRequests - totalHits - totalMisses - totalWMS) * 100.0) / totalRequests); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak request rate:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatRequests((peakRequests * 1.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak bandwidth:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatBits((peakBytes * 8.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th scope=\"col\">Interval</th><th scope=\"col\">Requests</th><th scope=\"col\">Rate</th><th scope=\"col\">Bytes</th><th scope=\"col\">Bandwidth</th></tr>\n"); for (int i = 0; i < intervals.length; i++) { if (runningTime < intervals[i]) { continue; } String[] requests = calculateRequests(intervals[i]); String[] bits = calculateBits(intervals[i]); str.append( "<tr><td>" + intervalDescs[i] + "</td><td>" + requests[0] + "</td><td>" + requests[1] + "</td><td>" + bits[0] + "</td><td>" + bits[1] + "</td><td>" + "</tr>\n"); } str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><td colspan=\"5\">All figures are " + pollInterval + " second(s) delayed and do not include HTTP overhead</td></tr>"); str.append( "<tr><td colspan=\"5\">The cache hit ratio does not account for metatiling</td></tr>"); str.append("</tbody>"); } return str.toString(); } } | RuntimeStats { public String getHTMLStats() { long runningTime = (clock.millis() - startTime) / 1000; StringBuilder str = new StringBuilder(); str.append("<table border=\"0\" cellspacing=\"5\" class=\"stats\">"); synchronized (bytes) { if (runningTime > 0) { str.append("<tbody>"); str.append("<tr><th colspan=\"2\" scope=\"row\">Started:</th><td colspan=\"3\">"); str.append( ServletUtils.formatTimestamp(this.startTime) + " (" + formatTimeDiff(runningTime) + ") "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of requests:</th><td colspan=\"3\">" + totalRequests); str.append(" (" + totalRequests / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of untiled WMS requests:</th><td colspan=\"3\">" + totalWMS); str.append(" (" + totalWMS / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of bytes:</th><td colspan=\"3\">" + totalBytes); str.append(" (" + formatBits((totalBytes * 8.0) / (runningTime)) + ") "); str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); } else { str.append("<tbody>"); str.append( "<tr><th colspan=\"5\">Runtime stats not yet available, try again in a few seconds.</th></tr>"); str.append("<tbody>"); } str.append( "<tr><th colspan=\"2\" scope=\"row\">Cache hit ratio:</th><td colspan=\"3\">"); if (totalHits + totalMisses > 0) { double hitPercentage = (totalHits * 100.0) / (totalHits + totalMisses); int rounded = (int) Math.round(hitPercentage * 100.0); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Blank/KML/HTML:</th><td colspan=\"3\">"); if (totalRequests > 0) { if (totalHits + totalMisses == 0) { str.append("100.0% of requests"); } else { int rounded = (int) Math.round( ((totalRequests - totalHits - totalMisses - totalWMS) * 100.0) / totalRequests); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak request rate:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatRequests((peakRequests * 1.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak bandwidth:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatBits((peakBytes * 8.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th scope=\"col\">Interval</th><th scope=\"col\">Requests</th><th scope=\"col\">Rate</th><th scope=\"col\">Bytes</th><th scope=\"col\">Bandwidth</th></tr>\n"); for (int i = 0; i < intervals.length; i++) { if (runningTime < intervals[i]) { continue; } String[] requests = calculateRequests(intervals[i]); String[] bits = calculateBits(intervals[i]); str.append( "<tr><td>" + intervalDescs[i] + "</td><td>" + requests[0] + "</td><td>" + requests[1] + "</td><td>" + bits[0] + "</td><td>" + bits[1] + "</td><td>" + "</tr>\n"); } str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><td colspan=\"5\">All figures are " + pollInterval + " second(s) delayed and do not include HTTP overhead</td></tr>"); str.append( "<tr><td colspan=\"5\">The cache hit ratio does not account for metatiling</td></tr>"); str.append("</tbody>"); } return str.toString(); } RuntimeStats(int pollInterval, List<Integer> intervals, List<String> intervalDescs); RuntimeStats(
int pollInterval, List<Integer> intervals, List<String> intervalDescs, Clock clock); } | RuntimeStats { public String getHTMLStats() { long runningTime = (clock.millis() - startTime) / 1000; StringBuilder str = new StringBuilder(); str.append("<table border=\"0\" cellspacing=\"5\" class=\"stats\">"); synchronized (bytes) { if (runningTime > 0) { str.append("<tbody>"); str.append("<tr><th colspan=\"2\" scope=\"row\">Started:</th><td colspan=\"3\">"); str.append( ServletUtils.formatTimestamp(this.startTime) + " (" + formatTimeDiff(runningTime) + ") "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of requests:</th><td colspan=\"3\">" + totalRequests); str.append(" (" + totalRequests / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of untiled WMS requests:</th><td colspan=\"3\">" + totalWMS); str.append(" (" + totalWMS / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of bytes:</th><td colspan=\"3\">" + totalBytes); str.append(" (" + formatBits((totalBytes * 8.0) / (runningTime)) + ") "); str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); } else { str.append("<tbody>"); str.append( "<tr><th colspan=\"5\">Runtime stats not yet available, try again in a few seconds.</th></tr>"); str.append("<tbody>"); } str.append( "<tr><th colspan=\"2\" scope=\"row\">Cache hit ratio:</th><td colspan=\"3\">"); if (totalHits + totalMisses > 0) { double hitPercentage = (totalHits * 100.0) / (totalHits + totalMisses); int rounded = (int) Math.round(hitPercentage * 100.0); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Blank/KML/HTML:</th><td colspan=\"3\">"); if (totalRequests > 0) { if (totalHits + totalMisses == 0) { str.append("100.0% of requests"); } else { int rounded = (int) Math.round( ((totalRequests - totalHits - totalMisses - totalWMS) * 100.0) / totalRequests); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak request rate:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatRequests((peakRequests * 1.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak bandwidth:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatBits((peakBytes * 8.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th scope=\"col\">Interval</th><th scope=\"col\">Requests</th><th scope=\"col\">Rate</th><th scope=\"col\">Bytes</th><th scope=\"col\">Bandwidth</th></tr>\n"); for (int i = 0; i < intervals.length; i++) { if (runningTime < intervals[i]) { continue; } String[] requests = calculateRequests(intervals[i]); String[] bits = calculateBits(intervals[i]); str.append( "<tr><td>" + intervalDescs[i] + "</td><td>" + requests[0] + "</td><td>" + requests[1] + "</td><td>" + bits[0] + "</td><td>" + bits[1] + "</td><td>" + "</tr>\n"); } str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><td colspan=\"5\">All figures are " + pollInterval + " second(s) delayed and do not include HTTP overhead</td></tr>"); str.append( "<tr><td colspan=\"5\">The cache hit ratio does not account for metatiling</td></tr>"); str.append("</tbody>"); } return str.toString(); } RuntimeStats(int pollInterval, List<Integer> intervals, List<String> intervalDescs); RuntimeStats(
int pollInterval, List<Integer> intervals, List<String> intervalDescs, Clock clock); void start(); void destroy(); void log(int size, CacheResult cacheResult); String getHTMLStats(); } | RuntimeStats { public String getHTMLStats() { long runningTime = (clock.millis() - startTime) / 1000; StringBuilder str = new StringBuilder(); str.append("<table border=\"0\" cellspacing=\"5\" class=\"stats\">"); synchronized (bytes) { if (runningTime > 0) { str.append("<tbody>"); str.append("<tr><th colspan=\"2\" scope=\"row\">Started:</th><td colspan=\"3\">"); str.append( ServletUtils.formatTimestamp(this.startTime) + " (" + formatTimeDiff(runningTime) + ") "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of requests:</th><td colspan=\"3\">" + totalRequests); str.append(" (" + totalRequests / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of untiled WMS requests:</th><td colspan=\"3\">" + totalWMS); str.append(" (" + totalWMS / (runningTime) + "/s ) "); str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Total number of bytes:</th><td colspan=\"3\">" + totalBytes); str.append(" (" + formatBits((totalBytes * 8.0) / (runningTime)) + ") "); str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); } else { str.append("<tbody>"); str.append( "<tr><th colspan=\"5\">Runtime stats not yet available, try again in a few seconds.</th></tr>"); str.append("<tbody>"); } str.append( "<tr><th colspan=\"2\" scope=\"row\">Cache hit ratio:</th><td colspan=\"3\">"); if (totalHits + totalMisses > 0) { double hitPercentage = (totalHits * 100.0) / (totalHits + totalMisses); int rounded = (int) Math.round(hitPercentage * 100.0); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Blank/KML/HTML:</th><td colspan=\"3\">"); if (totalRequests > 0) { if (totalHits + totalMisses == 0) { str.append("100.0% of requests"); } else { int rounded = (int) Math.round( ((totalRequests - totalHits - totalMisses - totalWMS) * 100.0) / totalRequests); int percents = rounded / 100; int decimals = rounded - percents * 100; str.append(percents + "." + decimals + "% of requests"); } } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak request rate:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatRequests((peakRequests * 1.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append( "<tr><th colspan=\"2\" scope=\"row\">Peak bandwidth:</th><td colspan=\"3\">"); if (totalRequests > 0) { str.append(formatBits((peakBytes * 8.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); } else { str.append("No data"); } str.append("</td></tr>\n"); str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><th scope=\"col\">Interval</th><th scope=\"col\">Requests</th><th scope=\"col\">Rate</th><th scope=\"col\">Bytes</th><th scope=\"col\">Bandwidth</th></tr>\n"); for (int i = 0; i < intervals.length; i++) { if (runningTime < intervals[i]) { continue; } String[] requests = calculateRequests(intervals[i]); String[] bits = calculateBits(intervals[i]); str.append( "<tr><td>" + intervalDescs[i] + "</td><td>" + requests[0] + "</td><td>" + requests[1] + "</td><td>" + bits[0] + "</td><td>" + bits[1] + "</td><td>" + "</tr>\n"); } str.append("</tbody>"); str.append("<tbody>"); str.append( "<tr><td colspan=\"5\">All figures are " + pollInterval + " second(s) delayed and do not include HTTP overhead</td></tr>"); str.append( "<tr><td colspan=\"5\">The cache hit ratio does not account for metatiling</td></tr>"); str.append("</tbody>"); } return str.toString(); } RuntimeStats(int pollInterval, List<Integer> intervals, List<String> intervalDescs); RuntimeStats(
int pollInterval, List<Integer> intervals, List<String> intervalDescs, Clock clock); void start(); void destroy(); void log(int size, CacheResult cacheResult); String getHTMLStats(); } |
@Test public void testGetLayerAssociatedFilesWithMultipleLevels() throws Exception { String pathTemplate = Utils.buildPath( "tiles", "{format}", "{style}", "zoom-{z}", "{layer}", "ranges-{x}-{y}.sqlite"); File fileAsiaA = createFileInRootDir( Utils.buildPath( "tiles", "png", "default", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaB = createFileInRootDir( Utils.buildPath( "tiles", "png", "default", "zoom-11", "asia", "ranges-100-500.sqlite")); File fileAsiaC = createFileInRootDir( Utils.buildPath( "tiles", "png", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaD = createFileInRootDir( Utils.buildPath( "tiles", "jpeg", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAfricaA = createFileInRootDir( Utils.buildPath( "tiles", "png", "default", "zoom-10", "africa", "ranges-0-500.sqlite")); File fileAmericaA = createFileInRootDir( Utils.buildPath( "tiles", "png", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileAmericaB = createFileInRootDir( Utils.buildPath( "tiles", "jpeg", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileEuropeA = createFileInRootDir( Utils.buildPath( "tiles", "gif", "dark-borders", "zoom-15", "europe", "ranges-4000-500.sqlite")); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 500, 500); List<File> asiaFiles = fileManager.getFiles("asia"); assertThat(asiaFiles, containsInAnyOrder(fileAsiaA, fileAsiaB, fileAsiaC, fileAsiaD)); List<File> africaFiles = fileManager.getFiles("africa"); assertThat(africaFiles, containsInAnyOrder(fileAfricaA)); List<File> americaFiles = fileManager.getFiles("america"); assertThat(americaFiles, containsInAnyOrder(fileAmericaA, fileAmericaB)); List<File> europeFiles = fileManager.getFiles("europe"); assertThat(europeFiles, containsInAnyOrder(fileEuropeA)); } | List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } |
@Test public void testGetLayerAssociatedFilesWithNoLayer() throws Exception { String pathTemplate = Utils.buildPath("tiles", "{z}", "tiles-{x}.sqlite"); File fileA = createFileInRootDir(Utils.buildPath("tiles", "10", "tiles-0.sqlite")); File fileB = createFileInRootDir(Utils.buildPath("tiles", "10", "tiles-500.sqlite")); File fileC = createFileInRootDir(Utils.buildPath("tiles", "11", "tiles-0.sqlite")); File fileD = createFileInRootDir(Utils.buildPath("tiles", "11", "tiles-500.sqlite")); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 1000, 1000); List<File> filesA = fileManager.getFiles((String) null); assertThat(filesA, containsInAnyOrder(fileA, fileB, fileC, fileD)); List<File> filesB = fileManager.getFiles("something"); assertThat(filesB, containsInAnyOrder(fileA, fileB, fileC, fileD)); } | List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } |
@Test public void testLayerAssociatedFilesWithOnlyOneLevel() throws Exception { String pathTemplate = "{layer}.sqlite"; File asiaFile = createFileInRootDir("asia.sqlite"); File americaFile = createFileInRootDir("america.sqlite"); File africaFile = createFileInRootDir("africa.sqlite"); File australiaFile = createFileInRootDir("australia.sqlite"); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 1000, 1000); List<File> asiaFiles = fileManager.getFiles("asia"); assertThat(asiaFiles, containsInAnyOrder(asiaFile)); List<File> americaFiles = fileManager.getFiles("america"); assertThat(americaFiles, containsInAnyOrder(americaFile)); List<File> africaFiles = fileManager.getFiles("africa"); assertThat(africaFiles, containsInAnyOrder(africaFile)); List<File> australiaFiles = fileManager.getFiles("australia"); assertThat(australiaFiles, containsInAnyOrder(australiaFile)); } | List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } |
@Test public void testGetGridSetAndLayerAssociatedFiles() throws Exception { String pathTemplate = Utils.buildPath( "tiles", "{grid}", "{format}", "{style}", "zoom-{z}", "{layer}", "ranges-{x}-{y}.sqlite"); File fileAsiaGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "png", "default", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaGrid2B = createFileInRootDir( Utils.buildPath( "tiles", "grid2", "png", "default", "zoom-11", "asia", "ranges-100-500.sqlite")); File fileAsiaGrid3C = createFileInRootDir( Utils.buildPath( "tiles", "grid3", "png", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAsiaGrid3D = createFileInRootDir( Utils.buildPath( "tiles", "grid3", "jpeg", "dark-borders", "zoom-10", "asia", "ranges-0-500.sqlite")); File fileAfricaGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "png", "default", "zoom-10", "africa", "ranges-0-500.sqlite")); File fileAmericaGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "png", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileAmericaGrid2B = createFileInRootDir( Utils.buildPath( "tiles", "grid2", "jpeg", "dark-borders", "zoom-10", "america", "ranges-0-500.sqlite")); File fileEuropeGrid1A = createFileInRootDir( Utils.buildPath( "tiles", "grid1", "gif", "dark-borders", "zoom-15", "europe", "ranges-4000-500.sqlite")); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 500, 500); List<File> asiaFilesGrid1 = fileManager.getFiles("asia", "grid1"); assertThat(asiaFilesGrid1, containsInAnyOrder(fileAsiaGrid1A)); List<File> asiaFilesGrid2 = fileManager.getFiles("asia", "grid2"); assertThat(asiaFilesGrid2, containsInAnyOrder(fileAsiaGrid2B)); List<File> asiaFilesGrid3 = fileManager.getFiles("asia", "grid3"); assertThat(asiaFilesGrid3, containsInAnyOrder(fileAsiaGrid3C, fileAsiaGrid3D)); List<File> africaFilesGrid1 = fileManager.getFiles("africa", "grid1"); assertThat(africaFilesGrid1, containsInAnyOrder(fileAfricaGrid1A)); List<File> americaFilesGrid1 = fileManager.getFiles("america", "grid1"); assertThat(americaFilesGrid1, containsInAnyOrder(fileAmericaGrid1A)); List<File> americaFilesGrid2 = fileManager.getFiles("america", "grid2"); assertThat(americaFilesGrid2, containsInAnyOrder(fileAmericaGrid2B)); List<File> europeFilesGrid1 = fileManager.getFiles("europe", "grid1"); assertThat(europeFilesGrid1, containsInAnyOrder(fileEuropeGrid1A)); } | List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } | FileManager { List<File> getFiles(String layerName) { String[] pathBuilderCopy = getPathBuilderCopy(); if (replaceLayerName.first) pathBuilderCopy[replaceLayerName.second] = layerName; return getFiles(pathBuilderCopy); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } |
@Test public void testPathTemplateWithTileObject() throws Exception { TileObject tile = TileObject.createCompleteTileObject( "africa", new long[] {7050, 5075, 11}, "wgs84", "jpeg", tuplesToMap(tuple("style", "dark borders"), tuple("background", "blue")), null); String pathTemplate = Utils.buildPath( "{format}-tiles", "{grid}", "{layer}-{style}", "zoom-{z}", "ranges-{x}_{y}.sqlite"); String expectedPath = Utils.buildPath( "jpeg-tiles", "wgs84", "africa-dark_borders", "zoom-11", "ranges-7000_4000.sqlite"); FileManager fileManager = new FileManager(getRootDirectory(), pathTemplate, 2000, 1000); File file = fileManager.getFile(tile); assertThat( file.getCanonicalPath(), is(getRootDirectoryPath() + File.separator + expectedPath)); } | File getFile(TileObject tile) { if (tile.getParametersId() == null && tile.getParameters() != null) { tile.setParametersId(ParametersUtils.getId(tile.getParameters())); } return getFile( tile.getParametersId(), tile.getXYZ(), tile.getLayerName(), tile.getGridSetId(), tile.getBlobFormat(), tile.getParameters()); } | FileManager { File getFile(TileObject tile) { if (tile.getParametersId() == null && tile.getParameters() != null) { tile.setParametersId(ParametersUtils.getId(tile.getParameters())); } return getFile( tile.getParametersId(), tile.getXYZ(), tile.getLayerName(), tile.getGridSetId(), tile.getBlobFormat(), tile.getParameters()); } } | FileManager { File getFile(TileObject tile) { if (tile.getParametersId() == null && tile.getParameters() != null) { tile.setParametersId(ParametersUtils.getId(tile.getParameters())); } return getFile( tile.getParametersId(), tile.getXYZ(), tile.getLayerName(), tile.getGridSetId(), tile.getBlobFormat(), tile.getParameters()); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); } | FileManager { File getFile(TileObject tile) { if (tile.getParametersId() == null && tile.getParameters() != null) { tile.setParametersId(ParametersUtils.getId(tile.getParameters())); } return getFile( tile.getParametersId(), tile.getXYZ(), tile.getLayerName(), tile.getGridSetId(), tile.getBlobFormat(), tile.getParameters()); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } | FileManager { File getFile(TileObject tile) { if (tile.getParametersId() == null && tile.getParameters() != null) { tile.setParametersId(ParametersUtils.getId(tile.getParameters())); } return getFile( tile.getParametersId(), tile.getXYZ(), tile.getLayerName(), tile.getGridSetId(), tile.getBlobFormat(), tile.getParameters()); } FileManager(
File rootDirectory, String pathTemplate, long rowRangeCount, long columnRangeCount); static String normalizePathValue(String value); } |
@Test public void testProxyRequestDefaultWhitelistRestrictedByFilter() throws Exception { SecurityDispatcher secDisp = mock(SecurityDispatcher.class); when(secDisp.isSecurityEnabled()).thenReturn(true); GeoWebCacheDispatcher gwcd = mock(GeoWebCacheDispatcher.class); when(gwcd.getServletPrefix()).thenReturn(null); String layerName = "mockLayer"; TestLayer tileLayer = mock(TestLayer.class); when(tld.getTileLayer(layerName)).thenReturn(tileLayer); service = new WMSService(sb, tld, mock(RuntimeStats.class), new NullURLMangler(), gwcd); service.setSecurityDispatcher(secDisp); doThrow(new SecurityException()).when(secDisp).checkSecurity(Mockito.any()); testProxyRequestPrevented(secDisp, layerName, tileLayer, "GetLegendGraphic"); } | public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); } | WMSService extends Service { public void setSecurityDispatcher(SecurityDispatcher securityDispatcher) { this.securityDispatcher = securityDispatcher; } protected WMSService(); WMSService(StorageBroker sb, TileLayerDispatcher tld, RuntimeStats stats); WMSService(
StorageBroker sb,
TileLayerDispatcher tld,
RuntimeStats stats,
URLMangler urlMangler,
GeoWebCacheDispatcher controller); @Override ConveyorTile getConveyor(HttpServletRequest request, HttpServletResponse response); void handleRequest(Conveyor conv); void setFullWMS(String trueFalse); void setProxyRequests(String trueFalse); void setProxyNonTiledRequests(String trueFalse); void setHintsConfig(String hintsConfig); void setUtility(WMSUtilities utility); void setSecurityDispatcher(SecurityDispatcher securityDispatcher); static final String GEOWEBCACHE_WMS_PROXY_REQUEST_WHITELIST; static final String SERVICE_WMS; } |
@Test public void shouldReturnHelloSomkiat() { Person somkiat = new Person("somkiat", "pui"); given(personRepository.findByFirstName("somkiat")) .willReturn(Optional.of(somkiat)); Hello hello = controllerWithRepository.sayHi("somkiat"); assertEquals("Hello somkiat", hello.getMessage()); } | @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> foundPerson = personRepository.findByFirstName(name); String result = foundPerson .map(person -> String.format("Hello %s", person.getFirstName())) .orElse("Data not found"); return new Hello(result); } | HelloControllerWithRepository { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> foundPerson = personRepository.findByFirstName(name); String result = foundPerson .map(person -> String.format("Hello %s", person.getFirstName())) .orElse("Data not found"); return new Hello(result); } } | HelloControllerWithRepository { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> foundPerson = personRepository.findByFirstName(name); String result = foundPerson .map(person -> String.format("Hello %s", person.getFirstName())) .orElse("Data not found"); return new Hello(result); } @Autowired HelloControllerWithRepository(PersonRepository personRepository); } | HelloControllerWithRepository { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> foundPerson = personRepository.findByFirstName(name); String result = foundPerson .map(person -> String.format("Hello %s", person.getFirstName())) .orElse("Data not found"); return new Hello(result); } @Autowired HelloControllerWithRepository(PersonRepository personRepository); @GetMapping("/hello/data/{name}") Hello sayHi(@PathVariable String name); } | HelloControllerWithRepository { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> foundPerson = personRepository.findByFirstName(name); String result = foundPerson .map(person -> String.format("Hello %s", person.getFirstName())) .orElse("Data not found"); return new Hello(result); } @Autowired HelloControllerWithRepository(PersonRepository personRepository); @GetMapping("/hello/data/{name}") Hello sayHi(@PathVariable String name); } |
@Test public void success_to_create_model_with_constructor() { Hello hello = new Hello("Somkiat"); assertEquals("Somkiat", hello.getMessage()); } | public String getMessage() { return message; } | Hello { public String getMessage() { return message; } } | Hello { public String getMessage() { return message; } Hello(String message); } | Hello { public String getMessage() { return message; } Hello(String message); String getMessage(); void setMessage(String message); } | Hello { public String getMessage() { return message; } Hello(String message); String getMessage(); void setMessage(String message); } |
@Test public void shouldReturnHelloSomkiat() { Person somkiat = new Person("somkiat", "pui"); given(personRepository.findByFirstName("somkiat")) .willReturn(Optional.of(somkiat)); Hello hello = controller.sayHi("somkiat"); assertEquals("Hello somkiat", hello.getMessage()); } | @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> person = personRepository.findByFirstName(name); String message = person.map(person1 -> String.format("Hello %s", person1.getFirstName())) .orElse("Data not found"); return new Hello(message); } | HelloWithRepositoryController { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> person = personRepository.findByFirstName(name); String message = person.map(person1 -> String.format("Hello %s", person1.getFirstName())) .orElse("Data not found"); return new Hello(message); } } | HelloWithRepositoryController { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> person = personRepository.findByFirstName(name); String message = person.map(person1 -> String.format("Hello %s", person1.getFirstName())) .orElse("Data not found"); return new Hello(message); } @Autowired HelloWithRepositoryController(PersonRepository personRepository); } | HelloWithRepositoryController { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> person = personRepository.findByFirstName(name); String message = person.map(person1 -> String.format("Hello %s", person1.getFirstName())) .orElse("Data not found"); return new Hello(message); } @Autowired HelloWithRepositoryController(PersonRepository personRepository); @GetMapping("/hello/data/{name}") Hello sayHi(@PathVariable String name); } | HelloWithRepositoryController { @GetMapping("/hello/data/{name}") public Hello sayHi(@PathVariable String name) { Optional<Person> person = personRepository.findByFirstName(name); String message = person.map(person1 -> String.format("Hello %s", person1.getFirstName())) .orElse("Data not found"); return new Hello(message); } @Autowired HelloWithRepositoryController(PersonRepository personRepository); @GetMapping("/hello/data/{name}") Hello sayHi(@PathVariable String name); } |
@Test public void shouldReturnSomkiat() { Hello hello = new Hello("somkiat"); assertEquals("somkiat", hello.getMessage()); } | public String getMessage() { return message; } | Hello { public String getMessage() { return message; } } | Hello { public String getMessage() { return message; } Hello(String message); } | Hello { public String getMessage() { return message; } Hello(String message); String getMessage(); } | Hello { public String getMessage() { return message; } Hello(String message); String getMessage(); } |
@Test public void lambdaVariant() { LambdaRecommendations recommendations = new LambdaRecommendations(makePurchases()); Map<Integer, List<Integer>> results = recommendations.calculateRecommendations(); assertTrue("product 5 is similar to 4", recommendations.alsoBought(4, 1, results).contains(5)); assertTrue("product 4 is similar to 5", recommendations.alsoBought(5, 1, results).contains(4)); } | public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } void setPurchases(Purchases purchases); Map<Integer, List<Integer>> calculateRecommendations(int reps); MutableMap<Integer, MutableList<Integer>> timeGSRecommendations(int reps); } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } void setPurchases(Purchases purchases); Map<Integer, List<Integer>> calculateRecommendations(int reps); MutableMap<Integer, MutableList<Integer>> timeGSRecommendations(int reps); } |
@Test public void imperativeVariant() { ImperativeRecommendations recommendations = new ImperativeRecommendations(makePurchases()); Map<Integer, List<Integer>> results = recommendations.calculateRecommendations(); List<Integer> similarTo4 = recommendations.alsoBought(4, 1, results); assertTrue("product 5 is similar to 4: " + similarTo4, similarTo4.contains(5)); assertTrue("product 4 is similar to 5", recommendations.alsoBought(5, 1, results).contains(4)); } | public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } void setPurchases(Purchases purchases); Map<Integer, List<Integer>> calculateRecommendations(int reps); MutableMap<Integer, MutableList<Integer>> timeGSRecommendations(int reps); } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } void setPurchases(Purchases purchases); Map<Integer, List<Integer>> calculateRecommendations(int reps); MutableMap<Integer, MutableList<Integer>> timeGSRecommendations(int reps); } |
@Ignore @Test public void gsVariant() { GSLambdaRecommendations recommendations = new GSLambdaRecommendations(makePurchases()); MutableMap<Integer, MutableList<Integer>> results = recommendations.calculateRecommendations(); Assert.assertEquals(4, results.get(5).get(0).intValue()); Assert.assertEquals(5, results.get(4).get(0).intValue()); } | public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } void setPurchases(Purchases purchases); Map<Integer, List<Integer>> calculateRecommendations(int reps); MutableMap<Integer, MutableList<Integer>> timeGSRecommendations(int reps); } | Recommendations extends SimpleBenchmark { public Map<Integer, List<Integer>> calculateRecommendations(int reps) { Map<Integer, List<Integer>> results = null; for (int i = 0; i < reps; i++) { results = lambdaRecommendations.calculateRecommendations(); } return results; } void setPurchases(Purchases purchases); Map<Integer, List<Integer>> calculateRecommendations(int reps); MutableMap<Integer, MutableList<Integer>> timeGSRecommendations(int reps); } |
@Test public void setView() { DummyView dummyView = (DummyView) dummyController.onCreateView(null, null); Assert.assertEquals(dummyController, dummyView.getController()); } | @NonNull @Override protected final View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) { U view = createView(inflater, container); view.setController(getThis()); return view; } | BaseController extends Controller { @NonNull @Override protected final View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) { U view = createView(inflater, container); view.setController(getThis()); return view; } } | BaseController extends Controller { @NonNull @Override protected final View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) { U view = createView(inflater, container); view.setController(getThis()); return view; } BaseController(); BaseController(@Nullable Bundle args); } | BaseController extends Controller { @NonNull @Override protected final View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) { U view = createView(inflater, container); view.setController(getThis()); return view; } BaseController(); BaseController(@Nullable Bundle args); } | BaseController extends Controller { @NonNull @Override protected final View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) { U view = createView(inflater, container); view.setController(getThis()); return view; } BaseController(); BaseController(@Nullable Bundle args); } |
@Test public void testServerLoginSuccess() { String email = "[email protected]"; String password = "password"; LoginResponse loginResponse = new LoginResponse(); doReturn(Observable.just(loginResponse)) .when(mMockLoginMvpInteractor) .doServerLoginApiCall(new LoginRequest .ServerLoginRequest(email, password)); mLoginPresenter.onServerLoginClick(email, password); mTestScheduler.triggerActions(); verify(mMockLoginMvpView).showLoading(); verify(mMockLoginMvpView).hideLoading(); verify(mMockLoginMvpView).openMainActivity(); } | @Override public void onServerLoginClick(String email, String password) { if (email == null || email.isEmpty()) { getMvpView().onError(R.string.empty_email); return; } if (!CommonUtils.isEmailValid(email)) { getMvpView().onError(R.string.invalid_email); return; } if (password == null || password.isEmpty()) { getMvpView().onError(R.string.empty_password); return; } getMvpView().showLoading(); getCompositeDisposable().add(getInteractor() .doServerLoginApiCall(new LoginRequest.ServerLoginRequest(email, password)) .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(new Consumer<LoginResponse>() { @Override public void accept(LoginResponse response) throws Exception { getInteractor().updateUserInfo( response.getAccessToken(), response.getUserId(), AppConstants.LoggedInMode.LOGGED_IN_MODE_SERVER, response.getUserName(), response.getUserEmail(), response.getGoogleProfilePicUrl()); if (!isViewAttached()) { return; } getMvpView().hideLoading(); getMvpView().openMainActivity(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!isViewAttached()) { return; } getMvpView().hideLoading(); if (throwable instanceof ANError) { ANError anError = (ANError) throwable; handleApiError(anError); } } })); } | LoginPresenter extends BasePresenter<V, I> implements LoginMvpPresenter<V, I> { @Override public void onServerLoginClick(String email, String password) { if (email == null || email.isEmpty()) { getMvpView().onError(R.string.empty_email); return; } if (!CommonUtils.isEmailValid(email)) { getMvpView().onError(R.string.invalid_email); return; } if (password == null || password.isEmpty()) { getMvpView().onError(R.string.empty_password); return; } getMvpView().showLoading(); getCompositeDisposable().add(getInteractor() .doServerLoginApiCall(new LoginRequest.ServerLoginRequest(email, password)) .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(new Consumer<LoginResponse>() { @Override public void accept(LoginResponse response) throws Exception { getInteractor().updateUserInfo( response.getAccessToken(), response.getUserId(), AppConstants.LoggedInMode.LOGGED_IN_MODE_SERVER, response.getUserName(), response.getUserEmail(), response.getGoogleProfilePicUrl()); if (!isViewAttached()) { return; } getMvpView().hideLoading(); getMvpView().openMainActivity(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!isViewAttached()) { return; } getMvpView().hideLoading(); if (throwable instanceof ANError) { ANError anError = (ANError) throwable; handleApiError(anError); } } })); } } | LoginPresenter extends BasePresenter<V, I> implements LoginMvpPresenter<V, I> { @Override public void onServerLoginClick(String email, String password) { if (email == null || email.isEmpty()) { getMvpView().onError(R.string.empty_email); return; } if (!CommonUtils.isEmailValid(email)) { getMvpView().onError(R.string.invalid_email); return; } if (password == null || password.isEmpty()) { getMvpView().onError(R.string.empty_password); return; } getMvpView().showLoading(); getCompositeDisposable().add(getInteractor() .doServerLoginApiCall(new LoginRequest.ServerLoginRequest(email, password)) .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(new Consumer<LoginResponse>() { @Override public void accept(LoginResponse response) throws Exception { getInteractor().updateUserInfo( response.getAccessToken(), response.getUserId(), AppConstants.LoggedInMode.LOGGED_IN_MODE_SERVER, response.getUserName(), response.getUserEmail(), response.getGoogleProfilePicUrl()); if (!isViewAttached()) { return; } getMvpView().hideLoading(); getMvpView().openMainActivity(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!isViewAttached()) { return; } getMvpView().hideLoading(); if (throwable instanceof ANError) { ANError anError = (ANError) throwable; handleApiError(anError); } } })); } @Inject LoginPresenter(I mvpInteractor,
SchedulerProvider schedulerProvider,
CompositeDisposable compositeDisposable); } | LoginPresenter extends BasePresenter<V, I> implements LoginMvpPresenter<V, I> { @Override public void onServerLoginClick(String email, String password) { if (email == null || email.isEmpty()) { getMvpView().onError(R.string.empty_email); return; } if (!CommonUtils.isEmailValid(email)) { getMvpView().onError(R.string.invalid_email); return; } if (password == null || password.isEmpty()) { getMvpView().onError(R.string.empty_password); return; } getMvpView().showLoading(); getCompositeDisposable().add(getInteractor() .doServerLoginApiCall(new LoginRequest.ServerLoginRequest(email, password)) .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(new Consumer<LoginResponse>() { @Override public void accept(LoginResponse response) throws Exception { getInteractor().updateUserInfo( response.getAccessToken(), response.getUserId(), AppConstants.LoggedInMode.LOGGED_IN_MODE_SERVER, response.getUserName(), response.getUserEmail(), response.getGoogleProfilePicUrl()); if (!isViewAttached()) { return; } getMvpView().hideLoading(); getMvpView().openMainActivity(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!isViewAttached()) { return; } getMvpView().hideLoading(); if (throwable instanceof ANError) { ANError anError = (ANError) throwable; handleApiError(anError); } } })); } @Inject LoginPresenter(I mvpInteractor,
SchedulerProvider schedulerProvider,
CompositeDisposable compositeDisposable); @Override void onServerLoginClick(String email, String password); @Override void onGoogleLoginClick(); @Override void onFacebookLoginClick(); } | LoginPresenter extends BasePresenter<V, I> implements LoginMvpPresenter<V, I> { @Override public void onServerLoginClick(String email, String password) { if (email == null || email.isEmpty()) { getMvpView().onError(R.string.empty_email); return; } if (!CommonUtils.isEmailValid(email)) { getMvpView().onError(R.string.invalid_email); return; } if (password == null || password.isEmpty()) { getMvpView().onError(R.string.empty_password); return; } getMvpView().showLoading(); getCompositeDisposable().add(getInteractor() .doServerLoginApiCall(new LoginRequest.ServerLoginRequest(email, password)) .subscribeOn(getSchedulerProvider().io()) .observeOn(getSchedulerProvider().ui()) .subscribe(new Consumer<LoginResponse>() { @Override public void accept(LoginResponse response) throws Exception { getInteractor().updateUserInfo( response.getAccessToken(), response.getUserId(), AppConstants.LoggedInMode.LOGGED_IN_MODE_SERVER, response.getUserName(), response.getUserEmail(), response.getGoogleProfilePicUrl()); if (!isViewAttached()) { return; } getMvpView().hideLoading(); getMvpView().openMainActivity(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (!isViewAttached()) { return; } getMvpView().hideLoading(); if (throwable instanceof ANError) { ANError anError = (ANError) throwable; handleApiError(anError); } } })); } @Inject LoginPresenter(I mvpInteractor,
SchedulerProvider schedulerProvider,
CompositeDisposable compositeDisposable); @Override void onServerLoginClick(String email, String password); @Override void onGoogleLoginClick(); @Override void onFacebookLoginClick(); } |
@Test public void getTask_requestsSingleTaskFromLocalDataSource() { mTasksRepository.getTask(TASK_TITLE, mGetTaskCallback); verify(mTasksLocalDataSource).getTask(eq(TASK_TITLE), any( TasksDataSource.GetTaskCallback.class)); } | @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } @Inject TasksRepository(@Remote TasksDataSource tasksRemoteDataSource,
@Local TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } @Inject TasksRepository(@Remote TasksDataSource tasksRemoteDataSource,
@Local TasksDataSource tasksLocalDataSource); @Override void getTasks(@NonNull final LoadTasksCallback callback); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } @Inject TasksRepository(@Remote TasksDataSource tasksRemoteDataSource,
@Local TasksDataSource tasksLocalDataSource); @Override void getTasks(@NonNull final LoadTasksCallback callback); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTaskWithBothDataSourcesUnavailable_firesOnDataUnavailable() { final String taskId = "123"; mTasksRepository.getTask(taskId, mGetTaskCallback); setTaskNotAvailable(mTasksLocalDataSource, taskId); setTaskNotAvailable(mTasksRemoteDataSource, taskId); verify(mGetTaskCallback).onDataNotAvailable(); } | @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } @Inject TasksRepository(@Remote TasksDataSource tasksRemoteDataSource,
@Local TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } @Inject TasksRepository(@Remote TasksDataSource tasksRemoteDataSource,
@Local TasksDataSource tasksLocalDataSource); @Override void getTasks(@NonNull final LoadTasksCallback callback); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback) { checkNotNull(taskId); checkNotNull(callback); Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { callback.onTaskLoaded(cachedTask); return; } mTasksLocalDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { mTasksRemoteDataSource.getTask(taskId, new GetTaskCallback() { @Override public void onTaskLoaded(Task task) { if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); callback.onTaskLoaded(task); } @Override public void onDataNotAvailable() { callback.onDataNotAvailable(); } }); } }); } @Inject TasksRepository(@Remote TasksDataSource tasksRemoteDataSource,
@Local TasksDataSource tasksLocalDataSource); @Override void getTasks(@NonNull final LoadTasksCallback callback); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override void getTask(@NonNull final String taskId, @NonNull final GetTaskCallback callback); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void clickOnFab_ShowsAddTaskUi() { mTasksPresenter.addNewTask(); verify(mTasksView).showAddTask(); } | @Override public void addNewTask() { if (mTasksView != null) { mTasksView.showAddTask(); } } | TasksPresenter implements TasksContract.Presenter { @Override public void addNewTask() { if (mTasksView != null) { mTasksView.showAddTask(); } } } | TasksPresenter implements TasksContract.Presenter { @Override public void addNewTask() { if (mTasksView != null) { mTasksView.showAddTask(); } } @Inject TasksPresenter(TasksRepository tasksRepository); } | TasksPresenter implements TasksContract.Presenter { @Override public void addNewTask() { if (mTasksView != null) { mTasksView.showAddTask(); } } @Inject TasksPresenter(TasksRepository tasksRepository); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override TasksFilterType getFiltering(); @Override void setFiltering(TasksFilterType requestType); @Override void takeView(TasksContract.View view); @Override void dropView(); } | TasksPresenter implements TasksContract.Presenter { @Override public void addNewTask() { if (mTasksView != null) { mTasksView.showAddTask(); } } @Inject TasksPresenter(TasksRepository tasksRepository); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override TasksFilterType getFiltering(); @Override void setFiltering(TasksFilterType requestType); @Override void takeView(TasksContract.View view); @Override void dropView(); } |
@Test public void clickOnTask_ShowsDetailUi() { Task requestedTask = new Task("Details Requested", "For this task"); mTasksPresenter.openTaskDetails(requestedTask); verify(mTasksView).showTaskDetailsUi(any(String.class)); } | @Override public void openTaskDetails(@NonNull Task requestedTask) { checkNotNull(requestedTask, "requestedTask cannot be null!"); if (mTasksView != null) { mTasksView.showTaskDetailsUi(requestedTask.getId()); } } | TasksPresenter implements TasksContract.Presenter { @Override public void openTaskDetails(@NonNull Task requestedTask) { checkNotNull(requestedTask, "requestedTask cannot be null!"); if (mTasksView != null) { mTasksView.showTaskDetailsUi(requestedTask.getId()); } } } | TasksPresenter implements TasksContract.Presenter { @Override public void openTaskDetails(@NonNull Task requestedTask) { checkNotNull(requestedTask, "requestedTask cannot be null!"); if (mTasksView != null) { mTasksView.showTaskDetailsUi(requestedTask.getId()); } } @Inject TasksPresenter(TasksRepository tasksRepository); } | TasksPresenter implements TasksContract.Presenter { @Override public void openTaskDetails(@NonNull Task requestedTask) { checkNotNull(requestedTask, "requestedTask cannot be null!"); if (mTasksView != null) { mTasksView.showTaskDetailsUi(requestedTask.getId()); } } @Inject TasksPresenter(TasksRepository tasksRepository); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override TasksFilterType getFiltering(); @Override void setFiltering(TasksFilterType requestType); @Override void takeView(TasksContract.View view); @Override void dropView(); } | TasksPresenter implements TasksContract.Presenter { @Override public void openTaskDetails(@NonNull Task requestedTask) { checkNotNull(requestedTask, "requestedTask cannot be null!"); if (mTasksView != null) { mTasksView.showTaskDetailsUi(requestedTask.getId()); } } @Inject TasksPresenter(TasksRepository tasksRepository); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override TasksFilterType getFiltering(); @Override void setFiltering(TasksFilterType requestType); @Override void takeView(TasksContract.View view); @Override void dropView(); } |
@Test public void completeTask_ShowsTaskMarkedComplete() { Task task = new Task("Details Requested", "For this task"); mTasksPresenter.completeTask(task); verify(mTasksRepository).completeTask(task); verify(mTasksView).showTaskMarkedComplete(); } | @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); if (mTasksView != null) { mTasksView.showTaskMarkedComplete(); } loadTasks(false, false); } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); if (mTasksView != null) { mTasksView.showTaskMarkedComplete(); } loadTasks(false, false); } } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); if (mTasksView != null) { mTasksView.showTaskMarkedComplete(); } loadTasks(false, false); } @Inject TasksPresenter(TasksRepository tasksRepository); } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); if (mTasksView != null) { mTasksView.showTaskMarkedComplete(); } loadTasks(false, false); } @Inject TasksPresenter(TasksRepository tasksRepository); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override TasksFilterType getFiltering(); @Override void setFiltering(TasksFilterType requestType); @Override void takeView(TasksContract.View view); @Override void dropView(); } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); if (mTasksView != null) { mTasksView.showTaskMarkedComplete(); } loadTasks(false, false); } @Inject TasksPresenter(TasksRepository tasksRepository); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override TasksFilterType getFiltering(); @Override void setFiltering(TasksFilterType requestType); @Override void takeView(TasksContract.View view); @Override void dropView(); } |
@Test public void getActiveTaskFromRepositoryAndLoadIntoView() { mTaskDetailPresenter = new TaskDetailPresenter( ACTIVE_TASK.getId(), mTasksRepository); mTaskDetailPresenter.takeView(mTaskDetailView); verify(mTasksRepository).getTask(eq(ACTIVE_TASK.getId()), mGetTaskCallbackCaptor.capture()); InOrder inOrder = inOrder(mTaskDetailView); inOrder.verify(mTaskDetailView).setLoadingIndicator(true); mGetTaskCallbackCaptor.getValue().onTaskLoaded(ACTIVE_TASK); inOrder.verify(mTaskDetailView).setLoadingIndicator(false); verify(mTaskDetailView).showTitle(TITLE_TEST); verify(mTaskDetailView).showDescription(DESCRIPTION_TEST); verify(mTaskDetailView).showCompletionStatus(false); } | @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } |
@Test public void getCompletedTaskFromRepositoryAndLoadIntoView() { mTaskDetailPresenter = new TaskDetailPresenter( COMPLETED_TASK.getId(), mTasksRepository); mTaskDetailPresenter.takeView(mTaskDetailView); verify(mTasksRepository).getTask( eq(COMPLETED_TASK.getId()), mGetTaskCallbackCaptor.capture()); InOrder inOrder = inOrder(mTaskDetailView); inOrder.verify(mTaskDetailView).setLoadingIndicator(true); mGetTaskCallbackCaptor.getValue().onTaskLoaded(COMPLETED_TASK); inOrder.verify(mTaskDetailView).setLoadingIndicator(false); verify(mTaskDetailView).showTitle(TITLE_TEST); verify(mTaskDetailView).showDescription(DESCRIPTION_TEST); verify(mTaskDetailView).showCompletionStatus(true); } | @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } |
@Test public void getUnknownTaskFromRepositoryAndLoadIntoView() { mTaskDetailPresenter = new TaskDetailPresenter( INVALID_TASK_ID, mTasksRepository); mTaskDetailPresenter.takeView(mTaskDetailView); verify(mTaskDetailView).showMissingTask(); } | @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void takeView(TaskDetailContract.View taskDetailView) { mTaskDetailView = taskDetailView; openTask(); } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } |
@Test public void deleteTask() { Task task = new Task(TITLE_TEST, DESCRIPTION_TEST); mTaskDetailPresenter = new TaskDetailPresenter( task.getId(), mTasksRepository); mTaskDetailPresenter.takeView(mTaskDetailView); mTaskDetailPresenter.deleteTask(); verify(mTasksRepository).deleteTask(task.getId()); verify(mTaskDetailView).showTaskDeleted(); } | @Override public void deleteTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.deleteTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskDeleted(); } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void deleteTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.deleteTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskDeleted(); } } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void deleteTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.deleteTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskDeleted(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void deleteTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.deleteTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskDeleted(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void deleteTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.deleteTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskDeleted(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } |
@Test public void completeTask() { Task task = new Task(TITLE_TEST, DESCRIPTION_TEST); mTaskDetailPresenter = new TaskDetailPresenter( task.getId(), mTasksRepository); mTaskDetailPresenter.takeView(mTaskDetailView); mTaskDetailPresenter.completeTask(); verify(mTasksRepository).completeTask(task.getId()); verify(mTaskDetailView).showTaskMarkedComplete(); } | @Override public void completeTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.completeTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedComplete(); } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void completeTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.completeTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedComplete(); } } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void completeTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.completeTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedComplete(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void completeTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.completeTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedComplete(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void completeTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.completeTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedComplete(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } |
@Test public void activateTask() { Task task = new Task(TITLE_TEST, DESCRIPTION_TEST, true); mTaskDetailPresenter = new TaskDetailPresenter( task.getId(), mTasksRepository); mTaskDetailPresenter.takeView(mTaskDetailView); mTaskDetailPresenter.activateTask(); verify(mTasksRepository).activateTask(task.getId()); verify(mTaskDetailView).showTaskMarkedActive(); } | @Override public void activateTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.activateTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedActive(); } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void activateTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.activateTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedActive(); } } } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void activateTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.activateTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedActive(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void activateTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.activateTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedActive(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } | TaskDetailPresenter implements TaskDetailContract.Presenter { @Override public void activateTask() { if (Strings.isNullOrEmpty(mTaskId)) { if (mTaskDetailView != null) { mTaskDetailView.showMissingTask(); } return; } mTasksRepository.activateTask(mTaskId); if (mTaskDetailView != null) { mTaskDetailView.showTaskMarkedActive(); } } @Inject TaskDetailPresenter(@Nullable String taskId,
TasksRepository tasksRepository); @Override void editTask(); @Override void deleteTask(); @Override void completeTask(); @Override void activateTask(); @Override void takeView(TaskDetailContract.View taskDetailView); @Override void dropView(); } |
@Test public void getTasks_repositoryCachesAfterFirstSubscription_whenTasksAvailableInLocalStorage() { setTasksAvailable(mTasksLocalDataSource, TASKS); setTasksNotAvailable(mTasksRemoteDataSource); TestSubscriber<List<Task>> testSubscriber1 = new TestSubscriber<>(); mTasksRepository.getTasks().subscribe(testSubscriber1); TestSubscriber<List<Task>> testSubscriber2 = new TestSubscriber<>(); mTasksRepository.getTasks().subscribe(testSubscriber2); verify(mTasksRemoteDataSource).getTasks(); verify(mTasksLocalDataSource).getTasks(); assertFalse(mTasksRepository.mCacheIsDirty); testSubscriber1.assertValue(TASKS); testSubscriber2.assertValue(TASKS); } | @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTasks_repositoryCachesAfterFirstSubscription_whenTasksAvailableInRemoteStorage() { setTasksAvailable(mTasksRemoteDataSource, TASKS); setTasksNotAvailable(mTasksLocalDataSource); TestSubscriber<List<Task>> testSubscriber1 = new TestSubscriber<>(); mTasksRepository.getTasks().subscribe(testSubscriber1); TestSubscriber<List<Task>> testSubscriber2 = new TestSubscriber<>(); mTasksRepository.getTasks().subscribe(testSubscriber2); verify(mTasksRemoteDataSource).getTasks(); verify(mTasksLocalDataSource).getTasks(); assertFalse(mTasksRepository.mCacheIsDirty); testSubscriber1.assertValue(TASKS); testSubscriber2.assertValue(TASKS); } | @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTasks_requestsAllTasksFromLocalDataSource() { setTasksAvailable(mTasksLocalDataSource, TASKS); setTasksNotAvailable(mTasksRemoteDataSource); mTasksRepository.getTasks().subscribe(mTasksTestSubscriber); verify(mTasksLocalDataSource).getTasks(); mTasksTestSubscriber.assertValue(TASKS); } | @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void saveTask_savesTaskToServiceAPI() { Task newTask = new Task(TASK_TITLE, "Some Task Description"); mTasksRepository.saveTask(newTask); verify(mTasksRemoteDataSource).saveTask(newTask); verify(mTasksLocalDataSource).saveTask(newTask); assertThat(mTasksRepository.mCachedTasks.size(), is(1)); } | @Override public void saveTask(@NonNull Task task) { checkNotNull(task); mTasksRemoteDataSource.saveTask(task); mTasksLocalDataSource.saveTask(task); if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); } | TasksRepository implements TasksDataSource { @Override public void saveTask(@NonNull Task task) { checkNotNull(task); mTasksRemoteDataSource.saveTask(task); mTasksLocalDataSource.saveTask(task); if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); } } | TasksRepository implements TasksDataSource { @Override public void saveTask(@NonNull Task task) { checkNotNull(task); mTasksRemoteDataSource.saveTask(task); mTasksLocalDataSource.saveTask(task); if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public void saveTask(@NonNull Task task) { checkNotNull(task); mTasksRemoteDataSource.saveTask(task); mTasksLocalDataSource.saveTask(task); if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public void saveTask(@NonNull Task task) { checkNotNull(task); mTasksRemoteDataSource.saveTask(task); mTasksLocalDataSource.saveTask(task); if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } mCachedTasks.put(task.getId(), task); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTask_requestsSingleTaskFromLocalDataSource() { Task task = new Task(TASK_TITLE, "Some Task Description", true); Optional<Task> taskOptional = Optional.of(task); setTaskAvailable(mTasksLocalDataSource, taskOptional); setTaskNotAvailable(mTasksRemoteDataSource, taskOptional.get().getId()); TestSubscriber<Optional<Task>> testSubscriber = new TestSubscriber<>(); mTasksRepository.getTask(task.getId()).subscribe(testSubscriber); verify(mTasksLocalDataSource).getTask(eq(task.getId())); testSubscriber.assertValue(taskOptional); } | @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTask_whenDataNotLocal_fails() { Task task = new Task(TASK_TITLE, "Some Task Description", true); Optional<Task> taskOptional = Optional.of(task); setTaskAvailable(mTasksRemoteDataSource, taskOptional); setTaskNotAvailable(mTasksLocalDataSource, task.getId()); TestSubscriber<Optional<Task>> testSubscriber = new TestSubscriber<>(); mTasksRepository.getTask(task.getId()).subscribe(testSubscriber); testSubscriber.assertValue(Optional.absent()); } | @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTasksWithLocalDataSourceUnavailable_tasksAreRetrievedFromRemote() { setTasksNotAvailable(mTasksLocalDataSource); setTasksAvailable(mTasksRemoteDataSource, TASKS); mTasksRepository.getTasks().subscribe(mTasksTestSubscriber); verify(mTasksRemoteDataSource).getTasks(); mTasksTestSubscriber.assertValue(TASKS); } | @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTasksWithBothDataSourcesUnavailable_firesOnDataUnavailable() { setTasksNotAvailable(mTasksLocalDataSource); setTasksNotAvailable(mTasksRemoteDataSource); mTasksRepository.getTasks().subscribe(mTasksTestSubscriber); mTasksTestSubscriber.assertNoValues(); mTasksTestSubscriber.assertError(NoSuchElementException.class); } | @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<List<Task>> getTasks() { if (mCachedTasks != null && !mCacheIsDirty) { return Flowable.fromIterable(mCachedTasks.values()).toList().toFlowable(); } else if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<List<Task>> remoteTasks = getAndSaveRemoteTasks(); if (mCacheIsDirty) { return remoteTasks; } else { Flowable<List<Task>> localTasks = getAndCacheLocalTasks(); return Flowable.concat(localTasks, remoteTasks) .filter(tasks -> !tasks.isEmpty()) .firstOrError() .toFlowable(); } } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void getTaskWithBothDataSourcesUnavailable_firesOnError() { final String taskId = "123"; setTaskNotAvailable(mTasksLocalDataSource, taskId); setTaskNotAvailable(mTasksRemoteDataSource, taskId); TestSubscriber<Optional<Task>> testSubscriber = new TestSubscriber<>(); mTasksRepository.getTask(taskId).subscribe(testSubscriber); testSubscriber.assertValue(Optional.absent()); } | @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } | TasksRepository implements TasksDataSource { @Override public Flowable<Optional<Task>> getTask(@NonNull final String taskId) { checkNotNull(taskId); final Task cachedTask = getTaskWithId(taskId); if (cachedTask != null) { return Flowable.just(Optional.of(cachedTask)); } if (mCachedTasks == null) { mCachedTasks = new LinkedHashMap<>(); } Flowable<Optional<Task>> localTask = getTaskWithIdFromLocalRepository(taskId); Flowable<Optional<Task>> remoteTask = mTasksRemoteDataSource .getTask(taskId) .doOnNext(taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); mTasksLocalDataSource.saveTask(task); mCachedTasks.put(task.getId(), task); } }); return Flowable.concat(localTask, remoteTask) .firstElement() .toFlowable(); } private TasksRepository(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static TasksRepository getInstance(@NonNull TasksDataSource tasksRemoteDataSource,
@NonNull TasksDataSource tasksLocalDataSource); static void destroyInstance(); @Override Flowable<List<Task>> getTasks(); @Override void saveTask(@NonNull Task task); @Override void completeTask(@NonNull Task task); @Override void completeTask(@NonNull String taskId); @Override void activateTask(@NonNull Task task); @Override void activateTask(@NonNull String taskId); @Override void clearCompletedTasks(); @Override Flowable<Optional<Task>> getTask(@NonNull final String taskId); @Override void refreshTasks(); @Override void deleteAllTasks(); @Override void deleteTask(@NonNull String taskId); } |
@Test public void completeTask_ShowsTaskMarkedComplete() { Task task = new Task("Details Requested", "For this task"); when(mTasksRepository.getTasks()).thenReturn(Flowable.empty()); mTasksPresenter.completeTask(task); verify(mTasksRepository).completeTask(task); verify(mTasksView).showTaskMarkedComplete(); } | @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); mTasksView.showTaskMarkedComplete(); loadTasks(false, false); } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); mTasksView.showTaskMarkedComplete(); loadTasks(false, false); } } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); mTasksView.showTaskMarkedComplete(); loadTasks(false, false); } TasksPresenter(@NonNull TasksRepository tasksRepository,
@NonNull TasksContract.View tasksView,
@NonNull BaseSchedulerProvider schedulerProvider); } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); mTasksView.showTaskMarkedComplete(); loadTasks(false, false); } TasksPresenter(@NonNull TasksRepository tasksRepository,
@NonNull TasksContract.View tasksView,
@NonNull BaseSchedulerProvider schedulerProvider); @Override void subscribe(); @Override void unsubscribe(); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override void setFiltering(@NonNull TasksFilterType requestType); @Override TasksFilterType getFiltering(); } | TasksPresenter implements TasksContract.Presenter { @Override public void completeTask(@NonNull Task completedTask) { checkNotNull(completedTask, "completedTask cannot be null!"); mTasksRepository.completeTask(completedTask); mTasksView.showTaskMarkedComplete(); loadTasks(false, false); } TasksPresenter(@NonNull TasksRepository tasksRepository,
@NonNull TasksContract.View tasksView,
@NonNull BaseSchedulerProvider schedulerProvider); @Override void subscribe(); @Override void unsubscribe(); @Override void result(int requestCode, int resultCode); @Override void loadTasks(boolean forceUpdate); @Override void addNewTask(); @Override void openTaskDetails(@NonNull Task requestedTask); @Override void completeTask(@NonNull Task completedTask); @Override void activateTask(@NonNull Task activeTask); @Override void clearCompletedTasks(); @Override void setFiltering(@NonNull TasksFilterType requestType); @Override TasksFilterType getFiltering(); } |
@Test public void populateTask_callsRepoAndUpdatesViewOnAbsentTask() { Task testTask = new Task("TITLE", "DESCRIPTION"); when(mTasksRepository.getTask(testTask.getId())).thenReturn(Flowable.just(Optional.absent())); mAddEditTaskPresenter = new AddEditTaskPresenter(testTask.getId(), mTasksRepository, mAddEditTaskView, true, mSchedulerProvider); mAddEditTaskPresenter.populateTask(); verify(mTasksRepository).getTask(eq(testTask.getId())); verify(mAddEditTaskView).showEmptyTaskError(); verify(mAddEditTaskView, never()).setTitle(testTask.getTitle()); verify(mAddEditTaskView, never()).setDescription(testTask.getDescription()); } | @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } AddEditTaskPresenter(@Nullable String taskId, @NonNull TasksDataSource tasksRepository,
@NonNull AddEditTaskContract.View addTaskView, boolean shouldLoadDataFromRepo,
@NonNull BaseSchedulerProvider schedulerProvider); } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } AddEditTaskPresenter(@Nullable String taskId, @NonNull TasksDataSource tasksRepository,
@NonNull AddEditTaskContract.View addTaskView, boolean shouldLoadDataFromRepo,
@NonNull BaseSchedulerProvider schedulerProvider); @Override void subscribe(); @Override void unsubscribe(); @Override void saveTask(String title, String description); @Override void populateTask(); @Override boolean isDataMissing(); } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } AddEditTaskPresenter(@Nullable String taskId, @NonNull TasksDataSource tasksRepository,
@NonNull AddEditTaskContract.View addTaskView, boolean shouldLoadDataFromRepo,
@NonNull BaseSchedulerProvider schedulerProvider); @Override void subscribe(); @Override void unsubscribe(); @Override void saveTask(String title, String description); @Override void populateTask(); @Override boolean isDataMissing(); } |
@Test public void populateTask_callsRepoAndUpdatesViewOnError() { Task testTask = new Task("TITLE", "DESCRIPTION"); when(mTasksRepository.getTask(testTask.getId())).thenReturn(Flowable.error(new Throwable("Some error"))); mAddEditTaskPresenter = new AddEditTaskPresenter(testTask.getId(), mTasksRepository, mAddEditTaskView, true, mSchedulerProvider); mAddEditTaskPresenter.populateTask(); verify(mTasksRepository).getTask(eq(testTask.getId())); verify(mAddEditTaskView).showEmptyTaskError(); verify(mAddEditTaskView, never()).setTitle(testTask.getTitle()); verify(mAddEditTaskView, never()).setDescription(testTask.getDescription()); } | @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } AddEditTaskPresenter(@Nullable String taskId, @NonNull TasksDataSource tasksRepository,
@NonNull AddEditTaskContract.View addTaskView, boolean shouldLoadDataFromRepo,
@NonNull BaseSchedulerProvider schedulerProvider); } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } AddEditTaskPresenter(@Nullable String taskId, @NonNull TasksDataSource tasksRepository,
@NonNull AddEditTaskContract.View addTaskView, boolean shouldLoadDataFromRepo,
@NonNull BaseSchedulerProvider schedulerProvider); @Override void subscribe(); @Override void unsubscribe(); @Override void saveTask(String title, String description); @Override void populateTask(); @Override boolean isDataMissing(); } | AddEditTaskPresenter implements AddEditTaskContract.Presenter { @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mCompositeDisposable.add(mTasksRepository .getTask(mTaskId) .subscribeOn(mSchedulerProvider.computation()) .observeOn(mSchedulerProvider.ui()) .subscribe( taskOptional -> { if (taskOptional.isPresent()) { Task task = taskOptional.get(); if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); mIsDataMissing = false; } } else { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } }, throwable -> { if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } })); } AddEditTaskPresenter(@Nullable String taskId, @NonNull TasksDataSource tasksRepository,
@NonNull AddEditTaskContract.View addTaskView, boolean shouldLoadDataFromRepo,
@NonNull BaseSchedulerProvider schedulerProvider); @Override void subscribe(); @Override void unsubscribe(); @Override void saveTask(String title, String description); @Override void populateTask(); @Override boolean isDataMissing(); } |
@Test public void testCombineArrays() { for (int i = 0; i < 200; i++) { push("ABCDEFGH"); push("IJK"); assertEquals("ABCDE", pop(5)); assertEquals("FGHIJK", pop(6)); } } | public void push(byte[] src) { push(src, 0, src.length); } | ByteArrayDequeue { public void push(byte[] src) { push(src, 0, src.length); } } | ByteArrayDequeue { public void push(byte[] src) { push(src, 0, src.length); } ByteArrayDequeue(); ByteArrayDequeue(int initalCapacity); } | ByteArrayDequeue { public void push(byte[] src) { push(src, 0, src.length); } ByteArrayDequeue(); ByteArrayDequeue(int initalCapacity); int getRemaining(); void push(byte[] src); void push(byte[] src, int srcOffset, int srcLengthToPush); void pushLast(byte[] src); void pushLast(byte[] src, int srcOffset, int srcLengthToPush); ByteBuffer popMaximum(int maximumLengthToPop); ByteBuffer popExactly(int lengthToPop); void popExactly(byte[] into); void clear(); } | ByteArrayDequeue { public void push(byte[] src) { push(src, 0, src.length); } ByteArrayDequeue(); ByteArrayDequeue(int initalCapacity); int getRemaining(); void push(byte[] src); void push(byte[] src, int srcOffset, int srcLengthToPush); void pushLast(byte[] src); void pushLast(byte[] src, int srcOffset, int srcLengthToPush); ByteBuffer popMaximum(int maximumLengthToPop); ByteBuffer popExactly(int lengthToPop); void popExactly(byte[] into); void clear(); } |
@Test public void testGetFieldsReturnsCorrectString_forAutoValueClass() { String detectedAVFields = ClassUtils.getMethodsList(ComicVolumeInfoList.class); String actualFields = "count_of_issues,id,image,name,publisher,start_year"; assertEquals("getMethodsList method returned incorrect list!", actualFields, detectedAVFields); } | public static String getMethodsList(Class<?> type) { final String SEPARATOR = ","; final List<Method> methods = Arrays.asList(type.getDeclaredMethods()); StringBuilder result = new StringBuilder(); Collections.sort(methods, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); for (Method method : methods) { int modifiers = method.getModifiers(); if (Modifier.isAbstract(modifiers)) { result.append(method.getName()).append(SEPARATOR); } } return result.deleteCharAt(result.length() - 1).toString(); } | ClassUtils { public static String getMethodsList(Class<?> type) { final String SEPARATOR = ","; final List<Method> methods = Arrays.asList(type.getDeclaredMethods()); StringBuilder result = new StringBuilder(); Collections.sort(methods, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); for (Method method : methods) { int modifiers = method.getModifiers(); if (Modifier.isAbstract(modifiers)) { result.append(method.getName()).append(SEPARATOR); } } return result.deleteCharAt(result.length() - 1).toString(); } } | ClassUtils { public static String getMethodsList(Class<?> type) { final String SEPARATOR = ","; final List<Method> methods = Arrays.asList(type.getDeclaredMethods()); StringBuilder result = new StringBuilder(); Collections.sort(methods, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); for (Method method : methods) { int modifiers = method.getModifiers(); if (Modifier.isAbstract(modifiers)) { result.append(method.getName()).append(SEPARATOR); } } return result.deleteCharAt(result.length() - 1).toString(); } } | ClassUtils { public static String getMethodsList(Class<?> type) { final String SEPARATOR = ","; final List<Method> methods = Arrays.asList(type.getDeclaredMethods()); StringBuilder result = new StringBuilder(); Collections.sort(methods, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); for (Method method : methods) { int modifiers = method.getModifiers(); if (Modifier.isAbstract(modifiers)) { result.append(method.getName()).append(SEPARATOR); } } return result.deleteCharAt(result.length() - 1).toString(); } static String getMethodsList(Class<?> type); } | ClassUtils { public static String getMethodsList(Class<?> type) { final String SEPARATOR = ","; final List<Method> methods = Arrays.asList(type.getDeclaredMethods()); StringBuilder result = new StringBuilder(); Collections.sort(methods, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName())); for (Method method : methods) { int modifiers = method.getModifiers(); if (Modifier.isAbstract(modifiers)) { result.append(method.getName()).append(SEPARATOR); } } return result.deleteCharAt(result.length() - 1).toString(); } static String getMethodsList(Class<?> type); } |
@Test public void testGetFormattedIssueName() { assertEquals("getFormattedIssueName method returned incorrect string!", FORMATTED_NAME_FULL, IssueTextUtils.getFormattedIssueName(ISSUE_NAME, VOLUME_NAME, ISSUE_NUMBER)); assertEquals("getFormattedIssueName method returned incorrect string!", FORMATTED_NAME_SHORT, IssueTextUtils.getFormattedIssueName(null, VOLUME_NAME, ISSUE_NUMBER)); } | public static String getFormattedIssueName(String issue, String volume, int number) { String name; if (issue != null) { name = String.format(Locale.US, "%s #%d - %s", volume, number, issue); } else { name = String.format(Locale.US, "%s #%d", volume, number); } return name; } | IssueTextUtils { public static String getFormattedIssueName(String issue, String volume, int number) { String name; if (issue != null) { name = String.format(Locale.US, "%s #%d - %s", volume, number, issue); } else { name = String.format(Locale.US, "%s #%d", volume, number); } return name; } } | IssueTextUtils { public static String getFormattedIssueName(String issue, String volume, int number) { String name; if (issue != null) { name = String.format(Locale.US, "%s #%d - %s", volume, number, issue); } else { name = String.format(Locale.US, "%s #%d", volume, number); } return name; } } | IssueTextUtils { public static String getFormattedIssueName(String issue, String volume, int number) { String name; if (issue != null) { name = String.format(Locale.US, "%s #%d - %s", volume, number, issue); } else { name = String.format(Locale.US, "%s #%d", volume, number); } return name; } static String getFormattedIssueName(String issue, String volume, int number); static String getFormattedIssueTitle(String volume, int number); } | IssueTextUtils { public static String getFormattedIssueName(String issue, String volume, int number) { String name; if (issue != null) { name = String.format(Locale.US, "%s #%d - %s", volume, number, issue); } else { name = String.format(Locale.US, "%s #%d", volume, number); } return name; } static String getFormattedIssueName(String issue, String volume, int number); static String getFormattedIssueTitle(String volume, int number); } |
@Test public void testGetFormattedIssueDetailsTitle() { assertEquals("getFormattedIssueTitle method returned incorrect string!", FORMATTED_NAME_SHORT, IssueTextUtils.getFormattedIssueTitle(VOLUME_NAME, ISSUE_NUMBER)); } | public static String getFormattedIssueTitle(String volume, int number) { return String.format(Locale.US, "%s #%d", volume, number); } | IssueTextUtils { public static String getFormattedIssueTitle(String volume, int number) { return String.format(Locale.US, "%s #%d", volume, number); } } | IssueTextUtils { public static String getFormattedIssueTitle(String volume, int number) { return String.format(Locale.US, "%s #%d", volume, number); } } | IssueTextUtils { public static String getFormattedIssueTitle(String volume, int number) { return String.format(Locale.US, "%s #%d", volume, number); } static String getFormattedIssueName(String issue, String volume, int number); static String getFormattedIssueTitle(String volume, int number); } | IssueTextUtils { public static String getFormattedIssueTitle(String volume, int number) { return String.format(Locale.US, "%s #%d", volume, number); } static String getFormattedIssueName(String issue, String volume, int number); static String getFormattedIssueTitle(String volume, int number); } |
@Test public void test() { List<Schema.Field> fields = Arrays.asList( new Schema.Field(Schema.Type.ARRAY.getName(), Schema.createArray(Schema.create(Schema.Type.BOOLEAN)), null, null), new Schema.Field(Schema.Type.RECORD.getName(), Schema.createRecord(Collections.emptyList()), null, null), new Schema.Field(Schema.Type.MAP.getName(), Schema.createMap(Schema.create(Schema.Type.BOOLEAN)), null, null), new Schema.Field(Schema.Type.BOOLEAN.getName(), Schema.create(Schema.Type.BOOLEAN), null, null), new Schema.Field(Schema.Type.STRING.getName(), Schema.create(Schema.Type.STRING), null, null), new Schema.Field(Schema.Type.INT.getName(), Schema.create(Schema.Type.INT), null, null), new Schema.Field(Schema.Type.LONG.getName(), Schema.create(Schema.Type.LONG), null, null), new Schema.Field(Schema.Type.FLOAT.getName(), Schema.create(Schema.Type.FLOAT), null, null), new Schema.Field(Schema.Type.BYTES.getName(), Schema.create(Schema.Type.BYTES), null, null), new Schema.Field(Schema.Type.DOUBLE.getName(), Schema.create(Schema.Type.DOUBLE), null, null), new Schema.Field(Schema.Type.NULL.getName(), Schema.create(Schema.Type.NULL), null, null), new Schema.Field(Schema.Type.FIXED.getName(), Schema.createFixed("fixed", null, "fixed", 1), null, null), new Schema.Field(Schema.Type.ENUM.getName(), Schema.createEnum("enum", null, "namespace", Arrays.asList("Foo", "Bar")), null, null), new Schema.Field(Schema.Type.UNION.getName(), Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), Schema.create(Schema.Type.STRING))), null, null)); assertEquals(Schema.Type.values().length, fields.size()); List<String> headers = new AvroHeadersFunction().getColumns(fields); assertEquals( Stream.of("boolean", "string", "int", "long", "float", "bytes", "double", "null", "fixed", "enum", "union").sorted().collect(Collectors.toList()), headers.stream().sorted().collect(Collectors.toList())); } | List<String> getColumns(List<Schema.Field> fields) { List<String> columns = new ArrayList<>(fields.size()); for (Schema.Field field : fields) { switch (field.schema().getType()) { case RECORD: case MAP: case ARRAY: break; default: columns.add(field.name()); } } return columns; } | AvroHeadersFunction implements Function<AvroWrapper, List<String>> { List<String> getColumns(List<Schema.Field> fields) { List<String> columns = new ArrayList<>(fields.size()); for (Schema.Field field : fields) { switch (field.schema().getType()) { case RECORD: case MAP: case ARRAY: break; default: columns.add(field.name()); } } return columns; } } | AvroHeadersFunction implements Function<AvroWrapper, List<String>> { List<String> getColumns(List<Schema.Field> fields) { List<String> columns = new ArrayList<>(fields.size()); for (Schema.Field field : fields) { switch (field.schema().getType()) { case RECORD: case MAP: case ARRAY: break; default: columns.add(field.name()); } } return columns; } } | AvroHeadersFunction implements Function<AvroWrapper, List<String>> { List<String> getColumns(List<Schema.Field> fields) { List<String> columns = new ArrayList<>(fields.size()); for (Schema.Field field : fields) { switch (field.schema().getType()) { case RECORD: case MAP: case ARRAY: break; default: columns.add(field.name()); } } return columns; } @Override List<String> call(AvroWrapper avroWrapper); } | AvroHeadersFunction implements Function<AvroWrapper, List<String>> { List<String> getColumns(List<Schema.Field> fields) { List<String> columns = new ArrayList<>(fields.size()); for (Schema.Field field : fields) { switch (field.schema().getType()) { case RECORD: case MAP: case ARRAY: break; default: columns.add(field.name()); } } return columns; } @Override List<String> call(AvroWrapper avroWrapper); } |
@Test public void getMaximumNumberOfGroups() { Assert.assertEquals(1, SparkVerifier.getMaximumNumberOfGroups(new BoundedDouble(100.0, 50.0, 0.0, 200.0), 10_000)); Assert.assertEquals(5, SparkVerifier.getMaximumNumberOfGroups(new BoundedDouble(100.0, 50.0, 0.0, 200.0), 20)); Assert.assertEquals(100, SparkVerifier.getMaximumNumberOfGroups(new BoundedDouble(100.0, 50.0, 0.0, 200.0), 1)); } | static int getMaximumNumberOfGroups(BoundedDouble approxCountBoundedDouble, int maxGroupSize) { long countApprox = Math.round(approxCountBoundedDouble.mean()); LOGGER.info("Approximate count of expected results: " + countApprox); LOGGER.info("Maximum group size: " + maxGroupSize); long maximumNumberOfGroups = Math.max(1, countApprox / maxGroupSize); if (maximumNumberOfGroups > Integer.MAX_VALUE) { throw new IllegalStateException("Invalid max group size: " + maximumNumberOfGroups); } return (int) maximumNumberOfGroups; } | SparkVerifier { static int getMaximumNumberOfGroups(BoundedDouble approxCountBoundedDouble, int maxGroupSize) { long countApprox = Math.round(approxCountBoundedDouble.mean()); LOGGER.info("Approximate count of expected results: " + countApprox); LOGGER.info("Maximum group size: " + maxGroupSize); long maximumNumberOfGroups = Math.max(1, countApprox / maxGroupSize); if (maximumNumberOfGroups > Integer.MAX_VALUE) { throw new IllegalStateException("Invalid max group size: " + maximumNumberOfGroups); } return (int) maximumNumberOfGroups; } } | SparkVerifier { static int getMaximumNumberOfGroups(BoundedDouble approxCountBoundedDouble, int maxGroupSize) { long countApprox = Math.round(approxCountBoundedDouble.mean()); LOGGER.info("Approximate count of expected results: " + countApprox); LOGGER.info("Maximum group size: " + maxGroupSize); long maximumNumberOfGroups = Math.max(1, countApprox / maxGroupSize); if (maximumNumberOfGroups > Integer.MAX_VALUE) { throw new IllegalStateException("Invalid max group size: " + maximumNumberOfGroups); } return (int) maximumNumberOfGroups; } SparkVerifier(List<String> groupKeyColumns); } | SparkVerifier { static int getMaximumNumberOfGroups(BoundedDouble approxCountBoundedDouble, int maxGroupSize) { long countApprox = Math.round(approxCountBoundedDouble.mean()); LOGGER.info("Approximate count of expected results: " + countApprox); LOGGER.info("Maximum group size: " + maxGroupSize); long maximumNumberOfGroups = Math.max(1, countApprox / maxGroupSize); if (maximumNumberOfGroups > Integer.MAX_VALUE) { throw new IllegalStateException("Invalid max group size: " + maximumNumberOfGroups); } return (int) maximumNumberOfGroups; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } | SparkVerifier { static int getMaximumNumberOfGroups(BoundedDouble approxCountBoundedDouble, int maxGroupSize) { long countApprox = Math.round(approxCountBoundedDouble.mean()); LOGGER.info("Approximate count of expected results: " + countApprox); LOGGER.info("Maximum group size: " + maxGroupSize); long maximumNumberOfGroups = Math.max(1, countApprox / maxGroupSize); if (maximumNumberOfGroups > Integer.MAX_VALUE) { throw new IllegalStateException("Invalid max group size: " + maximumNumberOfGroups); } return (int) maximumNumberOfGroups; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } |
@Test public void withoutPartialMatchTimeout() { this.verifier.starting(this.description.get()); this.verifier.withoutPartialMatchTimeout().verify("table1", TableTestUtils.ACTUAL, TableTestUtils.ACTUAL); this.verifier.succeeded(this.description.get()); } | public final TableVerifier withoutPartialMatchTimeout() { return this.withPartialMatchTimeoutMillis(0); } | TableVerifier extends TestWatcher { public final TableVerifier withoutPartialMatchTimeout() { return this.withPartialMatchTimeoutMillis(0); } } | TableVerifier extends TestWatcher { public final TableVerifier withoutPartialMatchTimeout() { return this.withPartialMatchTimeoutMillis(0); } } | TableVerifier extends TestWatcher { public final TableVerifier withoutPartialMatchTimeout() { return this.withPartialMatchTimeoutMillis(0); } final TableVerifier withExpectedDir(String expectedDirPath); final TableVerifier withExpectedDir(File expectedDir); final TableVerifier withOutputDir(String outputDirPath); final TableVerifier withOutputDir(File outputDir); final TableVerifier withMavenDirectoryStrategy(); final TableVerifier withMavenDirectoryStrategy(String expectedSubDir, String outputSubDir); final TableVerifier withRebase(); final boolean isRebasing(); final TableVerifier withFilePerMethod(); @Deprecated final TableVerifier withFilePerClass(); final TableVerifier withFileStrategy(FilenameStrategy filenameStrategy); final TableVerifier withDirectoryStrategy(DirectoryStrategy directoryStrategy); final TableVerifier withVerifyRowOrder(boolean verifyRowOrder); final TableVerifier withMetadata(String name, String value); final TableVerifier withTolerance(double tolerance); final TableVerifier withTolerance(String columnName, double tolerance); final TableVerifier withVarianceThreshold(double varianceThreshold); final TableVerifier withVarianceThreshold(String columnName, double varianceThreshold); final TableVerifier withHideMatchedRows(boolean hideMatchedRows); final TableVerifier withAlwaysShowMatchedRowsFor(String... tableNames); TableVerifier withHideMatchedColumns(boolean hideMatchedColumns); final TableVerifier withTablesNotToAdapt(String... tableNames); final TableVerifier withHideMatchedTables(boolean hideMatchedTables); final TableVerifier withHtmlRowLimit(int htmlRowLimit); final TableVerifier withCreateActualResults(boolean createActualResults); final TableVerifier withCreateActualResultsOnFailure(boolean createActualResultsOnFailure); final TableVerifier withAssertionSummary(boolean assertionSummary); final TableVerifier withActualAdapter(Function<VerifiableTable, VerifiableTable> actualAdapter); Function<VerifiableTable, VerifiableTable> getActualAdapter(); final TableVerifier withExpectedAdapter(Function<VerifiableTable, VerifiableTable> expectedAdapter); Function<VerifiableTable, VerifiableTable> getExpectedAdapter(); final TableVerifier withIgnoreSurplusRows(); final TableVerifier withIgnoreMissingRows(); TableVerifier withIgnoreSurplusColumns(); TableVerifier withIgnoreMissingColumns(); TableVerifier withIgnoreColumns(String... columnsToIgnore); TableVerifier withColumnFilter(final Predicate<String> columnFilter); TableVerifier withIgnoreTables(String... tableNames); TableVerifier withTableFilter(Predicate<String> tableFilter); final TableVerifier withBaselineHeaders(String... headers); final TableVerifier withExpectedResultsLoader(ExpectedResultsLoader expectedResultsLoader); final TableVerifier withSummarisedResults(boolean summarisedResults); final TableVerifier withPartialMatchTimeoutMillis(long partialMatchTimeoutMillis); final TableVerifier withoutPartialMatchTimeout(); final TableVerifier withLifecycleEventHandler(LifecycleEventHandler lifecycleEventHandler); final TableVerifier withExceptionHandler(ExceptionHandler exceptionHandler); @Override final void starting(Description description); @Override final void succeeded(Description description); @Override final void failed(Throwable e, Description description); @Override final void skipped(AssumptionViolatedException e, Description description); @Override final void finished(Description description); final File getExpectedFile(); final File getOutputFile(); final File getActualFile(); final void verify(String tableName, VerifiableTable actualTable); final void verify(NamedTable... actualTables); final void verify(List<NamedTable> actualTables); @Deprecated final void verify(Map<String, VerifiableTable> actualTables); ExpectedResults getExpectedResults(); final void verify(String name, VerifiableTable expectedTable, VerifiableTable actualTable); final void verify(List<NamedTable> expectedTables, List<NamedTable> actualTables); @Deprecated final void verify(Map<String, VerifiableTable> expectedTables, Map<String, VerifiableTable> actualTables); HtmlFormatter newHtmlFormatter(); SingleTableVerifier newSingleTableVerifier(); void investigate(Investigation investigation); void investigate(Investigation investigation, File outputFile); } | TableVerifier extends TestWatcher { public final TableVerifier withoutPartialMatchTimeout() { return this.withPartialMatchTimeoutMillis(0); } final TableVerifier withExpectedDir(String expectedDirPath); final TableVerifier withExpectedDir(File expectedDir); final TableVerifier withOutputDir(String outputDirPath); final TableVerifier withOutputDir(File outputDir); final TableVerifier withMavenDirectoryStrategy(); final TableVerifier withMavenDirectoryStrategy(String expectedSubDir, String outputSubDir); final TableVerifier withRebase(); final boolean isRebasing(); final TableVerifier withFilePerMethod(); @Deprecated final TableVerifier withFilePerClass(); final TableVerifier withFileStrategy(FilenameStrategy filenameStrategy); final TableVerifier withDirectoryStrategy(DirectoryStrategy directoryStrategy); final TableVerifier withVerifyRowOrder(boolean verifyRowOrder); final TableVerifier withMetadata(String name, String value); final TableVerifier withTolerance(double tolerance); final TableVerifier withTolerance(String columnName, double tolerance); final TableVerifier withVarianceThreshold(double varianceThreshold); final TableVerifier withVarianceThreshold(String columnName, double varianceThreshold); final TableVerifier withHideMatchedRows(boolean hideMatchedRows); final TableVerifier withAlwaysShowMatchedRowsFor(String... tableNames); TableVerifier withHideMatchedColumns(boolean hideMatchedColumns); final TableVerifier withTablesNotToAdapt(String... tableNames); final TableVerifier withHideMatchedTables(boolean hideMatchedTables); final TableVerifier withHtmlRowLimit(int htmlRowLimit); final TableVerifier withCreateActualResults(boolean createActualResults); final TableVerifier withCreateActualResultsOnFailure(boolean createActualResultsOnFailure); final TableVerifier withAssertionSummary(boolean assertionSummary); final TableVerifier withActualAdapter(Function<VerifiableTable, VerifiableTable> actualAdapter); Function<VerifiableTable, VerifiableTable> getActualAdapter(); final TableVerifier withExpectedAdapter(Function<VerifiableTable, VerifiableTable> expectedAdapter); Function<VerifiableTable, VerifiableTable> getExpectedAdapter(); final TableVerifier withIgnoreSurplusRows(); final TableVerifier withIgnoreMissingRows(); TableVerifier withIgnoreSurplusColumns(); TableVerifier withIgnoreMissingColumns(); TableVerifier withIgnoreColumns(String... columnsToIgnore); TableVerifier withColumnFilter(final Predicate<String> columnFilter); TableVerifier withIgnoreTables(String... tableNames); TableVerifier withTableFilter(Predicate<String> tableFilter); final TableVerifier withBaselineHeaders(String... headers); final TableVerifier withExpectedResultsLoader(ExpectedResultsLoader expectedResultsLoader); final TableVerifier withSummarisedResults(boolean summarisedResults); final TableVerifier withPartialMatchTimeoutMillis(long partialMatchTimeoutMillis); final TableVerifier withoutPartialMatchTimeout(); final TableVerifier withLifecycleEventHandler(LifecycleEventHandler lifecycleEventHandler); final TableVerifier withExceptionHandler(ExceptionHandler exceptionHandler); @Override final void starting(Description description); @Override final void succeeded(Description description); @Override final void failed(Throwable e, Description description); @Override final void skipped(AssumptionViolatedException e, Description description); @Override final void finished(Description description); final File getExpectedFile(); final File getOutputFile(); final File getActualFile(); final void verify(String tableName, VerifiableTable actualTable); final void verify(NamedTable... actualTables); final void verify(List<NamedTable> actualTables); @Deprecated final void verify(Map<String, VerifiableTable> actualTables); ExpectedResults getExpectedResults(); final void verify(String name, VerifiableTable expectedTable, VerifiableTable actualTable); final void verify(List<NamedTable> expectedTables, List<NamedTable> actualTables); @Deprecated final void verify(Map<String, VerifiableTable> expectedTables, Map<String, VerifiableTable> actualTables); HtmlFormatter newHtmlFormatter(); SingleTableVerifier newSingleTableVerifier(); void investigate(Investigation investigation); void investigate(Investigation investigation, File outputFile); } |
@Test public void testAllRows() { this.verify( TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5), TableAdapters.withRows(TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5), i -> true)); } | public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } |
@Test public void testNoRows() { VerifiableTable table = TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5); this.verify( TableTestUtils.createTable(1, "C"), TableAdapters.withRows(table, i -> false)); } | public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } |
@Test public void testSomeRows() { VerifiableTable table = TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5); this.verify( TableTestUtils.createTable(1, "C", 2, 4), TableAdapters.withRows(table, i -> (Integer) table.getValueAt(i, 0) % 2 == 0)); } | public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } | TableAdapters { public static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter) { return new RowFilterAdapter(delegate, rowFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } |
@Test public void testAllColumns() { this.verify( TableTestUtils.createTable(5, "C1", "C2", "C3", "C4", "C5"), TableAdapters.withColumns(TableTestUtils.createTable(5, "C1", "C2", "C3", "C4", "C5"), name -> true)); } | public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } private TableAdapters(); } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } |
@Test public void testSomeColumns() { this.verify( TableTestUtils.createTable(3, "C1", "C3", "C5"), TableAdapters.withColumns(TableTestUtils.createTable(5, "C1", "C2", "C3", "C4", "C5"), name -> name.matches("C[135]"))); } | public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } private TableAdapters(); } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } | TableAdapters { public static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter) { return new ColumnFilterAdapter(delegate, columnFilter); } private TableAdapters(); static VerifiableTable withRows(VerifiableTable delegate, IntPredicate rowFilter); static VerifiableTable withColumns(VerifiableTable delegate, Predicate<String> columnFilter); } |
@Test public void testParse() { File expected = new File(TableTestUtils.getExpectedDirectory(), ExpectedResultsParserTest.class.getSimpleName() + ".txt"); ExpectedResults results = new ExpectedResultsParser(new FileSystemExpectedResultsLoader(), expected).parse(); VerifiableTable summary = results.getTable("Summary"); Assert.assertEquals(6, summary.getColumnCount()); Assert.assertEquals(5, summary.getRowCount()); VerifiableTable drillDown = results.getTable("DrillDown"); Assert.assertEquals(6, drillDown.getColumnCount()); Assert.assertEquals(1, drillDown.getRowCount()); Assert.assertEquals(2, results.getMetadata().getData().size()); Assert.assertEquals(Collections.singletonMap("Recorded At", "2013-06-26 12:00:00").entrySet().iterator().next(), results.getMetadata().getData().get(0)); Assert.assertEquals(Collections.singletonMap("App Server URL", "http: } | public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } ExpectedResultsParser(ExpectedResultsLoader loader, File file); } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } ExpectedResultsParser(ExpectedResultsLoader loader, File file); ExpectedResults parse(); } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } ExpectedResultsParser(ExpectedResultsLoader loader, File file); ExpectedResults parse(); } |
@Test public void testCache() { File expected = new File(TableTestUtils.getExpectedDirectory(), ExpectedResultsParserTest.class.getSimpleName() + ".txt"); Map<ExpectedResults, String> results = new IdentityHashMap<>(); for (int i = 0; i < 10; i++) { results.put(ExpectedResultsCache.getExpectedResults(new FileSystemExpectedResultsLoader(), expected), ""); } Assert.assertTrue("cache was hit at least once", results.size() < 10); } | ExpectedResults getExpectedResults() { return this.results; } | ExpectedResultsParser { ExpectedResults getExpectedResults() { return this.results; } } | ExpectedResultsParser { ExpectedResults getExpectedResults() { return this.results; } ExpectedResultsParser(ExpectedResultsLoader loader, File file); } | ExpectedResultsParser { ExpectedResults getExpectedResults() { return this.results; } ExpectedResultsParser(ExpectedResultsLoader loader, File file); ExpectedResults parse(); } | ExpectedResultsParser { ExpectedResults getExpectedResults() { return this.results; } ExpectedResultsParser(ExpectedResultsLoader loader, File file); ExpectedResults parse(); } |
@Test public void testMissingExpectedResultsFileResultsInClearErrorMessage() { String missingFileName = "missing-expected-results.txt"; try { new ExpectedResultsParser(new FileSystemExpectedResultsLoader(), new File(missingFileName)).parse(); Assert.fail("Should have failed looking for non-existent file"); } catch (IllegalStateException expected) { Assert.assertTrue(expected.getMessage().contains(missingFileName)); } } | public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } ExpectedResultsParser(ExpectedResultsLoader loader, File file); } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } ExpectedResultsParser(ExpectedResultsLoader loader, File file); ExpectedResults parse(); } | ExpectedResultsParser { public ExpectedResults parse() { this.results = new ExpectedResults(); try (InputStream inputStream = this.loader.load(this.file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); parse(reader); return this.results; } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Parsing error reading '" + this.file + '\'', e); } } ExpectedResultsParser(ExpectedResultsLoader loader, File file); ExpectedResults parse(); } |
@Test public void runTestFail() throws IOException { runTest(AVRO, AVRO_X, false, newSparkVerifier(Arrays.asList("k2", "k1")) .withMaxGroupSize(2)); } | public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } |
@Test public void testCompareToleranceStringInputsFail() { Assert.assertFalse(this.varianceCellComparator.compare("ActualAndExpected", "ActualAndExpected")); Assert.assertFalse(this.varianceCellComparator.compare("Actual", "Expected")); } | protected abstract boolean compare(Object actual, Object expected); | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } |
@Test public void testCompareNumbersWithinTolerance() { Assert.assertTrue("Results match expected. Actual(20.0) and Expected(20.09) within Tolerance range(0.1).",this.toleranceCellComparator.compare(new Double(20.0), new Double(20.09))); Assert.assertTrue("Results match expected. Actual(7894.87) and Expected(7894.79) within Tolerance range(0.1).",this.toleranceCellComparator.compare(new Float(7894.87), new Float(7894.79))); } | protected abstract boolean compare(Object actual, Object expected); | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } |
@Test public void testCompareNumbersOutsideTolerance() { Assert.assertFalse("Results mismatch expected. Actual(20.0) and Expected(20.11) outside Tolerance range(0.1). ", this.toleranceCellComparator.compare(new Double(20.0), new Double(20.11))); Assert.assertFalse("Results mismatch expected. Actual(7894.87) and Expected(7894.75) outside Tolerance range(0.1). ", this.toleranceCellComparator.compare(new Float(7894.87), new Float(7894.75))); } | protected abstract boolean compare(Object actual, Object expected); | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } |
@Test public void testCompareVarianceStringInputsFail() { Assert.assertFalse(this.varianceCellComparator.compare("ActualAndExpected", "ActualAndExpected")); Assert.assertFalse(this.varianceCellComparator.compare("Actual", "Expected")); } | protected abstract boolean compare(Object actual, Object expected); | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } |
@Test public void testCompareNumbersWithinVariance() { Assert.assertTrue("Results match expected. Actual(2000.0) and Expected(2100.0) within Variance range(5%).", this.varianceCellComparator.compare(new Double(2000.0), new Double(2100.0))); Assert.assertTrue("Results match expected. Actual(735.0) and Expected(772.0) within Variance range(5%).", this.varianceCellComparator.compare(new Float(735.0), new Float(772.0))); } | protected abstract boolean compare(Object actual, Object expected); | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } |
@Test public void testCompareNumbersOutsideVariance() { Assert.assertFalse("Results mismatch expected. Actual(2000.0) and Expected(2110.0) outside Variance range(5%).", this.varianceCellComparator.compare(new Double(2000.0), new Double(2110))); Assert.assertFalse("Results mismatch expected. Actual(735.0) and Expected(775.0) outside Variance range(5%).", this.varianceCellComparator.compare(new Float(735.0), new Float(775.0))); Assert.assertFalse("Results mismatch expected. Actual(5600.0) and Expected(NaN) outside Variance range(5%).", this.varianceCellComparator.compare(new Double(5600.0), Double.NaN)); Assert.assertFalse("Results mismatch expected. Actual(NaN) and Expected(88.0) outside Variance range(5%).", this.varianceCellComparator.compare(Double.NaN,new Double(88.0) )); } | protected abstract boolean compare(Object actual, Object expected); | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } |
@Test public void testActualExpectedMismatchedTypes() { Assert.assertFalse("Results mismatch expected. Actual(390.0) and Expected(expected) outside Variance range(5%).", this.varianceCellComparator.compare(new Double(390.0),"expected")); Assert.assertFalse("Results mismatch expected. Actual(actual) and Expected(1045.0) outside Variance range(5%).", this.varianceCellComparator.compare("actual", new Double(1045.0))); } | protected abstract boolean compare(Object actual, Object expected); | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } | CellComparator implements Serializable { protected abstract boolean compare(Object actual, Object expected); CellComparator(CellFormatter formatter); CellFormatter getFormatter(); static boolean isFloatingPoint(Object object); boolean equals(Object actual, Object expected); int computeHashCode(Object object); } |
@Test public void create() throws SQLException { SimpleResultSet resultSet = new SimpleResultSet(); resultSet.addColumn("Name", Types.VARCHAR, 0, 0); resultSet.addColumn("Age", Types.INTEGER, 0, 0); resultSet.addColumn("Height", Types.DOUBLE, 0, 0); resultSet.addColumn("DoB", Types.DATE, 0, 0); resultSet.addRow("Joe", 70, 6.0, Date.valueOf("1940-02-16")); resultSet.addRow("Sue", 45, 5.8, Date.valueOf("1975-02-16")); VerifiableTable expected = new TestTable("Name", "Age", "Height", "DoB") .withRow("Joe", 70, 6.0, Date.valueOf("1940-02-16")) .withRow("Sue", 45, 5.8, Date.valueOf("1975-02-16")); VerifiableTable actual = ResultSetTable.create(resultSet); this.tableVerifier.verify( Collections.singletonList(new NamedTable("table", expected)), Collections.singletonList(new NamedTable("table", actual))); } | public static VerifiableTable create(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List<String> headers = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { headers.add(metaData.getColumnName(n)); } List<List> rows = new ArrayList<>(); while (resultSet.next()) { List<Object> row = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { row.add(resultSet.getObject(n)); } rows.add(row); } return ListVerifiableTable.create(headers, rows); } | ResultSetTable { public static VerifiableTable create(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List<String> headers = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { headers.add(metaData.getColumnName(n)); } List<List> rows = new ArrayList<>(); while (resultSet.next()) { List<Object> row = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { row.add(resultSet.getObject(n)); } rows.add(row); } return ListVerifiableTable.create(headers, rows); } } | ResultSetTable { public static VerifiableTable create(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List<String> headers = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { headers.add(metaData.getColumnName(n)); } List<List> rows = new ArrayList<>(); while (resultSet.next()) { List<Object> row = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { row.add(resultSet.getObject(n)); } rows.add(row); } return ListVerifiableTable.create(headers, rows); } private ResultSetTable(); } | ResultSetTable { public static VerifiableTable create(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List<String> headers = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { headers.add(metaData.getColumnName(n)); } List<List> rows = new ArrayList<>(); while (resultSet.next()) { List<Object> row = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { row.add(resultSet.getObject(n)); } rows.add(row); } return ListVerifiableTable.create(headers, rows); } private ResultSetTable(); static VerifiableTable create(ResultSet resultSet); } | ResultSetTable { public static VerifiableTable create(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); List<String> headers = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { headers.add(metaData.getColumnName(n)); } List<List> rows = new ArrayList<>(); while (resultSet.next()) { List<Object> row = new ArrayList<>(columnCount); for (int n = 1; n <= columnCount; n++) { row.add(resultSet.getObject(n)); } rows.add(row); } return ListVerifiableTable.create(headers, rows); } private ResultSetTable(); static VerifiableTable create(ResultSet resultSet); } |
@Test public void testHeaderTypes() throws Exception { List<Object> headersAsObjects = Collections.singletonList("Col"); List<List<Object>> headersAndDataAsObjects = Arrays.asList(headersAsObjects, Collections.<Object>singletonList("Val")); Assert.assertEquals("Test constructor with headers and rows in one List<List<Object>>", 1, new ListVerifiableTable(headersAndDataAsObjects).getRowCount()); Assert.assertEquals("Test constructor with headers as List<Object>", 2, new ListVerifiableTable(headersAsObjects, headersAndDataAsObjects).getRowCount()); List<String> headersAsStrings = Collections.singletonList("Col"); Assert.assertEquals("Test cast that used to be necessary for headers as List<String>", 2, new ListVerifiableTable((List) headersAsStrings, headersAndDataAsObjects).getRowCount()); Assert.assertEquals("Test headers as List<String> can now be passed in as-is", 2, new ListVerifiableTable(headersAsStrings, headersAndDataAsObjects).getRowCount()); } | @Override public int getRowCount() { return this.data.size(); } | ListVerifiableTable implements VerifiableTable { @Override public int getRowCount() { return this.data.size(); } } | ListVerifiableTable implements VerifiableTable { @Override public int getRowCount() { return this.data.size(); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); } | ListVerifiableTable implements VerifiableTable { @Override public int getRowCount() { return this.data.size(); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } | ListVerifiableTable implements VerifiableTable { @Override public int getRowCount() { return this.data.size(); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } |
@Test(expected = IllegalArgumentException.class) public void createList_headersNotStrings() { ListVerifiableTable.create(Arrays.asList(Arrays.asList('A', 'B'), Arrays.asList(1, 2))); } | public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } |
@Test public void runTestPass() throws IOException { runTest(AVRO, AVRO, true, newSparkVerifier(Collections.emptyList()) .withMaxGroupSize(2)); } | public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } |
@Test(expected = IllegalArgumentException.class) public void createList_wrongRowSize() { ListVerifiableTable.create(Arrays.asList(Arrays.asList("A", "B"), Arrays.asList(1, 2), Collections.singletonList(3))); } | public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } |
@Test(expected = IllegalArgumentException.class) public void createHeadersAndList_wrongRowSize() { ListVerifiableTable.create(Arrays.asList("A", "B"), Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4, 5))); } | public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } |
@Test(expected = IllegalArgumentException.class) public void createHeadersAndIterable_wrongRowSize() { ListVerifiableTable.create(Arrays.asList("A", "B"), new LinkedHashSet<>(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4, 5)))); } | public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } | ListVerifiableTable implements VerifiableTable { public static VerifiableTable create(Iterable<List> headersAndRows) { Iterator<List> iterator = headersAndRows.iterator(); List headers = iterator.next(); headers.forEach(ListVerifiableTable::verifyHeader); List rowList = new ArrayList(); iterator.forEachRemaining(verifyRowSize(headers).andThen(rowList::add)); return new ListVerifiableTable(headers, rowList); } ListVerifiableTable(List<List<Object>> headersAndData); ListVerifiableTable(List<?> headers, List<List<Object>> data); static VerifiableTable create(Iterable<List> headersAndRows); static VerifiableTable create(List<String> headers, Iterable<List> rows); @Override int getRowCount(); @Override int getColumnCount(); @Override String getColumnName(int columnIndex); @Override Object getValueAt(int rowIndex, int columnIndex); } |
@Test public void formatNumbers() { CellFormatter formatter = new CellFormatter(0.01, true); Assert.assertEquals("1", formatter.format(1.0d)); Assert.assertEquals("1.1", formatter.format(1.10d)); Assert.assertEquals("1.11", formatter.format(1.11d)); Assert.assertEquals("1.11", formatter.format(1.111d)); Assert.assertEquals("1.12", formatter.format(1.116d)); Assert.assertEquals("-1.12", formatter.format(-1.116d)); Assert.assertEquals("-1,000.12", formatter.format(-1000.116d)); Assert.assertEquals("-1,000.12", formatter.format(-1000.116f)); Assert.assertEquals("1,000", formatter.format(1000)); Assert.assertEquals("-1,000", formatter.format((long) -1000)); Assert.assertEquals("NaN", formatter.format(Double.NaN)); Assert.assertEquals("NaN", formatter.format(Float.NaN)); Assert.assertEquals("0", formatter.format(-0.0d)); Assert.assertEquals("0", formatter.format(-0)); Assert.assertEquals("0", formatter.format(-0.0001)); } | public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } CellFormatter(double tolerance, boolean isGroupingUsed); } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } CellFormatter(double tolerance, boolean isGroupingUsed); @Override String apply(Object object); String format(Object value); } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } CellFormatter(double tolerance, boolean isGroupingUsed); @Override String apply(Object object); String format(Object value); } |
@Test public void formatDate() { CellFormatter formatter = new CellFormatter(0, false); Assert.assertEquals("2009-02-13 23:31:30", formatter.format(Timestamp.valueOf("2009-02-13 23:31:30.0001"))); } | public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } CellFormatter(double tolerance, boolean isGroupingUsed); } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } CellFormatter(double tolerance, boolean isGroupingUsed); @Override String apply(Object object); String format(Object value); } | CellFormatter implements Function<Object, String>, Serializable { public String format(Object value) { if (isNumber(value)) { if (value.equals(Double.NaN) || value.equals(Float.NaN)) { return "NaN"; } String formatted = this.numberFormat.format(value); if (isNegativeZero(formatted)) { return formatted.substring(1); } return formatted; } if (value instanceof Date) { return this.dateFormat.format(value); } if (value == null) { return ""; } return this.formatString(String.valueOf(value)); } CellFormatter(double tolerance, boolean isGroupingUsed); @Override String apply(Object object); String format(Object value); } |
@Test public void formatString() { CellFormatter formatter = new CellFormatter(0, false); Assert.assertEquals("", formatter.format("")); Assert.assertEquals("foo", formatter.format("foo")); Assert.assertEquals("foo", formatter.format(" foo ")); Assert.assertEquals("foo bar", formatter.format("foo bar")); Assert.assertEquals("foo bar", formatter.format("foo bar")); Assert.assertEquals("foo bar", formatter.format("foo\nbar ")); Assert.assertEquals("foo bar", formatter.format(" foo\rbar")); Assert.assertEquals("foo bar", formatter.format(" foo\r \nbar ")); Assert.assertEquals("foo", formatter.format("foo\r")); Assert.assertEquals("foo", formatter.format("\n foo")); Assert.assertEquals("", formatter.format("\n \r ")); Assert.assertEquals("", formatter.format(" \n \r")); } | private String formatString(String untrimmedValue) { String value = untrimmedValue.trim(); this.builder.setLength(0); boolean changed = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isWhitespace(c)) { this.builder.append(' '); if (c != ' ') { changed = true; } } else { this.builder.append(c); } } return changed ? this.builder.toString() : value; } | CellFormatter implements Function<Object, String>, Serializable { private String formatString(String untrimmedValue) { String value = untrimmedValue.trim(); this.builder.setLength(0); boolean changed = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isWhitespace(c)) { this.builder.append(' '); if (c != ' ') { changed = true; } } else { this.builder.append(c); } } return changed ? this.builder.toString() : value; } } | CellFormatter implements Function<Object, String>, Serializable { private String formatString(String untrimmedValue) { String value = untrimmedValue.trim(); this.builder.setLength(0); boolean changed = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isWhitespace(c)) { this.builder.append(' '); if (c != ' ') { changed = true; } } else { this.builder.append(c); } } return changed ? this.builder.toString() : value; } CellFormatter(double tolerance, boolean isGroupingUsed); } | CellFormatter implements Function<Object, String>, Serializable { private String formatString(String untrimmedValue) { String value = untrimmedValue.trim(); this.builder.setLength(0); boolean changed = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isWhitespace(c)) { this.builder.append(' '); if (c != ' ') { changed = true; } } else { this.builder.append(c); } } return changed ? this.builder.toString() : value; } CellFormatter(double tolerance, boolean isGroupingUsed); @Override String apply(Object object); String format(Object value); } | CellFormatter implements Function<Object, String>, Serializable { private String formatString(String untrimmedValue) { String value = untrimmedValue.trim(); this.builder.setLength(0); boolean changed = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isWhitespace(c)) { this.builder.append(' '); if (c != ' ') { changed = true; } } else { this.builder.append(c); } } return changed ? this.builder.toString() : value; } CellFormatter(double tolerance, boolean isGroupingUsed); @Override String apply(Object object); String format(Object value); } |
@Test public void testException() throws IOException { String stackTraceToString = ExceptionHtml.stackTraceToString(new RuntimeException(new IllegalArgumentException(new UnsupportedOperationException()))); List<Map.Entry<String, List<String>>> stackTraces = getStackLineCount(stackTraceToString); Assert.assertEquals(3, stackTraces.size()); Assert.assertEquals(RuntimeException.class.getName() + ": " + IllegalArgumentException.class.getName() + ": " + UnsupportedOperationException.class.getName(), stackTraces.get(0).getKey()); Assert.assertTrue(stackTraces.get(0).getValue().size() > 1); Assert.assertEquals("Caused by: " + IllegalArgumentException.class.getName() + ": " + UnsupportedOperationException.class.getName(), stackTraces.get(1).getKey()); Assert.assertTrue(stackTraces.get(1).getValue().size() > 1); Assert.assertEquals("Caused by: " + UnsupportedOperationException.class.getName(), stackTraces.get(2).getKey()); Assert.assertTrue(stackTraces.get(2).getValue().size() > 1); } | static String stackTraceToString(Throwable e) throws UnsupportedEncodingException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bytes, false, "UTF-8"); stackTraceToString(e, out); out.close(); return bytes.toString("UTF-8"); } | ExceptionHtml { static String stackTraceToString(Throwable e) throws UnsupportedEncodingException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bytes, false, "UTF-8"); stackTraceToString(e, out); out.close(); return bytes.toString("UTF-8"); } } | ExceptionHtml { static String stackTraceToString(Throwable e) throws UnsupportedEncodingException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bytes, false, "UTF-8"); stackTraceToString(e, out); out.close(); return bytes.toString("UTF-8"); } private ExceptionHtml(); } | ExceptionHtml { static String stackTraceToString(Throwable e) throws UnsupportedEncodingException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bytes, false, "UTF-8"); stackTraceToString(e, out); out.close(); return bytes.toString("UTF-8"); } private ExceptionHtml(); static void create(File resultsFile, Throwable reason); } | ExceptionHtml { static String stackTraceToString(Throwable e) throws UnsupportedEncodingException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bytes, false, "UTF-8"); stackTraceToString(e, out); out.close(); return bytes.toString("UTF-8"); } private ExceptionHtml(); static void create(File resultsFile, Throwable reason); } |
@Test(expected = IllegalArgumentException.class) public void testAddPartialMatchFailsIfSelf() { this.unmatched.addMatch(2, this.unmatched); } | public void addMatch(int matchScore, UnmatchedIndexMap match) { if (this.equals(match)) { throw new IllegalArgumentException("Cannot add this as partial match"); } if (this.partialMatches == null) { this.partialMatches = new TreeSet<>(); } if (match.partialMatches == null) { match.partialMatches = new TreeSet<>(); } if (this.getExpectedIndex() < 0 || match.getActualIndex() < 0) { throw new IllegalStateException("Expecting this to be expected and that to be actual"); } this.partialMatches.add(new Match(matchScore, match)); match.partialMatches.add(new Match(matchScore, this)); } | UnmatchedIndexMap extends IndexMap { public void addMatch(int matchScore, UnmatchedIndexMap match) { if (this.equals(match)) { throw new IllegalArgumentException("Cannot add this as partial match"); } if (this.partialMatches == null) { this.partialMatches = new TreeSet<>(); } if (match.partialMatches == null) { match.partialMatches = new TreeSet<>(); } if (this.getExpectedIndex() < 0 || match.getActualIndex() < 0) { throw new IllegalStateException("Expecting this to be expected and that to be actual"); } this.partialMatches.add(new Match(matchScore, match)); match.partialMatches.add(new Match(matchScore, this)); } } | UnmatchedIndexMap extends IndexMap { public void addMatch(int matchScore, UnmatchedIndexMap match) { if (this.equals(match)) { throw new IllegalArgumentException("Cannot add this as partial match"); } if (this.partialMatches == null) { this.partialMatches = new TreeSet<>(); } if (match.partialMatches == null) { match.partialMatches = new TreeSet<>(); } if (this.getExpectedIndex() < 0 || match.getActualIndex() < 0) { throw new IllegalStateException("Expecting this to be expected and that to be actual"); } this.partialMatches.add(new Match(matchScore, match)); match.partialMatches.add(new Match(matchScore, this)); } UnmatchedIndexMap(int expectedIndex, int actualIndex); } | UnmatchedIndexMap extends IndexMap { public void addMatch(int matchScore, UnmatchedIndexMap match) { if (this.equals(match)) { throw new IllegalArgumentException("Cannot add this as partial match"); } if (this.partialMatches == null) { this.partialMatches = new TreeSet<>(); } if (match.partialMatches == null) { match.partialMatches = new TreeSet<>(); } if (this.getExpectedIndex() < 0 || match.getActualIndex() < 0) { throw new IllegalStateException("Expecting this to be expected and that to be actual"); } this.partialMatches.add(new Match(matchScore, match)); match.partialMatches.add(new Match(matchScore, this)); } UnmatchedIndexMap(int expectedIndex, int actualIndex); void addMatch(int matchScore, UnmatchedIndexMap match); boolean match(); UnmatchedIndexMap getBestMutualMatch(); } | UnmatchedIndexMap extends IndexMap { public void addMatch(int matchScore, UnmatchedIndexMap match) { if (this.equals(match)) { throw new IllegalArgumentException("Cannot add this as partial match"); } if (this.partialMatches == null) { this.partialMatches = new TreeSet<>(); } if (match.partialMatches == null) { match.partialMatches = new TreeSet<>(); } if (this.getExpectedIndex() < 0 || match.getActualIndex() < 0) { throw new IllegalStateException("Expecting this to be expected and that to be actual"); } this.partialMatches.add(new Match(matchScore, match)); match.partialMatches.add(new Match(matchScore, this)); } UnmatchedIndexMap(int expectedIndex, int actualIndex); void addMatch(int matchScore, UnmatchedIndexMap match); boolean match(); UnmatchedIndexMap getBestMutualMatch(); } |
@Test public void testInitialState() { Assert.assertNull(this.unmatched.getBestMutualMatch()); } | public UnmatchedIndexMap getBestMutualMatch() { return this.bestMutualMatch; } | UnmatchedIndexMap extends IndexMap { public UnmatchedIndexMap getBestMutualMatch() { return this.bestMutualMatch; } } | UnmatchedIndexMap extends IndexMap { public UnmatchedIndexMap getBestMutualMatch() { return this.bestMutualMatch; } UnmatchedIndexMap(int expectedIndex, int actualIndex); } | UnmatchedIndexMap extends IndexMap { public UnmatchedIndexMap getBestMutualMatch() { return this.bestMutualMatch; } UnmatchedIndexMap(int expectedIndex, int actualIndex); void addMatch(int matchScore, UnmatchedIndexMap match); boolean match(); UnmatchedIndexMap getBestMutualMatch(); } | UnmatchedIndexMap extends IndexMap { public UnmatchedIndexMap getBestMutualMatch() { return this.bestMutualMatch; } UnmatchedIndexMap(int expectedIndex, int actualIndex); void addMatch(int matchScore, UnmatchedIndexMap match); boolean match(); UnmatchedIndexMap getBestMutualMatch(); } |
@Test public void executionTimesOut() { try { PartialMatcher endlessMatcher = (allMissingRows, allSurplusRows, matchedColumns) -> { while (true); }; new TimeBoundPartialMatcher(endlessMatcher, 1L).match(null, null, null); Assert.fail("timeout expected"); } catch (RuntimeException e) { Assert.assertTrue(e.getCause() instanceof TimeoutException); } } | @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); @Override void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns); } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); @Override void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns); } |
@Test public void runTestWithSingleShardColumn() throws IOException { runTest(AVRO, AVRO_X, false, newSparkVerifier(Collections.singletonList("k2")) .withMaxGroupSize(2)); } | public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } | SparkVerifier { public SparkVerifier withMaxGroupSize(int maxGroupSize) { this.maxGroupSize = maxGroupSize; return this; } SparkVerifier(List<String> groupKeyColumns); final SparkVerifier withMetadata(String name, String value); SparkVerifier withIgnoreSurplusColumns(boolean ignoreSurplusColumns); SparkVerifier withColumnsToIgnore(Set<String> columnsToIgnore); SparkVerifier withTolerance(double tolerance); SparkVerifier withTolerance(String columnName, double tolerance); SparkVerifier withMaxGroupSize(int maxGroupSize); SparkResult verify(String dataName, Supplier<DistributedTable> actualDataSupplier, Supplier<DistributedTable> expectedDataSupplier); } |
@Test(expected = IndexOutOfBoundsException.class) public void matchingExceptionPropagates() { PartialMatcher dyingMatcher = (allMissingRows, allSurplusRows, matchedColumns) -> Collections.singletonList("foo").get(2); new TimeBoundPartialMatcher(dyingMatcher, Long.MAX_VALUE).match(null, null, null); } | @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); @Override void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns); } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); @Override void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns); } |
@Test public void matchingErrorPropagates() { PartialMatcher dyingMatcher = (allMissingRows, allSurplusRows, matchedColumns) -> { throw new NoSuchMethodError(); }; try { new TimeBoundPartialMatcher(dyingMatcher, Long.MAX_VALUE).match(null, null, null); Assert.fail(); } catch (RuntimeException e) { Assert.assertTrue(e.getCause() instanceof NoSuchMethodError); } } | @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); @Override void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns); } | TimeBoundPartialMatcher implements PartialMatcher { @Override public void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns) { LOGGER.debug("Starting partial match"); ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<?> result = executorService.submit(() -> TimeBoundPartialMatcher.this.delegate.match(allMissingRows, allSurplusRows, matchedColumns)); try { result.get(this.timeoutMillis, TimeUnit.MILLISECONDS); LOGGER.debug("Partial match complete"); } catch (InterruptedException e) { LOGGER.error("Partial match interrupted", e); } catch (ExecutionException e) { LOGGER.error("Partial match exception", e); Throwable cause = e.getCause(); throw cause instanceof RuntimeException ? (RuntimeException) cause : new RuntimeException(cause); } catch (TimeoutException e) { LOGGER.error("Partial match timed out"); throw new RuntimeException(e); } finally { if (!executorService.isTerminated()) { executorService.shutdownNow(); } } } TimeBoundPartialMatcher(PartialMatcher delegate, long timeoutMillis); @Override void match(final List<UnmatchedIndexMap> allMissingRows, final List<UnmatchedIndexMap> allSurplusRows, final List<IndexMap> matchedColumns); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.