diff --git a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV1.java b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV1.java index 96836bedbe..e2a3730247 100644 --- a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV1.java +++ b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV1.java @@ -43,8 +43,7 @@ public class ArcGISCompactCacheV1 extends ArcGISCompactCache { * contain directories for zoom levels (named "Lxx"). */ public ArcGISCompactCacheV1(String pathToCacheRoot) { - if (pathToCacheRoot.endsWith("" + File.separatorChar)) - this.pathToCacheRoot = pathToCacheRoot; + if (pathToCacheRoot.endsWith("" + File.separatorChar)) this.pathToCacheRoot = pathToCacheRoot; else this.pathToCacheRoot = pathToCacheRoot + File.separatorChar; indexCache = new BundlxCache(10000); @@ -60,16 +59,14 @@ public Resource getBundleFileResource(int zoom, int row, int col) { Resource res = null; if ((entry = indexCache.get(key)) != null) { - if (entry.size > 0) - res = new BundleFileResource(entry.pathToBundleFile, entry.offset, entry.size); + if (entry.size > 0) res = new BundleFileResource(entry.pathToBundleFile, entry.offset, entry.size); } else { String basePath = buildBundleFilePath(zoom, row, col); String pathToBundlxFile = basePath + BUNDLX_EXT; String pathToBundleFile = basePath + BUNDLE_EXT; - if (!(new File(pathToBundleFile)).exists() || !(new File(pathToBundlxFile)).exists()) - return null; + if (!(new File(pathToBundleFile)).exists() || !(new File(pathToBundlxFile)).exists()) return null; long tileOffset = readTileStartOffset(pathToBundlxFile, row, col); int tileSize = readTileSize(pathToBundleFile, tileOffset); @@ -89,8 +86,7 @@ public Resource getBundleFileResource(int zoom, int row, int col) { private long readTileStartOffset(String bundlxFile, int row, int col) { int index = BUNDLX_MAXIDX * (col % BUNDLX_MAXIDX) + (row % BUNDLX_MAXIDX); - ByteBuffer idxBytes = - readFromLittleEndianFile(bundlxFile, (index * 5) + COMPACT_CACHE_HEADER_LENGTH, 5); + ByteBuffer idxBytes = readFromLittleEndianFile(bundlxFile, (index * 5) + COMPACT_CACHE_HEADER_LENGTH, 5); return idxBytes.getLong(); } diff --git a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV2.java b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV2.java index afaa438305..ae7634faa1 100644 --- a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV2.java +++ b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheV2.java @@ -45,8 +45,7 @@ public class ArcGISCompactCacheV2 extends ArcGISCompactCache { * contain directories for zoom levels (named "Lxx"). */ public ArcGISCompactCacheV2(String pathToCacheRoot) { - if (pathToCacheRoot.endsWith("" + File.separatorChar)) - this.pathToCacheRoot = pathToCacheRoot; + if (pathToCacheRoot.endsWith("" + File.separatorChar)) this.pathToCacheRoot = pathToCacheRoot; else this.pathToCacheRoot = pathToCacheRoot + File.separatorChar; indexCache = new BundlxCache(10000); @@ -62,8 +61,7 @@ public Resource getBundleFileResource(int zoom, int row, int col) { Resource res = null; if ((entry = indexCache.get(key)) != null) { - if (entry.size > 0) - res = new BundleFileResource(entry.pathToBundleFile, entry.offset, entry.size); + if (entry.size > 0) res = new BundleFileResource(entry.pathToBundleFile, entry.offset, entry.size); } else { String basePath = buildBundleFilePath(zoom, row, col); @@ -73,8 +71,7 @@ public Resource getBundleFileResource(int zoom, int row, int col) { entry = createCacheEntry(pathToBundleFile, row, col); - if (entry.size > 0) - res = new BundleFileResource(pathToBundleFile, entry.offset, entry.size); + if (entry.size > 0) res = new BundleFileResource(pathToBundleFile, entry.offset, entry.size); indexCache.put(key, entry); } @@ -87,8 +84,7 @@ private BundlxCache.CacheEntry createCacheEntry(String bundleFile, int row, int int index = BUNDLX_MAXIDX * (row % BUNDLX_MAXIDX) + (col % BUNDLX_MAXIDX); // to save one addtional read, we read all 8 bytes in one read - ByteBuffer offsetAndSize = - readFromLittleEndianFile(bundleFile, (index * 8) + COMPACT_CACHE_HEADER_LENGTH, 8); + ByteBuffer offsetAndSize = readFromLittleEndianFile(bundleFile, (index * 8) + COMPACT_CACHE_HEADER_LENGTH, 8); byte[] offsetBytes = new byte[8]; byte[] sizeBytes = new byte[4]; @@ -96,7 +92,8 @@ private BundlxCache.CacheEntry createCacheEntry(String bundleFile, int row, int offsetAndSize.get(offsetBytes, 0, 5); offsetAndSize.get(sizeBytes, 0, 3); - long tileOffset = ByteBuffer.wrap(offsetBytes).order(ByteOrder.LITTLE_ENDIAN).getLong(); + long tileOffset = + ByteBuffer.wrap(offsetBytes).order(ByteOrder.LITTLE_ENDIAN).getLong(); int tileSize = ByteBuffer.wrap(sizeBytes).order(ByteOrder.LITTLE_ENDIAN).getInt(); return new BundlxCache.CacheEntry(bundleFile, tileOffset, tileSize); diff --git a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/BundleFileResource.java b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/BundleFileResource.java index d61391e9da..8bcd90739c 100644 --- a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/BundleFileResource.java +++ b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/compact/BundleFileResource.java @@ -57,7 +57,8 @@ public long transferTo(WritableByteChannel target) throws IOException { FileChannel in = fin.getChannel()) { final long size = tileSize; long written = 0; - while ((written += in.transferTo(tileOffset + written, size, target)) < size) ; + while ((written += in.transferTo(tileOffset + written, size, target)) < size) + ; return size; } } diff --git a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/config/CacheInfoPersister.java b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/config/CacheInfoPersister.java index ebf1151e84..b7d9bf6023 100644 --- a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/config/CacheInfoPersister.java +++ b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/config/CacheInfoPersister.java @@ -86,8 +86,7 @@ public BoundingBox parseLayerBounds(final Reader layerBoundsFile) { EnvelopeN envN = (EnvelopeN) getConfiguredXStream().fromXML(layerBoundsFile); - BoundingBox bbox = - new BoundingBox(envN.getXmin(), envN.getYmin(), envN.getXmax(), envN.getYmax()); + BoundingBox bbox = new BoundingBox(envN.getXmin(), envN.getYmin(), envN.getXmax(), envN.getYmax()); return bbox; } diff --git a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/ArcGISCacheLayer.java b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/ArcGISCacheLayer.java index 1caeb04b55..00a84fc036 100644 --- a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/ArcGISCacheLayer.java +++ b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/ArcGISCacheLayer.java @@ -158,20 +158,16 @@ protected boolean initializeInternal(GridSetBroker gridSetBroker) { this.enabled = true; } if (this.tilingScheme == null) { - throw new IllegalStateException( - "tilingScheme has not been set. It should point to the ArcGIS " - + "cache tiling scheme file for this layer (conf.xml)"); + throw new IllegalStateException("tilingScheme has not been set. It should point to the ArcGIS " + + "cache tiling scheme file for this layer (conf.xml)"); } if (tileCachePath != null) { - if (!tileCachePath.exists() - || !tileCachePath.isDirectory() - || !tileCachePath.canRead()) { - throw new IllegalStateException( - "tileCachePath property for layer '" - + getName() - + "' is set to '" - + tileCachePath - + "' but the directory either does not exist or is not readable"); + if (!tileCachePath.exists() || !tileCachePath.isDirectory() || !tileCachePath.canRead()) { + throw new IllegalStateException("tileCachePath property for layer '" + + getName() + + "' is set to '" + + tileCachePath + + "' but the directory either does not exist or is not readable"); } } if (this.hexZoom == null) { @@ -182,8 +178,7 @@ protected boolean initializeInternal(GridSetBroker gridSetBroker) { cacheInfo = tilingSchemeLoader.load(new FileReader(tilingScheme)); File layerBoundsFile = new File(tilingScheme.getParentFile(), "conf.cdi"); if (!layerBoundsFile.exists()) { - throw new RuntimeException( - "Layer bounds file not found: " + layerBoundsFile.getAbsolutePath()); + throw new RuntimeException("Layer bounds file not found: " + layerBoundsFile.getAbsolutePath()); } log.info("Parsing layer bounds for " + getName()); this.layerBounds = tilingSchemeLoader.parseLayerBounds(new FileReader(layerBoundsFile)); @@ -204,14 +199,12 @@ protected boolean initializeInternal(GridSetBroker gridSetBroker) { } } } catch (FileNotFoundException e) { - throw new IllegalStateException( - "Tiling scheme file not found: " + tilingScheme.getAbsolutePath()); + throw new IllegalStateException("Tiling scheme file not found: " + tilingScheme.getAbsolutePath()); } - log.info( - "Configuring layer " - + getName() - + " out of the ArcGIS tiling scheme " - + tilingScheme.getAbsolutePath()); + log.info("Configuring layer " + + getName() + + " out of the ArcGIS tiling scheme " + + tilingScheme.getAbsolutePath()); super.subSets = createGridSubsets(gridSetBroker); super.formats = loadMimeTypes(); @@ -251,8 +244,7 @@ private HashMap createGridSubsets(final GridSetBroker gridSe Integer zoomStart = lodInfos.get(0).getLevelID(); Integer zoomStop = lodInfos.get(lodInfos.size() - 1).getLevelID(); - GridSubset subSet = - GridSubsetFactory.createGridSubSet(gridSet, this.layerBounds, zoomStart, zoomStop); + GridSubset subSet = GridSubsetFactory.createGridSubSet(gridSet, this.layerBounds, zoomStart, zoomStop); HashMap subsets = new HashMap<>(); subsets.put(gridSet.getName(), subSet); @@ -465,8 +457,7 @@ public ConveyorTile getNoncachedTile(ConveyorTile tile) throws GeoWebCacheExcept * @see org.geowebcache.layer.TileLayer#seedTile(org.geowebcache.conveyor.ConveyorTile, boolean) */ @Override - public void seedTile(ConveyorTile tile, boolean tryCache) - throws GeoWebCacheException, IOException { + public void seedTile(ConveyorTile tile, boolean tryCache) throws GeoWebCacheException, IOException { throw new UnsupportedOperationException(); } diff --git a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/GridSetBuilder.java b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/GridSetBuilder.java index 7f3a319db0..3031b673b4 100644 --- a/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/GridSetBuilder.java +++ b/geowebcache/arcgiscache/src/main/java/org/geowebcache/arcgis/layer/GridSetBuilder.java @@ -34,8 +34,7 @@ class GridSetBuilder { /** Creates a {@link GridSet} out of a ArcGIS tiling scheme */ - public GridSet buildGridset( - final String layerName, final CacheInfo info, final BoundingBox layerBounds) { + public GridSet buildGridset(final String layerName, final CacheInfo info, final BoundingBox layerBounds) { Assert.notNull(layerName, "Layer name must be non null"); Assert.notNull(info, "Layer name must be non null"); @@ -106,20 +105,19 @@ public GridSet buildGridset( } String gridsetName = srs.toString() + "_" + layerName; - GridSet layerGridset = - GridSetFactory.createGridSet( - gridsetName, - srs, - gridSetExtent, - alignTopLeft, - resolutions, - scaleDenominators, - metersPerUnit, - pixelSize, - scaleNames, - tileWidth, - tileHeight, - yCoordinateFirst); + GridSet layerGridset = GridSetFactory.createGridSet( + gridsetName, + srs, + gridSetExtent, + alignTopLeft, + resolutions, + scaleDenominators, + metersPerUnit, + pixelSize, + scaleNames, + tileWidth, + tileHeight, + yCoordinateFirst); return layerGridset; } diff --git a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheTest.java b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheTest.java index 603925fb7f..31ae162f80 100755 --- a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheTest.java +++ b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/compact/ArcGISCompactCacheTest.java @@ -37,18 +37,7 @@ */ public class ArcGISCompactCacheTest { private static final byte[] JFIFHeader = { - (byte) 0xFF, - (byte) 0xD8, - (byte) 0xFF, - (byte) 0xE0, - 0x00, - 0x10, - 0x4A, - 0x46, - 0x49, - 0x46, - 0x00, - 0x01 + (byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01 }; @Test diff --git a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/config/CacheInfoPersisterTest.java b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/config/CacheInfoPersisterTest.java index 171ee49101..a0b8918400 100644 --- a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/config/CacheInfoPersisterTest.java +++ b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/config/CacheInfoPersisterTest.java @@ -13,23 +13,22 @@ public class CacheInfoPersisterTest { @Test public void testLoadSpatialReference() { - String spatialRef = - "" // - + " PROJCS["NZGD_2000_New_Zealand_Transverse_Mercator",GEOGCS["GCS_NZGD_2000",DATUM["D_NZGD_2000",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",1600000.0],PARAMETER["False_Northing",10000000.0],PARAMETER["Central_Meridian",173.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0],AUTHORITY["EPSG",2193]]" // - + " -4020900" // - + " 1900" // - + " 450445547.3910538" // - + " 0.5" // - + " 1" // - + " -100000" // - + " 10000" // - + " 0.0037383177570093459" // - + " 2" // - + " 2" // - + " true" // - + " 2193" // - + " 2193" // - + ""; + String spatialRef = "" // + + " PROJCS["NZGD_2000_New_Zealand_Transverse_Mercator",GEOGCS["GCS_NZGD_2000",DATUM["D_NZGD_2000",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",1600000.0],PARAMETER["False_Northing",10000000.0],PARAMETER["Central_Meridian",173.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0],AUTHORITY["EPSG",2193]]" // + + " -4020900" // + + " 1900" // + + " 450445547.3910538" // + + " 0.5" // + + " 1" // + + " -100000" // + + " 10000" // + + " 0.0037383177570093459" // + + " 2" // + + " 2" // + + " true" // + + " 2193" // + + " 2193" // + + ""; CacheInfoPersister persister = new CacheInfoPersister(); XStream xs = persister.getConfiguredXStream(); @@ -55,11 +54,10 @@ public void testLoadSpatialReference() { @Test public void testLoadTileOrigin() { - String tileOrigin = - "" // - + " -4020900" // - + " 19998100" // - + ""; + String tileOrigin = "" // + + " -4020900" // + + " 19998100" // + + ""; CacheInfoPersister persister = new CacheInfoPersister(); XStream xs = persister.getConfiguredXStream(); TileOrigin to = (TileOrigin) xs.fromXML(new StringReader(tileOrigin)); @@ -70,23 +68,22 @@ public void testLoadTileOrigin() { @Test public void testLoadTileCacheInfo() { - String tileCacheInfo = - "" // - + " " // - + " " // - + " " // - + " -4020900" // - + " 19998100" // - + " " // - + " 512" // - + " 512" // - + " 96" // - + " 96" // - + " " // - + " " // - + " " // - + " " // - + ""; + String tileCacheInfo = "" // + + " " // + + " " // + + " " // + + " -4020900" // + + " 19998100" // + + " " // + + " 512" // + + " 512" // + + " 96" // + + " 96" // + + " " // + + " " // + + " " // + + " " // + + ""; CacheInfoPersister persister = new CacheInfoPersister(); XStream xs = persister.getConfiguredXStream(); @@ -104,12 +101,11 @@ public void testLoadTileCacheInfo() { @Test public void testLoadLODInfo() { - String lodInfo = - "" // - + " 10" // - + " 6000000" // - + " 1587.5031750063501" // - + ""; + String lodInfo = "" // + + " 10" // + + " 6000000" // + + " 1587.5031750063501" // + + ""; CacheInfoPersister persister = new CacheInfoPersister(); XStream xs = persister.getConfiguredXStream(); @@ -122,14 +118,13 @@ public void testLoadLODInfo() { @Test public void testLoadTileImageInfo() { - String tileImageInfo = - "" // - + " JPEG" // - + " 80" // - + " true" // - + " 1" // - + " 0" // - + ""; + String tileImageInfo = "" // + + " JPEG" // + + " 80" // + + " true" // + + " 1" // + + " 0" // + + ""; CacheInfoPersister persister = new CacheInfoPersister(); XStream xs = persister.getConfiguredXStream(); @@ -144,11 +139,10 @@ public void testLoadTileImageInfo() { @Test public void testLoadCacheStorageInfo() { - String cacheStorageInfo = - "" // - + " esriMapCacheStorageModeExploded" // - + " 10" // - + ""; + String cacheStorageInfo = "" // + + " esriMapCacheStorageModeExploded" // + + " 10" // + + ""; CacheInfoPersister persister = new CacheInfoPersister(); XStream xs = persister.getConfiguredXStream(); diff --git a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISCacheLayerTest.java b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISCacheLayerTest.java index 25ebd8ee4e..498f524994 100644 --- a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISCacheLayerTest.java +++ b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISCacheLayerTest.java @@ -31,7 +31,8 @@ import org.springframework.context.ApplicationContext; public class ArcGISCacheLayerTest { - @Rule public TemporaryFolder temp = new TemporaryFolder(); + @Rule + public TemporaryFolder temp = new TemporaryFolder(); @Test public void testArcGISCacheLayerInitialization() throws Exception { diff --git a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISLayerXMLConfigurationProviderTest.java b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISLayerXMLConfigurationProviderTest.java index eca0488fed..0e67dd86ca 100644 --- a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISLayerXMLConfigurationProviderTest.java +++ b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/ArcGISLayerXMLConfigurationProviderTest.java @@ -13,15 +13,12 @@ public class ArcGISLayerXMLConfigurationProviderTest { public void testGetConfiguredXStream() { final Map aliases = new HashMap<>(); - XStream xs = - new ArcGISLayerXMLConfigurationProvider() - .getConfiguredXStream( - new GeoWebCacheXStream() { - @Override - public void alias(String alias, Class c) { - aliases.put(alias, c); - } - }); + XStream xs = new ArcGISLayerXMLConfigurationProvider().getConfiguredXStream(new GeoWebCacheXStream() { + @Override + public void alias(String alias, Class c) { + aliases.put(alias, c); + } + }); Assert.assertNotNull(xs); Assert.assertEquals(ArcGISCacheLayer.class, aliases.get("arcgisLayer")); diff --git a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/XMLConfigurationLayerConformanceWithArcGisLayersTest.java b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/XMLConfigurationLayerConformanceWithArcGisLayersTest.java index 963c67b0bf..814a875eed 100644 --- a/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/XMLConfigurationLayerConformanceWithArcGisLayersTest.java +++ b/geowebcache/arcgiscache/src/test/java/org/geowebcache/arcgis/layer/XMLConfigurationLayerConformanceWithArcGisLayersTest.java @@ -44,8 +44,7 @@ import org.hamcrest.Matchers; import org.junit.Test; -public class XMLConfigurationLayerConformanceWithArcGisLayersTest - extends XMLConfigurationLayerConformanceTest { +public class XMLConfigurationLayerConformanceWithArcGisLayersTest extends XMLConfigurationLayerConformanceTest { @Override public void setUpTestUnit() throws Exception { @@ -105,15 +104,13 @@ public ConveyorTile getNoncachedTile(ConveyorTile tile) throws GeoWebCacheExcept } @Override - public void seedTile(ConveyorTile tile, boolean tryCache) - throws GeoWebCacheException, IOException { + public void seedTile(ConveyorTile tile, boolean tryCache) throws GeoWebCacheException, IOException { // TODO Auto-generated method stub } @Override - public ConveyorTile doNonMetatilingRequest(ConveyorTile tile) - throws GeoWebCacheException { + public ConveyorTile doNonMetatilingRequest(ConveyorTile tile) throws GeoWebCacheException { // TODO Auto-generated method stub return null; } @@ -123,17 +120,12 @@ public ConveyorTile doNonMetatilingRequest(ConveyorTile tile) @Override protected Matcher infoEquals(TileLayer expected) { return new CustomMatcher<>( - "ArcGISCacheLayer matching " - + expected.getName() - + " with " - + expected.getBackendTimeout()) { + "ArcGISCacheLayer matching " + expected.getName() + " with " + expected.getBackendTimeout()) { @Override public boolean matches(Object item) { return item instanceof ArcGISCacheLayer - && ((ArcGISCacheLayer) item) - .getBackendTimeout() - .equals(expected.getBackendTimeout()); + && ((ArcGISCacheLayer) item).getBackendTimeout().equals(expected.getBackendTimeout()); } }; } @@ -166,22 +158,16 @@ protected void makeConfigFile() throws Exception { configDir = temp.getRoot(); configFile = temp.newFile("geowebcache.xml"); - URL source = - XMLConfigurationLayerConformanceWithArcGisLayersTest.class.getResource( - "geowebcache.xml"); + URL source = XMLConfigurationLayerConformanceWithArcGisLayersTest.class.getResource("geowebcache.xml"); try (Stream lines = Files.lines(Paths.get(source.toURI()))) { - List replaced = - lines.map( - line -> { - String tilingSchemePath = - resourceAsFile("/compactcache/Conf.xml") - .getAbsolutePath(); - // no need to use replaceAll and involve regex - // replacement rules - return line.replace( - "TILING_SCHEME_PATH", tilingSchemePath); - }) - .collect(Collectors.toList()); + List replaced = lines.map(line -> { + String tilingSchemePath = + resourceAsFile("/compactcache/Conf.xml").getAbsolutePath(); + // no need to use replaceAll and involve regex + // replacement rules + return line.replace("TILING_SCHEME_PATH", tilingSchemePath); + }) + .collect(Collectors.toList()); Files.write(configFile.toPath(), replaced); } } @@ -190,11 +176,8 @@ protected void makeConfigFile() throws Exception { @Override protected TileLayerConfiguration getConfig(MockWepAppContextRule extensions) throws Exception { extensions.addBean( - "ArcGISLayerConfigProvider", - new ArcGISLayerXMLConfigurationProvider(), - XMLConfigurationProvider.class); - ArcGISCacheGridsetConfiguration arcGISCacheGridsetConfiguration = - new ArcGISCacheGridsetConfiguration(); + "ArcGISLayerConfigProvider", new ArcGISLayerXMLConfigurationProvider(), XMLConfigurationProvider.class); + ArcGISCacheGridsetConfiguration arcGISCacheGridsetConfiguration = new ArcGISCacheGridsetConfiguration(); extensions.addBean( "ArcGISLayerGridSetConfiguration", arcGISCacheGridsetConfiguration, @@ -210,10 +193,7 @@ public void testGetExistingHasGridset() throws Exception { Optional retrieved = getInfo(config, getExistingInfo()); assertThat( retrieved, - isPresent( - hasProperty( - "gridSubsets", - Matchers.containsInAnyOrder("EPSG:3857_testExisting")))); + isPresent(hasProperty("gridSubsets", Matchers.containsInAnyOrder("EPSG:3857_testExisting")))); } @Test diff --git a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java index a3a08f8ec4..91f7228921 100644 --- a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java +++ b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java @@ -69,8 +69,7 @@ public class AzureBlobStore implements BlobStore { private volatile boolean shutDown = false; - public AzureBlobStore( - AzureBlobStoreData configuration, TileLayerDispatcher layers, LockProvider lockProvider) + public AzureBlobStore(AzureBlobStoreData configuration, TileLayerDispatcher layers, LockProvider lockProvider) throws StorageException { this.client = new AzureClient(configuration); @@ -81,16 +80,13 @@ public AzureBlobStore( boolean emptyFolder = !client.prefixExists(prefix); boolean existingMetadata = client.blobExists(keyBuilder.storeMetadata()); - CompositeBlobStore.checkSuitability( - configuration.getLocation(), existingMetadata, emptyFolder); + CompositeBlobStore.checkSuitability(configuration.getLocation(), existingMetadata, emptyFolder); // Just a marker to indicate this is a GWC cache. client.putProperties(keyBuilder.storeMetadata(), new Properties()); // deletes are a complicated beast, we have a dedicated class to run them - deleteManager = - new DeleteManager( - client, lockProvider, keyBuilder, configuration.getMaxConnections()); + deleteManager = new DeleteManager(client, lockProvider, keyBuilder, configuration.getMaxConnections()); deleteManager.issuePendingBulkDeletes(); } @@ -114,24 +110,21 @@ public boolean delete(String layerName) throws StorageException { } @Override - public boolean deleteByParametersId(String layerName, String parametersId) - throws StorageException { + public boolean deleteByParametersId(String layerName, String parametersId) throws StorageException { checkNotNull(layerName, "layerName"); checkNotNull(parametersId, "parametersId"); - boolean prefixExists = - keyBuilder.forParameters(layerName, parametersId).stream() - .map( - prefix -> { - try { - return deleteManager.scheduleAsyncDelete(prefix); - } catch (StorageException e) { - throw new UncheckedIOException(e); - } - }) - .reduce(Boolean::logicalOr) // Don't use Stream.anyMatch as it would short - // circuit - .orElse(false); + boolean prefixExists = keyBuilder.forParameters(layerName, parametersId).stream() + .map(prefix -> { + try { + return deleteManager.scheduleAsyncDelete(prefix); + } catch (StorageException e) { + throw new UncheckedIOException(e); + } + }) + .reduce(Boolean::logicalOr) // Don't use Stream.anyMatch as it would short + // circuit + .orElse(false); if (prefixExists) { listeners.sendParametersDeleted(layerName, parametersId); } @@ -139,8 +132,7 @@ public boolean deleteByParametersId(String layerName, String parametersId) } @Override - public boolean deleteByGridsetId(final String layerName, final String gridSetId) - throws StorageException { + public boolean deleteByGridsetId(final String layerName, final String gridSetId) throws StorageException { checkNotNull(layerName, "layerName"); checkNotNull(gridSetId, "gridSetId"); @@ -200,33 +192,26 @@ public boolean delete(TileRange tileRange) throws StorageException { } // open an iterator oer tile locations, to avoid memory accumulation - final Iterator tileLocations = - new AbstractIterator<>() { + final Iterator tileLocations = new AbstractIterator<>() { - // TileRange iterator with 1x1 meta tiling factor - private TileRangeIterator trIter = - new TileRangeIterator(tileRange, new int[] {1, 1}); + // TileRange iterator with 1x1 meta tiling factor + private TileRangeIterator trIter = new TileRangeIterator(tileRange, new int[] {1, 1}); - @Override - protected long[] computeNext() { - long[] gridLoc = trIter.nextMetaGridLocation(new long[3]); - return gridLoc == null ? endOfData() : gridLoc; - } - }; + @Override + protected long[] computeNext() { + long[] gridLoc = trIter.nextMetaGridLocation(new long[3]); + return gridLoc == null ? endOfData() : gridLoc; + } + }; // if no listeners, we don't need to gather extra tile info, use a dedicated fast path if (listeners.isEmpty()) { // if there are no listeners, don't bother requesting every tile // metadata to notify the listeners - Iterator keysIterator = - Iterators.transform( - tileLocations, - tl -> - keyBuilder.forLocation( - coordsPrefix, tl, tileRange.getMimeType())); + Iterator keysIterator = Iterators.transform( + tileLocations, tl -> keyBuilder.forLocation(coordsPrefix, tl, tileRange.getMimeType())); // split the iteration in parts to avoid memory accumulation - Iterator> partition = - Iterators.partition(keysIterator, DeleteManager.PAGE_SIZE); + Iterator> partition = Iterators.partition(keysIterator, DeleteManager.PAGE_SIZE); while (partition.hasNext() && !shutDown) { List locations = partition.next(); @@ -242,18 +227,12 @@ protected long[] computeNext() { String format = tileRange.getMimeType().getFormat(); Map parameters = tileRange.getParameters(); - Iterator> tilesIterator = - Iterators.transform( - tileLocations, - xyz -> { - TileObject tile = - TileObject.createQueryTileObject( - layerName, xyz, gridSetId, format, parameters); - tile.setParametersId(tileRange.getParametersId()); - return (Callable) () -> delete(tile); - }); - Iterator>> partition = - Iterators.partition(tilesIterator, DeleteManager.PAGE_SIZE); + Iterator> tilesIterator = Iterators.transform(tileLocations, xyz -> { + TileObject tile = TileObject.createQueryTileObject(layerName, xyz, gridSetId, format, parameters); + tile.setParametersId(tileRange.getParametersId()); + return (Callable) () -> delete(tile); + }); + Iterator>> partition = Iterators.partition(tilesIterator, DeleteManager.PAGE_SIZE); // once a page of callables is ready, run them in parallel on the delete manager while (partition.hasNext() && !shutDown) { @@ -322,11 +301,7 @@ public void put(TileObject obj) throws StorageException { client.upload(key, data, mimeType); } catch (StorageException e) { throw new StorageException( - "Failed to upload tile to Azure on container " - + client.getContainerName() - + " and key " - + key, - e); + "Failed to upload tile to Azure on container " + client.getContainerName() + " and key " + key, e); } catch (IOException e) { throw new StorageException("Error obtaining date from TileObject " + obj); } @@ -354,8 +329,7 @@ private String getMimeType(TileObject obj) { return mimeType; } - private void putParametersMetadata( - String layerName, String parametersId, Map parameters) { + private void putParametersMetadata(String layerName, String parametersId, Map parameters) { assert (isNull(parametersId) == isNull(parameters)); if (isNull(parametersId)) { return; diff --git a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreData.java b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreData.java index db30d793c2..d23a64db7e 100644 --- a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreData.java +++ b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreData.java @@ -38,14 +38,11 @@ public class AzureBlobStoreData { public AzureBlobStoreData() {} - public AzureBlobStoreData( - final AzureBlobStoreInfo storeInfo, final GeoWebCacheEnvironment environment) { + public AzureBlobStoreData(final AzureBlobStoreInfo storeInfo, final GeoWebCacheEnvironment environment) { environment .resolveValueIfEnabled(storeInfo.getContainer(), String.class) .ifPresent(x -> this.container = x); - environment - .resolveValueIfEnabled(storeInfo.getPrefix(), String.class) - .ifPresent(x -> this.prefix = x); + environment.resolveValueIfEnabled(storeInfo.getPrefix(), String.class).ifPresent(x -> this.prefix = x); environment .resolveValueIfEnabled(storeInfo.getAccountName(), String.class) .ifPresent(x -> this.accountName = x); @@ -175,9 +172,7 @@ public String getLocation() { Proxy getProxy() { if (proxyHost != null) { - return new Proxy( - Proxy.Type.HTTP, - new InetSocketAddress(proxyHost, proxyPort != null ? proxyPort : 8888)); + return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort != null ? proxyPort : 8888)); } return null; } diff --git a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreInfo.java b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreInfo.java index dcbadc6b3b..1b3c5c77f7 100644 --- a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreInfo.java +++ b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStoreInfo.java @@ -220,18 +220,13 @@ public void setProxyPassword(String proxyPassword) { } @Override - public BlobStore createInstance(TileLayerDispatcher layers, LockProvider lockProvider) - throws StorageException { + public BlobStore createInstance(TileLayerDispatcher layers, LockProvider lockProvider) throws StorageException { checkNotNull(layers); checkState(getName() != null); - checkState( - isEnabled(), - "Can't call AzureBlobStoreConfig.createInstance() is blob store is not enabled"); - if (log.isLoggable(Level.FINE)) - log.fine("Creating Azure Blob Store instance [name=" + getName() + "]"); + checkState(isEnabled(), "Can't call AzureBlobStoreConfig.createInstance() is blob store is not enabled"); + if (log.isLoggable(Level.FINE)) log.fine("Creating Azure Blob Store instance [name=" + getName() + "]"); final AzureBlobStoreData storeData = - new AzureBlobStoreData( - this, GeoWebCacheExtensions.bean(GeoWebCacheEnvironment.class)); + new AzureBlobStoreData(this, GeoWebCacheExtensions.bean(GeoWebCacheEnvironment.class)); return new AzureBlobStore(storeData, layers, lockProvider); } diff --git a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureClient.java b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureClient.java index eb8b3ad524..a0540b960a 100644 --- a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureClient.java +++ b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureClient.java @@ -93,11 +93,10 @@ BlobServiceClient createBlobServiceClient(AzureBlobStoreData configuration) { AzureNamedKeyCredential creds = getCredentials(configuration); ClientOptions clientOpts = new ClientOptions(); HttpClient httpClient = createHttpClient(configuration); - BlobServiceClientBuilder builder = - new BlobServiceClientBuilder() - .endpoint(serviceURL) - .clientOptions(clientOpts) - .httpClient(httpClient); + BlobServiceClientBuilder builder = new BlobServiceClientBuilder() + .endpoint(serviceURL) + .clientOptions(clientOpts) + .httpClient(httpClient); if (null != creds) { builder = builder.credential(creds); } @@ -193,9 +192,7 @@ public Properties getProperties(String key) { byte[] bytes = getBytes(key); if (bytes != null) { try { - properties.load( - new InputStreamReader( - new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)); + properties.load(new InputStreamReader(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -211,13 +208,11 @@ public void putProperties(String resourceKey, Properties properties) throws Stor try { upload(resourceKey, data, contentType); } catch (StorageException e) { - throw new StorageException( - "Failed to update e property file at " + resourceKey, e.getCause()); + throw new StorageException("Failed to update e property file at " + resourceKey, e.getCause()); } } - public void upload(String resourceKey, BinaryData data, String contentType) - throws StorageException { + public void upload(String resourceKey, BinaryData data, String contentType) throws StorageException { BlockBlobSimpleUploadOptions upload = new BlockBlobSimpleUploadOptions(data); upload.setHeaders(new BlobHttpHeaders().setContentType(contentType)); @@ -233,8 +228,7 @@ public void upload(String resourceKey, BinaryData data, String contentType) } int status = response.getStatusCode(); if (!HttpStatus.valueOf(status).is2xxSuccessful()) { - throw new StorageException( - "Upload request failed with status " + status + " on resource " + resourceKey); + throw new StorageException("Upload request failed with status " + status + " on resource " + resourceKey); } } diff --git a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/DeleteManager.java b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/DeleteManager.java index 0c5e4204d6..69098d5053 100644 --- a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/DeleteManager.java +++ b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/DeleteManager.java @@ -73,26 +73,20 @@ class DeleteManager implements Closeable { private ExecutorService deleteExecutor; private Map pendingDeletesKeyTime = new ConcurrentHashMap<>(); - public DeleteManager( - AzureClient client, LockProvider locks, TMSKeyBuilder keyBuilder, int maxConnections) { + public DeleteManager(AzureClient client, LockProvider locks, TMSKeyBuilder keyBuilder, int maxConnections) { this.keyBuilder = keyBuilder; this.client = client; this.locks = locks; this.concurrency = maxConnections; - this.deleteExecutor = - createDeleteExecutorService(client.getContainerName(), maxConnections); + this.deleteExecutor = createDeleteExecutorService(client.getContainerName(), maxConnections); } - private static ExecutorService createDeleteExecutorService( - String containerName, int parallelism) { - ThreadFactory tf = - new ThreadFactoryBuilder() - .setDaemon(true) - .setNameFormat( - "GWC AzureBlobStore bulk delete thread-%d. Container: " - + containerName) - .setPriority(Thread.MIN_PRIORITY) - .build(); + private static ExecutorService createDeleteExecutorService(String containerName, int parallelism) { + ThreadFactory tf = new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("GWC AzureBlobStore bulk delete thread-%d. Container: " + containerName) + .setPriority(Thread.MIN_PRIORITY) + .build(); return Executors.newFixedThreadPool(parallelism, tf); } @@ -133,10 +127,9 @@ public Long deleteParallel(List keys) throws StorageException { public boolean scheduleAsyncDelete(final String prefix) throws StorageException { final long timestamp = currentTimeSeconds(); - String msg = - String.format( - "Issuing bulk delete on '%s/%s' for objects older than %d", - client.getContainerName(), prefix, timestamp); + String msg = String.format( + "Issuing bulk delete on '%s/%s' for objects older than %d", + client.getContainerName(), prefix, timestamp); log.info(msg); try { @@ -174,10 +167,9 @@ public void issuePendingBulkDeletes() throws StorageException { final String prefix = e.getKey().toString(); final long timestamp = Long.parseLong(e.getValue().toString()); if (log.isLoggable(Level.INFO)) - log.info( - String.format( - "Restarting pending bulk delete on '%s/%s':%d", - client.getContainerName(), prefix, timestamp)); + log.info(String.format( + "Restarting pending bulk delete on '%s/%s':%d", + client.getContainerName(), prefix, timestamp)); if (!asyncDelete(prefix, timestamp)) { deletesToClear.add(prefix); } @@ -235,10 +227,8 @@ public Long call() throws Exception { try { checkInterrupted(); if (log.isLoggable(Level.INFO)) - log.info( - String.format( - "Running bulk delete on '%s/%s':%d", - client.getContainerName(), prefix, timestamp)); + log.info(String.format( + "Running bulk delete on '%s/%s':%d", client.getContainerName(), prefix, timestamp)); BlobContainerClient container = client.getContainer(); @@ -256,10 +246,9 @@ public Long call() throws Exception { } } } catch (InterruptedException | IllegalStateException e) { - log.info( - String.format( - "Azure bulk delete aborted for '%s/%s'. Will resume on next startup.", - client.getContainerName(), prefix)); + log.info(String.format( + "Azure bulk delete aborted for '%s/%s'. Will resume on next startup.", + client.getContainerName(), prefix)); throw e; } catch (RuntimeException e) { log.log( @@ -272,10 +261,9 @@ public Long call() throws Exception { } if (log.isLoggable(Level.INFO)) - log.info( - String.format( - "Finished bulk delete on '%s/%s':%d. %d objects deleted", - client.getContainerName(), prefix, timestamp, count)); + log.info(String.format( + "Finished bulk delete on '%s/%s':%d. %d objects deleted", + client.getContainerName(), prefix, timestamp, count)); clearPendingBulkDelete(prefix, timestamp); return count; @@ -287,8 +275,7 @@ private boolean equalOrAfter(BlobItem blobItem) { return timestamp >= lastModifiedSecs; } - private void clearPendingBulkDelete(final String prefix, final long timestamp) - throws GeoWebCacheException { + private void clearPendingBulkDelete(final String prefix, final long timestamp) throws GeoWebCacheException { Long taskTime = pendingDeletesKeyTime.get(prefix); if (taskTime == null) { return; // someone else cleared it up for us. A task that run after this one but @@ -303,15 +290,13 @@ private void clearPendingBulkDelete(final String prefix, final long timestamp) try { Properties deletes = client.getProperties(pendingDeletesKey); String storedVal = (String) deletes.remove(prefix); - long storedTimestamp = - storedVal == null ? Long.MIN_VALUE : Long.parseLong(storedVal); + long storedTimestamp = storedVal == null ? Long.MIN_VALUE : Long.parseLong(storedVal); if (timestamp >= storedTimestamp) { client.putProperties(pendingDeletesKey, deletes); } else if (log.isLoggable(Level.INFO)) { - log.info( - String.format( - "bulk delete finished but there's a newer one ongoing for container '%s/%s'", - client.getContainerName(), prefix)); + log.info(String.format( + "bulk delete finished but there's a newer one ongoing for container '%s/%s'", + client.getContainerName(), prefix)); } } catch (StorageException e) { throw new UncheckedIOException(e); @@ -320,21 +305,16 @@ private void clearPendingBulkDelete(final String prefix, final long timestamp) } } - private long deleteItems( - BlobContainerClient container, List segment, Predicate filter) + private long deleteItems(BlobContainerClient container, List segment, Predicate filter) throws ExecutionException, InterruptedException { - List> collect = - segment.stream() - .filter(filter) - .map( - item -> - deleteExecutor.submit( - () -> { - deleteItem(container, item.getName()); - return null; - })) - .collect(Collectors.toList()); + List> collect = segment.stream() + .filter(filter) + .map(item -> deleteExecutor.submit(() -> { + deleteItem(container, item.getName()); + return null; + })) + .collect(Collectors.toList()); for (Future f : collect) { f.get(); @@ -357,11 +337,9 @@ public Long call() throws Exception { try { checkInterrupted(); if (log.isLoggable(Level.FINER)) { - log.finer( - String.format( - "Running delete delete on list of items on '%s':%s ... (only the first 100 items listed)", - client.getContainerName(), - keys.subList(0, Math.min(keys.size(), 100)))); + log.finer(String.format( + "Running delete delete on list of items on '%s':%s ... (only the first 100 items listed)", + client.getContainerName(), keys.subList(0, Math.min(keys.size(), 100)))); } BlobContainerClient container = client.getContainer(); @@ -378,19 +356,16 @@ public Long call() throws Exception { } if (log.isLoggable(Level.INFO)) - log.info( - String.format( - "Finished bulk delete on %s, %d objects deleted", - client.getContainerName(), count)); + log.info(String.format( + "Finished bulk delete on %s, %d objects deleted", client.getContainerName(), count)); return count; } private long deleteItems(BlobContainerClient container, List itemNames) throws ExecutionException, InterruptedException { - List> collect = - itemNames.stream() - .map(item -> deleteExecutor.submit(() -> deleteItem(container, item))) - .collect(Collectors.toList()); + List> collect = itemNames.stream() + .map(item -> deleteExecutor.submit(() -> deleteItem(container, item))) + .collect(Collectors.toList()); for (Future f : collect) { f.get(); diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConfigProviderTest.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConfigProviderTest.java index 81af95560a..4bf1602d40 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConfigProviderTest.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConfigProviderTest.java @@ -34,8 +34,7 @@ public void setUp() throws Exception { System.setProperty("CONNECTIONS", "30"); System.setProperty("ENABLED", "true"); System.setProperty("ALLOW_ENV_PARAMETRIZATION", "true"); - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext("appContextTestAzure.xml"); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appContextTestAzure.xml"); GeoWebCacheExtensions gse = new GeoWebCacheExtensions(); gse.setApplicationContext(context); diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConformanceTest.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConformanceTest.java index e38cc0ad92..baa7031b9f 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConformanceTest.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreConformanceTest.java @@ -48,23 +48,19 @@ public void createTestUnit() throws Exception { TileLayerDispatcher layers = createMock(TileLayerDispatcher.class); LockProvider lockProvider = new NoOpLockProvider(); Stream.of("testLayer", "testLayer1", "testLayer2") - .map( - name -> { - TileLayer mock = createMock(name, TileLayer.class); - expect(mock.getName()).andStubReturn(name); - expect(mock.getId()).andStubReturn(name); - expect(mock.getGridSubsets()) - .andStubReturn(Collections.singleton("testGridSet")); - expect(mock.getMimeTypes()) - .andStubReturn( - Arrays.asList(org.geowebcache.mime.ImageMime.png)); - try { - expect(layers.getTileLayer(eq(name))).andStubReturn(mock); - } catch (GeoWebCacheException e) { - fail(); - } - return mock; - }) + .map(name -> { + TileLayer mock = createMock(name, TileLayer.class); + expect(mock.getName()).andStubReturn(name); + expect(mock.getId()).andStubReturn(name); + expect(mock.getGridSubsets()).andStubReturn(Collections.singleton("testGridSet")); + expect(mock.getMimeTypes()).andStubReturn(Arrays.asList(org.geowebcache.mime.ImageMime.png)); + try { + expect(layers.getTileLayer(eq(name))).andStubReturn(mock); + } catch (GeoWebCacheException e) { + fail(); + } + return mock; + }) .forEach(EasyMock::replay); replay(layers); store = new AzureBlobStore(config, layers, lockProvider); diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreDataTest.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreDataTest.java index bafee3db62..543331e2ce 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreDataTest.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreDataTest.java @@ -33,8 +33,7 @@ public void setUp() throws Exception { System.setProperty("ACCOUNT_KEY", "MYKEY"); System.setProperty("CONNECTIONS", "30"); System.setProperty("ALLOW_ENV_PARAMETRIZATION", "true"); - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext("appContextTestAzure.xml"); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appContextTestAzure.xml"); GeoWebCacheExtensions gse = new GeoWebCacheExtensions(); gse.setApplicationContext(context); } @@ -50,8 +49,7 @@ public void tearDown() throws Exception { @Test public void testEnvironmentProperties() { - GeoWebCacheEnvironment typedEnvironment = - GeoWebCacheExtensions.bean(GeoWebCacheEnvironment.class); + GeoWebCacheEnvironment typedEnvironment = GeoWebCacheExtensions.bean(GeoWebCacheEnvironment.class); final AzureBlobStoreInfo storeInfo = new AzureBlobStoreInfo("info1"); storeInfo.setContainer("${CONTAINER}"); storeInfo.setAccountName("${ACCOUNT_NAME}"); diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreIntegrationTest.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreIntegrationTest.java index 5906f9e7b2..73185fe59e 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreIntegrationTest.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreIntegrationTest.java @@ -285,8 +285,7 @@ public void testDeleteLayer() throws Exception { // check the tiles are gone too, give it up to 100 seconds long start = System.currentTimeMillis(); boolean t20Deleted = false, t21Deleted = false, t22Deleted = false; - while (System.currentTimeMillis() - start < 100000 - && (!t20Deleted || !t21Deleted || !t22Deleted)) { + while (System.currentTimeMillis() - start < 100000 && (!t20Deleted || !t21Deleted || !t22Deleted)) { if (!t20Deleted) { tile.getXYZ()[0] = 20; @@ -325,34 +324,21 @@ public void testDeleteGridSubset() throws Exception { // deletion by gridset is asynch, so we might have to wait a bit boolean t4326PngDeleted = false, t4326JpegDeleted = false; long start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < 100000 - && (!t4326PngDeleted || !t4326JpegDeleted)) { + while (System.currentTimeMillis() - start < 100000 && (!t4326PngDeleted || !t4326JpegDeleted)) { if (!t4326PngDeleted) { - t4326PngDeleted = - !blobStore.get(queryTile(DEFAULT_LAYER, "EPSG:4326", "png", 0, 0, 0)); + t4326PngDeleted = !blobStore.get(queryTile(DEFAULT_LAYER, "EPSG:4326", "png", 0, 0, 0)); } if (!t4326JpegDeleted) { t4326JpegDeleted = - !blobStore.get( - queryTile( - DEFAULT_LAYER, - "EPSG:4326", - "jpeg", - 0, - 0, - 0, - "param", - "value")); + !blobStore.get(queryTile(DEFAULT_LAYER, "EPSG:4326", "jpeg", 0, 0, 0, "param", "value")); } } assertTrue(t4326PngDeleted); assertTrue(t4326JpegDeleted); // these two should not have been touched assertTrue(blobStore.get(queryTile(DEFAULT_LAYER, "EPSG:3857", "png", 0, 0, 0))); - assertTrue( - blobStore.get( - queryTile(DEFAULT_LAYER, "EPSG:3857", "jpeg", 0, 0, 0, "param", "value"))); + assertTrue(blobStore.get(queryTile(DEFAULT_LAYER, "EPSG:3857", "jpeg", 0, 0, 0, "param", "value"))); } @Test @@ -366,8 +352,7 @@ public void testLayerMetadata() { } @Test - public void testTruncateShortCutsIfNoTilesInParametersPrefix() - throws StorageException, MimeException { + public void testTruncateShortCutsIfNoTilesInParametersPrefix() throws StorageException, MimeException { final int zoomStart = 0; final int zoomStop = 1; seed(zoomStart, zoomStop); @@ -375,8 +360,7 @@ public void testTruncateShortCutsIfNoTilesInParametersPrefix() blobStore.addListener(listener); GridSet gridset = - new GridSetBroker(Collections.singletonList(new DefaultGridsets(false, false))) - .getWorldEpsg4326(); + new GridSetBroker(Collections.singletonList(new DefaultGridsets(false, false))).getWorldEpsg4326(); GridSubset gridSubSet = GridSubsetFactory.createGridSubSet(gridset); long[][] rangeBounds = { // @@ -388,14 +372,7 @@ public void testTruncateShortCutsIfNoTilesInParametersPrefix() // use a parameters map for which there're no tiles Map parameters = ImmutableMap.of("someparam", "somevalue"); TileRange tileRange = - tileRange( - DEFAULT_LAYER, - DEFAULT_GRIDSET, - zoomStart, - zoomStop, - rangeBounds, - mimeType, - parameters); + tileRange(DEFAULT_LAYER, DEFAULT_GRIDSET, zoomStart, zoomStop, rangeBounds, mimeType, parameters); assertFalse(blobStore.delete(tileRange)); verify(listener, times(0)) @@ -411,8 +388,7 @@ public void testTruncateShortCutsIfNoTilesInParametersPrefix() } @Test - public void testTruncateShortCutsIfNoTilesInGridsetPrefix() - throws StorageException, MimeException { + public void testTruncateShortCutsIfNoTilesInGridsetPrefix() throws StorageException, MimeException { final int zoomStart = 0; final int zoomStop = 1; @@ -422,8 +398,7 @@ public void testTruncateShortCutsIfNoTilesInGridsetPrefix() // use a gridset for which there're no tiles GridSet gridset = - new GridSetBroker(Collections.singletonList(new DefaultGridsets(false, true))) - .getWorldEpsg3857(); + new GridSetBroker(Collections.singletonList(new DefaultGridsets(false, true))).getWorldEpsg3857(); GridSubset gridSubSet = GridSubsetFactory.createGridSubSet(gridset); long[][] rangeBounds = { // @@ -435,26 +410,12 @@ public void testTruncateShortCutsIfNoTilesInGridsetPrefix() Map parameters = null; TileRange tileRange = - tileRange( - DEFAULT_LAYER, - gridset.getName(), - zoomStart, - zoomStop, - rangeBounds, - mimeType, - parameters); + tileRange(DEFAULT_LAYER, gridset.getName(), zoomStart, zoomStop, rangeBounds, mimeType, parameters); assertFalse(blobStore.delete(tileRange)); verify(listener, times(0)) .tileDeleted( - anyString(), - anyString(), - anyString(), - anyString(), - anyLong(), - anyLong(), - anyInt(), - anyLong()); + anyString(), anyString(), anyString(), anyString(), anyLong(), anyLong(), anyInt(), anyLong()); } /** Seed levels 0 to 2, truncate levels 0 and 1, check level 2 didn't get deleted */ @@ -466,8 +427,7 @@ public void testTruncateRespectsLevels() throws StorageException, MimeException // use a gridset for which there're no tiles GridSet gridset = - new GridSetBroker(Collections.singletonList(new DefaultGridsets(false, true))) - .getWorldEpsg3857(); + new GridSetBroker(Collections.singletonList(new DefaultGridsets(false, true))).getWorldEpsg3857(); GridSubset gridSubSet = GridSubsetFactory.createGridSubSet(gridset); long[][] rangeBounds = gridSubSet.getCoverages(); @@ -483,15 +443,8 @@ public void testTruncateRespectsLevels() throws StorageException, MimeException final int truncateStart = 0, truncateStop = 1; - TileRange tileRange = - tileRange( - DEFAULT_LAYER, - gridset.getName(), - truncateStart, - truncateStop, - rangeBounds, - mimeType, - parameters); + TileRange tileRange = tileRange( + DEFAULT_LAYER, gridset.getName(), truncateStart, truncateStop, rangeBounds, mimeType, parameters); assertTrue(blobStore.delete(tileRange)); @@ -538,15 +491,8 @@ public void testTruncateOptimizationIfNoListeners() throws StorageException, Mim final int truncateStart = 0, truncateStop = 1; - TileRange tileRange = - tileRange( - DEFAULT_LAYER, - DEFAULT_GRIDSET, - truncateStart, - truncateStop, - rangeBounds, - mimeType, - parameters); + TileRange tileRange = tileRange( + DEFAULT_LAYER, DEFAULT_GRIDSET, truncateStart, truncateStop, rangeBounds, mimeType, parameters); @SuppressWarnings("PMD.CloseResource") // closed by the store DeleteManager deleteManager = Mockito.spy(blobStore.deleteManager); @@ -580,14 +526,7 @@ private TileRange tileRange( Map parameters) { TileRange tileRange = - new TileRange( - layerName, - gridSetId, - zoomStart, - zoomStop, - rangeBounds, - mimeType, - parameters); + new TileRange(layerName, gridSetId, zoomStart, zoomStop, rangeBounds, mimeType, parameters); return tileRange; } @@ -596,15 +535,10 @@ private void seed(int zoomStart, int zoomStop) throws StorageException { } private void seed( - int zoomStart, - int zoomStop, - String gridset, - String formatExtension, - Map parameters) + int zoomStart, int zoomStop, String gridset, String formatExtension, Map parameters) throws StorageException { - Preconditions.checkArgument( - zoomStop < 5, "don't use high zoom levels for integration testing"); + Preconditions.checkArgument(zoomStop < 5, "don't use high zoom levels for integration testing"); for (int z = zoomStart; z <= zoomStop; z++) { int max = (int) Math.pow(2, z); for (int x = 0; x < max; x++) { @@ -617,12 +551,7 @@ private void seed( } private TileObject put( - long x, - long y, - int z, - String gridset, - String formatExtension, - Map parameters) + long x, long y, int z, String gridset, String formatExtension, Map parameters) throws StorageException { return put(x, y, z, DEFAULT_LAYER, gridset, formatExtension, parameters); } @@ -648,19 +577,12 @@ private TileObject queryTile(long x, long y, int z) { return queryTile(DEFAULT_LAYER, DEFAULT_GRIDSET, DEFAULT_FORMAT, x, y, z); } - private TileObject queryTile( - String layer, String gridset, String extension, long x, long y, int z) { + private TileObject queryTile(String layer, String gridset, String extension, long x, long y, int z) { return queryTile(layer, gridset, extension, x, y, z, (Map) null); } private TileObject queryTile( - String layer, - String gridset, - String extension, - long x, - long y, - int z, - String... parameters) { + String layer, String gridset, String extension, long x, long y, int z, String... parameters) { Map parametersMap = null; if (parameters != null) { @@ -673,13 +595,7 @@ private TileObject queryTile( } private TileObject queryTile( - String layer, - String gridset, - String extension, - long x, - long y, - int z, - Map parameters) { + String layer, String gridset, String extension, long x, long y, int z, Map parameters) { String format; try { @@ -688,9 +604,7 @@ private TileObject queryTile( throw new RuntimeException(e); } - TileObject tile = - TileObject.createQueryTileObject( - layer, new long[] {x, y, z}, gridset, format, parameters); + TileObject tile = TileObject.createQueryTileObject(layer, new long[] {x, y, z}, gridset, format, parameters); return tile; } } diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreSuitabilityTest.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreSuitabilityTest.java index ea56ca3d92..bb6899a345 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreSuitabilityTest.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/AzureBlobStoreSuitabilityTest.java @@ -84,11 +84,9 @@ public BlobStore create(Object dir) throws Exception { for (String path : (String[]) dir) { String fullPath = info.getPrefix() + "/" + path; BinaryData data = BinaryData.fromString("testAbc"); - Response response = - getClient() - .getBlockBlobClient(fullPath) - .uploadWithResponse( - new BlockBlobSimpleUploadOptions(data), null, Context.NONE); + Response response = getClient() + .getBlockBlobClient(fullPath) + .uploadWithResponse(new BlockBlobSimpleUploadOptions(data), null, Context.NONE); assertTrue(HttpStatus.valueOf(response.getStatusCode()).is2xxSuccessful()); } return new AzureBlobStore(info, tld, locks); diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreConformanceIT.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreConformanceIT.java index aae6b52cdd..83eb147ae5 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreConformanceIT.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreConformanceIT.java @@ -34,7 +34,8 @@ public class AzuriteAzureBlobStoreConformanceIT extends AzureBlobStoreConformanc public static AzuriteContainer azurite = AzuriteContainer.latest().disabledWithoutDocker(); /** Used to get a per-test case Azure container */ - @Rule public TestName testName = new TestName(); + @Rule + public TestName testName = new TestName(); @Override protected AzureBlobStoreData getConfiguration() { diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreIntegrationIT.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreIntegrationIT.java index ac5ca2763d..6e4dba2545 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreIntegrationIT.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreIntegrationIT.java @@ -34,7 +34,8 @@ public class AzuriteAzureBlobStoreIntegrationIT extends AzureBlobStoreIntegratio public static AzuriteContainer azurite = AzuriteContainer.latest().disabledWithoutDocker(); /** Used to get a per-test case Azure container */ - @Rule public TestName testName = new TestName(); + @Rule + public TestName testName = new TestName(); @Override protected AzureBlobStoreData getConfiguration() { diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreSuitabilityIT.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreSuitabilityIT.java index ed7298e8d8..38eba25a31 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreSuitabilityIT.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/container/AzuriteAzureBlobStoreSuitabilityIT.java @@ -38,7 +38,8 @@ public class AzuriteAzureBlobStoreSuitabilityIT extends AzureBlobStoreSuitabilit public static AzuriteContainer azurite = AzuriteContainer.latest().disabledWithoutDocker(); /** Used to get a per-test case Azure container */ - @Rule public TestName testName = new TestName(); + @Rule + public TestName testName = new TestName(); @Override protected AzureBlobStoreData getConfiguration() { diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreConformanceIT.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreConformanceIT.java index ab89916d5b..b5740818c0 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreConformanceIT.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreConformanceIT.java @@ -23,8 +23,7 @@ public class OnlineAzureBlobStoreConformanceIT extends AzureBlobStoreConformance public PropertiesLoader testConfigLoader = new PropertiesLoader(); @Rule - public TemporaryAzureFolder tempFolder = - new TemporaryAzureFolder(testConfigLoader.getProperties()); + public TemporaryAzureFolder tempFolder = new TemporaryAzureFolder(testConfigLoader.getProperties()); @Override protected AzureBlobStoreData getConfiguration() { diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreIntegrationIT.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreIntegrationIT.java index 9571021536..ab556e1d8b 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreIntegrationIT.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreIntegrationIT.java @@ -27,8 +27,7 @@ public class OnlineAzureBlobStoreIntegrationIT extends AzureBlobStoreIntegration private PropertiesLoader testConfigLoader = new PropertiesLoader(); @Rule - public TemporaryAzureFolder tempFolder = - new TemporaryAzureFolder(testConfigLoader.getProperties()); + public TemporaryAzureFolder tempFolder = new TemporaryAzureFolder(testConfigLoader.getProperties()); @Override protected AzureBlobStoreData getConfiguration() { diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreSuitabilityIT.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreSuitabilityIT.java index c996d07529..2e78196d62 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreSuitabilityIT.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/OnlineAzureBlobStoreSuitabilityIT.java @@ -32,8 +32,7 @@ public class OnlineAzureBlobStoreSuitabilityIT extends AzureBlobStoreSuitability public PropertiesLoader testConfigLoader = new PropertiesLoader(); @Rule - public TemporaryAzureFolder tempFolder = - new TemporaryAzureFolder(testConfigLoader.getProperties()); + public TemporaryAzureFolder tempFolder = new TemporaryAzureFolder(testConfigLoader.getProperties()); @Override protected AzureBlobStoreData getConfiguration() { diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/PropertiesLoader.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/PropertiesLoader.java index 80c9887ce9..807eb5c2ec 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/PropertiesLoader.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/PropertiesLoader.java @@ -44,8 +44,7 @@ public class PropertiesLoader { public PropertiesLoader() { String home = System.getProperty("user.home"); File configFile = new File(home, ".gwc_azure_tests.properties"); - log.info( - "Loading Azure tests config. File must have keys 'container', 'accountName', and 'accountKey'"); + log.info("Loading Azure tests config. File must have keys 'container', 'accountName', and 'accountKey'"); if (configFile.exists()) { try (InputStream in = new FileInputStream(configFile)) { properties.load(in); @@ -59,15 +58,11 @@ public PropertiesLoader() { null != properties.getProperty("accountKey"), "accountKey not provided in config file " + configFile.getAbsolutePath()); } catch (IOException e) { - log.log( - Level.SEVERE, - "Error loading Azure tests config: " + configFile.getAbsolutePath(), - e); + log.log(Level.SEVERE, "Error loading Azure tests config: " + configFile.getAbsolutePath(), e); } } else { - log.warning( - "Azure storage config file not found. Azure Azure tests will be ignored. " - + configFile.getAbsolutePath()); + log.warning("Azure storage config file not found. Azure Azure tests will be ignored. " + + configFile.getAbsolutePath()); } } diff --git a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/TemporaryAzureFolder.java b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/TemporaryAzureFolder.java index c6d8222b76..4d6adf75a8 100644 --- a/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/TemporaryAzureFolder.java +++ b/geowebcache/azureblob/src/test/java/org/geowebcache/azure/tests/online/TemporaryAzureFolder.java @@ -116,13 +116,10 @@ public void delete() { } try (Stream blobs = client.listBlobs(temporaryPrefix)) { - blobs.forEach( - blob -> { - BlockBlobClient blockBlobURL = client.getBlockBlobClient(blob.getName()); - assertTrue( - "Expected success while deleting " + blob.getName(), - blockBlobURL.deleteIfExists()); - }); + blobs.forEach(blob -> { + BlockBlobClient blockBlobURL = client.getBlockBlobClient(blob.getName()); + assertTrue("Expected success while deleting " + blob.getName(), blockBlobURL.deleteIfExists()); + }); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCache.java b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCache.java index b85fc47c47..4408ad6aa4 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCache.java +++ b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCache.java @@ -18,8 +18,7 @@ public class GeoWebCache { /** @return current the GWC version */ - @SuppressWarnings( - "deprecation") // Package.getPackage is deprecated in java 11 but replacement is not + @SuppressWarnings("deprecation") // Package.getPackage is deprecated in java 11 but replacement is not // available in Java 8 public static String getVersion() { Package versionInfo = Package.getPackage("org.geowebcache"); @@ -28,8 +27,7 @@ public static String getVersion() { } /** @return the current build revision number/hash */ - @SuppressWarnings( - "deprecation") // Package.getPackage is deprecated in java 11 but replacement is not + @SuppressWarnings("deprecation") // Package.getPackage is deprecated in java 11 but replacement is not // available in Java 8 public static String getBuildRevision() { Package versionInfo = Package.getPackage("org.geowebcache"); diff --git a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheDispatcher.java b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheDispatcher.java index 3d155116fa..8f266857cc 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheDispatcher.java +++ b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheDispatcher.java @@ -174,15 +174,12 @@ private Map loadServices() { for (Service aService : plugins) { services.put(aService.getPathName(), aService); } - LOG.info( - "Done loading GWC Service extensions. Found : " - + new ArrayList<>(services.keySet())); + LOG.info("Done loading GWC Service extensions. Found : " + new ArrayList<>(services.keySet())); return services; } private void loadBlankTile() { - String blankTilePath = - defaultStorageFinder.findEnvVar(DefaultStorageFinder.GWC_BLANK_TILE_PATH); + String blankTilePath = defaultStorageFinder.findEnvVar(DefaultStorageFinder.GWC_BLANK_TILE_PATH); if (blankTilePath != null) { File fh = new File(blankTilePath); @@ -260,16 +257,15 @@ String normalizeURL(HttpServletRequest request) { *

If a tile is requested the request will be handed off to handleServiceRequest. */ @Override - protected ModelAndView handleRequestInternal( - HttpServletRequest request, HttpServletResponse originalResponse) throws Exception { + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse originalResponse) + throws Exception { - HttpServletResponseWrapper response = - new HttpServletResponseWrapper(originalResponse) { - @Override - public ServletOutputStream getOutputStream() throws IOException { - return new DispatcherOutputStream(super.getOutputStream()); - } - }; + HttpServletResponseWrapper response = new HttpServletResponseWrapper(originalResponse) { + @Override + public ServletOutputStream getOutputStream() throws IOException { + return new DispatcherOutputStream(super.getOutputStream()); + } + }; // Break the request into components, {type, service name} String[] requestComps = null; @@ -290,8 +286,7 @@ public ServletOutputStream getOutputStream() throws IOException { || requestComps[0].equalsIgnoreCase(TYPE_DEMO + "s")) { handleDemoRequest(requestComps[1], request, response); } else { - ResponseUtils.writeErrorPage( - response, 404, "Unknown path: " + requestComps[0], runtimeStats); + ResponseUtils.writeErrorPage(response, 404, "Unknown path: " + requestComps[0], runtimeStats); } } catch (HttpErrorCodeException e) { ResponseUtils.writeFixedResponse( @@ -390,8 +385,7 @@ private String[] parseRequest(String servletPath) throws GeoWebCacheException { } /** This is the main method for handling service requests. See comments in the code. */ - private void handleServiceRequest( - String serviceStr, HttpServletRequest request, HttpServletResponse response) + private void handleServiceRequest(String serviceStr, HttpServletRequest request, HttpServletResponse response) throws Exception { Conveyor conv = null; @@ -407,11 +401,7 @@ private void handleServiceRequest( if (Objects.nonNull(layerName)) { layer = tileLayerDispatcher.getTileLayer(layerName); if (!layer.isEnabled()) { - throw new OWSException( - 400, - "InvalidParameterValue", - "LAYERS", - "Layer '" + layerName + "' is disabled"); + throw new OWSException(400, "InvalidParameterValue", "LAYERS", "Layer '" + layerName + "' is disabled"); } if (conv instanceof ConveyorTile) { ((ConveyorTile) conv).setTileLayer(layer); @@ -426,17 +416,11 @@ private void handleServiceRequest( service.handleRequest(conv); } else { ResponseUtils.writeTile( - getSecurityDispatcher(), - conv, - layerName, - tileLayerDispatcher, - defaultStorageFinder, - runtimeStats); + getSecurityDispatcher(), conv, layerName, tileLayerDispatcher, defaultStorageFinder, runtimeStats); } } - private void handleDemoRequest( - String action, HttpServletRequest request, HttpServletResponse response) + private void handleDemoRequest(String action, HttpServletRequest request, HttpServletResponse response) throws GeoWebCacheException { Demo.makeMap(tileLayerDispatcher, gridSetBroker, action, request, response); } @@ -489,48 +473,35 @@ private void handleFrontPage(HttpServletRequest request, HttpServletResponse res commitId = "{NO BUILD INFO IN MANIFEST}"; } - str.append( - "\n" - + ServletUtils.gwcHtmlHeader(baseUrl, "GWC Home") - + "\n" - + ServletUtils.gwcHtmlLogoLink(baseUrl)); - str.append( - "

Welcome to GeoWebCache version " - + version - + ", build " - + commitId - + "

\n"); - str.append( - "

GeoWebCache is an advanced tile cache for WMS servers."); + str.append("\n" + + ServletUtils.gwcHtmlHeader(baseUrl, "GWC Home") + + "\n" + + ServletUtils.gwcHtmlLogoLink(baseUrl)); + str.append("

Welcome to GeoWebCache version " + version + ", build " + commitId + "

\n"); + str.append("

GeoWebCache is an advanced tile cache for WMS servers."); str.append( "It supports a large variety of protocols and formats, including WMS-C, WMTS, KML, Google Maps and Virtual Earth.

"); str.append("

Automatically Generated Demos:

\n"); str.append( - "\n"); + "\n"); str.append("

GetCapabilities:

\n"); - str.append( - "\n"); if (runtimeStats != null) { str.append("

Runtime Statistics

\n"); str.append(runtimeStats.getHTMLStats()); str.append("\n"); } - if (!Boolean.parseBoolean( - GeoWebCacheExtensions.getProperty("GEOWEBCACHE_HIDE_STORAGE_LOCATIONS"))) { + if (!Boolean.parseBoolean(GeoWebCacheExtensions.getProperty("GEOWEBCACHE_HIDE_STORAGE_LOCATIONS"))) { appendStorageLocations(str); } @@ -539,8 +510,7 @@ private void handleFrontPage(HttpServletRequest request, HttpServletResponse res } str.append("\n"); - ResponseUtils.writePage( - response, 200, str.toString(), runtimeStats, MediaType.TEXT_HTML_VALUE); + ResponseUtils.writePage(response, 200, str.toString(), runtimeStats, MediaType.TEXT_HTML_VALUE); } private void appendStorageLocations(StringBuilder str) { @@ -667,9 +637,8 @@ private void appendInternalCacheStats(StringBuilder strGlobal) { str.append(""); - str.append( - "\n"); str.append(""); @@ -692,25 +661,20 @@ private void appendInternalCacheStats(StringBuilder strGlobal) { str.append(""); - str.append( - "\n"); str.append(""); - str.append( - "\n"); str.append(""); - str.append( - "\n"); str.append(""); diff --git a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheEnvironment.java b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheEnvironment.java index dbff374ceb..377789c4b0 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheEnvironment.java +++ b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheEnvironment.java @@ -63,15 +63,13 @@ public class GeoWebCacheEnvironment { private static final String nullValue = "null"; - private final PropertyPlaceholderHelper helper = - new PropertyPlaceholderHelper( - constants.asString("DEFAULT_PLACEHOLDER_PREFIX"), - constants.asString("DEFAULT_PLACEHOLDER_SUFFIX"), - constants.asString("DEFAULT_VALUE_SEPARATOR"), - true); + private final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper( + constants.asString("DEFAULT_PLACEHOLDER_PREFIX"), + constants.asString("DEFAULT_PLACEHOLDER_SUFFIX"), + constants.asString("DEFAULT_VALUE_SEPARATOR"), + true); - private final PlaceholderResolver resolver = - placeholderName -> resolvePlaceholder(placeholderName); + private final PlaceholderResolver resolver = placeholderName -> resolvePlaceholder(placeholderName); private Properties props; @@ -170,13 +168,11 @@ public Optional resolveValueIfEnabled(final String value, Integer intValue = Integer.valueOf(resultValue); return (Optional) Optional.of(intValue); } catch (NumberFormatException ex) { - throw new IllegalArgumentException( - "Illegal String parameter: Resolved value is not an integer.", ex); + throw new IllegalArgumentException("Illegal String parameter: Resolved value is not an integer.", ex); } } else if (type.isAssignableFrom(Boolean.class)) { if (!validateBoolean(resultValue)) - throw new IllegalArgumentException( - "Illegal String parameter: Resolved value is not a boolean."); + throw new IllegalArgumentException("Illegal String parameter: Resolved value is not a boolean."); Boolean boolValue = Boolean.valueOf(value); return (Optional) Optional.of(boolValue); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheExtensions.java b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheExtensions.java index 8cee7cd9ac..601c06290e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheExtensions.java +++ b/geowebcache/core/src/main/java/org/geowebcache/GeoWebCacheExtensions.java @@ -88,8 +88,7 @@ public void setApplicationContext(ApplicationContext context) throws BeansExcept * @return A collection of the extensions, or an empty collection. */ @SuppressWarnings("unchecked") - public static final List extensions( - Class extensionPoint, ApplicationContext context) { + public static final List extensions(Class extensionPoint, ApplicationContext context) { String[] names; if (GeoWebCacheExtensions.context == context) { names = extensionsCache.get(extensionPoint); @@ -151,8 +150,7 @@ public static String[] getBeansNamesOrderedByPriority(Class extensionType * rather than the bean itself to avoid breaking the singleton directive. */ @SuppressWarnings("unchecked") - private static String[] getBeansNamesOrderedByPriority( - Class extensionType, ApplicationContext context) { + private static String[] getBeansNamesOrderedByPriority(Class extensionType, ApplicationContext context) { // asking spring for a map that will contains all beans that match the extensions type // indexed by their name Map beans = context.getBeansOfType(extensionType); @@ -163,22 +161,16 @@ private static String[] getBeansNamesOrderedByPriority( // this extension type is priority aware List> beansEntries = new ArrayList<>(beans.entrySet()); // sorting beans by their priority - Collections.sort( - beansEntries, - (extensionA, extensionB) -> { - GeoWebCacheExtensionPriority extensionPriorityA = - ((Map.Entry) extensionA) - .getValue(); - GeoWebCacheExtensionPriority extensionPriorityB = - ((Map.Entry) extensionB) - .getValue(); - if (extensionPriorityA.getPriority() < extensionPriorityB.getPriority()) { - return -1; - } - return extensionPriorityA.getPriority() == extensionPriorityB.getPriority() - ? 0 - : 1; - }); + Collections.sort(beansEntries, (extensionA, extensionB) -> { + GeoWebCacheExtensionPriority extensionPriorityA = + ((Map.Entry) extensionA).getValue(); + GeoWebCacheExtensionPriority extensionPriorityB = + ((Map.Entry) extensionB).getValue(); + if (extensionPriorityA.getPriority() < extensionPriorityB.getPriority()) { + return -1; + } + return extensionPriorityA.getPriority() == extensionPriorityB.getPriority() ? 0 : 1; + }); // returning only the beans names return beansEntries.stream().map(Map.Entry::getKey).toArray(String[]::new); } @@ -204,11 +196,7 @@ public static final List extensions(Class extensionPoint) { public static List configurations( Class extensionPoint, ApplicationContext context) { return extensions(extensionPoint, context).stream() - .sorted( - (x, y) -> - Integer.signum( - x.getPriority(extensionPoint) - - y.getPriority(extensionPoint))) + .sorted((x, y) -> Integer.signum(x.getPriority(extensionPoint) - y.getPriority(extensionPoint))) .collect(Collectors.toList()); } @@ -237,10 +225,7 @@ public static void reinitialize(ApplicationContext context) { + ((BaseConfiguration) bean).getLocation(), e); } else { - LOGGER.log( - Level.SEVERE, - "Error while preparing bean to reinitialize " + bean.toString(), - e); + LOGGER.log(Level.SEVERE, "Error while preparing bean to reinitialize " + bean.toString(), e); } } } @@ -257,8 +242,7 @@ public static void reinitialize(ApplicationContext context) { + ((BaseConfiguration) bean).getLocation(), e); } else { - LOGGER.log( - Level.SEVERE, "Error while reinitializing bean " + bean.toString(), e); + LOGGER.log(Level.SEVERE, "Error while reinitializing bean " + bean.toString(), e); } } } @@ -301,8 +285,7 @@ public static final T bean(Class type) throws IllegalArgumentException { * @throws IllegalArgumentException If there are multiple beans of the specified type in the * context. */ - public static final T bean(Class type, ApplicationContext context) - throws IllegalArgumentException { + public static final T bean(Class type, ApplicationContext context) throws IllegalArgumentException { List beans = extensions(type, context); if (beans.isEmpty()) { return null; @@ -387,9 +370,7 @@ public static String getProperty(String propertyName, ServletContext context) { // than strictly necessary final String[] typeStrs = { - "Java environment variable ", - "Servlet context parameter ", - "System environment variable " + "Java environment variable ", "Servlet context parameter ", "System environment variable " }; String result = null; diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/BaseConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/BaseConfiguration.java index 1cb334990c..e1dc58c363 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/BaseConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/BaseConfiguration.java @@ -19,8 +19,7 @@ import org.springframework.beans.factory.InitializingBean; /** Superinterface for GeoWebCache configuration beans, defining basic shared functionality */ -public interface BaseConfiguration - extends InitializingBean, ReinitializingBean, GeoWebCacheExtensionPriority { +public interface BaseConfiguration extends InitializingBean, ReinitializingBean, GeoWebCacheExtensionPriority { /** Default priority for configuration beans. Lower values will have higher priority. */ public static final int BASE_PRIORITY = 50; diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfiguration.java index 2afa9b6671..7b7836342d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfiguration.java @@ -61,8 +61,7 @@ public interface BlobStoreConfiguration extends BaseConfiguration { * @throws IllegalArgumentException If this configuration can't, for some reason, modify the * blob store identified by the supplied name (for example, the configuration is read-only). */ - void modifyBlobStore(BlobStoreInfo info) - throws NoSuchElementException, IllegalArgumentException; + void modifyBlobStore(BlobStoreInfo info) throws NoSuchElementException, IllegalArgumentException; /** * Retrieve a set of {@link BlobStoreInfo} names in this configuration. @@ -108,8 +107,7 @@ void modifyBlobStore(BlobStoreInfo info) * @throws IllegalArgumentException If this configuration can't, for some reason, rename the * blob store identified by the supplied name (for example, newName is null or invalid). */ - void renameBlobStore(String oldName, String newName) - throws NoSuchElementException, IllegalArgumentException; + void renameBlobStore(String oldName, String newName) throws NoSuchElementException, IllegalArgumentException; /** * Indicates if this configurations contains a {@link BlobStoreInfo) identified by a given name. diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfigurationListener.java b/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfigurationListener.java index abf7606c0f..9ceb500a1e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfigurationListener.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/BlobStoreConfigurationListener.java @@ -34,8 +34,7 @@ void handleAddBlobStore(BlobStoreInfo newBlobStore) throws UnsuitableStorageException, GeoWebCacheException, IOException; /** @param removedBlobStore The old configuration for the blobstore that was removed */ - void handleRemoveBlobStore(BlobStoreInfo removedBlobStore) - throws GeoWebCacheException, IOException; + void handleRemoveBlobStore(BlobStoreInfo removedBlobStore) throws GeoWebCacheException, IOException; /** * @param modifiedBlobStore The new configuration for the blobstore diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/DefaultGridsets.java b/geowebcache/core/src/main/java/org/geowebcache/config/DefaultGridsets.java index 905fb0f4f9..46b78407d1 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/DefaultGridsets.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/DefaultGridsets.java @@ -96,86 +96,76 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { } } - WORLD_EPSG4326 = - GridSetFactory.createGridSet( - unprojectedName, - SRS.getEPSG4326(), - BoundingBox.WORLD4326, - false, - GridSetFactory.DEFAULT_LEVELS, - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - 256, - 256, - true); - WORLD_EPSG4326.setDescription( - "A default WGS84 tile matrix set where the first zoom level " - + "covers the world with two tiles on the horizontal axis and one tile " - + "over the vertical axis and each subsequent zoom level is calculated by half " - + "the resolution of its previous one. Tiles are 256px wide."); + WORLD_EPSG4326 = GridSetFactory.createGridSet( + unprojectedName, + SRS.getEPSG4326(), + BoundingBox.WORLD4326, + false, + GridSetFactory.DEFAULT_LEVELS, + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + 256, + 256, + true); + WORLD_EPSG4326.setDescription("A default WGS84 tile matrix set where the first zoom level " + + "covers the world with two tiles on the horizontal axis and one tile " + + "over the vertical axis and each subsequent zoom level is calculated by half " + + "the resolution of its previous one. Tiles are 256px wide."); addInternal(WORLD_EPSG4326); - WORLD_EPSG4326x2 = - GridSetFactory.createGridSet( - unprojectedName + "x2", - SRS.getEPSG4326(), - BoundingBox.WORLD4326, - false, - GridSetFactory.DEFAULT_LEVELS, - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - 512, - 512, - true); - WORLD_EPSG4326x2.setDescription( - "A default WGS84 tile matrix set where the first zoom level " - + "covers the world with two tiles on the horizontal axis and one tile " - + "over the vertical axis and each subsequent zoom level is calculated by half " - + "the resolution of its previous one. Tiles are 512px wide."); + WORLD_EPSG4326x2 = GridSetFactory.createGridSet( + unprojectedName + "x2", + SRS.getEPSG4326(), + BoundingBox.WORLD4326, + false, + GridSetFactory.DEFAULT_LEVELS, + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + 512, + 512, + true); + WORLD_EPSG4326x2.setDescription("A default WGS84 tile matrix set where the first zoom level " + + "covers the world with two tiles on the horizontal axis and one tile " + + "over the vertical axis and each subsequent zoom level is calculated by half " + + "the resolution of its previous one. Tiles are 512px wide."); addInternal(WORLD_EPSG4326x2); final SRS googleMapsCompatibleSRS = useEPSG900913 ? SRS.getEPSG900913() : SRS.getEPSG3857(); - log.fine( - "Adding " - + googleMapsCompatibleSRS - + " grid set for Spherical Mercator / GoogleMapsCompatible"); - - WORLD_EPSG3857 = - GridSetFactory.createGridSet( - mercatorName, - googleMapsCompatibleSRS, - BoundingBox.WORLD3857, - false, - commonPractice900913Resolutions(), - null, - 1.0D, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - null, - 256, - 256, - false); - WORLD_EPSG3857.setDescription( - "This well-known scale set has been defined to be compatible with Google Maps and" - + " Microsoft Live Map projections and zoom levels. Level 0 allows representing the whole " - + "world in a single 256x256 pixels. The next level represents the whole world in 2x2 tiles " - + "of 256x256 pixels and so on in powers of 2. Scale denominator is only accurate near the equator."); + log.fine("Adding " + googleMapsCompatibleSRS + " grid set for Spherical Mercator / GoogleMapsCompatible"); + + WORLD_EPSG3857 = GridSetFactory.createGridSet( + mercatorName, + googleMapsCompatibleSRS, + BoundingBox.WORLD3857, + false, + commonPractice900913Resolutions(), + null, + 1.0D, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + null, + 256, + 256, + false); + WORLD_EPSG3857.setDescription("This well-known scale set has been defined to be compatible with Google Maps and" + + " Microsoft Live Map projections and zoom levels. Level 0 allows representing the whole " + + "world in a single 256x256 pixels. The next level represents the whole world in 2x2 tiles " + + "of 256x256 pixels and so on in powers of 2. Scale denominator is only accurate near the equator."); addInternal(WORLD_EPSG3857); - WORLD_EPSG3857x2 = - GridSetFactory.createGridSet( - mercatorName + "x2", - googleMapsCompatibleSRS, - BoundingBox.WORLD3857, - false, - halveResolutions(commonPractice900913Resolutions()), - null, - 1.0D, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - null, - 512, - 512, - false); + WORLD_EPSG3857x2 = GridSetFactory.createGridSet( + mercatorName + "x2", + googleMapsCompatibleSRS, + BoundingBox.WORLD3857, + false, + halveResolutions(commonPractice900913Resolutions()), + null, + 1.0D, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + null, + 512, + 512, + false); WORLD_EPSG3857x2.setDescription( "This well-known scale set has been defined to be compatible with Google Maps and" + " Microsoft Live Map projections and zoom levels. Level 0 allows representing the whole " @@ -184,65 +174,60 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { addInternal(WORLD_EPSG3857x2); log.fine("Adding GlobalCRS84Pixel"); - GridSet GlobalCRS84Pixel = - GridSetFactory.createGridSet( - "GlobalCRS84Pixel", - SRS.getEPSG4326(), - BoundingBox.WORLD4326, - true, - scalesCRS84PixelResolutions(), - null, - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - null, - 256, - 256, - true); - GlobalCRS84Pixel.setDescription( - "This well-known scale set has been defined for global cartographic products. " - + "Rounded pixel sizes have been chosen for intuitive cartographic representation of raster data. " - + "Some values have been chosen to coincide with original pixel size of commonly used global" - + "products like STRM (1\" and 3\"), GTOPO (30\") or ETOPO (2' and 5'). Scale denominator" - + "and approximated pixel size in meters are only accurate near the equator."); + GridSet GlobalCRS84Pixel = GridSetFactory.createGridSet( + "GlobalCRS84Pixel", + SRS.getEPSG4326(), + BoundingBox.WORLD4326, + true, + scalesCRS84PixelResolutions(), + null, + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + null, + 256, + 256, + true); + GlobalCRS84Pixel.setDescription("This well-known scale set has been defined for global cartographic products. " + + "Rounded pixel sizes have been chosen for intuitive cartographic representation of raster data. " + + "Some values have been chosen to coincide with original pixel size of commonly used global" + + "products like STRM (1\" and 3\"), GTOPO (30\") or ETOPO (2' and 5'). Scale denominator" + + "and approximated pixel size in meters are only accurate near the equator."); addInternal(GlobalCRS84Pixel); log.fine("Adding GlobalCRS84Scale"); - GridSet GlobalCRS84Scale = - GridSetFactory.createGridSet( - "GlobalCRS84Scale", - SRS.getEPSG4326(), - BoundingBox.WORLD4326, - true, - null, - scalesCRS84ScaleDenominators(), - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - null, - 256, - 256, - true); - GlobalCRS84Scale.setDescription( - "This well-known scale set has been defined for global cartographic products. " - + "Rounded scales have been chosen for intuitive cartographic representation of vector data. " - + "Scale denominator is only accurate near the equator."); + GridSet GlobalCRS84Scale = GridSetFactory.createGridSet( + "GlobalCRS84Scale", + SRS.getEPSG4326(), + BoundingBox.WORLD4326, + true, + null, + scalesCRS84ScaleDenominators(), + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + null, + 256, + 256, + true); + GlobalCRS84Scale.setDescription("This well-known scale set has been defined for global cartographic products. " + + "Rounded scales have been chosen for intuitive cartographic representation of vector data. " + + "Scale denominator is only accurate near the equator."); addInternal(GlobalCRS84Scale); log.fine("Adding GoogleCRS84Quad"); - GridSet GoogleCRS84Quad = - GridSetFactory.createGridSet( - "GoogleCRS84Quad", - SRS.getEPSG4326(), - BoundingBox.WORLD4326, - true, - null, - scalesCRS84QuadScaleDenominators(), - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - null, - 256, - 256, - true); + GridSet GoogleCRS84Quad = GridSetFactory.createGridSet( + "GoogleCRS84Quad", + SRS.getEPSG4326(), + BoundingBox.WORLD4326, + true, + null, + scalesCRS84QuadScaleDenominators(), + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + null, + 256, + 256, + true); GoogleCRS84Quad.setDescription( "This well-known scale set has been defined to allow quadtree " + "pyramids in CRS84. Level 0 allows representing the whole world " @@ -253,49 +238,48 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { addInternal(GoogleCRS84Quad); log.fine("Adding OGC TMS WebMercatorQuad"); - WEB_MERCATOR_QUAD = - GridSetFactory.createGridSet( - "WebMercatorQuad", - SRS.getEPSG3857(), - BoundingBox.WORLD3857, - true, - null, - new double[] { - 559082264.028717, - 279541132.014358, - 139770566.007179, - 69885283.0035897, - 34942641.5017948, - 17471320.7508974, - 8735660.37544871, - 4367830.18772435, - 2183915.09386217, - 1091957.54693108, - 545978.773465544, - 272989.386732772, - 136494.693366386, - 68247.346683193, - 34123.6733415964, - 17061.8366707982, - 8530.91833539913, - 4265.45916769956, - 2132.72958384978, - 1066.36479192489, - 533.182395962445, - 266.591197981222, - 133.295598990611, - 66.6477994953056, - 33.3238997476528 - }, - 1d, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" - }, - 256, - 256, - true); + WEB_MERCATOR_QUAD = GridSetFactory.createGridSet( + "WebMercatorQuad", + SRS.getEPSG3857(), + BoundingBox.WORLD3857, + true, + null, + new double[] { + 559082264.028717, + 279541132.014358, + 139770566.007179, + 69885283.0035897, + 34942641.5017948, + 17471320.7508974, + 8735660.37544871, + 4367830.18772435, + 2183915.09386217, + 1091957.54693108, + 545978.773465544, + 272989.386732772, + 136494.693366386, + 68247.346683193, + 34123.6733415964, + 17061.8366707982, + 8530.91833539913, + 4265.45916769956, + 2132.72958384978, + 1066.36479192489, + 533.182395962445, + 266.591197981222, + 133.295598990611, + 66.6477994953056, + 33.3238997476528 + }, + 1d, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] { + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", + "18", "19", "20", "21", "22", "23", "24" + }, + 256, + 256, + true); // copied from the OGC TMS spec WEB_MERCATOR_QUAD.setDescription( "This tile matrix set is the most used tile matrix set in the mass market: for example, by Google Maps, Microsoft Bing Maps and Open Street Map tiles. Nevertheless, it has been long criticized because it is a based on a spherical Mercator instead of an ellipsoid. The use of WebMercatorQuad should be limited to visualization. Any additional use (including distance measurements, routing etc.) needs to use the Mercator spherical expressions to transform the coordinate to an appropriate CRS first. The risks caused by imprecision in the use of Web Mercator is also emphasized by the US National Geospatial Agency (NGA). NGA has issued an Advisory Notice on web Mercator (http://earth-info.nga.mil/GandG/wgs84/web_mercator/index.html) that says that “it may cause geo-location / geo-coordinate errors up to 40,000 meters. This erroneous geospatial positioning information poses an unacceptable risk to global safety of navigation activities, and department of defense, intelligence community, and allied partner systems, missions, and operations that require accurate and precise positioning and navigation information.” The use of WorldMercatorWGS84Quad is recommended."); @@ -303,42 +287,41 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { addx2Gridset(WEB_MERCATOR_QUAD); log.fine("Adding OGC TMS WorldCRS84Quad"); - WORLD_CRS84_QUAD = - GridSetFactory.createGridSet( - "WorldCRS84Quad", - SRS.getEPSG4326(), - BoundingBox.WORLD4326, - true, - null, - new double[] { - 279541132.0143589, - 139770566.0071794, - 69885283.00358972, - 34942641.50179486, - 17471320.75089743, - 8735660.375448715, - 4367830.187724357, - 2183915.093862179, - 1091957.546931089, - 545978.7734655447, - 272989.3867327723, - 136494.6933663862, - 68247.34668319309, - 34123.67334159654, - 17061.83667079827, - 8530.918335399136, - 4265.459167699568, - 2132.729583849784, - }, - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18" - }, - 256, - 256, - true); + WORLD_CRS84_QUAD = GridSetFactory.createGridSet( + "WorldCRS84Quad", + SRS.getEPSG4326(), + BoundingBox.WORLD4326, + true, + null, + new double[] { + 279541132.0143589, + 139770566.0071794, + 69885283.00358972, + 34942641.50179486, + 17471320.75089743, + 8735660.375448715, + 4367830.187724357, + 2183915.093862179, + 1091957.546931089, + 545978.7734655447, + 272989.3867327723, + 136494.6933663862, + 68247.34668319309, + 34123.67334159654, + 17061.83667079827, + 8530.918335399136, + 4265.459167699568, + 2132.729583849784, + }, + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] { + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", + "18" + }, + 256, + 256, + true); // copied from the OGC TMS spec WORLD_CRS84_QUAD.setDescription( "This Tile Matrix Set defines tiles in the Equirectangular Plate Carrée projection in the CRS84 CRS for the whole world."); @@ -346,53 +329,48 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { addx2Gridset(WORLD_CRS84_QUAD); log.fine("Adding OGC TMS WorldMercatorWGS84Quad"); - WORLD_MERCATOR_WGS84_QUAD = - GridSetFactory.createGridSet( - "WorldMercatorWGS84Quad", - SRS.getSRS(3395), - new BoundingBox( - -20037508.3427892, - -20037508.3427892, - 20037508.3427892, - 20037508.3427892), - true, - null, - new double[] { - 559082264.028717, - 279541132.014358, - 139770566.007179, - 69885283.0035897, - 34942641.5017948, - 17471320.7508974, - 8735660.37544871, - 4367830.18772435, - 2183915.09386217, - 1091957.54693108, - 545978.773465544, - 272989.386732772, - 136494.693366386, - 68247.346683193, - 34123.6733415964, - 17061.8366707982, - 8530.91833539913, - 4265.45916769956, - 2132.72958384978, - 1066.36479192489, - 533.182395962445, - 266.591197981222, - 133.295598990611, - 66.6477994953056, - 33.3238997476528, - }, - 1d, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" - }, - 256, - 256, - true); + WORLD_MERCATOR_WGS84_QUAD = GridSetFactory.createGridSet( + "WorldMercatorWGS84Quad", + SRS.getSRS(3395), + new BoundingBox(-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892), + true, + null, + new double[] { + 559082264.028717, + 279541132.014358, + 139770566.007179, + 69885283.0035897, + 34942641.5017948, + 17471320.7508974, + 8735660.37544871, + 4367830.18772435, + 2183915.09386217, + 1091957.54693108, + 545978.773465544, + 272989.386732772, + 136494.693366386, + 68247.346683193, + 34123.6733415964, + 17061.8366707982, + 8530.91833539913, + 4265.45916769956, + 2132.72958384978, + 1066.36479192489, + 533.182395962445, + 266.591197981222, + 133.295598990611, + 66.6477994953056, + 33.3238997476528, + }, + 1d, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] { + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", + "18", "19", "20", "21", "22", "23", "24" + }, + 256, + 256, + true); // not from the spec, it does not have one WORLD_MERCATOR_WGS84_QUAD.setDescription( "This Tile Matrix Set defines tiles in the Mercator projection in the WGS84 CRS for the whole world."); @@ -430,32 +408,25 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { // the 60 UTM zones from the OGC TMS specification for (int i = 1; i <= 60; i++) { String id = "UTM" + (i < 10 ? "0" : "") + i + "WGS84Quad"; - GridSet utmGridset = - GridSetFactory.createGridSet( - id, - SRS.getSRS(32600 + i), - new BoundingBox( - -9501965.72931276, - -20003931.4586255, - 10501965.7293128, - 20003931.4586255), - true, - null, - UTM_SCALES, - 1d, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", - "24" - }, - 256, - 256, - true); + GridSet utmGridset = GridSetFactory.createGridSet( + id, + SRS.getSRS(32600 + i), + new BoundingBox(-9501965.72931276, -20003931.4586255, 10501965.7293128, 20003931.4586255), + true, + null, + UTM_SCALES, + 1d, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] { + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", + "17", "18", "19", "20", "21", "22", "23", "24" + }, + 256, + 256, + true); // not from the spec, it does not have one utmGridset.setDescription( - "This Tile Matrix Set defines tiles in the Universal Transverse Mercator, zone " - + i); + "This Tile Matrix Set defines tiles in the Universal Transverse Mercator, zone " + i); addInternal(utmGridset); addx2Gridset(utmGridset); } @@ -489,26 +460,23 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { 54.68446545, 27.34223273 }; - BoundingBox upsBounds = - new BoundingBox( - -14440759.350252, -14440759.350252, 18440759.350252, 18440759.350252); - final GridSet upsArctic = - GridSetFactory.createGridSet( - "UPSArcticWGS84Quad", - SRS.getSRS(5041), - upsBounds, - true, - null, - upsScales, - 1d, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" - }, - 256, - 256, - true); + BoundingBox upsBounds = new BoundingBox(-14440759.350252, -14440759.350252, 18440759.350252, 18440759.350252); + final GridSet upsArctic = GridSetFactory.createGridSet( + "UPSArcticWGS84Quad", + SRS.getSRS(5041), + upsBounds, + true, + null, + upsScales, + 1d, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] { + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", + "18", "19", "20", "21", "22", "23", "24" + }, + 256, + 256, + true); // not from the spec, it does not have one upsArctic.setDescription( "This Tile Matrix Set defines tiles in the Universal Polar Stereographics for the arctic"); @@ -517,23 +485,22 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { // UPS antarctic log.fine("Adding OGC TMS UPSAntarcticWGS84Quad"); - final GridSet upsAntarctic = - GridSetFactory.createGridSet( - "UPSAntarcticWGS84Quad", - SRS.getSRS(5042), - upsBounds, - true, - null, - upsScales, - 1d, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" - }, - 256, - 256, - true); + final GridSet upsAntarctic = GridSetFactory.createGridSet( + "UPSAntarcticWGS84Quad", + SRS.getSRS(5042), + upsBounds, + true, + null, + upsScales, + 1d, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] { + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", + "18", "19", "20", "21", "22", "23", "24" + }, + 256, + 256, + true); // not from the spec, it does not have one upsAntarctic.setDescription( "This Tile Matrix Set defines tiles in the Universal Polar Stereographics for the Antarctic"); @@ -541,95 +508,85 @@ public DefaultGridsets(boolean useEPSG900913, boolean useGWC11xNames) { addx2Gridset(upsAntarctic); log.fine("Adding OGC TMS EuropeanETRS89_LAEAQuad"); - GridSet euETRS89LaeaQuad = - GridSetFactory.createGridSet( - "EuropeanETRS89_LAEAQuad", - SRS.getSRS(3035), - new BoundingBox(2000000.0, 1000000.0, 6500000, 5500000.0), - true, - null, - new double[] { - 62779017.857142866, - 31389508.928571433, - 15694754.464285716, - 7847377.232142858, - 3923688.616071429, - 1961844.3080357146, - 980922.1540178573, - 490461.07700892864, - 245230.53850446432, - 122615.26925223216, - 61307.63462611608, - 30653.81731305804, - 15326.90865652902, - 7663.45432826451, - 3831.727164132255, - 1915.8635820661275, - }, - 1d, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15" - }, - 256, - 256, - true); + GridSet euETRS89LaeaQuad = GridSetFactory.createGridSet( + "EuropeanETRS89_LAEAQuad", + SRS.getSRS(3035), + new BoundingBox(2000000.0, 1000000.0, 6500000, 5500000.0), + true, + null, + new double[] { + 62779017.857142866, + 31389508.928571433, + 15694754.464285716, + 7847377.232142858, + 3923688.616071429, + 1961844.3080357146, + 980922.1540178573, + 490461.07700892864, + 245230.53850446432, + 122615.26925223216, + 61307.63462611608, + 30653.81731305804, + 15326.90865652902, + 7663.45432826451, + 3831.727164132255, + 1915.8635820661275, + }, + 1d, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}, + 256, + 256, + true); // not from the spec, it does not have one euETRS89LaeaQuad.setDescription("Lambert Azimuthal Equal Area ETRS89 for Europe"); addInternal(euETRS89LaeaQuad); addx2Gridset(euETRS89LaeaQuad); log.fine("Adding OGC TMS CanadianNAD83_LCC"); - GridSet canadianNAD83Lcc = - GridSetFactory.createGridSet( - "CanadianNAD83_LCC", - SRS.getSRS(3978), - new BoundingBox( - -7786476.885838887, - -5153821.09213678, - 7148753.233541353, - 7928343.534071138), - true, - null, - new double[] { - 137016643.080905, - 80320101.1163925, - 47247118.3037603, - 28348270.9822562, - 16536491.4063161, - 9449423.66075207, - 5669654.19645125, - 3307298.28126323, - 1889884.73215041, - 1133930.83929025, - 661459.656252643, - 396875.793751586, - 236235.591518802, - 137016.643080905, - 80320.1011163925, - 47247.1183037603, - 28348.2709822562, - 16536.4914063161, - 9449.42366075207, - 5669.65419645125, - 3307.29828126323, - 1889.88473215041, - 1133.93083929025, - 661.459656252643, - 396.875793751586, - 236.235591518802 - }, - 1d, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - new String[] { - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", - "25" - }, - 256, - 256, - true); + GridSet canadianNAD83Lcc = GridSetFactory.createGridSet( + "CanadianNAD83_LCC", + SRS.getSRS(3978), + new BoundingBox(-7786476.885838887, -5153821.09213678, 7148753.233541353, 7928343.534071138), + true, + null, + new double[] { + 137016643.080905, + 80320101.1163925, + 47247118.3037603, + 28348270.9822562, + 16536491.4063161, + 9449423.66075207, + 5669654.19645125, + 3307298.28126323, + 1889884.73215041, + 1133930.83929025, + 661459.656252643, + 396875.793751586, + 236235.591518802, + 137016.643080905, + 80320.1011163925, + 47247.1183037603, + 28348.2709822562, + 16536.4914063161, + 9449.42366075207, + 5669.65419645125, + 3307.29828126323, + 1889.88473215041, + 1133.93083929025, + 661.459656252643, + 396.875793751586, + 236.235591518802 + }, + 1d, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + new String[] { + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", + "18", "19", "20", "21", "22", "23", "24", "25" + }, + 256, + 256, + true); // not from the spec, it does not have one canadianNAD83Lcc.setDescription("Lambert Conformal Conic for Canada"); addInternal(canadianNAD83Lcc); @@ -648,20 +605,19 @@ private void addx2Gridset(GridSet base) { scaleNames[i] = base.getGrid(i).getName(); } - GridSet x2 = - GridSetFactory.createGridSet( - base.getName() + "x2", - base.getSrs(), - base.getOriginalExtent(), - base.isTopLeftAligned(), - null, - scales, - base.getMetersPerUnit(), - base.getPixelSize(), - scaleNames, - 512, - 512, - base.isyCoordinateFirst()); + GridSet x2 = GridSetFactory.createGridSet( + base.getName() + "x2", + base.getSrs(), + base.getOriginalExtent(), + base.isTopLeftAligned(), + null, + scales, + base.getMetersPerUnit(), + base.getPixelSize(), + scaleNames, + 512, + 512, + base.isyCoordinateFirst()); addInternal(x2); } @@ -777,8 +733,8 @@ private double[] scalesCRS84ScaleDenominators() { // // return scalesCRS84Pixel; double[] scalesCRS84Pixel = { - 500E6, 250E6, 100E6, 50E6, 25E6, 10E6, 5E6, 2.5E6, 1E6, 500E3, 250E3, 100E3, 50E3, 25E3, - 10E3, 5E3, 2.5E3, 1000, 500, 250, 100 + 500E6, 250E6, 100E6, 50E6, 25E6, 10E6, 5E6, 2.5E6, 1E6, 500E3, 250E3, 100E3, 50E3, 25E3, 10E3, 5E3, 2.5E3, + 1000, 500, 250, 100 }; return scalesCRS84Pixel; diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/FileBlobStoreInfo.java b/geowebcache/core/src/main/java/org/geowebcache/config/FileBlobStoreInfo.java index 8f89e4b45d..a35fc3e457 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/FileBlobStoreInfo.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/FileBlobStoreInfo.java @@ -123,33 +123,22 @@ public String toString() { /** @see BlobStoreInfo#createInstance(TileLayerDispatcher, LockProvider) */ @Override - public BlobStore createInstance(TileLayerDispatcher layers, LockProvider lockProvider) - throws StorageException { + public BlobStore createInstance(TileLayerDispatcher layers, LockProvider lockProvider) throws StorageException { checkState(getName() != null, "id not set"); - checkState( - isEnabled(), - "Can't call FileBlobStoreConfig.createInstance() is blob store is not enabled"); + checkState(isEnabled(), "Can't call FileBlobStoreConfig.createInstance() is blob store is not enabled"); checkState(baseDirectory != null, "baseDirectory not provided"); - checkState( - fileSystemBlockSize >= 0, - "fileSystemBlockSize must be a positive integer: %s", - fileSystemBlockSize); + checkState(fileSystemBlockSize >= 0, "fileSystemBlockSize must be a positive integer: %s", fileSystemBlockSize); FileBlobStore fileBlobStore; if (pathGeneratorType == null || pathGeneratorType == PathGeneratorType.DEFAULT) { - fileBlobStore = - new FileBlobStore(baseDirectory, new DefaultFilePathGenerator(baseDirectory)); + fileBlobStore = new FileBlobStore(baseDirectory, new DefaultFilePathGenerator(baseDirectory)); } else if (pathGeneratorType == PathGeneratorType.TMS) { - fileBlobStore = - new FileBlobStore( - baseDirectory, - new XYZFilePathGenerator( - baseDirectory, layers, XYZFilePathGenerator.Convention.TMS)); + fileBlobStore = new FileBlobStore( + baseDirectory, + new XYZFilePathGenerator(baseDirectory, layers, XYZFilePathGenerator.Convention.TMS)); } else { - fileBlobStore = - new FileBlobStore( - baseDirectory, - new XYZFilePathGenerator( - baseDirectory, layers, XYZFilePathGenerator.Convention.XYZ)); + fileBlobStore = new FileBlobStore( + baseDirectory, + new XYZFilePathGenerator(baseDirectory, layers, XYZFilePathGenerator.Convention.XYZ)); } if (fileSystemBlockSize > 0) { fileBlobStore.setBlockSize(fileSystemBlockSize); diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java index 872d4724db..08e84b806e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java @@ -91,8 +91,7 @@ private Object readResolve() { xmlns = "http://geowebcache.org/schema/" + getVersion(); - xsi_schemaLocation = - xmlns + " http://geowebcache.org/schema/" + getVersion() + "/geowebcache.xsd"; + xsi_schemaLocation = xmlns + " http://geowebcache.org/schema/" + getVersion() + "/geowebcache.xsd"; if (layers == null) { layers = new ArrayList<>(); @@ -117,8 +116,7 @@ public String getVersion() { public void setVersion(String version) { this.version = version; xmlns = "http://geowebcache.org/schema/" + version; - xsi_schemaLocation = - xmlns + " http://geowebcache.org/schema/" + version + "/geowebcache.xsd"; + xsi_schemaLocation = xmlns + " http://geowebcache.org/schema/" + version + "/geowebcache.xsd"; } /** @see ServerConfiguration#getBackendTimeout() */ @@ -231,14 +229,11 @@ public LockProvider getLockProvider() { Object provider = GeoWebCacheExtensions.bean(lockProvider); if (provider == null) { throw new RuntimeException( - "Could not find lock provider " - + lockProvider - + " in the spring application context"); + "Could not find lock provider " + lockProvider + " in the spring application context"); } else if (!(provider instanceof LockProvider)) { - throw new RuntimeException( - "Found bean " - + lockProvider - + " in the spring application context, but it was not a LockProvider"); + throw new RuntimeException("Found bean " + + lockProvider + + " in the spring application context, but it was not a LockProvider"); } else { lockProviderInstance = (LockProvider) provider; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/GridSetConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/GridSetConfiguration.java index 6f6ce697ca..fa000858dc 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/GridSetConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/GridSetConfiguration.java @@ -47,8 +47,7 @@ default Set getGridSetNames() { * type of gridset given, or if any required piece of information is missing or invalid in * the gridset (for example, a missing or duplicated name or id, etc). */ - void addGridSet(final GridSet gridSet) - throws UnsupportedOperationException, IllegalArgumentException; + void addGridSet(final GridSet gridSet) throws UnsupportedOperationException, IllegalArgumentException; /** * Removes an existing gridset from the configuration @@ -56,8 +55,7 @@ void addGridSet(final GridSet gridSet) * @throws NoSuchElementException If there is no existing gridset by that name. * @throws UnsupportedOperationException if removing this gridset is not supported */ - void removeGridSet(String gridSetName) - throws NoSuchElementException, UnsupportedOperationException; + void removeGridSet(String gridSetName) throws NoSuchElementException, UnsupportedOperationException; /** * Changes a gridset diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/ListenerCollection.java b/geowebcache/core/src/main/java/org/geowebcache/config/ListenerCollection.java index a94149ed75..bfeeea7b0f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/ListenerCollection.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/ListenerCollection.java @@ -54,23 +54,19 @@ public static interface HandlerMethod { * others added as suppressed exceptions. If an Error is thrown, it will be propagated * immediately. */ - public synchronized void safeForEach(HandlerMethod method) - throws GeoWebCacheException, IOException { - LinkedList exceptions = - listeners.stream() - .map( - l -> { - try { - method.callOn(l); - return Optional.empty(); - } catch (Exception ex) { - return Optional.of(ex); - } - }) - .filter(Optional::isPresent) - .map(Optional::get) - .collect( - Collectors.collectingAndThen(Collectors.toList(), LinkedList::new)); + public synchronized void safeForEach(HandlerMethod method) throws GeoWebCacheException, IOException { + LinkedList exceptions = listeners.stream() + .map(l -> { + try { + method.callOn(l); + return Optional.empty(); + } catch (Exception ex) { + return Optional.of(ex); + } + }) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.collectingAndThen(Collectors.toList(), LinkedList::new)); if (!exceptions.isEmpty()) { Iterator it = exceptions.descendingIterator(); Exception ex = it.next(); diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/SimpleGridSetConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/SimpleGridSetConfiguration.java index f38fce8a74..82fb8ed16e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/SimpleGridSetConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/SimpleGridSetConfiguration.java @@ -44,14 +44,12 @@ public Collection getGridSets() { } @Override - public void addGridSet(GridSet gridSet) - throws UnsupportedOperationException, IllegalArgumentException { + public void addGridSet(GridSet gridSet) throws UnsupportedOperationException, IllegalArgumentException { throw new UnsupportedOperationException(); } @Override - public void removeGridSet(String gridSetName) - throws NoSuchElementException, UnsupportedOperationException { + public void removeGridSet(String gridSetName) throws NoSuchElementException, UnsupportedOperationException { throw new UnsupportedOperationException(); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/TileLayerConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/TileLayerConfiguration.java index 8817dcb8ba..1e1efefa9c 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/TileLayerConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/TileLayerConfiguration.java @@ -87,8 +87,7 @@ public interface TileLayerConfiguration extends BaseConfiguration { * @throws NoSuchElementException If no tile layer with a matching name exists. * @throws IllegalArgumentException If a tile layer with the new name already exists */ - void renameLayer(String oldName, String newName) - throws NoSuchElementException, IllegalArgumentException; + void renameLayer(String oldName, String newName) throws NoSuchElementException, IllegalArgumentException; /** * Adds the given tile layer to this configuration, provided {@link #canSave(TileLayer) diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java index 7bb2a81639..a85b1c16e3 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java @@ -132,16 +132,14 @@ public class XMLConfiguration private GridSetBroker gridSetBroker; - private ListenerCollection blobStoreListeners = - new ListenerCollection<>(); + private ListenerCollection blobStoreListeners = new ListenerCollection<>(); /** * Base Constructor with custom {@link ConfigurationResourceProvider}. * * @param appCtx use to lookup {@link XMLConfigurationProvider} extensions, may be {@code null} */ - public XMLConfiguration( - final ApplicationContextProvider appCtx, final ConfigurationResourceProvider inFac) { + public XMLConfiguration(final ApplicationContextProvider appCtx, final ConfigurationResourceProvider inFac) { this.context = appCtx == null ? null : appCtx.getApplicationContext(); this.resourceProvider = inFac; } @@ -159,10 +157,7 @@ public XMLConfiguration( this( appCtx, new XMLFileResourceProvider( - DEFAULT_CONFIGURATION_FILE_NAME, - appCtx, - configFileDirectory, - storageDirFinder)); + DEFAULT_CONFIGURATION_FILE_NAME, appCtx, configFileDirectory, storageDirFinder)); resourceProvider.setTemplate("/" + DEFAULT_CONFIGURATION_FILE_NAME); } @@ -172,21 +167,16 @@ public XMLConfiguration( * * @param appCtx use to lookup {@link XMLConfigurationProvider} extenions, may be {@code null} */ - public XMLConfiguration( - final ApplicationContextProvider appCtx, final DefaultStorageFinder storageDirFinder) + public XMLConfiguration(final ApplicationContextProvider appCtx, final DefaultStorageFinder storageDirFinder) throws ConfigurationException { - this( - appCtx, - new XMLFileResourceProvider( - DEFAULT_CONFIGURATION_FILE_NAME, appCtx, storageDirFinder)); + this(appCtx, new XMLFileResourceProvider(DEFAULT_CONFIGURATION_FILE_NAME, appCtx, storageDirFinder)); resourceProvider.setTemplate("/" + DEFAULT_CONFIGURATION_FILE_NAME); } /** * Constructor that will accept an absolute or relative path for finding {@code geowebcache.xml} */ - public XMLConfiguration( - final ApplicationContextProvider appCtx, final String configFileDirectory) + public XMLConfiguration(final ApplicationContextProvider appCtx, final String configFileDirectory) throws ConfigurationException { this(appCtx, configFileDirectory, null); } @@ -276,29 +266,22 @@ public void setDefaultValues(TileLayer layer) { } catch (MalformedURLException e) { log.log( Level.SEVERE, - "could not parse proxy URL " - + wl.getProxyUrl() - + " ! continuing WITHOUT proxy!", + "could not parse proxy URL " + wl.getProxyUrl() + " ! continuing WITHOUT proxy!", e); } final WMSHttpHelper sourceHelper; if (wl.getHttpUsername() != null) { - sourceHelper = - new WMSHttpHelper(wl.getHttpUsername(), wl.getHttpPassword(), proxyUrl); - log.fine( - "Using per-layer HTTP credentials for " - + wl.getName() - + ", " - + "username " - + wl.getHttpUsername()); + sourceHelper = new WMSHttpHelper(wl.getHttpUsername(), wl.getHttpPassword(), proxyUrl); + log.fine("Using per-layer HTTP credentials for " + + wl.getName() + + ", " + + "username " + + wl.getHttpUsername()); } else if (getGwcConfig().getHttpUsername() != null) { - sourceHelper = - new WMSHttpHelper( - getGwcConfig().getHttpUsername(), - getGwcConfig().getHttpPassword(), - proxyUrl); + sourceHelper = new WMSHttpHelper( + getGwcConfig().getHttpUsername(), getGwcConfig().getHttpPassword(), proxyUrl); log.fine("Using global HTTP credentials for " + wl.getName()); } else { sourceHelper = new WMSHttpHelper(null, null, proxyUrl); @@ -317,18 +300,15 @@ private GeoWebCacheConfiguration loadConfiguration() throws ConfigurationExcepti return loadConfiguration(in); } } catch (IOException e) { - throw new ConfigurationException( - "Error parsing config file " + resourceProvider.getId(), e); + throw new ConfigurationException("Error parsing config file " + resourceProvider.getId(), e); } } - private GeoWebCacheConfiguration loadConfiguration(InputStream xmlFile) - throws IOException, ConfigurationException { + private GeoWebCacheConfiguration loadConfiguration(InputStream xmlFile) throws IOException, ConfigurationException { Node rootNode = loadDocument(xmlFile); XStream xs = getConfiguredXStreamWithContext(new GeoWebCacheXStream(), Context.PERSIST); - GeoWebCacheConfiguration config = - (GeoWebCacheConfiguration) xs.unmarshal(new DomReader((Element) rootNode)); + GeoWebCacheConfiguration config = (GeoWebCacheConfiguration) xs.unmarshal(new DomReader((Element) rootNode)); return config; } @@ -340,10 +320,7 @@ private synchronized void save() throws IOException { try { resourceProvider.backup(); } catch (Exception e) { - log.log( - Level.WARNING, - "Error creating back up of configuration file " + resourceProvider.getId(), - e); + log.log(Level.WARNING, "Error creating back up of configuration file " + resourceProvider.getId(), e); } persistToFile(); @@ -363,9 +340,7 @@ public XStream getConfiguredXStreamWithContext( } public static XStream getConfiguredXStreamWithContext( - XStream xs, - WebApplicationContext context, - ContextualConfigurationProvider.Context providerContext) { + XStream xs, WebApplicationContext context, ContextualConfigurationProvider.Context providerContext) { { // Allow any implementation of these extension points @@ -460,8 +435,7 @@ public static XStream getConfiguredXStreamWithContext( && // Check if the context is applicable for the provider (providerContext == null - || !((ContextualConfigurationProvider) extension) - .appliesTo(providerContext))) { + || !((ContextualConfigurationProvider) extension).appliesTo(providerContext))) { // If so, try the next one continue; } @@ -494,13 +468,8 @@ private void persistToFile() throws IOException { } catch (FileNotFoundException fnfe) { throw fnfe; } catch (IOException e) { - throw (IOException) - new IOException( - "Error writing to " - + resourceProvider.getId() - + ": " - + e.getMessage()) - .initCause(e); + throw (IOException) new IOException("Error writing to " + resourceProvider.getId() + ": " + e.getMessage()) + .initCause(e); } log.info("Wrote configuration to " + resourceProvider.getId()); @@ -522,8 +491,7 @@ protected boolean canSaveIfNotTransient(TileLayer tl) { if (tl instanceof WMSLayer) { return true; } - return GeoWebCacheExtensions.extensions(XMLConfigurationProvider.class, this.context) - .stream() + return GeoWebCacheExtensions.extensions(XMLConfigurationProvider.class, this.context).stream() .anyMatch(provider -> provider.canSave(tl)); } @@ -590,19 +558,14 @@ public synchronized void modifyLayer(TileLayer tl) throws NoSuchElementException } protected TileLayer findLayer(String layerName) throws NoSuchElementException { - TileLayer layer = - getLayer(layerName) - .orElseThrow( - () -> - new NoSuchElementException( - "Layer " + layerName + " does not exist")); + TileLayer layer = getLayer(layerName) + .orElseThrow(() -> new NoSuchElementException("Layer " + layerName + " does not exist")); return layer; } /** @see TileLayerConfiguration#renameLayer(String, String) */ @Override - public void renameLayer(String oldName, String newName) - throws NoSuchElementException, IllegalArgumentException { + public void renameLayer(String oldName, String newName) throws NoSuchElementException, IllegalArgumentException { throw new UnsupportedOperationException( "renameLayer is not supported by " + getClass().getSimpleName()); } @@ -634,8 +597,7 @@ public synchronized void removeLayer(final String layerName) } /** */ - private synchronized void addOrReplaceGridSet(final XMLGridSet gridSet) - throws IllegalArgumentException { + private synchronized void addOrReplaceGridSet(final XMLGridSet gridSet) throws IllegalArgumentException { final String gridsetName = gridSet.getName(); List xmlGridSets = getGwcConfig().getGridSets(); @@ -758,9 +720,7 @@ private static Node checkAndTransform(Document doc) throws ConfigurationExceptio // Check again after transform if (!rootNode.getNodeName().equals("gwcConfiguration")) { - log.log( - Level.SEVERE, - "Unable to parse file, expected gwcConfiguration at root after transform."); + log.log(Level.SEVERE, "Unable to parse file, expected gwcConfiguration at root after transform."); throw new ConfigurationException("Unable to parse after transform."); } else { // Parsing the schema file @@ -869,29 +829,24 @@ private void updateLayers() { private void loadGridSets() { if (getGwcConfig().getGridSets() != null) { - this.gridSets = - getGwcConfig().getGridSets().stream() - .map( - (xmlGridSet) -> { - if (log.isLoggable(Level.FINE)) { - log.fine("Reading " + xmlGridSet.getName()); - } - - GridSet gridSet = xmlGridSet.makeGridSet(); - - log.info("Read GridSet " + gridSet.getName()); - return gridSet; - }) - .collect( - Collectors.toMap( - GridSet::getName, - Function.identity(), - (GridSet x, GridSet y) -> { - throw new IllegalStateException( - "Gridsets with duplicate name " - + x.getName()); - }, - HashMap::new)); + this.gridSets = getGwcConfig().getGridSets().stream() + .map((xmlGridSet) -> { + if (log.isLoggable(Level.FINE)) { + log.fine("Reading " + xmlGridSet.getName()); + } + + GridSet gridSet = xmlGridSet.makeGridSet(); + + log.info("Read GridSet " + gridSet.getName()); + return gridSet; + }) + .collect(Collectors.toMap( + GridSet::getName, + Function.identity(), + (GridSet x, GridSet y) -> { + throw new IllegalStateException("Gridsets with duplicate name " + x.getName()); + }, + HashMap::new)); } } @@ -989,28 +944,23 @@ public void setFullWMS(Boolean isFullWMS) throws IOException { @Override public List getBlobStores() { // need to return an unmodifiable list of unmodifiable BlobStoreInfos - return Collections.unmodifiableList( - getGwcConfig().getBlobStores().stream() - .map( - (info) -> { - return (BlobStoreInfo) info.clone(); - }) - .collect(Collectors.toList())); + return Collections.unmodifiableList(getGwcConfig().getBlobStores().stream() + .map((info) -> { + return (BlobStoreInfo) info.clone(); + }) + .collect(Collectors.toList())); } /** @see BlobStoreConfiguration#addBlobStore(org.geowebcache.config.BlobStoreInfo) */ @Override public synchronized void addBlobStore(BlobStoreInfo info) { if (info.getName() == null) { - throw new IllegalArgumentException( - "Failed to add BlobStoreInfo. A BlobStoreInfo name cannot be null"); + throw new IllegalArgumentException("Failed to add BlobStoreInfo. A BlobStoreInfo name cannot be null"); } // ensure there isn't a BlobStoreInfo with the same name already if (getBlobStoreNames().contains(info.getName())) { - throw new IllegalArgumentException( - String.format( - "Failed to add BlobStoreInfo. A BlobStoreInfo with name \"%s\" already exists", - info.getName())); + throw new IllegalArgumentException(String.format( + "Failed to add BlobStoreInfo. A BlobStoreInfo with name \"%s\" already exists", info.getName())); } // add the BlobStoreInfo final List blobStores = getGwcConfig().getBlobStores(); @@ -1021,14 +971,12 @@ public synchronized void addBlobStore(BlobStoreInfo info) { } catch (IOException ioe) { // save failed, roll back the add blobStores.remove(info); - throw new ConfigurationPersistenceException( - String.format("Unable to add BlobStoreInfo \"%s\"", info), ioe); + throw new ConfigurationPersistenceException(String.format("Unable to add BlobStoreInfo \"%s\"", info), ioe); } try { - blobStoreListeners.safeForEach( - listener -> { - listener.handleAddBlobStore(info); - }); + blobStoreListeners.safeForEach(listener -> { + listener.handleAddBlobStore(info); + }); } catch (IOException | GeoWebCacheException e) { if (ExceptionUtils.isOrSuppresses(e, UnsuitableStorageException.class)) { // Can't store here, roll back @@ -1044,14 +992,9 @@ public synchronized void addBlobStore(BlobStoreInfo info) { @Override public synchronized void removeBlobStore(String name) { // ensure there is a BlobStoreInfo with the name - final BlobStoreInfo infoToRemove = - getBlobStore(name) - .orElseThrow( - () -> - new NoSuchElementException( - String.format( - "Failed to remove BlobStoreInfo. A BlobStoreInfo with name \"%s\" does not exist.", - name))); + final BlobStoreInfo infoToRemove = getBlobStore(name) + .orElseThrow(() -> new NoSuchElementException(String.format( + "Failed to remove BlobStoreInfo. A BlobStoreInfo with name \"%s\" does not exist.", name))); // remove the BlobStoreInfo final List blobStores = getGwcConfig().getBlobStores(); blobStores.remove(infoToRemove); @@ -1065,10 +1008,9 @@ public synchronized void removeBlobStore(String name) { String.format("Unable to remove BlobStoreInfo \"%s\"", name), ioe); } try { - blobStoreListeners.safeForEach( - listener -> { - listener.handleRemoveBlobStore(infoToRemove); - }); + blobStoreListeners.safeForEach(listener -> { + listener.handleRemoveBlobStore(infoToRemove); + }); } catch (IOException | GeoWebCacheException e) { throw new ConfigurationPersistenceException(e); } @@ -1083,10 +1025,9 @@ public synchronized void modifyBlobStore(BlobStoreInfo info) { // ensure there is a BlobStoreInfo with the name final Optional optionalInfo = getBlobStore(info.getName()); if (!optionalInfo.isPresent()) { - throw new NoSuchElementException( - String.format( - "Failed to modify BlobStoreInfo. A BlobStoreInfo with name \"%s\" does not exist.", - info.getName())); + throw new NoSuchElementException(String.format( + "Failed to modify BlobStoreInfo. A BlobStoreInfo with name \"%s\" does not exist.", + info.getName())); } // remove existing and add the new one final List blobStores = getGwcConfig().getBlobStores(); @@ -1104,10 +1045,9 @@ public synchronized void modifyBlobStore(BlobStoreInfo info) { String.format("Unable to modify BlobStoreInfo \"%s\"", info.getName()), ioe); } try { - blobStoreListeners.safeForEach( - listener -> { - listener.handleModifyBlobStore(info); - }); + blobStoreListeners.safeForEach(listener -> { + listener.handleModifyBlobStore(info); + }); } catch (IOException | GeoWebCacheException e) { if (ExceptionUtils.isOrSuppresses(e, UnsuitableStorageException.class)) { // Can't store here, roll back @@ -1130,10 +1070,9 @@ public int getBlobStoreCount() { @Override public Set getBlobStoreNames() { return getGwcConfig().getBlobStores().stream() - .map( - (info) -> { - return info.getName(); - }) + .map((info) -> { + return info.getName(); + }) .collect(Collectors.toSet()); } @@ -1165,9 +1104,7 @@ public void renameBlobStore(String oldName, String newName) final Optional newInfo = getBlobStore(newName); if (newInfo.isPresent()) { throw new IllegalArgumentException( - "BlobStoreInfo rename unsuccessful. A BlobStoreInfo with name \"" - + newName - + "\" already exists."); + "BlobStoreInfo rename unsuccessful. A BlobStoreInfo with name \"" + newName + "\" already exists."); } // get the list of BlobStoreInfos final List blobStoreInfos = getGwcConfig().getBlobStores(); @@ -1190,9 +1127,7 @@ public void renameBlobStore(String oldName, String newName) // if we didn't remove one, it wasn't in there to be removed if (blobStoreInfoToRename == null) { throw new NoSuchElementException( - "BlobStoreInfo rename unsuccessful. No BlobStoreInfo with name \"" - + oldName - + "\" exists."); + "BlobStoreInfo rename unsuccessful. No BlobStoreInfo with name \"" + oldName + "\" exists."); } // rename it and add it back to the list // for BlobStoreInfo instances, "name" and "id" are the same thing. @@ -1203,10 +1138,7 @@ public void renameBlobStore(String oldName, String newName) save(); if (log.isLoggable(Level.FINER)) { - log.finer( - String.format( - "BlobStoreInfo rename from \"%s\" to \"%s\" successful.", - oldName, newName)); + log.finer(String.format("BlobStoreInfo rename from \"%s\" to \"%s\" successful.", oldName, newName)); } } catch (IOException ioe) { // save didn't work, need to roll things back @@ -1223,25 +1155,20 @@ public void renameBlobStore(String oldName, String newName) if (blobStoreInfoToRevert == null) { // we're really messed up now as we couldn't find the BlobStoreInfo that was just // renamed. - throw new ConfigurationPersistenceException( - String.format( - "Error reverting BlobStoreInfo modification. Could not revert rename from \"%s\" to \"%s\"", - oldName, newName)); + throw new ConfigurationPersistenceException(String.format( + "Error reverting BlobStoreInfo modification. Could not revert rename from \"%s\" to \"%s\"", + oldName, newName)); } // revert the name and add it back to the list blobStoreInfoToRevert.setName(oldName); blobStoreInfos.add(blobStoreInfoToRevert); throw new ConfigurationPersistenceException( - String.format( - "Unable to rename BlobStoreInfo from \"%s\" to \"%s\"", - oldName, newName), - ioe); + String.format("Unable to rename BlobStoreInfo from \"%s\" to \"%s\"", oldName, newName), ioe); } try { - blobStoreListeners.safeForEach( - listener -> { - listener.handleRenameBlobStore(oldName, blobStoreInfoToRename); - }); + blobStoreListeners.safeForEach(listener -> { + listener.handleRenameBlobStore(oldName, blobStoreInfoToRename); + }); } catch (IOException | GeoWebCacheException e) { throw new ConfigurationPersistenceException( String.format( @@ -1294,10 +1221,7 @@ private GeoWebCacheConfiguration getGwcConfig() { } } catch (ConfigurationException e) { throw new IllegalStateException( - "Configuration " - + getIdentifier() - + " is not fully initialized and lazy initialization failed", - e); + "Configuration " + getIdentifier() + " is not fully initialized and lazy initialization failed", e); } return gwcConfig; } @@ -1420,8 +1344,7 @@ public synchronized void removeGridSet(String gridSetName) { assert Objects.isNull(gsRemoved) == Objects.isNull(xgsRemoved); if (Objects.isNull(gsRemoved)) { - throw new NoSuchElementException( - "Could not remeove GridSet " + gridSetName + " as it does not exist"); + throw new NoSuchElementException("Could not remeove GridSet " + gridSetName + " as it does not exist"); } try { @@ -1429,8 +1352,7 @@ public synchronized void removeGridSet(String gridSetName) { } catch (IOException ex) { getGridSetsInternal().put(gridSetName, gsRemoved); getGwcConfig().getGridSets().add(xgsRemoved); - throw new ConfigurationPersistenceException( - "Could not persist removal of Gridset " + gridSetName, ex); + throw new ConfigurationPersistenceException("Could not persist removal of Gridset " + gridSetName, ex); } } @@ -1453,9 +1375,7 @@ protected Map getGridSetsInternal() { @Override public Collection getGridSets() { - return getGridSetsInternal().values().stream() - .map(GridSet::new) - .collect(Collectors.toList()); + return getGridSetsInternal().values().stream().map(GridSet::new).collect(Collectors.toList()); } @Override diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/XMLFileResourceProvider.java b/geowebcache/core/src/main/java/org/geowebcache/config/XMLFileResourceProvider.java index e039bb4d8e..648b2620ff 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/XMLFileResourceProvider.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/XMLFileResourceProvider.java @@ -65,8 +65,7 @@ public XMLFileResourceProvider( throws ConfigurationException { if (configFileDirectory == null && storageDirFinder == null) { - throw new NullPointerException( - "At least one of configFileDirectory or storageDirFinder must not be null"); + throw new NullPointerException("At least one of configFileDirectory or storageDirFinder must not be null"); } this.context = appCtx; @@ -76,24 +75,19 @@ public XMLFileResourceProvider( // Use the given path if (new File(configFileDirectory).isAbsolute()) { - log.config( - "Provided configuration directory as absolute path '" - + configFileDirectory - + "'"); + log.config("Provided configuration directory as absolute path '" + configFileDirectory + "'"); this.configDirectory = new File(configFileDirectory); } else { ServletContext servletContext = context.getServletContext(); if (servletContext != null) { String baseDir = servletContext.getRealPath(""); - log.config( - "Provided configuration directory relative to servlet context '" - + baseDir - + "': " - + configFileDirectory); + log.config("Provided configuration directory relative to servlet context '" + + baseDir + + "': " + + configFileDirectory); this.configDirectory = new File(baseDir, configFileDirectory); } else { - throw new IllegalStateException( - "Unexpected, cannot locate the config directory"); + throw new IllegalStateException("Unexpected, cannot locate the config directory"); } } } else { @@ -127,11 +121,7 @@ public XMLFileResourceProvider( final ApplicationContextProvider appCtx, final DefaultStorageFinder storageDirFinder) throws ConfigurationException { - this( - configFileName, - appCtx, - getConfigDirVar(appCtx.getApplicationContext()), - storageDirFinder); + this(configFileName, appCtx, getConfigDirVar(appCtx.getApplicationContext()), storageDirFinder); } /** @@ -183,16 +173,13 @@ private File findConfigFile() throws IOException { } if (!configDirectory.exists() && !configDirectory.mkdirs()) { - throw new IOException( - "TileLayerConfiguration directory does not exist and cannot be created: '" - + configDirectory.getAbsolutePath() - + "'"); + throw new IOException("TileLayerConfiguration directory does not exist and cannot be created: '" + + configDirectory.getAbsolutePath() + + "'"); } if (!configDirectory.canWrite()) { throw new IOException( - "TileLayerConfiguration directory is not writable: '" - + configDirectory.getAbsolutePath() - + "'"); + "TileLayerConfiguration directory is not writable: '" + configDirectory.getAbsolutePath() + "'"); } File xmlFile = new File(configDirectory, configFileName); @@ -216,11 +203,10 @@ private File findOrCreateConfFile() throws IOException { if (xmlFile.exists()) { log.config("Found configuration file in " + configDirectory.getAbsolutePath()); } else if (templateLocation != null) { - log.warning( - "Found no configuration file in config directory, will create one at '" - + xmlFile.getAbsolutePath() - + "' from template " - + getClass().getResource(templateLocation).toExternalForm()); + log.warning("Found no configuration file in config directory, will create one at '" + + xmlFile.getAbsolutePath() + + "' from template " + + getClass().getResource(templateLocation).toExternalForm()); // grab template from classpath try { try (InputStream templateStream = getClass().getResourceAsStream(templateLocation); @@ -229,8 +215,7 @@ private File findOrCreateConfFile() throws IOException { output.flush(); } } catch (IOException e) { - throw new IOException( - "Error copying template config to " + xmlFile.getAbsolutePath(), e); + throw new IOException("Error copying template config to " + xmlFile.getAbsolutePath(), e); } } @@ -244,28 +229,21 @@ private void backUpConfig(final File xmlFile) throws IOException { log.fine("Backing up config file " + xmlFile.getName() + " to " + backUpFileName); - String[] previousBackUps = - parentFile.list( - (dir, name) -> { - if (configFileName.equals(name)) { - return false; - } - if (name.startsWith(configFileName) && name.endsWith(".bak")) { - return true; - } - return false; - }); + String[] previousBackUps = parentFile.list((dir, name) -> { + if (configFileName.equals(name)) { + return false; + } + if (name.startsWith(configFileName) && name.endsWith(".bak")) { + return true; + } + return false; + }); final int maxBackups = 10; if (previousBackUps != null && previousBackUps.length > maxBackups) { Arrays.sort(previousBackUps); String oldest = previousBackUps[0]; - log.fine( - "Deleting oldest config backup " - + oldest - + " to keep a maximum of " - + maxBackups - + " backups."); + log.fine("Deleting oldest config backup " + oldest + " to keep a maximum of " + maxBackups + " backups."); new File(parentFile, oldest).delete(); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSet.java b/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSet.java index d7d99d7d0d..e57a5ae5a9 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSet.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSet.java @@ -67,10 +67,13 @@ public XMLGridSet() { public XMLGridSet(XMLGridSet orig) { setAlignTopLeft(orig.getAlignTopLeft()); setExtent(orig.getExtent() == null ? null : new BoundingBox(orig.getExtent())); - setResolutions(orig.getResolutions() == null ? null : orig.getResolutions().clone()); + setResolutions( + orig.getResolutions() == null ? null : orig.getResolutions().clone()); setLevels(orig.getLevels()); setScaleDenominators( - orig.getScaleDenominators() == null ? null : orig.getScaleDenominators().clone()); + orig.getScaleDenominators() == null + ? null + : orig.getScaleDenominators().clone()); setMetersPerUnit(orig.getMetersPerUnit()); setName(orig.getName()); setDescription(orig.getDescription()); @@ -185,38 +188,36 @@ public GridSet makeGridSet() { Boolean yCoordinateFirst = getYCoordinateFirst(); if (getResolutions() != null || getScaleDenominators() != null) { - gridSet = - GridSetFactory.createGridSet( - name, - srs, - extent, - alignTopLeft, - resolutions, - scaleDenominators, - metersPerUnit, - pixelSize, - scaleNames, - tileWidth, - tileHeight, - yCoordinateFirst); + gridSet = GridSetFactory.createGridSet( + name, + srs, + extent, + alignTopLeft, + resolutions, + scaleDenominators, + metersPerUnit, + pixelSize, + scaleNames, + tileWidth, + tileHeight, + yCoordinateFirst); } else { if (getLevels() == null) { setLevels(18); } Integer levels = getLevels(); - gridSet = - GridSetFactory.createGridSet( - name, - srs, - extent, - alignTopLeft, - levels, - metersPerUnit, - pixelSize, - tileWidth, - tileHeight, - yCoordinateFirst); + gridSet = GridSetFactory.createGridSet( + name, + srs, + extent, + alignTopLeft, + levels, + metersPerUnit, + pixelSize, + tileWidth, + tileHeight, + yCoordinateFirst); } gridSet.setDescription(getDescription()); diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSubset.java b/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSubset.java index 73b81043f5..f0c443844c 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSubset.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/XMLGridSubset.java @@ -70,10 +70,7 @@ public XMLGridSubset(XMLGridSubset sset) { /** Builds an XMLGridSubset out of a {@link GridSubset} */ public XMLGridSubset(GridSubset sset) { setGridSetName(sset.getName()); - setExtent( - sset.getOriginalExtent() == null - ? null - : new BoundingBox(sset.getOriginalExtent())); + setExtent(sset.getOriginalExtent() == null ? null : new BoundingBox(sset.getOriginalExtent())); setZoomStart(sset.getZoomStart()); setZoomStop(sset.getZoomStop()); setMinCachedLevel(sset.getMinCachedZoom()); @@ -94,12 +91,7 @@ public GridSubset getGridSubSet(GridSetBroker gridSetBroker) { return null; } return GridSubsetFactory.createGridSubSet( - gridSet, - getExtent(), - getZoomStart(), - getZoomStop(), - minCachedLevel, - maxCachedLevel); + gridSet, getExtent(), getZoomStart(), getZoomStop(), minCachedLevel, maxCachedLevel); } public String getGridSetName() { diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/XMLOldGrid.java b/geowebcache/core/src/main/java/org/geowebcache/config/XMLOldGrid.java index f4b2e11378..ffc2348749 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/XMLOldGrid.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/XMLOldGrid.java @@ -30,10 +30,7 @@ *

The problem is that it cannot use the GridSetBroker, so we end up with one GridSet per layer * anyway. */ -@SuppressFBWarnings({ - "NP_UNWRITTEN_FIELD", - "NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", - "UWF_NULL_FIELD" +@SuppressFBWarnings({"NP_UNWRITTEN_FIELD", "NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_NULL_FIELD" }) // field assignment done by XStream public class XMLOldGrid implements Serializable { @@ -72,52 +69,45 @@ public GridSubset convertToGridSubset(GridSetBroker gridSetBroker) { GridSet gridSet; - if (srs.equals(SRS.getEPSG4326()) - && gridBounds.equals(BoundingBox.WORLD4326) - && resolutions == null) { + if (srs.equals(SRS.getEPSG4326()) && gridBounds.equals(BoundingBox.WORLD4326) && resolutions == null) { gridSet = gridSetBroker.getWorldEpsg4326(); - } else if (srs.equals(SRS.getEPSG3857()) - && gridBounds.equals(BoundingBox.WORLD3857) - && resolutions == null) { + } else if (srs.equals(SRS.getEPSG3857()) && gridBounds.equals(BoundingBox.WORLD3857) && resolutions == null) { gridSet = gridSetBroker.getWorldEpsg3857(); } else { if (resolutions != null) { - gridSet = - GridSetFactory.createGridSet( - srs.toString(), - srs, - gridBounds, - false, - resolutions, - null, - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - null, - 256, - 256, - false); + gridSet = GridSetFactory.createGridSet( + srs.toString(), + srs, + gridBounds, + false, + resolutions, + null, + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + null, + 256, + 256, + false); } else { if (zoomStop == null) { zoomStop = 30; } - gridSet = - GridSetFactory.createGridSet( - srs.toString(), - srs, - gridBounds, - false, - zoomStop + 1, - null, - GridSetFactory.DEFAULT_PIXEL_SIZE_METER, - 256, - 256, - false); + gridSet = GridSetFactory.createGridSet( + srs.toString(), + srs, + gridBounds, + false, + zoomStop + 1, + null, + GridSetFactory.DEFAULT_PIXEL_SIZE_METER, + 256, + 256, + false); } } - GridSubset gridSubset = - GridSubsetFactory.createGridSubSet(gridSet, dataBounds, zoomStart, zoomStop); + GridSubset gridSubset = GridSubsetFactory.createGridSubSet(gridSet, dataBounds, zoomStart, zoomStop); return gridSubset; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendInfoBuilder.java b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendInfoBuilder.java index bfd077d6d8..9b7d5b9d2a 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendInfoBuilder.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendInfoBuilder.java @@ -123,13 +123,11 @@ public LegendInfo build() { String finalStyleName = styleName == null ? "" : styleName; // building the legend url String finalUrl = buildFinalUrl(finalStyleName, finalWidth, finalHeight, finalFormat); - return new LegendInfo( - finalStyleName, finalWidth, finalHeight, finalFormat, finalUrl, minScale, maxScale); + return new LegendInfo(finalStyleName, finalWidth, finalHeight, finalFormat, finalUrl, minScale, maxScale); } /** Helper method that builds the legend get url using the available info. */ - private String buildFinalUrl( - String finalStyleName, Integer finalWidth, Integer finalHeight, String finalFormat) { + private String buildFinalUrl(String finalStyleName, Integer finalWidth, Integer finalHeight, String finalFormat) { if (completeUrl != null) { // we have a complete url so let's just return it return completeUrl; diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendRawInfo.java b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendRawInfo.java index fe75050391..882f0da814 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendRawInfo.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendRawInfo.java @@ -98,11 +98,7 @@ public void setMaxScale(Double maxScale) { * values. */ public LegendInfo getLegendInfo( - String layerName, - String layerUrl, - Integer defaultWidth, - Integer defaultHeight, - String defaultFormat) { + String layerName, String layerUrl, Integer defaultWidth, Integer defaultHeight, String defaultFormat) { return new LegendInfoBuilder() .withLayerName(layerName) .withLayerUrl(layerUrl) @@ -130,10 +126,8 @@ public boolean equals(Object other) { if (height != null ? !height.equals(that.height) : that.height != null) return false; if (format != null ? !format.equals(that.format) : that.format != null) return false; if (url != null ? !url.equals(that.url) : that.url != null) return false; - if (completeUrl != null ? !completeUrl.equals(that.completeUrl) : that.completeUrl != null) - return false; - if (minScale != null ? !minScale.equals(that.minScale) : that.minScale != null) - return false; + if (completeUrl != null ? !completeUrl.equals(that.completeUrl) : that.completeUrl != null) return false; + if (minScale != null ? !minScale.equals(that.minScale) : that.minScale != null) return false; return maxScale != null ? maxScale.equals(that.maxScale) : that.maxScale == null; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfo.java b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfo.java index 5fd9bf651a..90bb7b5262 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfo.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfo.java @@ -69,8 +69,7 @@ public Map getLegendsInfo(String layerName, String layerUrl) for (LegendRawInfo legendRawInfo : legendsRawInfo) { legendsInfo.put( legendRawInfo.getStyle(), - legendRawInfo.getLegendInfo( - layerName, layerUrl, defaultWidth, defaultHeight, defaultFormat)); + legendRawInfo.getLegendInfo(layerName, layerUrl, defaultWidth, defaultHeight, defaultFormat)); } return legendsInfo; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfoConverter.java b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfoConverter.java index 971f086929..13965cf3e5 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfoConverter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/config/legends/LegendsRawInfoConverter.java @@ -24,8 +24,7 @@ public class LegendsRawInfoConverter implements Converter { @Override - public void marshal( - Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { LegendsRawInfo legendsRawInfo = (LegendsRawInfo) source; // encode default values writer.addAttribute("defaultWidth", String.valueOf(legendsRawInfo.getDefaultWidth())); diff --git a/geowebcache/core/src/main/java/org/geowebcache/controller/GeoWebCacheDispatcherController.java b/geowebcache/core/src/main/java/org/geowebcache/controller/GeoWebCacheDispatcherController.java index a093edc8af..f7ef2141d1 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/controller/GeoWebCacheDispatcherController.java +++ b/geowebcache/core/src/main/java/org/geowebcache/controller/GeoWebCacheDispatcherController.java @@ -39,8 +39,7 @@ public class GeoWebCacheDispatcherController { private GeoWebCacheDispatcher gwcDispatcher; @RequestMapping(path = {"", "/home", "/service/**", "/demo/**", "/proxy/**"}) - public void handleRestApiRequest(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handleRestApiRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { gwcDispatcher.handleRequest( new HttpServletRequestWrapper(request) { @Override diff --git a/geowebcache/core/src/main/java/org/geowebcache/conveyor/Conveyor.java b/geowebcache/core/src/main/java/org/geowebcache/conveyor/Conveyor.java index 93fcf446dc..76eb6c6d2f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/conveyor/Conveyor.java +++ b/geowebcache/core/src/main/java/org/geowebcache/conveyor/Conveyor.java @@ -66,8 +66,7 @@ public static enum CacheResult { protected CacheResult cacheResult; - protected Conveyor( - String layerId, StorageBroker sb, HttpServletRequest srq, HttpServletResponse srp) { + protected Conveyor(String layerId, StorageBroker sb, HttpServletRequest srq, HttpServletResponse srp) { this.layerId = layerId; storageBroker = sb; servletReq = srq; diff --git a/geowebcache/core/src/main/java/org/geowebcache/conveyor/ConveyorTile.java b/geowebcache/core/src/main/java/org/geowebcache/conveyor/ConveyorTile.java index 0baf3e2c74..2485ef78c6 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/conveyor/ConveyorTile.java +++ b/geowebcache/core/src/main/java/org/geowebcache/conveyor/ConveyorTile.java @@ -60,10 +60,7 @@ public class ConveyorTile extends Conveyor implements TileResponseReceiver { private boolean isMetaTileCacheOnly; public ConveyorTile( - StorageBroker sb, - String layerId, - HttpServletRequest servletReq, - HttpServletResponse servletResp) { + StorageBroker sb, String layerId, HttpServletRequest servletReq, HttpServletResponse servletResp) { super(layerId, sb, servletReq, servletResp); } @@ -78,15 +75,7 @@ public ConveyorTile( Map filteringParameters, HttpServletRequest servletReq, HttpServletResponse servletResp) { - this( - sb, - layerId, - gridSetId, - tileIndex, - mimeType, - filteringParameters, - servletReq, - servletResp); + this(sb, layerId, gridSetId, tileIndex, mimeType, filteringParameters, servletReq, servletResp); this.fullParameters = fullParameters; } @@ -116,9 +105,7 @@ public ConveyorTile( this.filteringParameters = filteringParameters; - stObj = - TileObject.createQueryTileObject( - layerId, idx, gridSetId, mimeType.getFormat(), filteringParameters); + stObj = TileObject.createQueryTileObject(layerId, idx, gridSetId, mimeType.getFormat(), filteringParameters); } public Map getFilteringParameters() { diff --git a/geowebcache/core/src/main/java/org/geowebcache/demo/Demo.java b/geowebcache/core/src/main/java/org/geowebcache/demo/Demo.java index 135892dd70..7032b1d561 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/demo/Demo.java +++ b/geowebcache/core/src/main/java/org/geowebcache/demo/Demo.java @@ -74,8 +74,7 @@ public static void makeMap( String rawGridSet = request.getParameter("gridSet"); String gridSetStr = null; - if (rawGridSet != null) - gridSetStr = ServletUtils.URLDecode(rawGridSet, request.getCharacterEncoding()); + if (rawGridSet != null) gridSetStr = ServletUtils.URLDecode(rawGridSet, request.getCharacterEncoding()); if (gridSetStr == null) { gridSetStr = request.getParameter("srs"); @@ -101,8 +100,7 @@ public static void makeMap( if (request.getRequestURI().endsWith("/")) { try { String reqUri = request.getRequestURI(); - response.sendRedirect( - response.encodeRedirectURL(reqUri.substring(0, reqUri.length() - 1))); + response.sendRedirect(response.encodeRedirectURL(reqUri.substring(0, reqUri.length() - 1))); } catch (IOException e) { LOGGER.log(Level.WARNING, "Error sending redirect response", e); } @@ -121,8 +119,7 @@ public static void makeMap( } } - private static String generateHTML( - TileLayerDispatcher tileLayerDispatcher, GridSetBroker gridSetBroker) + private static String generateHTML(TileLayerDispatcher tileLayerDispatcher, GridSetBroker gridSetBroker) throws GeoWebCacheException { String reloadPath = "rest/reload"; String truncatePath = "rest/masstruncate"; @@ -133,47 +130,43 @@ private static String generateHTML( buf.append(ServletUtils.gwcHtmlHeader("", "GWC Demos")); buf.append("\n"); buf.append(ServletUtils.gwcHtmlLogoLink("")); - buf.append( - "

Total number of requests:" - + (requestCount >= 0 ? requestCount + "" : "Unavailable")); + str.append("
Total number of requests:" + + (requestCount >= 0 ? requestCount + "" : "Unavailable")); str.append("
Total number of evicted tiles:" - + (evictionCount >= 0 ? evictionCount + "" : "Unavailable")); + str.append("
Total number of evicted tiles:" + + (evictionCount >= 0 ? evictionCount + "" : "Unavailable")); str.append("
Cache Memory occupation:" - + (currentMemory >= 0 ? currentMemory + " %" : "Unavailable")); + str.append("
Cache Memory occupation:" + + (currentMemory >= 0 ? currentMemory + " %" : "Unavailable")); str.append("
Cache Actual Size/ Total Size :" - + (totalSize >= 0 && actualSize >= 0 - ? actualSize + " / " + totalSize + " Mb" - : "Unavailable")); + str.append("
Cache Actual Size/ Total Size :" + + (totalSize >= 0 && actualSize >= 0 ? actualSize + " / " + totalSize + " Mb" : "Unavailable")); str.append("
\n" - + "\n" - + "\n" - + "\n"); + buf.append("
Layer name:Enabled:Grids Sets:
\n" + + "\n" + + "\n" + + "\n"); buf.append("\n"); tableRows(buf, tileLayerDispatcher, gridSetBroker); buf.append("
Layer name:Enabled:Grids Sets:
\n"); buf.append("
"); - buf.append( - "These are just quick demos. GeoWebCache also supports:
\n" - + "
  • WMTS, TMS, Virtual Earth and Google Maps
  • \n" - + "
  • Proxying GetFeatureInfo, GetLegend and other WMS requests
  • \n" - + "
  • Advanced request and parameter filters
  • \n" - + "
  • Output format adjustments, such as compression level
  • \n" - + "
  • Adjustable expiration headers and automatic cache expiration
  • \n" - + "
  • RESTful interface for seeding and configuration (beta)
  • \n" - + "
\n" - + "
\n" - + "Reload TileLayerConfiguration:
\n" - + "

You can reload the configuration by pressing the following button. " - + "The username / password is configured in WEB-INF/user.properties, or the admin " - + " user in GeoServer if you are using the plugin.

\n" - + "
These are just quick demos. GeoWebCache also supports:
\n" + + "
  • WMTS, TMS, Virtual Earth and Google Maps
  • \n" + + "
  • Proxying GetFeatureInfo, GetLegend and other WMS requests
  • \n" + + "
  • Advanced request and parameter filters
  • \n" + + "
  • Output format adjustments, such as compression level
  • \n" + + "
  • Adjustable expiration headers and automatic cache expiration
  • \n" + + "
  • RESTful interface for seeding and configuration (beta)
  • \n" + + "
\n" + + "
\n" + + "Reload TileLayerConfiguration:
\n" + + "

You can reload the configuration by pressing the following button. " + + "The username / password is configured in WEB-INF/user.properties, or the admin " + + " user in GeoServer if you are using the plugin.

\n" + + "" - + "" - + "" - + "
" - + "
Truncate All Layers:
\n" - + "

Truncate all layers" - + "

" + + "" + + "" + + "
" + + "
Truncate All Layers:
\n" + + "

Truncate all layers" + + "

\" value=\"\"/>" - + "" - + "

" - + ""); + .append("\" method=\"post\">\" value=\"\"/>" + + "" + + "
" + + ""); return buf.toString(); } @@ -192,9 +185,7 @@ private static void tableRows( buf.append("") .append(escapedLayerName) .append("
\n"); - buf.append("Seed this layer\n"); + buf.append("Seed this layer\n"); buf.append("").append(layer.isEnabled()).append(""); buf.append(""); @@ -208,16 +199,10 @@ private static void tableRows( buf.append(""); str.append("\n"); - str.append( - "\n"); @@ -196,9 +187,8 @@ public String getHTMLStats() { str.append(" (" + totalWMS / (runningTime) + "/s ) "); str.append("\n"); - str.append( - "\n"); @@ -211,8 +201,7 @@ public String getHTMLStats() { str.append(""); } - str.append( - "\n"); - str.append( - ""); str.append(""); - str.append( - "\n"); - str.append( - "\n"); + str.append("\n"); } str.append(""); str.append(""); - str.append( - ""); + str.append(""); - str.append( - ""); + str.append(""); str.append(""); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java index 5851e38be5..437810447f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java @@ -50,8 +50,7 @@ public interface BlobStore { * * @return {@literal true} if successful, {@literal false} otherwise */ - public boolean deleteByGridsetId(final String layerName, final String gridSetId) - throws StorageException; + public boolean deleteByGridsetId(final String layerName, final String gridSetId) throws StorageException; /** * Delete the cache for the named layer and parameters. @@ -59,8 +58,8 @@ public boolean deleteByGridsetId(final String layerName, final String gridSetId) * @param parameters Complete filtered parameters to generate the ID * @return {@literal true} if successful, {@literal false} otherwise */ - public default boolean deleteByParameters( - final String layerName, final Map parameters) throws StorageException { + public default boolean deleteByParameters(final String layerName, final Map parameters) + throws StorageException { return deleteByParametersId(layerName, ParametersUtils.getId(parameters)); } @@ -69,8 +68,7 @@ public default boolean deleteByParameters( * * @return {@literal true} if successful, {@literal false} otherwise */ - public boolean deleteByParametersId(final String layerName, String parametersId) - throws StorageException; + public boolean deleteByParametersId(final String layerName, String parametersId) throws StorageException; /** * Delete the cached blob associated with the specified TileObject. The passed in object itself @@ -120,8 +118,7 @@ public boolean deleteByParametersId(final String layerName, String parametersId) public boolean removeListener(BlobStoreListener listener); /** Get the cached parameter maps for a layer */ - public default Set> getParameters(String layerName) - throws StorageException { + public default Set> getParameters(String layerName) throws StorageException { return getParametersMapping(layerName).values().stream() .filter(Optional::isPresent) .map(Optional::get) @@ -184,44 +181,40 @@ public default boolean purgeOrphans(TileLayer layer) throws StorageException { final List parameterFilters = layer.getParameterFilters(); // Given known parameter mapping, figures out if the parameters need to be purged - final Function, Boolean> parametersNeedPurge = - parameters -> { - return parameters.size() != parameterFilters.size() - || // Should have the same number of parameters as the layer has - // filters - parameterFilters.stream() - .allMatch( - pfilter -> { // Do all the parameter filters on the - // layer consider their parameter legal - final String key = pfilter.getKey(); - final String value = parameters.get(key); - if (Objects.isNull(value)) { - return true; // No parameter for this filter - // so purge - } - return !pfilter.isFilteredValue( - value); // purge if it's not a filtered - // value - }); - }; + final Function, Boolean> parametersNeedPurge = parameters -> { + return parameters.size() != parameterFilters.size() + || // Should have the same number of parameters as the layer has + // filters + parameterFilters.stream() + .allMatch( + pfilter -> { // Do all the parameter filters on the + // layer consider their parameter legal + final String key = pfilter.getKey(); + final String value = parameters.get(key); + if (Objects.isNull(value)) { + return true; // No parameter for this filter + // so purge + } + return !pfilter.isFilteredValue(value); // purge if it's not a filtered + // value + }); + }; return getParametersMapping(layer.getName()).entrySet().stream() - .filter( - parameterMapping -> { - return parameterMapping - .getValue() - .map(parametersNeedPurge) - .orElse(true); // Don't have the original values so purge - }) + .filter(parameterMapping -> { + return parameterMapping + .getValue() + .map(parametersNeedPurge) + .orElse(true); // Don't have the original values so purge + }) .map(Map.Entry::getKey) // The parameter id - .map( - id -> { - try { - return this.deleteByParametersId(layer.getName(), id); - } catch (StorageException e) { - throw new UncheckedIOException(e); - } - }) + .map(id -> { + try { + return this.deleteByParametersId(layer.getName(), id); + } catch (StorageException e) { + throw new UncheckedIOException(e); + } + }) .reduce((x, y) -> x || y) // OR results without short circuiting .orElse(false); } catch (UncheckedIOException ex) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreAggregator.java b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreAggregator.java index bc6d841ae2..f2a187723f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreAggregator.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreAggregator.java @@ -99,15 +99,12 @@ public BlobStoreInfo getBlobStore(final String blobStoreName) throws GeoWebCache .filter(Optional::isPresent) .map(Optional::get) .findFirst() - .orElseThrow( - () -> - new GeoWebCacheException( - "Thread " - + Thread.currentThread().getName() - + " Unknown blob store " - + blobStoreName - + ". Check the logfiles," - + " it may not have loaded properly.")); + .orElseThrow(() -> new GeoWebCacheException("Thread " + + Thread.currentThread().getName() + + " Unknown blob store " + + blobStoreName + + ". Check the logfiles," + + " it may not have loaded properly.")); } /** @@ -118,8 +115,7 @@ public BlobStoreInfo getBlobStore(final String blobStoreName) throws GeoWebCache * generate a new one. */ public void reInit() { - List extensions = - GeoWebCacheExtensions.extensions(BlobStoreConfiguration.class); + List extensions = GeoWebCacheExtensions.extensions(BlobStoreConfiguration.class); this.configs = new ArrayList<>(extensions); this.layers = GeoWebCacheExtensions.bean(TileLayerDispatcher.class); initialize(); @@ -161,7 +157,8 @@ public List getBlobStoreNames() { * @return a list view of this blob store aggregators's internal blob stores */ public Iterable getBlobStores() { - List> perConfigBlobStores = new ArrayList<>(getConfigs().size()); + List> perConfigBlobStores = + new ArrayList<>(getConfigs().size()); for (BlobStoreConfiguration config : getConfigs()) { perConfigBlobStores.add(config.getBlobStores()); @@ -180,18 +177,14 @@ private void initialize() { private int initialize(BlobStoreConfiguration config) { if (config == null) { - throw new IllegalStateException( - "BlobStoreConfiguration got a null GWC configuration object"); + throw new IllegalStateException("BlobStoreConfiguration got a null GWC configuration object"); } String configIdent; try { configIdent = config.getIdentifier(); } catch (Exception gwce) { - log.log( - Level.SEVERE, - "Error obtaining identify from BlobStoreConfiguration " + config, - gwce); + log.log(Level.SEVERE, "Error obtaining identify from BlobStoreConfiguration " + config, gwce); return 0; } @@ -203,10 +196,7 @@ private int initialize(BlobStoreConfiguration config) { int blobStoreCount = config.getBlobStoreCount(); if (blobStoreCount <= 0) { - log.config( - "BlobStoreConfiguration " - + config.getIdentifier() - + " contained no blob store infos."); + log.config("BlobStoreConfiguration " + config.getIdentifier() + " contained no blob store infos."); } // Check whether there is any general service information @@ -238,16 +228,14 @@ public void destroy() throws Exception { * * @param blobStoreName the name of the blob store to remove */ - public synchronized void removeBlobStore(final String blobStoreName) - throws IllegalArgumentException { + public synchronized void removeBlobStore(final String blobStoreName) throws IllegalArgumentException { for (BlobStoreConfiguration config : getConfigs()) { if (config.containsBlobStore(blobStoreName)) { config.removeBlobStore(blobStoreName); return; } } - throw new NoSuchElementException( - "No configuration found containing blob store " + blobStoreName); + throw new NoSuchElementException("No configuration found containing blob store " + blobStoreName); } /** * Adds a blob store and returns the {@link BlobStoreConfiguration} to which the blob stores was @@ -293,8 +281,7 @@ public synchronized void renameBlobStore(final String oldName, final String newN * * @param bs The blob store to modify */ - public synchronized void modifyBlobStore(final BlobStoreInfo bs) - throws IllegalArgumentException { + public synchronized void modifyBlobStore(final BlobStoreInfo bs) throws IllegalArgumentException { BlobStoreConfiguration config = getConfiguration(bs); // TODO: this won't work with GetCapabilitiesConfiguration config.modifyBlobStore(bs); @@ -307,8 +294,7 @@ public synchronized void modifyBlobStore(final BlobStoreInfo bs) * @param bs BlobStoreInfo for this configuration * @return The BlobStoreConfiguration for BlobStoreInfo */ - public BlobStoreConfiguration getConfiguration(BlobStoreInfo bs) - throws IllegalArgumentException { + public BlobStoreConfiguration getConfiguration(BlobStoreInfo bs) throws IllegalArgumentException { Assert.notNull(bs, "blobStore is null"); return getConfiguration(bs.getName()); } @@ -317,16 +303,14 @@ public BlobStoreConfiguration getConfiguration(BlobStoreInfo bs) * Returns the BlobStoreConfiguration for the given Blob Store Name, if found in list of blob * store configurations. */ - public BlobStoreConfiguration getConfiguration(final String blobStoreName) - throws IllegalArgumentException { + public BlobStoreConfiguration getConfiguration(final String blobStoreName) throws IllegalArgumentException { Assert.notNull(blobStoreName, "blobStoreName is null"); for (BlobStoreConfiguration c : getConfigs()) { if (c.containsBlobStore(blobStoreName)) { return c; } } - throw new IllegalArgumentException( - "No configuration found containing blob store " + blobStoreName); + throw new IllegalArgumentException("No configuration found containing blob store " + blobStoreName); } /** diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreListenerList.java b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreListenerList.java index 1f5c8a554d..75a4dc2a53 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreListenerList.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStoreListenerList.java @@ -41,31 +41,27 @@ public synchronized boolean removeListener(BlobStoreListener listener) { } public void sendLayerDeleted(String layerName) { - listeners.forEach( - listener -> { - listener.layerDeleted(layerName); - }); + listeners.forEach(listener -> { + listener.layerDeleted(layerName); + }); } public void sendLayerRenamed(String oldLayerName, String newLayerName) { - listeners.forEach( - listener -> { - listener.layerRenamed(oldLayerName, newLayerName); - }); + listeners.forEach(listener -> { + listener.layerRenamed(oldLayerName, newLayerName); + }); } public void sendGridSubsetDeleted(String layerName, String gridSetId) { - listeners.forEach( - listener -> { - listener.gridSubsetDeleted(layerName, gridSetId); - }); + listeners.forEach(listener -> { + listener.gridSubsetDeleted(layerName, gridSetId); + }); } public void sendParametersDeleted(String layerName, String parametersId) { - listeners.forEach( - listener -> { - listener.parametersDeleted(layerName, parametersId); - }); + listeners.forEach(listener -> { + listener.parametersDeleted(layerName, parametersId); + }); } public void sendTileDeleted( @@ -77,11 +73,9 @@ public void sendTileDeleted( long y, int z, long length) { - listeners.forEach( - listener -> { - listener.tileDeleted( - layerName, gridSetId, blobFormat, parametersId, x, y, z, length); - }); + listeners.forEach(listener -> { + listener.tileDeleted(layerName, gridSetId, blobFormat, parametersId, x, y, z, length); + }); } public void sendTileDeleted(final TileObject stObj) { @@ -93,8 +87,7 @@ public void sendTileDeleted(final TileObject stObj) { final String paramsId = stObj.getParametersId(); final int blobSize = stObj.getBlobSize(); - sendTileDeleted( - layerName, gridSetId, blobFormat, paramsId, xyz[0], xyz[1], (int) xyz[2], blobSize); + sendTileDeleted(layerName, gridSetId, blobFormat, paramsId, xyz[0], xyz[1], (int) xyz[2], blobSize); } public void sendTileStored( @@ -106,11 +99,9 @@ public void sendTileStored( long y, int z, long length) { - listeners.forEach( - listener -> { - listener.tileStored( - layerName, gridSetId, blobFormat, parametersId, x, y, z, length); - }); + listeners.forEach(listener -> { + listener.tileStored(layerName, gridSetId, blobFormat, parametersId, x, y, z, length); + }); } public void sendTileStored(final TileObject stObj) { @@ -122,8 +113,7 @@ public void sendTileStored(final TileObject stObj) { final String paramsId = stObj.getParametersId(); final int blobSize = stObj.getBlobSize(); - sendTileStored( - layerName, gridSetId, blobFormat, paramsId, xyz[0], xyz[1], (int) xyz[2], blobSize); + sendTileStored(layerName, gridSetId, blobFormat, paramsId, xyz[0], xyz[1], (int) xyz[2], blobSize); } public void sendTileUpdated( @@ -136,19 +126,9 @@ public void sendTileUpdated( int z, long blobSize, long oldSize) { - listeners.forEach( - listener -> { - listener.tileUpdated( - layerName, - gridSetId, - blobFormat, - parametersId, - x, - y, - z, - blobSize, - oldSize); - }); + listeners.forEach(listener -> { + listener.tileUpdated(layerName, gridSetId, blobFormat, parametersId, x, y, z, blobSize, oldSize); + }); } public void sendTileUpdated(final TileObject stObj, final long oldSize) { @@ -160,15 +140,6 @@ public void sendTileUpdated(final TileObject stObj, final long oldSize) { final String paramsId = stObj.getParametersId(); final int blobSize = stObj.getBlobSize(); - sendTileUpdated( - layerName, - gridSetId, - blobFormat, - paramsId, - xyz[0], - xyz[1], - (int) xyz[2], - blobSize, - oldSize); + sendTileUpdated(layerName, gridSetId, blobFormat, paramsId, xyz[0], xyz[1], (int) xyz[2], blobSize, oldSize); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java index fcf96ceb95..dee672448e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java @@ -59,14 +59,14 @@ */ public class CompositeBlobStore implements BlobStore, BlobStoreConfigurationListener { - static final String GEOWEBCACHE_BLOBSTORE_SUITABILITY_CHECK = - "GEOWEBCACHE_BLOBSTORE_SUITABILITY_CHECK"; + static final String GEOWEBCACHE_BLOBSTORE_SUITABILITY_CHECK = "GEOWEBCACHE_BLOBSTORE_SUITABILITY_CHECK"; private static Logger log = Logging.getLogger(CompositeBlobStore.class.getName()); public static final String DEFAULT_STORE_DEFAULT_ID = "_DEFAULT_STORE_"; - @VisibleForTesting Map blobStores = new ConcurrentHashMap<>(); + @VisibleForTesting + Map blobStores = new ConcurrentHashMap<>(); private TileLayerDispatcher layers; @@ -103,14 +103,10 @@ public static enum StoreSuitabilityCheck { } @VisibleForTesting - static final ThreadLocal storeSuitability = - ThreadLocal.withInitial( - () -> - Optional.ofNullable( - GeoWebCacheExtensions.getProperty( - GEOWEBCACHE_BLOBSTORE_SUITABILITY_CHECK)) - .map(StoreSuitabilityCheck::valueOf) - .orElse(StoreSuitabilityCheck.EXISTING)); + static final ThreadLocal storeSuitability = ThreadLocal.withInitial( + () -> Optional.ofNullable(GeoWebCacheExtensions.getProperty(GEOWEBCACHE_BLOBSTORE_SUITABILITY_CHECK)) + .map(StoreSuitabilityCheck::valueOf) + .orElse(StoreSuitabilityCheck.EXISTING)); /** Specifies how new blob stores should check the existing content of their persistence. */ public static StoreSuitabilityCheck getStoreSuitabilityCheck() { @@ -214,49 +210,45 @@ private void destroy(Map blobStores) { /** Adds the listener to all enabled blob stores */ @Override public void addListener(BlobStoreListener listener) { - readAction( - () -> { - this.listeners.addListener( - listener); // save it for later in case setBlobStores is - // called - for (LiveStore bs : blobStores.values()) { - if (bs.config.isEnabled()) { - bs.liveInstance.addListener(listener); - } - } - }); + readAction(() -> { + this.listeners.addListener(listener); // save it for later in case setBlobStores is + // called + for (LiveStore bs : blobStores.values()) { + if (bs.config.isEnabled()) { + bs.liveInstance.addListener(listener); + } + } + }); } /** Removes the listener from all the enabled blob stores */ @Override public boolean removeListener(BlobStoreListener listener) { - return readFunction( - () -> { - this.listeners.removeListener(listener); - return blobStores.values().stream() - .filter(bs -> bs.config.isEnabled()) - .map(bs -> bs.liveInstance.removeListener(listener)) - .collect(Collectors.reducing((x, y) -> x || y)) // Don't use anyMatch or - // findFirst as we don't want it - // to shortcut - .orElse(false); - }); + return readFunction(() -> { + this.listeners.removeListener(listener); + return blobStores.values().stream() + .filter(bs -> bs.config.isEnabled()) + .map(bs -> bs.liveInstance.removeListener(listener)) + .collect(Collectors.reducing((x, y) -> x || y)) // Don't use anyMatch or + // findFirst as we don't want it + // to shortcut + .orElse(false); + }); } @Override public boolean rename(String oldLayerName, String newLayerName) throws StorageException { - return readFunctionUnsafe( - () -> { - for (LiveStore bs : blobStores.values()) { - BlobStoreInfo config = bs.config; - if (config.isEnabled()) { - if (bs.liveInstance.rename(oldLayerName, newLayerName)) { - return true; - } - } + return readFunctionUnsafe(() -> { + for (LiveStore bs : blobStores.values()) { + BlobStoreInfo config = bs.config; + if (config.isEnabled()) { + if (bs.liveInstance.rename(oldLayerName, newLayerName)) { + return true; } - return false; - }); + } + } + return false; + }); } @Override @@ -266,21 +258,15 @@ public String getLayerMetadata(String layerName, String key) { @Override public void putLayerMetadata(String layerName, String key, String value) { - readAction( - () -> { - store(layerName).putLayerMetadata(layerName, key, value); - }); + readAction(() -> { + store(layerName).putLayerMetadata(layerName, key, value); + }); } @Override public boolean layerExists(String layerName) { - return readFunction( - () -> - blobStores.values().stream() - .anyMatch( - bs -> - bs.config.isEnabled() - && bs.liveInstance.layerExists(layerName))); + return readFunction(() -> blobStores.values().stream() + .anyMatch(bs -> bs.config.isEnabled() && bs.liveInstance.layerExists(layerName))); } private BlobStore store(String layerId) throws StorageException { @@ -292,8 +278,7 @@ private BlobStore store(String layerId) throws StorageException { throw new StorageException(e.getMessage(), e); } if (!store.config.isEnabled()) { - throw new StorageException( - "Attempted to use a blob store that's disabled: " + store.config.getName()); + throw new StorageException("Attempted to use a blob store that's disabled: " + store.config.getName()); } return store.liveInstance; @@ -380,8 +365,7 @@ Map loadBlobStores(Iterable configs) config.setBaseDirectory(defaultStorageFinder.getDefaultPath()); BlobStore store = new FileBlobStore(config.getBaseDirectory()); - stores.put( - CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID, new LiveStore(config, store)); + stores.put(CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID, new LiveStore(config, store)); } } catch (ConfigurationException | StorageException e) { destroy(stores); @@ -410,20 +394,17 @@ private LiveStore loadBlobStore(Map stores, BlobStoreInfo con final String id = config.getName(); final boolean enabled = config.isEnabled(); - LiveStore defaultStore = - stores.getOrDefault(CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID, null); + LiveStore defaultStore = stores.getOrDefault(CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID, null); if (Strings.isNullOrEmpty(id)) { throw new ConfigurationException("No id provided for blob store " + config); } if (stores.containsKey(id)) { - throw new ConfigurationException( - "Duplicate blob store id: " + id + ". Check your configuration."); + throw new ConfigurationException("Duplicate blob store id: " + id + ". Check your configuration."); } if (CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID.equals(id)) { - throw new ConfigurationException( - CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID - + " is a reserved identifier, please don't use it in the configuration"); + throw new ConfigurationException(CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID + + " is a reserved identifier, please don't use it in the configuration"); } BlobStore store = null; @@ -437,27 +418,21 @@ private LiveStore loadBlobStore(Map stores, BlobStoreInfo con if (config.isDefault()) { if (defaultStore == null || defaultStore.config.getName().equals(config.getName())) { if (!enabled) { - throw new ConfigurationException( - "The default blob store can't be disabled: " + config.getName()); + throw new ConfigurationException("The default blob store can't be disabled: " + config.getName()); } stores.put(CompositeBlobStore.DEFAULT_STORE_DEFAULT_ID, liveStore); } else { throw new ConfigurationException( - "Duplicate default blob store: " - + defaultStore.config.getName() - + " and " - + config.getName()); + "Duplicate default blob store: " + defaultStore.config.getName() + " and " + config.getName()); } } return liveStore; } @Override - public boolean deleteByParametersId(String layerName, String parametersId) - throws StorageException { - return readFunctionUnsafe( - () -> store(layerName).deleteByParametersId(layerName, parametersId)); + public boolean deleteByParametersId(String layerName, String parametersId) throws StorageException { + return readFunctionUnsafe(() -> store(layerName).deleteByParametersId(layerName, parametersId)); } @Override @@ -498,21 +473,17 @@ protected T readFunction(StorageAccessor function) { } protected void readActionUnsafe(StorageAction function) throws StorageException { - readFunctionUnsafe( - (StorageAccessor) - () -> { - function.run(); - return null; - }); + readFunctionUnsafe((StorageAccessor) () -> { + function.run(); + return null; + }); } protected void readAction(StorageAction function) { - readFunction( - (StorageAccessor) - () -> { - function.run(); - return null; - }); + readFunction((StorageAccessor) () -> { + function.run(); + return null; + }); } @Override @@ -521,8 +492,7 @@ public Map>> getParametersMapping(String la } @Override - public void handleAddBlobStore(BlobStoreInfo newBlobStore) - throws ConfigurationException, StorageException { + public void handleAddBlobStore(BlobStoreInfo newBlobStore) throws ConfigurationException, StorageException { if (newBlobStore.isDefault()) { loadBlobStoreOverwritingDefault(blobStores, newBlobStore); } else { @@ -531,26 +501,26 @@ public void handleAddBlobStore(BlobStoreInfo newBlobStore) } @Override - public void handleRemoveBlobStore(BlobStoreInfo removedBlobStore) - throws ConfigurationException, StorageException { + public void handleRemoveBlobStore(BlobStoreInfo removedBlobStore) throws ConfigurationException, StorageException { if (removedBlobStore .getName() .equals(blobStores.get(DEFAULT_STORE_DEFAULT_ID).config.getName())) { - throw new ConfigurationException( - "The default blob store can't be removed: " + removedBlobStore.getName()); + throw new ConfigurationException("The default blob store can't be removed: " + removedBlobStore.getName()); } blobStores.remove(removedBlobStore.getName()); } @Override - public void handleModifyBlobStore(BlobStoreInfo modifiedBlobStore) - throws ConfigurationException, StorageException { + public void handleModifyBlobStore(BlobStoreInfo modifiedBlobStore) throws ConfigurationException, StorageException { LiveStore removedStore = blobStores.remove(modifiedBlobStore.getName()); try { if (modifiedBlobStore.isDefault() && !modifiedBlobStore .getName() - .equals(blobStores.get(DEFAULT_STORE_DEFAULT_ID).config.getName())) { + .equals(blobStores + .get(DEFAULT_STORE_DEFAULT_ID) + .config + .getName())) { loadBlobStoreOverwritingDefault(blobStores, modifiedBlobStore); } else { loadBlobStore(blobStores, modifiedBlobStore); @@ -608,8 +578,7 @@ public void handleRenameBlobStore(String oldName, BlobStoreInfo modifiedBlobStor * @param stores The blobStores map to update * @param config The new default blob store */ - private void loadBlobStoreOverwritingDefault( - Map stores, BlobStoreInfo config) + private void loadBlobStoreOverwritingDefault(Map stores, BlobStoreInfo config) throws StorageException, ConfigurationException { LiveStore oldDefaultStore = stores.get(DEFAULT_STORE_DEFAULT_ID); try { @@ -646,9 +615,7 @@ public static void checkSuitability(String location, final boolean exists, boole case EMPTY: if (!empty) { throw new UnsuitableStorageException( - "Attempted to create Blob Store in " - + location - + " but it was not empty"); + "Attempted to create Blob Store in " + location + " but it was not empty"); } case NONE: } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/DefaultStorageBroker.java b/geowebcache/core/src/main/java/org/geowebcache/storage/DefaultStorageBroker.java index a3ab8e29dd..c4c6a2a95b 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/DefaultStorageBroker.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/DefaultStorageBroker.java @@ -53,8 +53,7 @@ public boolean delete(String layerName) throws StorageException { } @Override - public boolean deleteByGridSetId(final String layerName, final String gridSetId) - throws StorageException { + public boolean deleteByGridSetId(final String layerName, final String gridSetId) throws StorageException { return blobStore.deleteByGridsetId(layerName, gridSetId); } @@ -65,8 +64,7 @@ public boolean deleteByParameters(final String layerName, final Map parameters) { - super( - layerName, - gridSetId, - zoomStart, - zoomStop, - rasterMask.getGridCoverages(), - mimeType, - parameters); + super(layerName, gridSetId, zoomStart, zoomStop, rasterMask.getGridCoverages(), mimeType, parameters); this.mask = rasterMask; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/MetastoreRemover.java b/geowebcache/core/src/main/java/org/geowebcache/storage/MetastoreRemover.java index 6a8e0ec00a..dcfd7e45a7 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/MetastoreRemover.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/MetastoreRemover.java @@ -111,155 +111,133 @@ private void migrateParameters(JdbcTemplate template, final File root) { + " join parameters on parameters.id = tiles.parameters_id\n" + "group by layer, gridset, z, parameters, parameters_id"; - final long total = - Optional.ofNullable( - template.queryForObject( - "select count(*) from (" + query + ")", Long.class)) - .orElse(0l); + final long total = Optional.ofNullable( + template.queryForObject("select count(*) from (" + query + ")", Long.class)) + .orElse(0l); log.info("Migrating " + total + " parameters from the metastore to the file system"); - template.query( - query, - new RowCallbackHandler() { - - long count = 0; - - @Override - public void processRow(ResultSet rs) throws SQLException { - String layer = rs.getString(1); - String gridset = rs.getString(2); - int z = rs.getInt(3); - String paramsKvp = rs.getString(4); - String paramsId = rs.getString(5); - - String sha = getParamsSha1(paramsKvp); - - // move the folders containing params - File origin = new File(buildFolderPath(root, layer, gridset, z, paramsId)); - File destination = new File(buildFolderPath(root, layer, gridset, z, sha)); - org.geowebcache.util.FileUtils.renameFile(origin, destination); - - count++; - if (count % 1000 == 0 || count >= total) { - log.info( - "Migrated " - + count - + "/" - + total - + " parameters from the metastore to the file system"); - } - } + template.query(query, new RowCallbackHandler() { - private String buildFolderPath( - final File root, String layer, String gridset, int z, String paramsId) { - // build the old path - StringBuilder path = new StringBuilder(); - path.append(root.getPath()); - path.append(File.separatorChar); - appendFiltered(layer, path); - path.append(File.separatorChar); - FilePathUtils.appendGridsetZoomLevelDir(gridset, z, path); - path.append('_'); - path.append(paramsId); - path.append(File.separatorChar); - - return path.toString(); - } + long count = 0; - private String getParamsSha1(String paramsKvp) { - Map params = toMap(paramsKvp); - return ParametersUtils.getId(params); - } + @Override + public void processRow(ResultSet rs) throws SQLException { + String layer = rs.getString(1); + String gridset = rs.getString(2); + int z = rs.getInt(3); + String paramsKvp = rs.getString(4); + String paramsId = rs.getString(5); - /** - * Parses the param list stored in the db to a parameter list (since this is - * coming from the database the assumption is that the contents are sane) - */ - private Map toMap(String paramsKvp) { - // TODO: wondering, shall we URL decode the values?? - Map result = new HashMap<>(); - String[] kvps = paramsKvp.split("&"); - for (String kvp : kvps) { - if (kvp != null && !"".equals(kvp)) { - String[] kv = kvp.split("="); - result.put(kv[0], kv[1]); - } - } - - return result; + String sha = getParamsSha1(paramsKvp); + + // move the folders containing params + File origin = new File(buildFolderPath(root, layer, gridset, z, paramsId)); + File destination = new File(buildFolderPath(root, layer, gridset, z, sha)); + org.geowebcache.util.FileUtils.renameFile(origin, destination); + + count++; + if (count % 1000 == 0 || count >= total) { + log.info("Migrated " + count + "/" + total + " parameters from the metastore to the file system"); + } + } + + private String buildFolderPath(final File root, String layer, String gridset, int z, String paramsId) { + // build the old path + StringBuilder path = new StringBuilder(); + path.append(root.getPath()); + path.append(File.separatorChar); + appendFiltered(layer, path); + path.append(File.separatorChar); + FilePathUtils.appendGridsetZoomLevelDir(gridset, z, path); + path.append('_'); + path.append(paramsId); + path.append(File.separatorChar); + + return path.toString(); + } + + private String getParamsSha1(String paramsKvp) { + Map params = toMap(paramsKvp); + return ParametersUtils.getId(params); + } + + /** + * Parses the param list stored in the db to a parameter list (since this is + * coming from the database the assumption is that the contents are sane) + */ + private Map toMap(String paramsKvp) { + // TODO: wondering, shall we URL decode the values?? + Map result = new HashMap<>(); + String[] kvps = paramsKvp.split("&"); + for (String kvp : kvps) { + if (kvp != null && !"".equals(kvp)) { + String[] kv = kvp.split("="); + result.put(kv[0], kv[1]); } - }); + } + + return result; + } + }); } private void migrateTileDates(JdbcTemplate template, final FilePathGenerator generator) { - String query = - "select layers.value as layer, gridsets.value as gridset, " - + "tiles.parameters_id, tiles.z, tiles.x, tiles.y, created, formats.value as format \n" - + "from tiles join layers on layers.id = tiles.layer_id \n" - + "join gridsets on gridsets.id = tiles.gridset_id \n" - + "join formats on formats.id = tiles.format_id \n" - + "order by layer_id, parameters_id, gridset, z, x, y"; - - final long total = - Optional.ofNullable( - template.queryForObject( - "select count(*) from (" + query + ")", Long.class)) - .orElse(0l); - log.info( - "Migrating " - + total - + " tile creation dates from the metastore to the file system"); - - template.query( - query, - new RowCallbackHandler() { - - int count = 0; - - @Override - public void processRow(ResultSet rs) throws SQLException { - // read the result set - String layer = rs.getString(1); - String gridset = rs.getString(2); - String paramsId = rs.getString(3); - long z = rs.getLong(4); - long x = rs.getLong(5); - long y = rs.getLong(6); - long created = rs.getLong(7); - String format = rs.getString(8); - - // create the tile and thus the tile path - TileObject tile = - TileObject.createCompleteTileObject( - layer, new long[] {x, y, z}, gridset, format, null, null); - tile.setParametersId(paramsId); - try { - File file = generator.tilePath(tile, MimeType.createFromFormat(format)); - - // update the last modified according to the date - if (file.exists()) { - file.setLastModified(created); - } - } catch (MimeException e) { - log.log( - Level.SEVERE, - "Failed to locate mime type for format '" - + format - + "', this should never happen!"); - } catch (GeoWebCacheException e) { - log.log(Level.SEVERE, "Failed to compute tile path", e); - } - - count++; - if (count % 10000 == 0 || count >= total) { - log.info( - "Migrated " - + count - + "/" - + total - + " tile creation dates from the metastore to the file system"); - } + String query = "select layers.value as layer, gridsets.value as gridset, " + + "tiles.parameters_id, tiles.z, tiles.x, tiles.y, created, formats.value as format \n" + + "from tiles join layers on layers.id = tiles.layer_id \n" + + "join gridsets on gridsets.id = tiles.gridset_id \n" + + "join formats on formats.id = tiles.format_id \n" + + "order by layer_id, parameters_id, gridset, z, x, y"; + + final long total = Optional.ofNullable( + template.queryForObject("select count(*) from (" + query + ")", Long.class)) + .orElse(0l); + log.info("Migrating " + total + " tile creation dates from the metastore to the file system"); + + template.query(query, new RowCallbackHandler() { + + int count = 0; + + @Override + public void processRow(ResultSet rs) throws SQLException { + // read the result set + String layer = rs.getString(1); + String gridset = rs.getString(2); + String paramsId = rs.getString(3); + long z = rs.getLong(4); + long x = rs.getLong(5); + long y = rs.getLong(6); + long created = rs.getLong(7); + String format = rs.getString(8); + + // create the tile and thus the tile path + TileObject tile = + TileObject.createCompleteTileObject(layer, new long[] {x, y, z}, gridset, format, null, null); + tile.setParametersId(paramsId); + try { + File file = generator.tilePath(tile, MimeType.createFromFormat(format)); + + // update the last modified according to the date + if (file.exists()) { + file.setLastModified(created); } - }); + } catch (MimeException e) { + log.log( + Level.SEVERE, + "Failed to locate mime type for format '" + format + "', this should never happen!"); + } catch (GeoWebCacheException e) { + log.log(Level.SEVERE, "Failed to compute tile path", e); + } + + count++; + if (count % 10000 == 0 || count >= total) { + log.info("Migrated " + + count + + "/" + + total + + " tile creation dates from the metastore to the file system"); + } + } + }); } private String getVariable(String variable, String defaultValue) { @@ -271,16 +249,13 @@ private String getVariable(String variable, String defaultValue) { } } - private Connection getMetaStoreConnection(File root) - throws ClassNotFoundException, SQLException { + private Connection getMetaStoreConnection(File root) throws ClassNotFoundException, SQLException { try { String username = getVariable(DefaultStorageFinder.GWC_METASTORE_USERNAME, "sa"); String password = getVariable(DefaultStorageFinder.GWC_METASTORE_PASSWORD, ""); String defaultJDBCURL = getDefaultJDBCURL(root); - String jdbcString = - getVariable(DefaultStorageFinder.GWC_METASTORE_JDBC_URL, defaultJDBCURL); - String driver = - getVariable(DefaultStorageFinder.GWC_METASTORE_DRIVER_CLASS, "org.h2.Driver"); + String jdbcString = getVariable(DefaultStorageFinder.GWC_METASTORE_JDBC_URL, defaultJDBCURL); + String driver = getVariable(DefaultStorageFinder.GWC_METASTORE_DRIVER_CLASS, "org.h2.Driver"); if (defaultJDBCURL.equals(jdbcString)) { defaultLocation = true; @@ -303,15 +278,11 @@ private Connection getMetaStoreConnection(File root) return DriverManager.getConnection(jdbcString, username, password); } catch (ClassNotFoundException e) { Level logLevel = Level.WARNING; - if (getVariable(DefaultStorageFinder.GWC_METASTORE_DRIVER_CLASS, null) == null) - logLevel = Level.FINE; + if (getVariable(DefaultStorageFinder.GWC_METASTORE_DRIVER_CLASS, null) == null) logLevel = Level.FINE; log.log(logLevel, "Could not find the metastore driver, skipping migration", e); return null; } catch (SQLException e) { - log.log( - Level.WARNING, - "Failed to connect to the legacy metastore, skipping migration", - e); + log.log(Level.WARNING, "Failed to connect to the legacy metastore, skipping migration", e); return null; } } @@ -324,8 +295,7 @@ private File getDefaultH2Path(File root) { private String getDefaultJDBCURL(File root) { String path = root.getPath() + File.separator + "meta_jdbc_h2"; - String jdbcString = - "jdbc:h2:file:" + path + File.separator + "gwc_metastore" + ";TRACE_LEVEL_FILE=0"; + String jdbcString = "jdbc:h2:file:" + path + File.separator + "gwc_metastore" + ";TRACE_LEVEL_FILE=0"; return jdbcString; } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/RasterMask.java b/geowebcache/core/src/main/java/org/geowebcache/storage/RasterMask.java index 9d9dd2bda0..5ca2f5973d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/RasterMask.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/RasterMask.java @@ -39,8 +39,7 @@ public class RasterMask implements TileRangeMask { * * @see #RasterMask(BufferedImage[], long[][], long[][], int) */ - public RasterMask( - BufferedImage[] byLevelMasks, long[][] fullCoverage, final long[][] coveredBounds) { + public RasterMask(BufferedImage[] byLevelMasks, long[][] fullCoverage, final long[][] coveredBounds) { this(byLevelMasks, fullCoverage, coveredBounds, 0); } @@ -63,10 +62,7 @@ public RasterMask( * the pixel location) */ public RasterMask( - BufferedImage[] byLevelMasks, - long[][] fullCoverage, - final long[][] coveredBounds, - final int noDataValue) { + BufferedImage[] byLevelMasks, long[][] fullCoverage, final long[][] coveredBounds, final int noDataValue) { this.byLevelMasks = byLevelMasks; this.fullCoverage = fullCoverage; this.coveredBounds = coveredBounds; @@ -90,10 +86,7 @@ public boolean lookup(final long x, final long y, final int z) { int level = z; long[] coverage = getGridCoverages()[level]; - if (tileX < coverage[0] - || tileX > coverage[2] - || tileY < coverage[1] - || tileY > coverage[3]) { + if (tileX < coverage[0] || tileX > coverage[2] || tileY < coverage[1] || tileY > coverage[3]) { return false; } @@ -123,10 +116,7 @@ public boolean lookup(final long x, final long y, final int z) { private boolean isTileSet(long tileX, long tileY, int level) { long[] coverage = getGridCoverages()[level]; - if (tileX < coverage[0] - || tileX > coverage[2] - || tileY < coverage[1] - || tileY > coverage[3]) { + if (tileX < coverage[0] || tileX > coverage[2] || tileY < coverage[1] || tileY > coverage[3]) { return false; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/StorageBroker.java b/geowebcache/core/src/main/java/org/geowebcache/storage/StorageBroker.java index 1a74c5450b..7ab437c05f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/StorageBroker.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/StorageBroker.java @@ -39,8 +39,7 @@ public interface StorageBroker { boolean deleteByParametersId(String layerName, String parametersId) throws StorageException; /** Completely deletes the cache for a layer/parameters combination */ - boolean deleteByParameters(String layerName, Map parameters) - throws StorageException; + boolean deleteByParameters(String layerName, Map parameters) throws StorageException; boolean rename(String oldLayerName, String newLayerName) throws StorageException; diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/TileObject.java b/geowebcache/core/src/main/java/org/geowebcache/storage/TileObject.java index bdb7c0a75e..418c7ef4c9 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/TileObject.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/TileObject.java @@ -44,11 +44,7 @@ public class TileObject extends StorageObject implements Serializable { String gridSetId; public static TileObject createQueryTileObject( - String layerName, - long[] xyz, - String gridSetId, - String format, - Map parameters) { + String layerName, long[] xyz, String gridSetId, String format, Map parameters) { TileObject obj = new TileObject(); obj.layer_name = layerName; diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/TileRange.java b/geowebcache/core/src/main/java/org/geowebcache/storage/TileRange.java index 439f38b370..4a3663d376 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/TileRange.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/TileRange.java @@ -164,8 +164,7 @@ public long[] rangeBounds(final int zoomLevel) { } long[] zlevelBounds = rangeBounds.get(Integer.valueOf(zoomLevel)); if (zlevelBounds == null) { - throw new IllegalStateException( - "Found no range bounds for z level " + zoomLevel + ": " + rangeBounds); + throw new IllegalStateException("Found no range bounds for z level " + zoomLevel + ": " + rangeBounds); } return zlevelBounds; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/TileRangeIterator.java b/geowebcache/core/src/main/java/org/geowebcache/storage/TileRangeIterator.java index 9f7ca97bd1..6260d7fed6 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/TileRangeIterator.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/TileRangeIterator.java @@ -123,8 +123,7 @@ public synchronized long[] nextMetaGridLocation(final long[] gridLoc) { private int tilesForLocation(long x, long y, long[] levelBounds) { long boundsMaxX = levelBounds[2]; long boundsMaxY = levelBounds[3]; - return (int) Math.min(metaX, 1 + (boundsMaxX - x)) - * (int) Math.min(metaY, 1 + (boundsMaxY - y)); + return (int) Math.min(metaX, 1 + (boundsMaxX - x)) * (int) Math.min(metaY, 1 + (boundsMaxY - y)); } private int tilesForLocation(long[] gridLoc, long[] levelBounds) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/TransientCache.java b/geowebcache/core/src/main/java/org/geowebcache/storage/TransientCache.java index 9ae019ff57..7779a8681c 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/TransientCache.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/TransientCache.java @@ -51,17 +51,16 @@ public class TransientCache { */ private static FilePathGenerator keyGenerator = new DefaultFilePathGenerator(""); - private Map cache = - new LinkedHashMap<>() { + private Map cache = new LinkedHashMap<>() { - /** serialVersionUID */ - private static final long serialVersionUID = -4106644240603796847L; + /** serialVersionUID */ + private static final long serialVersionUID = -4106644240603796847L; - @Override - protected boolean removeEldestEntry(Entry eldest) { - return removeEntries(eldest); - } - }; + @Override + protected boolean removeEldestEntry(Entry eldest) { + return removeEntries(eldest); + } + }; /** * @param maxTiles Maximum number of tiles in cache diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/UnsuitableStorageException.java b/geowebcache/core/src/main/java/org/geowebcache/storage/UnsuitableStorageException.java index aec9a2bf91..1d92054659 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/UnsuitableStorageException.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/UnsuitableStorageException.java @@ -39,9 +39,7 @@ public static void checkSuitability(String location, final boolean exists, boole case EMPTY: if (!empty) { throw new UnsuitableStorageException( - "Attempted to create Blob Store in " - + location - + " but it was not empty"); + "Attempted to create Blob Store in " + location + " but it was not empty"); } case NONE: } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/DefaultFilePathGenerator.java b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/DefaultFilePathGenerator.java index 33e082e390..89bc856199 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/DefaultFilePathGenerator.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/DefaultFilePathGenerator.java @@ -104,8 +104,7 @@ public File tilePath(TileObject tile, MimeType mimeType) { } @Override - public void visitRange(File layerDirectory, TileRange range, TileFileVisitor visitor) - throws StorageException { + public void visitRange(File layerDirectory, TileRange range, TileFileVisitor visitor) throws StorageException { final FilenameFilter tileFinder = new DefaultFilePathFilter(range); File[] srsZoomDirs = listFilesNullSafe(layerDirectory, tileFinder); diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java index 0d57555d53..97daa5a52f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java @@ -79,8 +79,7 @@ interface FileWriter { void write(File file) throws IOException; } - private static Logger log = - Logging.getLogger(org.geowebcache.storage.blobstore.file.FileBlobStore.class.getName()); + private static Logger log = Logging.getLogger(org.geowebcache.storage.blobstore.file.FileBlobStore.class.getName()); static final int DEFAULT_DISK_BLOCK_SIZE = 4096; @@ -104,8 +103,7 @@ interface FileWriter { private TempFileNameGenerator tmpGenerator = new TempFileNameGenerator(); - public FileBlobStore(DefaultStorageFinder defStoreFinder) - throws StorageException, ConfigurationException { + public FileBlobStore(DefaultStorageFinder defStoreFinder) throws StorageException, ConfigurationException { this(defStoreFinder.getDefaultPath()); } @@ -152,10 +150,7 @@ public FileBlobStore(String rootPath, FilePathGenerator pathGenerator) throws St // In future it should store key value pairs. metadataFile.createNewFile(); } catch (IOException e) { - log.log( - Level.SEVERE, - "Error while writing blobstore metadata file " + metadataFile.getPath(), - e); + log.log(Level.SEVERE, "Error while writing blobstore metadata file " + metadataFile.getPath(), e); } stagingArea = new File(path, "_gwc_in_progress_deletes_"); @@ -170,8 +165,7 @@ private void issuePendingDeletes() { } if (!stagingArea.isDirectory() || !stagingArea.canWrite()) { throw new IllegalStateException( - "Staging area is not writable or is not a directory: " - + stagingArea.getAbsolutePath()); + "Staging area is not writable or is not a directory: " + stagingArea.getAbsolutePath()); } File[] pendings = listFilesNullSafe(stagingArea); for (File directory : pendings) { @@ -186,8 +180,7 @@ private void deletePending(final File pendingDeleteDirectory) { } private void createDeleteExecutorService() { - CustomizableThreadFactory tf = - new CustomizableThreadFactory("GWC FileStore delete " + "directory thread-"); + CustomizableThreadFactory tf = new CustomizableThreadFactory("GWC FileStore delete " + "directory thread-"); tf.setDaemon(true); tf.setThreadPriority(Thread.MIN_PRIORITY); deleteExecutorService = Executors.newFixedThreadPool(1); @@ -214,15 +207,11 @@ public void run() { try { deleteDirectory(directory); } catch (IOException e) { - log.log( - Level.WARNING, - "Exception occurred while deleting '" + directory.getAbsolutePath() + "'", - e); + log.log(Level.WARNING, "Exception occurred while deleting '" + directory.getAbsolutePath() + "'", e); } catch (InterruptedException e) { - log.info( - "FileStore delete background service interrupted while deleting '" - + directory.getAbsolutePath() - + "'. Process will be resumed at next start up"); + log.info("FileStore delete background service interrupted while deleting '" + + directory.getAbsolutePath() + + "'. Process will be resumed at next start up"); Thread.currentThread().interrupt(); } } @@ -267,8 +256,7 @@ public boolean delete(final String layerName) throws StorageException { return ret; } - private boolean stageDelete(final File source, final String targetName) - throws StorageException { + private boolean stageDelete(final File source, final String targetName) throws StorageException { if (!source.exists() || !source.canWrite()) { log.info(source + " does not exist or is not writable"); @@ -276,8 +264,7 @@ private boolean stageDelete(final File source, final String targetName) } if (!stagingArea.exists() && !stagingArea.mkdirs()) { - throw new StorageException( - "Can't create staging directory for deletes: " + stagingArea.getAbsolutePath()); + throw new StorageException("Can't create staging directory for deletes: " + stagingArea.getAbsolutePath()); } File tmpFolder = new File(stagingArea, targetName); @@ -289,12 +276,11 @@ private boolean stageDelete(final File source, final String targetName) } boolean renamed = FileUtils.renameFile(source, tmpFolder); if (!renamed) { - throw new IllegalStateException( - "Can't rename " - + source.getAbsolutePath() - + " to " - + tmpFolder.getAbsolutePath() - + " for deletion"); + throw new IllegalStateException("Can't rename " + + source.getAbsolutePath() + + " to " + + tmpFolder.getAbsolutePath() + + " for deletion"); } deletePending(tmpFolder); return true; @@ -304,8 +290,7 @@ private boolean stageDelete(final File source, final String targetName) * @see org.geowebcache.storage.BlobStore#deleteByGridsetId(java.lang.String, java.lang.String) */ @Override - public boolean deleteByGridsetId(final String layerName, final String gridSetId) - throws StorageException { + public boolean deleteByGridsetId(final String layerName, final String gridSetId) throws StorageException { final File layerPath = getLayerPath(layerName); if (!layerPath.exists() || !layerPath.canWrite()) { @@ -314,14 +299,13 @@ public boolean deleteByGridsetId(final String layerName, final String gridSetId) } final String filteredGridSetId = filteredGridSetId(gridSetId); - FileFilter filter = - pathname -> { - if (!pathname.isDirectory()) { - return false; - } - String dirName = pathname.getName(); - return dirName.startsWith(filteredGridSetId); - }; + FileFilter filter = pathname -> { + if (!pathname.isDirectory()) { + return false; + } + String dirName = pathname.getName(); + return dirName.startsWith(filteredGridSetId); + }; File[] gridSubsetCaches = listFilesNullSafe(layerPath, filter); for (File gridSubsetCache : gridSubsetCaches) { @@ -344,18 +328,16 @@ public boolean deleteByGridsetId(final String layerName, final String gridSetId) * @see org.geowebcache.storage.BlobStore#rename */ @Override - public boolean rename(final String oldLayerName, final String newLayerName) - throws StorageException { + public boolean rename(final String oldLayerName, final String newLayerName) throws StorageException { final File oldLayerPath = getLayerPath(oldLayerName); final File newLayerPath = getLayerPath(newLayerName); if (newLayerPath.exists()) { - throw new StorageException( - "Can't rename layer directory " - + oldLayerPath - + " to " - + newLayerPath - + ". Target directory already exists"); + throw new StorageException("Can't rename layer directory " + + oldLayerPath + + " to " + + newLayerPath + + ". Target directory already exists"); } if (!oldLayerPath.exists()) { this.listeners.sendLayerRenamed(oldLayerName, newLayerName); @@ -369,8 +351,7 @@ public boolean rename(final String oldLayerName, final String newLayerName) if (renamed) { this.listeners.sendLayerRenamed(oldLayerName, newLayerName); } else { - throw new StorageException( - "Couldn't rename layer directory " + oldLayerPath + " to " + newLayerPath); + throw new StorageException("Couldn't rename layer directory " + oldLayerPath + " to " + newLayerPath); } return renamed; } @@ -436,35 +417,24 @@ public boolean delete(TileRange trObj) throws StorageException { final String parametersId = trObj.getParametersId(); AtomicLong count = new AtomicLong(); - pathGenerator.visitRange( - layerPath, - trObj, - new TileFileVisitor() { - - @Override - public void visitFile(File tile, long x, long y, int z) { - long length = tile.length(); - boolean deleted = tile.delete(); - if (deleted) { - listeners.sendTileDeleted( - layerName, - gridSetId, - blobFormat, - parametersId, - x, - y, - z, - padSize(length)); - count.incrementAndGet(); - } - } + pathGenerator.visitRange(layerPath, trObj, new TileFileVisitor() { + + @Override + public void visitFile(File tile, long x, long y, int z) { + long length = tile.length(); + boolean deleted = tile.delete(); + if (deleted) { + listeners.sendTileDeleted(layerName, gridSetId, blobFormat, parametersId, x, y, z, padSize(length)); + count.incrementAndGet(); + } + } - @Override - public void postVisitDirectory(File dir) { - // will delete only if empty - dir.delete(); - } - }); + @Override + public void postVisitDirectory(File dir) { + // will delete only if empty + dir.delete(); + } + }); log.info("Truncated " + count + " tiles"); @@ -507,10 +477,7 @@ public void put(TileObject stObj) throws StorageException { try { fh.setLastModified(stObj.getCreated()); } catch (Exception e) { - log.log( - Level.FINE, - "Failed to set the last modified time to match the tile request time", - e); + log.log(Level.FINE, "Failed to set the last modified time to match the tile request time", e); } } @@ -527,8 +494,7 @@ public void put(TileObject stObj) throws StorageException { } } - private void putParametersMetadata( - String layerName, String parametersId, Map parameters) + private void putParametersMetadata(String layerName, String parametersId, Map parameters) throws StorageException { // check if we even need to use any IO if (parametersId == null || parameters == null || parameters.isEmpty()) return; @@ -536,26 +502,20 @@ private void putParametersMetadata( File parametersFile = parametersFile(layerName, parametersId); if (parametersFile.exists()) return; - writeFile( - parametersFile, - false, - file -> { - Properties properties = new Properties(); - parameters.forEach(properties::setProperty); - try (OutputStream os = new FileOutputStream(file)) { - properties.store(os, "Parameters values for identifier: " + parametersId); - } - }); + writeFile(parametersFile, false, file -> { + Properties properties = new Properties(); + parameters.forEach(properties::setProperty); + try (OutputStream os = new FileOutputStream(file)) { + properties.store(os, "Parameters values for identifier: " + parametersId); + } + }); } private File parametersFile(String layerName, String parametersId) { - String path = - FilePathUtils.buildPath( - this.path, - layerName, - PARAMETERS_METADATA_OBJECT_PREFIX - + parametersId - + PARAMETERS_METADATA_OBJECT_SUFFIX); + String path = FilePathUtils.buildPath( + this.path, + layerName, + PARAMETERS_METADATA_OBJECT_PREFIX + parametersId + PARAMETERS_METADATA_OBJECT_SUFFIX); return new File(path); } @@ -592,15 +552,12 @@ private Resource readFile(File fh) throws StorageException { } private void writeTile(File target, TileObject stObj, boolean existed) throws StorageException { - writeFile( - target, - existed, - file -> { - try (FileOutputStream fos = new FileOutputStream(file); - FileChannel channel = fos.getChannel()) { - stObj.getBlob().transferTo(channel); - } - }); + writeFile(target, existed, file -> { + try (FileOutputStream fos = new FileOutputStream(file); + FileChannel channel = fos.getChannel()) { + stObj.getBlob().transferTo(channel); + } + }); } /** @@ -609,8 +566,7 @@ private void writeTile(File target, TileObject stObj, boolean existed) throws St * * @throws StorageException */ - private void writeFile(File target, boolean existed, FileWriter writer) - throws StorageException { + private void writeFile(File target, boolean existed, FileWriter writer) throws StorageException { // first write to temp file tmp.mkdirs(); File temp = new File(tmp, tmpGenerator.newName()); @@ -635,10 +591,7 @@ private void writeFile(File target, boolean existed, FileWriter writer) } } finally { if (temp != null) { - log.warning( - "Tile " - + target.getPath() - + " was already written by another thread/process"); + log.warning("Tile " + target.getPath() + " was already written by another thread/process"); temp.delete(); } } @@ -761,8 +714,7 @@ private long padSize(long fileSize) { } @Override - public boolean deleteByParametersId(String layerName, String parametersId) - throws StorageException { + public boolean deleteByParametersId(String layerName, String parametersId) throws StorageException { final File layerPath = getLayerPath(layerName); if (!layerPath.exists() || !layerPath.canWrite()) { @@ -779,23 +731,18 @@ public boolean deleteByParametersId(String layerName, String parametersId) } catch (IOException e) { log.log( Level.WARNING, - String.format( - "Failed to clean up metadata for parameters %s in layer %s", - parametersId, layerName), + String.format("Failed to clean up metadata for parameters %s in layer %s", parametersId, layerName), e); } // delete the caches - File[] parameterCaches = - listFilesNullSafe( - layerPath, - (pathname) -> { - if (!pathname.isDirectory()) { - return false; - } - String dirName = pathname.getName(); - return dirName.endsWith(parametersId); - }); + File[] parameterCaches = listFilesNullSafe(layerPath, (pathname) -> { + if (!pathname.isDirectory()) { + return false; + } + String dirName = pathname.getName(); + return dirName.endsWith(parametersId); + }); for (File parameterCache : parameterCaches) { String target = filteredLayerName(layerName) + "_" + parameterCache.getName(); @@ -807,15 +754,14 @@ public boolean deleteByParametersId(String layerName, String parametersId) return true; } - private Stream layerChildStream( - final String layerName, DirectoryStream.Filter filter) throws IOException { + private Stream layerChildStream(final String layerName, DirectoryStream.Filter filter) + throws IOException { final File layerPath = getLayerPath(layerName); if (!layerPath.exists()) { return Stream.of(); } @SuppressWarnings("PMD.CloseResource") // wrapped and closed in the return value - final DirectoryStream layerDirStream = - Files.newDirectoryStream(layerPath.toPath(), filter); + final DirectoryStream layerDirStream = Files.newDirectoryStream(layerPath.toPath(), filter); return StreamSupport.stream(layerDirStream.spliterator(), false) .onClose( // Delegate closing so that when the returned stream is closed, so is the // underlying DirectoryStream @@ -828,11 +774,9 @@ private Stream layerChildStream( }); } - public boolean isParameterIdCached(String layerName, final String parametersId) - throws IOException { + public boolean isParameterIdCached(String layerName, final String parametersId) throws IOException { try (Stream layerChildStream = - layerChildStream( - layerName, (p) -> Files.isDirectory(p) && p.endsWith(parametersId))) { + layerChildStream(layerName, (p) -> Files.isDirectory(p) && p.endsWith(parametersId))) { return layerChildStream.findAny().isPresent(); } } @@ -849,19 +793,15 @@ public Map>> getParametersMapping(String la log.fine("Optimistic read of metadata mappings failed"); return null; } - Map>> result = - parameterIds.stream() - .collect( - Collectors.toMap( - (id) -> id, - (id) -> { - String kvp = p.get("parameters." + id); - if (Objects.isNull(kvp)) { - return Optional.empty(); - } - kvp = urlDecUtf8(kvp); - return Optional.of(ParametersUtils.getMap(kvp)); - })); + Map>> result = parameterIds.stream() + .collect(Collectors.toMap((id) -> id, (id) -> { + String kvp = p.get("parameters." + id); + if (Objects.isNull(kvp)) { + return Optional.empty(); + } + kvp = urlDecUtf8(kvp); + return Optional.of(ParametersUtils.getMap(kvp)); + })); // go look for the current parameter files too though, and overwrite the legacy metadata for (String parameterId : parameterIds) { @@ -882,8 +822,8 @@ public Map>> getParametersMapping(String la private static Map propertiesToMap(Properties properties) { return properties.entrySet().stream() - .collect( - Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString())); + .collect(Collectors.toMap( + e -> e.getKey().toString(), e -> e.getValue().toString())); } static final int paramIdLength = @@ -891,8 +831,7 @@ private static Map propertiesToMap(Properties properties) { @Override public Set getParameterIds(String layerName) { - try (Stream layerChildStream = - layerChildStream(layerName, (p) -> Files.isDirectory(p))) { + try (Stream layerChildStream = layerChildStream(layerName, (p) -> Files.isDirectory(p))) { return layerChildStream .map(p -> p.getFileName().toString()) .map(s -> s.substring(s.lastIndexOf('_') + 1)) diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathGenerator.java b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathGenerator.java index 3ac54b3f75..c89cc29291 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathGenerator.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathGenerator.java @@ -31,6 +31,5 @@ public interface FilePathGenerator { * Visits a directory containing a layer, hitting all tiles matching the tile range, and * invoking the visitor on them. */ - void visitRange(File layerDirectory, TileRange range, TileFileVisitor visitor) - throws StorageException; + void visitRange(File layerDirectory, TileRange range, TileFileVisitor visitor) throws StorageException; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathUtils.java b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathUtils.java index ea19da4d3c..2304aec794 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathUtils.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FilePathUtils.java @@ -92,8 +92,7 @@ public static int findZoomLevel(final String gridsetPrefix, final String dirName try { return Integer.parseInt(zlevel); } catch (NumberFormatException e) { - throw new RuntimeException( - String.format("unable to find zoom level in '%s'", gridsetPrefix), e); + throw new RuntimeException(String.format("unable to find zoom level in '%s'", gridsetPrefix), e); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/LayerMetadataStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/LayerMetadataStore.java index 71aedb9332..ad0d9fe59d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/LayerMetadataStore.java +++ b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/LayerMetadataStore.java @@ -50,17 +50,14 @@ public class LayerMetadataStore { private static Logger log = Logging.getLogger(LayerMetadataStore.class.getName()); - public static final String PROPERTY_METADATA_MAX_RW_ATTEMPTS = - "gwc.layermetadatastore.maxRWAttempts"; + public static final String PROPERTY_METADATA_MAX_RW_ATTEMPTS = "gwc.layermetadatastore.maxRWAttempts"; - public static final String PROPERTY_WAIT_AFTER_RENAME = - "gwc.layermetadatastore.waitAfterRename"; + public static final String PROPERTY_WAIT_AFTER_RENAME = "gwc.layermetadatastore.waitAfterRename"; static final int METADATA_MAX_RW_ATTEMPTS = Integer.parseInt(System.getProperty(PROPERTY_METADATA_MAX_RW_ATTEMPTS, "50")); - static final int WAIT_AFTER_RENAME = - Integer.parseInt(System.getProperty(PROPERTY_WAIT_AFTER_RENAME, "50")); + static final int WAIT_AFTER_RENAME = Integer.parseInt(System.getProperty(PROPERTY_WAIT_AFTER_RENAME, "50")); static final String METADATA_GZIP_EXTENSION = ".gz"; @@ -72,10 +69,9 @@ public class LayerMetadataStore { private static final int lockShardSize = 32; /** handling of local-process concurrent access to layer metadata files */ - private ReadWriteLock[] locks = - IntStream.range(0, lockShardSize) - .mapToObj(i -> new ReentrantReadWriteLock()) - .toArray(ReadWriteLock[]::new); + private ReadWriteLock[] locks = IntStream.range(0, lockShardSize) + .mapToObj(i -> new ReentrantReadWriteLock()) + .toArray(ReadWriteLock[]::new); public LayerMetadataStore(String rootPath, File tmpPath) { this.path = rootPath; @@ -100,8 +96,7 @@ public String getEntry(final String layerName, final String key) throws IOExcept * @see org.geowebcache.storage.BlobStore#putLayerMetadata(java.lang.String, java.lang.String, * java.lang.String) */ - public void putEntry(final String layerName, final String key, final String value) - throws IOException { + public void putEntry(final String layerName, final String key, final String value) throws IOException { final File metadataFile = resolveMetadataFile(layerName); Properties metadata = loadLayerMetadata(metadataFile); @@ -135,10 +130,9 @@ private static String urlDecUtf8(String value) { } private int resolveLockBucket(File file) { - long consistentFileNameHash = - Hashing.farmHashFingerprint64() - .hashString(file.getAbsolutePath(), StandardCharsets.UTF_8) - .asLong(); + long consistentFileNameHash = Hashing.farmHashFingerprint64() + .hashString(file.getAbsolutePath(), StandardCharsets.UTF_8) + .asLong(); int bucket = Hashing.consistentHash(consistentFileNameHash, locks.length); return bucket; } @@ -155,8 +149,8 @@ private ReadWriteLock getLock(File file) { * @throws IOException */ @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE") - private void writeMetadataOptimisticLock( - final String key, final String value, final File metadataFile) throws IOException { + private void writeMetadataOptimisticLock(final String key, final String value, final File metadataFile) + throws IOException { final ReadWriteLock rwLock = getLock(metadataFile); final int maxAttempts = LayerMetadataStore.METADATA_MAX_RW_ATTEMPTS; Properties metadata = loadLayerMetadata(metadataFile); @@ -178,39 +172,30 @@ private void writeMetadataOptimisticLock( // compare content between renamed file and memory content Properties metadataAfterRename = loadLayerMetadata(metadataFile); if (!metadata.equals(metadataAfterRename)) { - log.fine( - "Renamed file content differs from expected saved content.\nCurrent:" - + metadataAfterRename.toString() - + "\nExpected: " - + metadata.toString()); + log.fine("Renamed file content differs from expected saved content.\nCurrent:" + + metadataAfterRename.toString() + + "\nExpected: " + + metadata.toString()); attempt++; } else { - log.fine( - "Temporary file renamed successfully (metadata: " - + metadata.toString() - + ")"); + log.fine("Temporary file renamed successfully (metadata: " + metadata.toString() + ")"); return; } } else { - log.info( - "Reattempting to write metadata file, because an error while renaming metadata file " - + metadataFile.getPath()); + log.info("Reattempting to write metadata file, because an error while renaming metadata file " + + metadataFile.getPath()); attempt++; } tempFile.delete(); } else { - log.fine( - "Reattempting to write metadata file since timestamp changed (metadata: " - + metadata.toString() - + ")"); + log.fine("Reattempting to write metadata file since timestamp changed (metadata: " + + metadata.toString() + + ")"); } // another process beat us, reload // next line triggers a false-positive DLS_DEAD_LOCAL_STORE if (metadata.isEmpty()) { - log.fine( - "Reattempting to write metadata file with empty metadata: " - + metadata.toString() - + ")"); + log.fine("Reattempting to write metadata file with empty metadata: " + metadata.toString() + ")"); } metadata = loadLayerMetadata(metadataFile); lastModified = metadataFile.lastModified(); @@ -229,8 +214,7 @@ private void writeMetadataOptimisticLock( private File writeTempMetadataFile(Properties metadata) { tmp.mkdirs(); try { - final File metadataFile = - File.createTempFile("tmp", LayerMetadataStore.METADATA_GZIP_EXTENSION, tmp); + final File metadataFile = File.createTempFile("tmp", LayerMetadataStore.METADATA_GZIP_EXTENSION, tmp); return this.writeMetadataFile(metadata, metadataFile); } catch (IOException e) { log.log(Level.SEVERE, "Cannot create temporary file"); @@ -264,22 +248,19 @@ private void createParentIfNeeded(File metadataFile) { File parentDir = metadataFile.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { if (!parentDir.exists()) - throw new IllegalStateException( - "Unable to create parent directory " + parentDir.getAbsolutePath()); + throw new IllegalStateException("Unable to create parent directory " + parentDir.getAbsolutePath()); } } private Writer compressingWriter(File file) throws FileNotFoundException, IOException { - return new OutputStreamWriter( - new GZIPOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8); + return new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8); } private Properties getUncompressedLayerMetadata(final File metadataFile) throws IOException { return loadLayerMetadata(metadataFile, this::open); } - private Properties loadLayerMetadata(File metadataFile, Function isProvider) - throws IOException { + private Properties loadLayerMetadata(File metadataFile, Function isProvider) throws IOException { // out-of-process concurrency control final int maxAttempts = LayerMetadataStore.METADATA_MAX_RW_ATTEMPTS; long lastModified = metadataFile.lastModified(); @@ -297,10 +278,9 @@ private Properties loadLayerMetadata(File metadataFile, Function POLICIES = - Collections.unmodifiableList( - Arrays.asList( - EvictionPolicy.NULL, - EvictionPolicy.EXPIRE_AFTER_ACCESS, - EvictionPolicy.EXPIRE_AFTER_WRITE)); + public static final List POLICIES = Collections.unmodifiableList( + Arrays.asList(EvictionPolicy.NULL, EvictionPolicy.EXPIRE_AFTER_ACCESS, EvictionPolicy.EXPIRE_AFTER_WRITE)); /** * This class handles the {@link CacheStats} object returned by the guava cache. @@ -83,8 +79,7 @@ public static class GuavaCacheStatistics extends CacheStatistics { /** serialVersionUID */ private static final long serialVersionUID = 1L; - public GuavaCacheStatistics( - CacheStats stats, double currentSpace, long actualSize, long totalSize) { + public GuavaCacheStatistics(CacheStats stats, double currentSpace, long actualSize, long totalSize) { this.setEvictionCount(stats.evictionCount()); this.setHitCount(stats.hitCount()); this.setMissCount(stats.missCount()); @@ -149,39 +144,33 @@ private void initCache(CacheConfiguration configuration) { // Create the CacheBuilder CacheBuilder builder = CacheBuilder.newBuilder(); // Add weigher - Weigher weigher = - (key, value) -> { - currentSize.addAndGet(value.getBlobSize()); - return value.getBlobSize(); - }; + Weigher weigher = (key, value) -> { + currentSize.addAndGet(value.getBlobSize()); + return value.getBlobSize(); + }; // Create the builder - CacheBuilder newBuilder = - builder.maximumWeight(maxMemory) - .recordStats() - .weigher(weigher) - .concurrencyLevel(concurrency) - .removalListener( - notification -> { - // TODO This operation is not atomic - TileObject obj = notification.getValue(); - // Update the current size - currentSize.addAndGet(-obj.getBlobSize()); - final String tileKey = generateTileKey(obj); - final String layerName = obj.getLayerName(); - multimap.removeTile(layerName, tileKey); - if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.fine( - "Removed tile " - + tileKey - + " for layer " - + layerName - + " due to reason:" - + notification.getCause().toString()); - LOGGER.fine( - "Removed tile was evicted? " - + notification.wasEvicted()); - } - }); + CacheBuilder newBuilder = builder.maximumWeight(maxMemory) + .recordStats() + .weigher(weigher) + .concurrencyLevel(concurrency) + .removalListener(notification -> { + // TODO This operation is not atomic + TileObject obj = notification.getValue(); + // Update the current size + currentSize.addAndGet(-obj.getBlobSize()); + final String tileKey = generateTileKey(obj); + final String layerName = obj.getLayerName(); + multimap.removeTile(layerName, tileKey); + if (LOGGER.isLoggable(Level.FINE)) { + LOGGER.fine("Removed tile " + + tileKey + + " for layer " + + layerName + + " due to reason:" + + notification.getCause().toString()); + LOGGER.fine("Removed tile was evicted? " + notification.wasEvicted()); + } + }); // Handle eviction policy boolean configuredPolicy = false; if (policy != null && evictionTime > 0) { @@ -211,22 +200,21 @@ private void initCache(CacheConfiguration configuration) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Configuring Scheduled Task for cache eviction"); } - Runnable command = - () -> { - if (configured.get()) { - // Increment the number of current operations - // This behavior is used in order to wait - // the end of all the operations after setting - // the configured parameter to false - actualOperations.incrementAndGet(); - try { - cache.cleanUp(); - } finally { - // Decrement the number of current operations. - actualOperations.decrementAndGet(); - } - } - }; + Runnable command = () -> { + if (configured.get()) { + // Increment the number of current operations + // This behavior is used in order to wait + // the end of all the operations after setting + // the configured parameter to false + actualOperations.incrementAndGet(); + try { + cache.cleanUp(); + } finally { + // Decrement the number of current operations. + actualOperations.decrementAndGet(); + } + } + }; // Initialization of the internal Scheduler task for scheduling cache cleanup scheduledPool = Executors.newScheduledThreadPool(CORE_POOL_SIZE); scheduledPool.scheduleAtFixedRate(command, 10, evictionTime + 1, TimeUnit.SECONDS); @@ -467,13 +455,7 @@ public CacheStatistics getStatistics() { try { // Get cache statistics long actualSize = currentSize.get(); - long currentSpace = - (long) - (100L - - (1L) - * (100 - * ((1.0d) * (maxMemory - actualSize)) - / maxMemory)); + long currentSpace = (long) (100L - (1L) * (100 * ((1.0d) * (maxMemory - actualSize)) / maxMemory)); if (currentSpace < 0) { currentSpace = 0; } @@ -500,14 +482,13 @@ public CacheStatistics getStatistics() { public static String generateTileKey(TileObject obj) { Map parameters = obj.getParameters(); - StringBuilder builder = - new StringBuilder(obj.getLayerName()) - .append(SEPARATOR) - .append(obj.getGridSetId()) - .append(SEPARATOR) - .append(Arrays.toString(obj.getXYZ())) - .append(SEPARATOR) - .append(obj.getBlobFormat()); + StringBuilder builder = new StringBuilder(obj.getLayerName()) + .append(SEPARATOR) + .append(obj.getGridSetId()) + .append(SEPARATOR) + .append(Arrays.toString(obj.getXYZ())) + .append(SEPARATOR) + .append(obj.getBlobFormat()); // If parameters are present they must be handled if (parameters != null && !parameters.isEmpty()) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/ApplicationContextProvider.java b/geowebcache/core/src/main/java/org/geowebcache/util/ApplicationContextProvider.java index b268ee1211..fbc6d5cb59 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/ApplicationContextProvider.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/ApplicationContextProvider.java @@ -46,16 +46,11 @@ public String getSystemVar(String varName, String defaultValue) { throw new RuntimeException(msg); } - String tmpVar = - Optional.ofNullable(ctx.getServletContext()) - .map(sc -> sc.getInitParameter(varName)) - .orElse(null); + String tmpVar = Optional.ofNullable(ctx.getServletContext()) + .map(sc -> sc.getInitParameter(varName)) + .orElse(null); if (tmpVar != null && tmpVar.length() > 7) { - log.info( - "Using servlet init context parameter to configure " - + varName - + " to " - + tmpVar); + log.info("Using servlet init context parameter to configure " + varName + " to " + tmpVar); return tmpVar; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/ExceptionUtils.java b/geowebcache/core/src/main/java/org/geowebcache/util/ExceptionUtils.java index a31c62fe23..ecc8fc23e4 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/ExceptionUtils.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/ExceptionUtils.java @@ -26,7 +26,6 @@ private ExceptionUtils() {} * suppresses is. */ public static boolean isOrSuppresses(T e, Class klazz) { - return Streams.concat(Stream.of(e), Arrays.stream(e.getSuppressed())) - .anyMatch(klazz::isInstance); + return Streams.concat(Stream.of(e), Arrays.stream(e.getSuppressed())).anyMatch(klazz::isInstance); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/FileUtils.java b/geowebcache/core/src/main/java/org/geowebcache/util/FileUtils.java index 71f4daf89c..03d1ff18ab 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/FileUtils.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/FileUtils.java @@ -79,8 +79,7 @@ public static void traverseDepth(final File path, final FileFilter filter) { } if (!path.exists() || !path.isDirectory() || !path.canRead()) { throw new IllegalArgumentException( - path.getAbsolutePath() - + " either does not exist, or is not a readable directory"); + path.getAbsolutePath() + " either does not exist, or is not a readable directory"); } // Use path.list() instead of path.listFiles() to avoid the simultaneous creation of // thousands of File objects as well as its String objects for the path name. Faster and diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/GWCVars.java b/geowebcache/core/src/main/java/org/geowebcache/util/GWCVars.java index 3eef962bd5..71f8f91b84 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/GWCVars.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/GWCVars.java @@ -53,8 +53,7 @@ public static enum VariableType { SERVLET("servlet context parameter") { protected @Override String apply(ApplicationContext context, String varName) { if (context instanceof WebApplicationContext) { - ServletContext servletContext = - ((WebApplicationContext) context).getServletContext(); + ServletContext servletContext = ((WebApplicationContext) context).getServletContext(); return servletContext == null ? null : servletContext.getInitParameter(varName); } return null; diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/HttpClientBuilder.java b/geowebcache/core/src/main/java/org/geowebcache/util/HttpClientBuilder.java index 8045bda577..36b0988596 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/HttpClientBuilder.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/HttpClientBuilder.java @@ -36,8 +36,7 @@ public class HttpClientBuilder { private AuthScope authscope = null; private Integer backendTimeoutMillis = null; - private static final HttpClientConnectionManager connectionManager = - new PoolingHttpClientConnectionManager(); + private static final HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); private boolean doAuthentication = false; @@ -56,27 +55,20 @@ public HttpClientBuilder() { * to be used against a single server only */ public HttpClientBuilder( - URL url, - Integer backendTimeout, - String httpUsername, - String httpPassword, - URL proxyUrl, - int concurrency) { + URL url, Integer backendTimeout, String httpUsername, String httpPassword, URL proxyUrl, int concurrency) { if (url != null) { - this.setHttpCredentials( - httpUsername, httpPassword, new AuthScope(url.getHost(), url.getPort())); + this.setHttpCredentials(httpUsername, httpPassword, new AuthScope(url.getHost(), url.getPort())); } else { this.setHttpCredentials(httpUsername, httpPassword, AuthScope.ANY); } this.setBackendTimeout(backendTimeout); - setConnectionConfig( - RequestConfig.custom() - .setCookieSpec(CookieSpecs.DEFAULT) - .setExpectContinueEnabled(true) - .setSocketTimeout(backendTimeoutMillis) - .setConnectTimeout(backendTimeoutMillis) - .setRedirectsEnabled(true) - .build()); + setConnectionConfig(RequestConfig.custom() + .setCookieSpec(CookieSpecs.DEFAULT) + .setExpectContinueEnabled(true) + .setSocketTimeout(backendTimeoutMillis) + .setConnectTimeout(backendTimeoutMillis) + .setRedirectsEnabled(true) + .build()); clientBuilder = org.apache.http.impl.client.HttpClientBuilder.create(); clientBuilder.useSystemProperties(); diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/NullURLMangler.java b/geowebcache/core/src/main/java/org/geowebcache/util/NullURLMangler.java index b7d439bd44..7385296404 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/NullURLMangler.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/NullURLMangler.java @@ -27,11 +27,7 @@ public String buildURL(String baseURL, String contextPath, String path) { if (context == null || context.isEmpty()) { return StringUtils.strip(baseURL, "/") + "/" + StringUtils.strip(path, "/"); } else { - return StringUtils.strip(baseURL, "/") - + "/" - + context - + "/" - + StringUtils.strip(path, "/"); + return StringUtils.strip(baseURL, "/") + "/" + context + "/" + StringUtils.strip(path, "/"); } } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/ResponseUtils.java b/geowebcache/core/src/main/java/org/geowebcache/util/ResponseUtils.java index 5a1a7dc14c..874fe83030 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/ResponseUtils.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/ResponseUtils.java @@ -176,8 +176,7 @@ private static void writeData(ConveyorTile tile, RuntimeStats runtimeStats) thro } int contentLength = (int) (blob == null ? -1 : blob.getSize()); - writeFixedResponse( - servletResp, httpCode, mimeType, blob, cacheResult, contentLength, runtimeStats); + writeFixedResponse(servletResp, httpCode, mimeType, blob, cacheResult, contentLength, runtimeStats); } private static void writeEmpty( @@ -206,13 +205,7 @@ private static void writeEmpty( // handle no-content in case we have to return no result at all (e.g., expected for pbf) int status = emptyTileContents == null ? 204 : 200; - writeFixedResponse( - tile.servletResp, - status, - mimeType, - emptyTileContents, - CacheResult.OTHER, - runtimeStats); + writeFixedResponse(tile.servletResp, status, mimeType, emptyTileContents, CacheResult.OTHER, runtimeStats); } /** @@ -220,10 +213,7 @@ private static void writeEmpty( * tiles */ private static void writeEmpty( - DefaultStorageFinder defaultStorageFinder, - ConveyorTile tile, - String message, - RuntimeStats runtimeStats) { + DefaultStorageFinder defaultStorageFinder, ConveyorTile tile, String message, RuntimeStats runtimeStats) { writeEmpty( defaultStorageFinder, tile, @@ -252,8 +242,7 @@ public static void writeFixedResponse( RuntimeStats runtimeStats) { int contentLength = (int) (resource == null ? -1 : resource.getSize()); - writeFixedResponse( - response, httpCode, contentType, resource, cacheRes, contentLength, runtimeStats); + writeFixedResponse(response, httpCode, contentType, resource, cacheRes, contentLength, runtimeStats); } /** @@ -295,8 +284,7 @@ public static void writeFixedResponse( private static ByteArrayResource loadBlankTile(DefaultStorageFinder defaultStorageFinder) { ByteArrayResource blankTile = null; - String blankTilePath = - defaultStorageFinder.findEnvVar(DefaultStorageFinder.GWC_BLANK_TILE_PATH); + String blankTilePath = defaultStorageFinder.findEnvVar(DefaultStorageFinder.GWC_BLANK_TILE_PATH); if (blankTilePath != null) { File fh = new File(blankTilePath); @@ -353,22 +341,18 @@ private static void loadBlankTile(Resource blankTile, URL source) throws IOExcep * @param errorMsg the actual error message, human readable */ public static void writeErrorPage( - HttpServletResponse response, - int httpCode, - String errorMsg, - RuntimeStats runtimeStats) { + HttpServletResponse response, int httpCode, String errorMsg, RuntimeStats runtimeStats) { log.fine(errorMsg); - errorMsg = - "\n" - + ServletUtils.gwcHtmlHeader("../", "GWC Error") - + "\n" - + ServletUtils.gwcHtmlLogoLink("../") - + "

" - + httpCode - + ": " - + ServletUtils.disableHTMLTags(errorMsg) - + "

" - + "\n"; + errorMsg = "\n" + + ServletUtils.gwcHtmlHeader("../", "GWC Error") + + "\n" + + ServletUtils.gwcHtmlLogoLink("../") + + "

" + + httpCode + + ": " + + ServletUtils.disableHTMLTags(errorMsg) + + "

" + + "\n"; writePage(response, httpCode, errorMsg, runtimeStats, MediaType.TEXT_HTML_VALUE); } @@ -382,10 +366,7 @@ public static void writeErrorPage( * @param runtimeStats runtime statistics */ public static void writeErrorAsXML( - HttpServletResponse response, - int httpCode, - String errorMsg, - RuntimeStats runtimeStats) { + HttpServletResponse response, int httpCode, String errorMsg, RuntimeStats runtimeStats) { log.fine(errorMsg); writePage(response, httpCode, errorMsg, runtimeStats, MediaType.APPLICATION_XML_VALUE); } @@ -401,16 +382,11 @@ public static void writeErrorAsXML( * @param contentType HTTP response content type */ public static void writePage( - HttpServletResponse response, - int httpCode, - String message, - RuntimeStats runtimeStats, - String contentType) { + HttpServletResponse response, int httpCode, String message, RuntimeStats runtimeStats, String contentType) { Resource res = null; if (message != null) { res = new ByteArrayResource(message.getBytes()); } - ResponseUtils.writeFixedResponse( - response, httpCode, contentType, res, CacheResult.OTHER, runtimeStats); + ResponseUtils.writeFixedResponse(response, httpCode, contentType, res, CacheResult.OTHER, runtimeStats); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/ServletUtils.java b/geowebcache/core/src/main/java/org/geowebcache/util/ServletUtils.java index 9a463e6658..22a2b408a2 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/ServletUtils.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/ServletUtils.java @@ -36,8 +36,7 @@ import org.geotools.util.logging.Logging; public class ServletUtils { - private static Logger log = - Logging.getLogger(org.geowebcache.util.ServletUtils.class.toString()); + private static Logger log = Logging.getLogger(org.geowebcache.util.ServletUtils.class.toString()); // Calendar objects are unfortunately expensive and not thread safe :( private static Calendar calendar = new GregorianCalendar(); @@ -81,8 +80,7 @@ public static String stringFromMap(Map map, String encoding, S } /** Case insensitive lookup for a couple of strings, drops everything else */ - public static String[][] selectedStringArraysFromMap( - Map map, String encoding, String[] keys) { + public static String[][] selectedStringArraysFromMap(Map map, String encoding, String[] keys) { String[][] retAr = new String[keys.length][]; Iterator> iter = map.entrySet().iterator(); @@ -108,16 +106,14 @@ public static String[][] selectedStringArraysFromMap( * upper case */ @SuppressWarnings("unchecked") - public static Map selectedStringsFromMap( - Map map, String encoding, String... keys) { + public static Map selectedStringsFromMap(Map map, String encoding, String... keys) { map = new CaseInsensitiveMap<>(map); Map selected = new CaseInsensitiveMap<>(); for (String key : keys) { Object value = map.get(key); if (value != null) { - String sValue = - value instanceof String[] ? ((String[]) value)[0] : String.valueOf(value); + String sValue = value instanceof String[] ? ((String[]) value)[0] : String.valueOf(value); selected.put(key.toUpperCase(), URLDecode(sValue, encoding)); } } @@ -156,13 +152,12 @@ public static Map selectedStringsFromMap( * @param tmpBufferSize how many bytes to read at a time, -1 = 1024 * @return a compacted buffer with all the data */ - public static byte[] readStream(InputStream is, int bufferHint, int tmpBufferSize) - throws IOException { + public static byte[] readStream(InputStream is, int bufferHint, int tmpBufferSize) throws IOException { return readStream(is, bufferHint, tmpBufferSize, true); } - public static byte[] readStream( - InputStream is, int bufferHint, int tmpBufferSize, boolean close) throws IOException { + public static byte[] readStream(InputStream is, int bufferHint, int tmpBufferSize, boolean close) + throws IOException { byte[] buffer = null; if (bufferHint > 0) { buffer = new byte[bufferHint]; @@ -220,8 +215,7 @@ public static String formatTimestamp(long timestamp) { String ret; synchronized (calendar) { if (ServletUtils.format == null) { - ServletUtils.format = - new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + ServletUtils.format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); ServletUtils.format.setTimeZone(ServletUtils.timeZone); } @@ -241,8 +235,7 @@ public static long parseExpiresHeader(String expiresHeader) { synchronized (calendar) { if (ServletUtils.format == null) { - ServletUtils.format = - new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + ServletUtils.format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); ServletUtils.format.setTimeZone(ServletUtils.timeZone); } @@ -365,10 +358,7 @@ public static String gwcHtmlHeader(String relBasePath, String pageTitle, String .append(relBasePath) .append("rest/web/gwc.css\" type=\"text/css\"/>\n"); if (jsFile != null) { - builder.append("\n"); + builder.append("\n"); } builder.append("\n"); return builder.toString(); @@ -378,9 +368,7 @@ public static String gwcHtmlLogoLink(String relBasePath) { StringBuilder builder = new StringBuilder(); builder.append("\n"); return builder.toString(); @@ -443,8 +431,7 @@ public static String getServletBaseURL(HttpServletRequest req, String servletPre } /** Generate the context path of the request, less the specified trailing path */ - public static String getServletContextPath( - HttpServletRequest req, String trailingPath, String servletPrefix) { + public static String getServletContextPath(HttpServletRequest req, String trailingPath, String servletPrefix) { String reqUrl = req.getRequestURL().toString(); String servletBase = ServletUtils.getServletBaseURL(req, servletPrefix); int prefixIdx = servletBase.length(); @@ -457,8 +444,7 @@ public static String getServletContextPath( } /** Generate the context path of the request, try the specified trailing path */ - public static String getServletContextPath( - HttpServletRequest req, String[] trailingPaths, String servletPrefix) { + public static String getServletContextPath(HttpServletRequest req, String[] trailingPaths, String servletPrefix) { String context = ""; for (String trailingPath : trailingPaths) { context = getServletContextPath(req, trailingPath, servletPrefix); diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java b/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java index c7b1f81f91..a887dfffec 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java +++ b/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java @@ -77,9 +77,7 @@ public Set layerFormats(String layerName) { } catch (GeoWebCacheException e) { throw new RuntimeException(e); } - return layer.getMimeTypes().stream() - .map(MimeType::getFileExtension) - .collect(Collectors.toSet()); + return layer.getMimeTypes().stream().map(MimeType::getFileExtension).collect(Collectors.toSet()); } public String forTile(TileObject obj) { @@ -117,17 +115,7 @@ public String forTile(TileObject obj) { // Key format, comprised of // {@code ///////.} - String key = - join( - false, - prefix, - layer, - gridset, - shortFormat, - parametersId, - z, - x, - y + "." + extension); + String key = join(false, prefix, layer, gridset, shortFormat, parametersId, z, x, y + "." + extension); return key; } @@ -181,9 +169,7 @@ public String parametersMetadata(final String layerName, final String parameters false, prefix, layerId, - PARAMETERS_METADATA_OBJECT_PREFIX - + parametersId - + PARAMETERS_METADATA_OBJECT_SUFFIX); + PARAMETERS_METADATA_OBJECT_PREFIX + parametersId + PARAMETERS_METADATA_OBJECT_SUFFIX); } public String parametersMetadataPrefix(final String layerName) { diff --git a/geowebcache/core/src/test/java/org/geowebcache/DemoTest.java b/geowebcache/core/src/test/java/org/geowebcache/DemoTest.java index c5d6dde10c..a4b33c6cb1 100644 --- a/geowebcache/core/src/test/java/org/geowebcache/DemoTest.java +++ b/geowebcache/core/src/test/java/org/geowebcache/DemoTest.java @@ -47,23 +47,11 @@ public void testAdvertised() throws GeoWebCacheException, IOException { // Creating an advertised Layer and an unadvertised one HashMap subSets = new HashMap<>(); TileLayer advertisedLayer = - new WMSLayer( - "testAdv", null, null, null, null, subSets, null, null, null, false, null); + new WMSLayer("testAdv", null, null, null, null, subSets, null, null, null, false, null); advertisedLayer.setEnabled(true); advertisedLayer.setAdvertised(true); TileLayer unAdvertisedLayer = - new WMSLayer( - "testNotAdv", - null, - null, - null, - null, - subSets, - null, - null, - null, - false, - null); + new WMSLayer("testNotAdv", null, null, null, null, subSets, null, null, null, false, null); unAdvertisedLayer.setEnabled(true); unAdvertisedLayer.setAdvertised(false); @@ -115,8 +103,7 @@ public void testEscapingWithoutLayer() throws Exception { when(layer.getGridSubsets()).thenReturn(gridSubsets); when(layer.getGridSubset(epsg4326)).thenReturn(subSet2); when(layer.getGridSubset(unescapedSubset)).thenReturn(subSet1); - when(layer.getMimeTypes()) - .thenReturn(Collections.singletonList(MimeType.createFromFormat("image/png"))); + when(layer.getMimeTypes()).thenReturn(Collections.singletonList(MimeType.createFromFormat("image/png"))); TileLayerDispatcher tld = mock(TileLayerDispatcher.class); when(tld.getLayerNames()).thenReturn(Collections.singleton(unescapedLayer)); @@ -217,8 +204,7 @@ public void testRemovedInlineJavaScript() throws Exception { Demo.makeMap(tld, null, "layer", new MockHttpServletRequest(), response); String result = response.getContentAsString(); - assertThat( - result, containsString("")); + assertThat(result, containsString("")); assertThat(result, containsString("")); assertThat(result, not(containsString("
").append(gridSetName); buf.append("OpenLayers: ["); - buf.append( - layer.getMimeTypes().stream() - .filter(type -> type.supportsTiling() || type.isVector()) - .map( - type -> - generateDemoUrl( - escapedLayerName, - escapeHtml4(gridSubset.getName()), - type)) - .collect(Collectors.joining(", "))); + buf.append(layer.getMimeTypes().stream() + .filter(type -> type.supportsTiling() || type.isVector()) + .map(type -> generateDemoUrl(escapedLayerName, escapeHtml4(gridSubset.getName()), type)) + .collect(Collectors.joining(", "))); buf.append("]\n"); @@ -236,29 +221,19 @@ private static void outputKMLSupport(StringBuffer buf, TileLayer layer) { buf.append("   KML: ["); String prefix = ""; - buf.append( - layer.getMimeTypes().stream() - .filter( - type -> - type instanceof ImageMime - || type == XMLMime.kml - || type == XMLMime.kmz) - .map( - type -> { - if (type == XMLMime.kmz) { - return String.format( - "kmz", - prefix, escapeHtml4(layer.getName())); - } else { - return String.format( - "%s", - prefix, - escapeHtml4(layer.getName()), - type.getFileExtension(), - type.getFileExtension()); - } - }) - .collect(Collectors.joining(", "))); + buf.append(layer.getMimeTypes().stream() + .filter(type -> type instanceof ImageMime || type == XMLMime.kml || type == XMLMime.kmz) + .map(type -> { + if (type == XMLMime.kmz) { + return String.format( + "kmz", prefix, escapeHtml4(layer.getName())); + } else { + return String.format( + "%s", + prefix, escapeHtml4(layer.getName()), type.getFileExtension(), type.getFileExtension()); + } + }) + .collect(Collectors.joining(", "))); buf.append("]"); } @@ -300,24 +275,21 @@ private static String generateHTML(TileLayer layer, String gridSetStr, String fo buf.append(" ").append(escapeHtml4(gridSubset.getName())); buf.append(" ").append(escapeHtml4(formatStr)); buf.append("\n"); - buf.append( - "\n"); + buf.append("\n"); buf.append("\n"); - buf.append("\n"); + buf.append("\n"); buf.append("\n"); buf.append("\n" + "\n"); buf.append("
") @@ -325,14 +297,13 @@ private static String generateHTML(TileLayer layer, String gridSetStr, String fo .append("
\n"); buf.append("
\n" + "
\n"); - buf.append( - "
\n" - + "
\n" - + " Attributes\n" - + " \n" - + "
\n" - + "
\n" - + "
"); + buf.append("
\n" + + "
\n" + + " Attributes\n" + + " \n" + + "
\n" + + "
\n" + + "
"); // add parameters in hidden inputs makeHiddenInput(buf, "dpi", Double.toString(gridSubset.getDotsPerInch())); @@ -346,9 +317,7 @@ private static String generateHTML(TileLayer layer, String gridSetStr, String fo makeHiddenInput( buf, "gridNamesNumeric", - String.valueOf( - Arrays.stream(gridSubset.getGridNames()) - .allMatch(n -> StringUtils.isNumeric(n)))); + String.valueOf(Arrays.stream(gridSubset.getGridNames()).allMatch(n -> StringUtils.isNumeric(n)))); makeHiddenInput(buf, "format", formatStr); makeHiddenInput(buf, "layerName", layerName); makeHiddenInput(buf, "SRS", gridSubset.getSRS().toString()); @@ -360,8 +329,7 @@ private static String generateHTML(TileLayer layer, String gridSetStr, String fo } else if (doubleEquals(mpu, 0.3048)) { unit = "ft"; // Use the average of equatorial and polar radius, and a large margin of error - } else if (doubleEquals( - mpu, Math.PI * (6378137 + 6356752) / 360, Math.PI * (6378137 - 6356752) / 360)) { + } else if (doubleEquals(mpu, Math.PI * (6378137 + 6356752) / 360, Math.PI * (6378137 - 6356752) / 360)) { unit = "degrees"; } makeHiddenInput(buf, "unit", unit); @@ -465,8 +433,7 @@ private static String makeModifiableParameters(TileLayer tl) { return doc.toString(); } - private static Map makeParametersMap( - String defaultValue, List legalValues) { + private static Map makeParametersMap(String defaultValue, List legalValues) { Map map = new TreeMap<>(); for (String s : legalValues) { map.put(s, s); @@ -483,8 +450,7 @@ private static void makeHiddenInput(StringBuilder doc, String id, String value) .append("\" />\n"); } - private static void makePullDown( - StringBuilder doc, String id, Map keysValues, String defaultKey) { + private static void makePullDown(StringBuilder doc, String id, Map keysValues, String defaultKey) { doc.append("\n"); + doc.append("\n"); } private static boolean doubleEquals(double d1, double d2) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/CaseNormalizingParameterFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/CaseNormalizingParameterFilter.java index d6c54e8d0b..e0d79e827d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/CaseNormalizingParameterFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/CaseNormalizingParameterFilter.java @@ -85,10 +85,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return "CaseNormalizingParameterFilter [normalize=" - + normalize - + ", " - + super.toString() - + "]"; + return "CaseNormalizingParameterFilter [normalize=" + normalize + ", " + super.toString() + "]"; } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/FloatParameterFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/FloatParameterFilter.java index 0d6ae90bb0..ec428185b3 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/FloatParameterFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/FloatParameterFilter.java @@ -122,15 +122,14 @@ public String apply(@Nullable String str) throws ParameterException { return Float.toString(best); } - throw new ParameterException( - "Closest match for " - + super.getKey() - + "=" - + str - + " is " - + best - + ", but this exceeds the threshold of " - + threshold); + throw new ParameterException("Closest match for " + + super.getKey() + + "=" + + str + + " is " + + best + + ", but this exceeds the threshold of " + + threshold); } @Override @@ -180,12 +179,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return "FloatParameterFilter [values=" - + values - + ", threshold=" - + threshold - + ", " - + super.toString() - + "]"; + return "FloatParameterFilter [values=" + values + ", threshold=" + threshold + ", " + super.toString() + "]"; } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/IntegerParameterFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/IntegerParameterFilter.java index 6d5d31ec35..80581955d9 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/IntegerParameterFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/IntegerParameterFilter.java @@ -122,15 +122,14 @@ public String apply(@Nullable String str) throws ParameterException { return Integer.toString(best); } - throw new ParameterException( - "Closest match for " - + super.getKey() - + "=" - + str - + " is " - + best - + ", but this exceeds the threshold of " - + threshold); + throw new ParameterException("Closest match for " + + super.getKey() + + "=" + + str + + " is " + + best + + ", but this exceeds the threshold of " + + threshold); } @Override @@ -180,12 +179,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return "IntegerParameterFilter [values=" - + values - + ", threshold=" - + threshold - + ", " - + super.toString() - + "]"; + return "IntegerParameterFilter [values=" + values + ", threshold=" + threshold + ", " + super.toString() + "]"; } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/ParameterFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/ParameterFilter.java index 0de53ce45e..aaf2d99896 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/ParameterFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/parameters/ParameterFilter.java @@ -111,8 +111,7 @@ public boolean applies(@Nullable String parameterValue) { public void setKey(String key) { Preconditions.checkNotNull(key); Preconditions.checkArgument(!key.isEmpty(), "ParameterFilter key must be non-empty"); - Preconditions.checkState( - this.key == null, "The key for this ParameterFilter has already been set"); + Preconditions.checkState(this.key == null, "The key for this ParameterFilter has already been set"); this.key = key; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/request/CircularExtentFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/request/CircularExtentFilter.java index 8a2cdc46d1..21e655b64f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/request/CircularExtentFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/request/CircularExtentFilter.java @@ -74,14 +74,12 @@ public void initialize(TileLayer layer) throws GeoWebCacheException { } @Override - public void update(TileLayer layer, String gridSetId, int zoomStart, int zoomStop) - throws GeoWebCacheException { + public void update(TileLayer layer, String gridSetId, int zoomStart, int zoomStop) throws GeoWebCacheException { // Do nothing } @Override - public void update(byte[] filterData, TileLayer layer, String gridSetId, int z) - throws GeoWebCacheException { + public void update(byte[] filterData, TileLayer layer, String gridSetId, int z) throws GeoWebCacheException { // Do nothing } diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/request/FileRasterFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/request/FileRasterFilter.java index fc874f61f5..9839a0bb15 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/request/FileRasterFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/request/FileRasterFilter.java @@ -56,8 +56,7 @@ protected BufferedImage loadMatrix(TileLayer layer, String gridSetId, int zoomLe File fh = new File(createFilePath(gridSetId, zoomLevel)); if (!fh.exists() || !fh.canRead()) { - throw new GeoWebCacheException( - fh.getAbsolutePath() + " does not exist or is not readable"); + throw new GeoWebCacheException(fh.getAbsolutePath() + " does not exist or is not readable"); } BufferedImage img = ImageIO.read(fh); @@ -65,16 +64,15 @@ protected BufferedImage loadMatrix(TileLayer layer, String gridSetId, int zoomLe int[] widthHeight = calculateWidthHeight(layer.getGridSubset(gridSetId), zoomLevel); if (img.getWidth() != widthHeight[0] || img.getHeight() != widthHeight[1]) { - String msg = - fh.getAbsolutePath() - + " has dimensions " - + img.getWidth() - + "," - + img.getHeight() - + ", expected " - + widthHeight[0] - + "," - + widthHeight[1]; + String msg = fh.getAbsolutePath() + + " has dimensions " + + img.getWidth() + + "," + + img.getHeight() + + ", expected " + + widthHeight[0] + + "," + + widthHeight[1]; throw new GeoWebCacheException(msg); } @@ -83,21 +81,12 @@ protected BufferedImage loadMatrix(TileLayer layer, String gridSetId, int zoomLe private String createFilePath(String gridSetId, int zoomLevel) { String path = - storagePath - + File.separator - + this.getName() - + "_" - + gridSetId - + "_" - + zoomLevel - + "." - + fileExtension; + storagePath + File.separator + this.getName() + "_" + gridSetId + "_" + zoomLevel + "." + fileExtension; return path; } - public void saveMatrix(byte[] data, TileLayer layer, String gridSetId, int zoomLevel) - throws IOException { + public void saveMatrix(byte[] data, TileLayer layer, String gridSetId, int zoomLevel) throws IOException { // Persist File fh = new File(createFilePath(gridSetId, zoomLevel)); try (FileOutputStream fos = new FileOutputStream(fh)) { @@ -106,31 +95,25 @@ public void saveMatrix(byte[] data, TileLayer layer, String gridSetId, int zoomL } @Override - public void update(byte[] filterData, TileLayer layer, String gridSetId, int z) - throws GeoWebCacheException { + public void update(byte[] filterData, TileLayer layer, String gridSetId, int z) throws GeoWebCacheException { try { saveMatrix(filterData, layer, gridSetId, z); } catch (IOException e) { throw new GeoWebCacheException( - this.getName() - + " encountered an error while persisting matrix, " - + e.getMessage()); + this.getName() + " encountered an error while persisting matrix, " + e.getMessage()); } try { super.setMatrix(layer, gridSetId, z, true); } catch (IOException e) { throw new GeoWebCacheException( - this.getName() - + " encountered an error while loading matrix, " - + e.getMessage()); + this.getName() + " encountered an error while loading matrix, " + e.getMessage()); } } @Override - public void update(TileLayer layer, String gridSetId, int zoomStart, int zoomStop) - throws GeoWebCacheException { + public void update(TileLayer layer, String gridSetId, int zoomStart, int zoomStop) throws GeoWebCacheException { throw new GeoWebCacheException( "TileLayer layer, String gridSetId, int z) is not appropriate for FileRasterFilters"); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/request/RasterFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/request/RasterFilter.java index 4f0b047395..dd06c53327 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/request/RasterFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/request/RasterFilter.java @@ -149,9 +149,7 @@ public void apply(ConveyorTile convTile) throws RequestFilterException { idx[2] = zoomStop; } - if (matrices == null - || matrices.get(gridSetId) == null - || matrices.get(gridSetId)[(int) idx[2]] == null) { + if (matrices == null || matrices.get(gridSetId) == null || matrices.get(gridSetId)[(int) idx[2]] == null) { try { setMatrix(convTile.getLayer(), gridSetId, (int) idx[2], false); } catch (Exception e) { @@ -166,11 +164,7 @@ public void apply(ConveyorTile convTile) throws RequestFilterException { + " : " + e.getMessage()); throw new RequestFilterException( - this, - 500, - "Failed while trying to load filter for " - + idx[2] - + ", please check the logs"); + this, 500, "Failed while trying to load filter for " + idx[2] + ", please check the logs"); } } @@ -281,17 +275,7 @@ private boolean lookupQuad(GridSubset grid, long[] idx) { } } } catch (ArrayIndexOutOfBoundsException aioob) { - log.log( - Level.SEVERE, - "x:" - + x - + " y:" - + y - + " (" - + mat.getWidth() - + " " - + mat.getHeight() - + ")"); + log.log(Level.SEVERE, "x:" + x + " y:" + y + " (" + mat.getWidth() + " " + mat.getHeight() + ")"); } } @@ -350,17 +334,7 @@ private boolean lookupSubsample(GridSubset grid, long[] idx, int zoomDiff) { y = startY; } } catch (ArrayIndexOutOfBoundsException aioob) { - log.log( - Level.SEVERE, - "x:" - + x - + " y:" - + y - + " (" - + mat.getWidth() - + " " - + mat.getHeight() - + ")"); + log.log(Level.SEVERE, "x:" + x + " y:" + y + " (" + mat.getWidth() + " " + mat.getHeight() + ")"); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/request/WMSRasterFilter.java b/geowebcache/core/src/main/java/org/geowebcache/filter/request/WMSRasterFilter.java index c72cdecef9..52b85a4aa1 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/request/WMSRasterFilter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/request/WMSRasterFilter.java @@ -101,15 +101,14 @@ protected BufferedImage loadMatrix(TileLayer tlayer, String gridSetId, int z) String urlStr = layer.getWMSurl()[0]; Map requestParams = wmsParams(layer, gridSet, z, widthHeight); - log.info( - "Updated WMS raster filter, zoom level " - + z - + " for " - + getName() - + " (" - + layer.getName() - + ") , " - + urlStr); + log.info("Updated WMS raster filter, zoom level " + + z + + " for " + + getName() + + " (" + + layer.getName() + + ") , " + + urlStr); URL wmsUrl = URLs.of(urlStr); @@ -120,9 +119,7 @@ protected BufferedImage loadMatrix(TileLayer tlayer, String gridSetId, int z) HttpResponse httpResponse = null; BufferedImage img = null; - httpResponse = - srcHelper.executeRequest( - wmsUrl, requestParams, backendTimeout, WMSLayer.HttpRequestMode.Get); + httpResponse = srcHelper.executeRequest(wmsUrl, requestParams, backendTimeout, WMSLayer.HttpRequestMode.Get); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != 200) { @@ -130,12 +127,11 @@ protected BufferedImage loadMatrix(TileLayer tlayer, String gridSetId, int z) } if (!httpResponse.getFirstHeader("Content-Type").getValue().startsWith("image/")) { - throw new GeoWebCacheException( - "Unexpected response content type " - + httpResponse.getFirstHeader("Content-Type").getValue() - + " , request was " - + urlStr - + "\n"); + throw new GeoWebCacheException("Unexpected response content type " + + httpResponse.getFirstHeader("Content-Type").getValue() + + " , request was " + + urlStr + + "\n"); } byte[] ret = ServletUtils.readStream(httpResponse.getEntity().getContent(), 16384, 2048); @@ -145,16 +141,15 @@ protected BufferedImage loadMatrix(TileLayer tlayer, String gridSetId, int z) img = ImageIO.read(is); if (img.getWidth() != widthHeight[0] || img.getHeight() != widthHeight[1]) { - String msg = - "WMS raster filter has dimensions " - + img.getWidth() - + "," - + img.getHeight() - + ", expected " - + widthHeight[0] - + "," - + widthHeight[1] - + "\n"; + String msg = "WMS raster filter has dimensions " + + img.getWidth() + + "," + + img.getHeight() + + ", expected " + + widthHeight[0] + + "," + + widthHeight[1] + + "\n"; throw new GeoWebCacheException(msg); } @@ -162,8 +157,7 @@ protected BufferedImage loadMatrix(TileLayer tlayer, String gridSetId, int z) } /** Generates the URL used to create the lookup raster */ - protected Map wmsParams( - WMSLayer layer, GridSubset gridSubset, int z, int[] widthHeight) + protected Map wmsParams(WMSLayer layer, GridSubset gridSubset, int z, int[] widthHeight) throws GeoWebCacheException { BoundingBox bbox = gridSubset.getCoverageBounds(z); @@ -197,8 +191,7 @@ protected Map wmsParams( } @Override - public void update(byte[] filterData, TileLayer layer, String gridSetId, int z) - throws GeoWebCacheException { + public void update(byte[] filterData, TileLayer layer, String gridSetId, int z) throws GeoWebCacheException { throw new GeoWebCacheException( "update(byte[] filterData, TileLayer layer, String gridSetId, int z) is not appropriate for WMSRasterFilters"); } @@ -216,8 +209,7 @@ public boolean update(TileLayer layer, String gridSetId) { } @Override - public void update(TileLayer layer, String gridSetId, int zStart, int zStop) - throws GeoWebCacheException { + public void update(TileLayer layer, String gridSetId, int zStart, int zStop) throws GeoWebCacheException { for (int z = zStart; z <= zStop; z++) { try { this.setMatrix(layer, gridSetId, z, true); diff --git a/geowebcache/core/src/main/java/org/geowebcache/filter/security/SecurityDispatcher.java b/geowebcache/core/src/main/java/org/geowebcache/filter/security/SecurityDispatcher.java index 6b8ae0065a..65a89f381f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/filter/security/SecurityDispatcher.java +++ b/geowebcache/core/src/main/java/org/geowebcache/filter/security/SecurityDispatcher.java @@ -43,8 +43,7 @@ public Collection getFilters() { * * @throws SecurityException if any of the filter throw it */ - public void checkSecurity(final ConveyorTile tile) - throws SecurityException, GeoWebCacheException { + public void checkSecurity(final ConveyorTile tile) throws SecurityException, GeoWebCacheException { final TileLayer layer = tile.getLayer(); final GridSubset gridSubset = tile.getGridSubset(); final BoundingBox bounds; @@ -68,8 +67,7 @@ public void checkSecurity(final ConveyorTile tile) public void checkSecurity(TileLayer layer, @Nullable BoundingBox extent, @Nullable SRS srs) throws SecurityException, GeoWebCacheException { if (Objects.isNull(extent) != Objects.isNull(srs)) { - throw new NullPointerException( - "Extent and srs must either both be null or both be non-null"); + throw new NullPointerException("Extent and srs must either both be null or both be non-null"); } for (SecurityFilter filter : getFilters()) { filter.checkSecurity(layer, extent, srs); @@ -77,8 +75,7 @@ public void checkSecurity(TileLayer layer, @Nullable BoundingBox extent, @Nullab } @Override - public void setApplicationContext(final ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/BoundingBox.java b/geowebcache/core/src/main/java/org/geowebcache/grid/BoundingBox.java index 9a42811814..d687aeb1e4 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/BoundingBox.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/BoundingBox.java @@ -43,13 +43,11 @@ private NumberFormat getCoordinateFormatter() { public static final BoundingBox WORLD4326 = new BoundingBox(-180.0, -90.0, 180.0, 90.0); - public static final BoundingBox WORLD3857 = - new BoundingBox(-20037508.34, -20037508.34, 20037508.34, 20037508.34); + public static final BoundingBox WORLD3857 = new BoundingBox(-20037508.34, -20037508.34, 20037508.34, 20037508.34); // exactly as defined in the OGC TMS specification public static final BoundingBox WORLD3857_TMS = - new BoundingBox( - -20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892); + new BoundingBox(-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892); // minx, miny, maxx, maxy private double[] coords = new double[4]; @@ -166,14 +164,7 @@ public void setFromBBOXString(String BBOX, int recWatch) { * @return a readable string */ public String getReadableString() { - return "Min X: " - + coords[0] - + " Min Y: " - + coords[1] - + " Max X: " - + coords[2] - + " Max Y: " - + coords[3]; + return "Min X: " + coords[0] + " Min Y: " + coords[1] + " Max X: " + coords[2] + " Max Y: " + coords[3]; } /** Returns a comma separated value String suitable for URL output */ diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/Grid.java b/geowebcache/core/src/main/java/org/geowebcache/grid/Grid.java index 25c8f95aac..e0cb0006c4 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/Grid.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/Grid.java @@ -42,8 +42,7 @@ public boolean equals(Object obj) { if (numTilesHigh != other.numTilesHigh) return false; - if (Math.abs(other.resolution - resolution) / Math.abs(other.resolution + resolution) - > 0.005) return false; + if (Math.abs(other.resolution - resolution) / Math.abs(other.resolution + resolution) > 0.005) return false; return true; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/GridAlignmentMismatchException.java b/geowebcache/core/src/main/java/org/geowebcache/grid/GridAlignmentMismatchException.java index f3d5709f79..cc82fb1d65 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/GridAlignmentMismatchException.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/GridAlignmentMismatchException.java @@ -17,18 +17,17 @@ public class GridAlignmentMismatchException extends GridMismatchException { public GridAlignmentMismatchException(double x, long posX, double y, long posY) { - super( - "X,Y values for the tile index were calculated to be {" - + x - + ", " - + y - + "} " - + " which had to be rounded to {" - + posX - + ", " - + posY - + "} " - + " and exceeds the threshold of 10%. Perhaps the client is using" - + " the wrong origin ?"); + super("X,Y values for the tile index were calculated to be {" + + x + + ", " + + y + + "} " + + " which had to be rounded to {" + + posX + + ", " + + posY + + "} " + + " and exceeds the threshold of 10%. Perhaps the client is using" + + " the wrong origin ?"); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSet.java b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSet.java index b4cdf60290..2bc9164901 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSet.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSet.java @@ -125,12 +125,11 @@ public BoundingBox boundsFromIndex(long[] tileIndex) { 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)); + BoundingBox tileBounds = new BoundingBox( + tileOrigin[0] + width * tileX, + tileOrigin[1] + height * (tileY), + tileOrigin[0] + width * (tileX + 1), + tileOrigin[1] + height * (tileY + 1)); return tileBounds; } @@ -192,8 +191,7 @@ protected long[] closestIndex(BoundingBox tileBounds) throws GridMismatchExcepti return closestIndex(bestLevel, tileBounds); } - protected long[] closestIndex(int level, BoundingBox tileBounds) - throws GridAlignmentMismatchException { + protected long[] closestIndex(int level, BoundingBox tileBounds) throws GridAlignmentMismatchException { Grid grid = getGrid(level); double width = grid.getResolution() * getTileWidth(); @@ -234,8 +232,7 @@ public long[] closestRectangle(BoundingBox rectangleBounds) { 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)); + double error = Math.abs(countX - Math.round(countX)) + Math.abs(countY - Math.round(countY)); if (error < bestError) { bestError = error; @@ -286,16 +283,15 @@ public boolean equals(Object obj) { if (this == other) return true; - boolean equals = - Objects.equals(getSrs(), other.getSrs()) - && Objects.equals(getName(), other.getName()) - && Objects.equals(getDescription(), other.getDescription()) - && Objects.equals(getTileWidth(), other.getTileWidth()) - && Objects.equals(getTileHeight(), other.getTileHeight()) - && Objects.equals(isTopLeftAligned(), other.isTopLeftAligned()) - && Objects.equals(isyCoordinateFirst(), other.isyCoordinateFirst()) - && Objects.equals(getOriginalExtent(), other.getOriginalExtent()) - && Arrays.equals(gridLevels, other.gridLevels); + boolean equals = Objects.equals(getSrs(), other.getSrs()) + && Objects.equals(getName(), other.getName()) + && Objects.equals(getDescription(), other.getDescription()) + && Objects.equals(getTileWidth(), other.getTileWidth()) + && Objects.equals(getTileHeight(), other.getTileHeight()) + && Objects.equals(isTopLeftAligned(), other.isTopLeftAligned()) + && Objects.equals(isyCoordinateFirst(), other.isyCoordinateFirst()) + && Objects.equals(getOriginalExtent(), other.getOriginalExtent()) + && Arrays.equals(gridLevels, other.gridLevels); return equals; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetBroker.java b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetBroker.java index 661f765408..f4021f6700 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetBroker.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetBroker.java @@ -38,9 +38,7 @@ /** Exposes {@link GridSet}s from all {@link GridSetConfiguration}s */ public class GridSetBroker - implements ConfigurationAggregator, - ApplicationContextAware, - InitializingBean { + implements ConfigurationAggregator, ApplicationContextAware, InitializingBean { private static Logger log = Logging.getLogger(GridSetBroker.class.getName()); private List configurations; @@ -53,12 +51,11 @@ public GridSetBroker() {} public GridSetBroker(List configurations) { this.configurations = configurations; - defaults = - configurations.stream() - .filter(DefaultGridsets.class::isInstance) - .findFirst() - .map(DefaultGridsets.class::cast) - .get(); + defaults = configurations.stream() + .filter(DefaultGridsets.class::isInstance) + .findFirst() + .map(DefaultGridsets.class::cast) + .get(); } @Override @@ -101,12 +98,11 @@ public Collection getGridSets() { return getConfigurations().stream() .map(GridSetConfiguration::getGridSets) .flatMap(Collection::stream) - .collect( - Collectors.toMap( - GridSet::getName, - g -> g, - (g1, g2) -> g1, // Prefer the first one - HashMap::new)) + .collect(Collectors.toMap( + GridSet::getName, + g -> g, + (g1, g2) -> g1, // Prefer the first one + HashMap::new)) .values(); } @@ -120,11 +116,8 @@ public void addGridSet(GridSet gridSet) { getConfigurations().stream() .filter(c -> c.canSave(gridSet)) .findFirst() - .orElseThrow( - () -> - new UnsupportedOperationException( - "No Configuration is able to save gridset " - + gridSet.getName())) + .orElseThrow(() -> new UnsupportedOperationException( + "No Configuration is able to save gridset " + gridSet.getName())) .addGridSet(gridSet); } @@ -136,21 +129,19 @@ public void addGridSet(GridSet gridSet) { */ public synchronized GridSet remove(final String gridSetName) { return getGridSet(gridSetName) - .map( - g -> { - removeGridSet(gridSetName); - return g; - }) + .map(g -> { + removeGridSet(gridSetName); + return g; + }) .orElse(null); } public synchronized void removeGridSet(final String gridSetName) { getConfigurations().stream() .filter(c -> c.getGridSet(gridSetName).isPresent()) - .forEach( - c -> { - c.removeGridSet(gridSetName); - }); + .forEach(c -> { + c.removeGridSet(gridSetName); + }); } public DefaultGridsets getDefaults() { @@ -162,12 +153,10 @@ public DefaultGridsets getDefaults() { getConfigurations(DefaultGridsets.class).iterator(); defaults = it.next(); if (it.hasNext()) { - log.warning( - "GridSetBroker has more than one DefaultGridSets configuration"); + log.warning("GridSetBroker has more than one DefaultGridSets configuration"); } } catch (NoSuchElementException ex) { - throw new IllegalStateException( - "GridSetBroker has no DefaultGridsets configuration", ex); + throw new IllegalStateException("GridSetBroker has no DefaultGridsets configuration", ex); } } } @@ -211,8 +200,7 @@ public GridSet getWorldEpsg3857() { @Override @SuppressWarnings("unchecked") - public List getConfigurations( - Class type) { + public List getConfigurations(Class type) { return (List) getConfigurations().stream().filter(type::isInstance).collect(Collectors.toList()); } @@ -220,21 +208,17 @@ public List getConfigurations( private Collection getConfigurations() { // We set DefaultGridsets in the constructor, need to account for it. if (this.configurations == null - || (this.configurations.size() == 1 - && this.configurations.get(0) instanceof DefaultGridsets)) { + || (this.configurations.size() == 1 && this.configurations.get(0) instanceof DefaultGridsets)) { synchronized (this) { if (this.configurations == null || (this.configurations.size() == 1 && this.configurations.get(0).equals(defaults))) { if (Objects.nonNull(applicationContext)) { configurations = - GeoWebCacheExtensions.configurations( - GridSetConfiguration.class, applicationContext); + GeoWebCacheExtensions.configurations(GridSetConfiguration.class, applicationContext); } else { - log.fine( - "GridSetBroker.initialize() called without having set application context"); - configurations = - GeoWebCacheExtensions.configurations(GridSetConfiguration.class); + log.fine("GridSetBroker.initialize() called without having set application context"); + configurations = GeoWebCacheExtensions.configurations(GridSetConfiguration.class); } if (defaults != null && !configurations.contains(defaults)) { configurations.add(defaults); diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetFactory.java b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetFactory.java index 8e0befd441..ff68f1f39d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetFactory.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSetFactory.java @@ -77,31 +77,29 @@ public static GridSet createGridSet( for (int i = 1; resolutions != null && i < resolutions.length; i++) { if (resolutions[i] >= resolutions[i - 1]) { - throw new IllegalArgumentException( - "Each resolution should be lower than it's prior one. Res[" - + i - + "] == " - + resolutions[i] - + ", Res[" - + (i - 1) - + "] == " - + resolutions[i - 1] - + "."); + throw new IllegalArgumentException("Each resolution should be lower than it's prior one. Res[" + + i + + "] == " + + resolutions[i] + + ", Res[" + + (i - 1) + + "] == " + + resolutions[i - 1] + + "."); } } for (int i = 1; scaleDenoms != null && i < scaleDenoms.length; i++) { if (scaleDenoms[i] >= scaleDenoms[i - 1]) { - throw new IllegalArgumentException( - "Each scale denominator should be lower than it's prior one. Scale[" - + i - + "] == " - + scaleDenoms[i] - + ", Scale[" - + (i - 1) - + "] == " - + scaleDenoms[i - 1] - + "."); + throw new IllegalArgumentException("Each scale denominator should be lower than it's prior one. Scale[" + + i + + "] == " + + scaleDenoms[i] + + ", Scale[" + + (i - 1) + + "] == " + + scaleDenoms[i - 1] + + "."); } } @@ -123,17 +121,15 @@ public static GridSet createGridSet( gridSet.setMetersPerUnit(EPSG3857_TO_METERS); } else { if (resolutions == null) { - log.config( - "GridSet " - + name - + " was defined without metersPerUnit, assuming 1m/unit." - + " All scales will be off if this is incorrect."); + log.config("GridSet " + + name + + " was defined without metersPerUnit, assuming 1m/unit." + + " All scales will be off if this is incorrect."); } else { - log.config( - "GridSet " - + name - + " was defined without metersPerUnit. " - + "Assuming 1m per SRS unit for WMTS scale output."); + log.config("GridSet " + + name + + " was defined without metersPerUnit. " + + "Assuming 1m per SRS unit for WMTS scale output."); gridSet.setScaleWarning(true); } @@ -157,17 +153,14 @@ public static GridSet createGridSet( curGrid.setResolution(pixelSize * (scaleDenoms[i] / gridSet.getMetersPerUnit())); } else { curGrid.setResolution(resolutions[i]); - curGrid.setScaleDenominator( - (resolutions[i] * gridSet.getMetersPerUnit()) / DEFAULT_PIXEL_SIZE_METER); + curGrid.setScaleDenominator((resolutions[i] * gridSet.getMetersPerUnit()) / DEFAULT_PIXEL_SIZE_METER); } final double mapUnitWidth = tileWidth * curGrid.getResolution(); final double mapUnitHeight = tileHeight * curGrid.getResolution(); - final long tilesWide = - (long) Math.ceil((extent.getWidth() - mapUnitWidth * 0.01) / mapUnitWidth); - final long tilesHigh = - (long) Math.ceil((extent.getHeight() - mapUnitHeight * 0.01) / mapUnitHeight); + final long tilesWide = (long) Math.ceil((extent.getWidth() - mapUnitWidth * 0.01) / mapUnitWidth); + final long tilesHigh = (long) Math.ceil((extent.getHeight() - mapUnitHeight * 0.01) / mapUnitHeight); curGrid.setNumTilesWide(tilesWide); curGrid.setNumTilesHigh(tilesHigh); diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubset.java b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubset.java index fcdf8e8e82..6325c6051f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubset.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubset.java @@ -41,10 +41,7 @@ public class GridSubset { private final Integer maxCachedZoom; protected GridSubset( - GridSet gridSet, - Map coverages, - BoundingBox originalExtent, - boolean fullCoverage) { + GridSet gridSet, Map coverages, BoundingBox originalExtent, boolean fullCoverage) { this(gridSet, coverages, originalExtent, fullCoverage, null, null); } @@ -109,10 +106,7 @@ public boolean covers(long[] index) { return false; } - if (index[0] >= coverage[0] - && index[0] <= coverage[2] - && index[1] >= coverage[1] - && index[1] <= coverage[3]) { + if (index[0] >= coverage[0] && index[0] <= coverage[2] && index[1] >= coverage[1] && index[1] <= coverage[3]) { return true; } @@ -135,8 +129,7 @@ public void checkCoverage(long[] index) throws OutsideCoverageException { public void checkTileDimensions(int width, int height) throws TileDimensionsMismatchException { if (width != gridSet.getTileWidth() || height != gridSet.getTileHeight()) { - throw new TileDimensionsMismatchException( - width, height, gridSet.getTileWidth(), gridSet.getTileWidth()); + throw new TileDimensionsMismatchException(width, height, gridSet.getTileWidth(), gridSet.getTileWidth()); } } @@ -332,14 +325,12 @@ public long[][] getSubGrid(long[] gridLoc) throws GeoWebCacheException { if ((idx - firstLevel + 1) <= zoomStop) { // Check whether this grid is doubling - double resolutionCheck = - gridSet.getGrid(idx).getResolution() / 2 - - gridSet.getGrid(idx + 1).getResolution(); + double resolutionCheck = gridSet.getGrid(idx).getResolution() / 2 + - gridSet.getGrid(idx + 1).getResolution(); if (Math.abs(resolutionCheck) > gridSet.getGrid(idx + 1).getResolution() * 0.025) { throw new GeoWebCacheException( - "The resolution is not decreasing by a factor of two for " - + this.getName()); + "The resolution is not decreasing by a factor of two for " + this.getName()); } else { long[] coverage = getCoverage(idx + 1); diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubsetFactory.java b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubsetFactory.java index be3a925f91..8b1a616b19 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubsetFactory.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/GridSubsetFactory.java @@ -24,9 +24,7 @@ public class GridSubsetFactory { public static GridSubset createGridSubSet(GridSet gridSet) { - GridSubset ret = - createGridSubSet( - gridSet, gridSet.getOriginalExtent(), 0, gridSet.getNumLevels() - 1); + GridSubset ret = createGridSubSet(gridSet, gridSet.getOriginalExtent(), 0, gridSet.getNumLevels() - 1); return ret; } @@ -54,15 +52,14 @@ public static GridSubset createGridSubSet( if (zoomStop == null) { zoomStop = maxLevel; } else if (zoomStop > maxLevel) { - String message = - "Requested to create GridSubset with zoomStop " - + zoomStop - + " for GridSet " - + gridSet.getName() - + " whose max zoom level is " - + maxLevel - + ". Limiting GridSubset to zoomStop = " - + maxLevel; + String message = "Requested to create GridSubset with zoomStop " + + zoomStop + + " for GridSet " + + gridSet.getName() + + " whose max zoom level is " + + maxLevel + + ". Limiting GridSubset to zoomStop = " + + maxLevel; log.warning(message); zoomStop = maxLevel; } @@ -96,14 +93,7 @@ public static GridSubset createGridSubSet( originalExtent = gridSetBounds; } - GridSubset ret = - new GridSubset( - gridSet, - coverages, - originalExtent, - fullCoverage, - minCachedZoom, - maxCachedZoom); + GridSubset ret = new GridSubset(gridSet, coverages, originalExtent, fullCoverage, minCachedZoom, maxCachedZoom); return ret; } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/GridUtil.java b/geowebcache/core/src/main/java/org/geowebcache/grid/GridUtil.java index 15d7e94016..1272bef6ce 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/GridUtil.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/GridUtil.java @@ -37,8 +37,7 @@ public static GridSubset findBestMatchingGrid( final int tileWidth = crsMatch.getTileWidth(); final int tileHeight = crsMatch.getTileHeight(); if ((expectedTileWidth != null && expectedTileWidth.intValue() != tileWidth) - || (expectedTileHeight != null - && expectedTileHeight.intValue() != tileHeight)) { + || (expectedTileHeight != null && expectedTileHeight.intValue() != tileHeight)) { // don't even consider it continue; } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/OutsideCoverageException.java b/geowebcache/core/src/main/java/org/geowebcache/grid/OutsideCoverageException.java index 7fd4d85b26..ab9eabf583 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/OutsideCoverageException.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/OutsideCoverageException.java @@ -22,21 +22,13 @@ public class OutsideCoverageException extends GeoWebCacheException { private static final long serialVersionUID = -2465389680194367974L; public OutsideCoverageException(long[] index, long firstLevel, long lastLevel) { - super( - "Zoom level was " - + index[2] - + ", but value has to be in [" - + firstLevel - + "," - + lastLevel - + "]"); + super("Zoom level was " + index[2] + ", but value has to be in [" + firstLevel + "," + lastLevel + "]"); } public OutsideCoverageException(long[] index, long[] coverage) { - super( - "Coverage [minx,miny,maxx,maxy] is " - + Arrays.toString(coverage) - + ", index [x,y,z] is " - + Arrays.toString(index)); + super("Coverage [minx,miny,maxx,maxy] is " + + Arrays.toString(coverage) + + ", index [x,y,z] is " + + Arrays.toString(index)); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/ResolutionMismatchException.java b/geowebcache/core/src/main/java/org/geowebcache/grid/ResolutionMismatchException.java index ae7e1278a9..dfd1447b87 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/ResolutionMismatchException.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/ResolutionMismatchException.java @@ -17,13 +17,12 @@ public class ResolutionMismatchException extends GridMismatchException { public ResolutionMismatchException(double wRes, double bestResolution) { - super( - "Requested horizontal resolution: " - + wRes - + " , best match: " - + bestResolution - + " exceeds 10% threshold. Perhaps the client is configured " - + " with an incorrect set of scales (resolutions), " - + " or the DPI setting is off compared to the one in GWC ?"); + super("Requested horizontal resolution: " + + wRes + + " , best match: " + + bestResolution + + " exceeds 10% threshold. Perhaps the client is configured " + + " with an incorrect set of scales (resolutions), " + + " or the DPI setting is off compared to the one in GWC ?"); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/SRS.java b/geowebcache/core/src/main/java/org/geowebcache/grid/SRS.java index a46258e90e..25a7b3e3c4 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/SRS.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/SRS.java @@ -34,16 +34,14 @@ public class SRS implements Comparable, Serializable { * EPSG:102113 or EPSG:102100 identifies web mercator. The "community" first defined it as * EPSG:900913. */ - private static final SRS EPSG3857 = - new SRS(3857, new ArrayList<>(asList(900913, 102113, 102100))); + private static final SRS EPSG3857 = new SRS(3857, new ArrayList<>(asList(900913, 102113, 102100))); /** * The EPSG says EPSG:3857 is the identifier for web mercator. ArcGIS 10 says either of * EPSG:102113 or EPSG:102100 identifies web mercator. The "community" first defined it as * EPSG:900913. */ - private static final SRS EPSG900913 = - new SRS(900913, new ArrayList<>(asList(3857, 102113, 102100))); + private static final SRS EPSG900913 = new SRS(900913, new ArrayList<>(asList(3857, 102113, 102100))); private int number; diff --git a/geowebcache/core/src/main/java/org/geowebcache/grid/TileDimensionsMismatchException.java b/geowebcache/core/src/main/java/org/geowebcache/grid/TileDimensionsMismatchException.java index 294c113a91..b4fd6b85c1 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/grid/TileDimensionsMismatchException.java +++ b/geowebcache/core/src/main/java/org/geowebcache/grid/TileDimensionsMismatchException.java @@ -17,15 +17,14 @@ public class TileDimensionsMismatchException extends GridMismatchException { public TileDimensionsMismatchException(int height, int width, int gsHeight, int gsWidth) { - super( - "The requested tile dimensions " - + width - + "x" - + height - + " do not match those of the grid set (" - + gsWidth - + "x" - + gsHeight - + ")"); + super("The requested tile dimensions " + + width + + "x" + + height + + " do not match those of the grid set (" + + gsWidth + + "x" + + gsHeight + + ")"); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/io/ByteArrayResource.java b/geowebcache/core/src/main/java/org/geowebcache/io/ByteArrayResource.java index fd54ede86a..a08d66dd98 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/io/ByteArrayResource.java +++ b/geowebcache/core/src/main/java/org/geowebcache/io/ByteArrayResource.java @@ -66,8 +66,7 @@ public ByteArrayResource(byte[] data, int offset, int length) { } else { this.data = data; Assert.isTrue(offset < data.length, "Offset should be less than data length"); - Assert.isTrue( - offset + length <= data.length, "Offset + length should be less than length"); + Assert.isTrue(offset + length <= data.length, "Offset + length should be less than length"); this.offset = offset; this.length = length; } @@ -97,7 +96,8 @@ public long transferTo(WritableByteChannel channel) throws IOException { if (length > 0) { ByteBuffer buffer = ByteBuffer.wrap(data, offset, length); long written = 0; - while ((written += channel.write(buffer)) < length) ; + while ((written += channel.write(buffer)) < length) + ; } return length; } @@ -115,7 +115,8 @@ public long transferFrom(ReadableByteChannel channel) throws IOException { } ByteBuffer buffer = ByteBuffer.wrap(data); int read = 0; - while ((read += channel.read(buffer)) < length) ; + while ((read += channel.read(buffer)) < length) + ; } else { offset = 0; length = 0; @@ -198,8 +199,7 @@ public SeekableInputStream(ByteArrayResource res) { public void seek(long pos) throws IOException { if (pos < 0 || pos > super.count) { - throw new IOException( - "Can't seek to pos " + pos + ". buffer is 0.." + (super.count - 1)); + throw new IOException("Can't seek to pos " + pos + ". buffer is 0.." + (super.count - 1)); } super.pos = (int) (lower + pos); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/io/CollectionConverter.java b/geowebcache/core/src/main/java/org/geowebcache/io/CollectionConverter.java index cea32d6334..6ec636a31d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/io/CollectionConverter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/io/CollectionConverter.java @@ -24,8 +24,7 @@ import java.util.List; import java.util.Set; -public class CollectionConverter - extends com.thoughtworks.xstream.converters.collections.CollectionConverter { +public class CollectionConverter extends com.thoughtworks.xstream.converters.collections.CollectionConverter { public static final String UNMODIFIABLE_LIST = "java.util.Collections$UnmodifiableList"; public static final String UNMODIFIABLE_SET = "java.util.Collections$UnmodifiableSet"; diff --git a/geowebcache/core/src/main/java/org/geowebcache/io/FileResource.java b/geowebcache/core/src/main/java/org/geowebcache/io/FileResource.java index a5ff477019..7dbdfb66fb 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/io/FileResource.java +++ b/geowebcache/core/src/main/java/org/geowebcache/io/FileResource.java @@ -57,7 +57,8 @@ public long transferTo(WritableByteChannel target) throws IOException { FileChannel in = fis.getChannel()) { final long size = in.size(); long written = 0; - while ((written += in.transferTo(written, size, target)) < size) ; + while ((written += in.transferTo(written, size, target)) < size) + ; return size; } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/io/GeoWebCacheXStream.java b/geowebcache/core/src/main/java/org/geowebcache/io/GeoWebCacheXStream.java index 1d786893f2..73fe04eb8e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/io/GeoWebCacheXStream.java +++ b/geowebcache/core/src/main/java/org/geowebcache/io/GeoWebCacheXStream.java @@ -89,13 +89,7 @@ public GeoWebCacheXStream( Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { - super( - reflectionProvider, - driver, - classLoaderReference, - mapper, - converterLookup, - converterRegistry); + super(reflectionProvider, driver, classLoaderReference, mapper, converterLookup, converterRegistry); init(); } @@ -117,8 +111,7 @@ public GeoWebCacheXStream( } public GeoWebCacheXStream( - ReflectionProvider reflectionProvider, - HierarchicalStreamDriver hierarchicalStreamDriver) { + ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { super(reflectionProvider, hierarchicalStreamDriver); init(); } @@ -152,16 +145,13 @@ public GeoWebCacheXStream( @Deprecated public GeoWebCacheXStream( - ReflectionProvider reflectionProvider, - HierarchicalStreamDriver driver, - ClassLoader classLoader) { + ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader) { super(reflectionProvider, driver, classLoader); init(); } @Deprecated - public GeoWebCacheXStream( - ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { + public GeoWebCacheXStream(ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { super(reflectionProvider, mapper, driver); init(); } @@ -190,29 +180,27 @@ private void init() { addPermission(new PrimitiveTypePermission()); // Common non-primitives - allowTypes( - new Class[] { - java.lang.String.class, - java.util.Date.class, - java.sql.Date.class, - java.sql.Timestamp.class, - java.sql.Time.class, - }); + allowTypes(new Class[] { + java.lang.String.class, + java.util.Date.class, + java.sql.Date.class, + java.sql.Timestamp.class, + java.sql.Time.class, + }); // Common collections - allowTypes( - new Class[] { - java.util.TreeSet.class, - java.util.SortedSet.class, - java.util.Set.class, - java.util.HashSet.class, - java.util.List.class, - java.util.ArrayList.class, - java.util.Map.class, - java.util.HashMap.class, - java.util.concurrent.CopyOnWriteArrayList.class, - java.util.concurrent.ConcurrentHashMap.class, - }); + allowTypes(new Class[] { + java.util.TreeSet.class, + java.util.SortedSet.class, + java.util.Set.class, + java.util.HashSet.class, + java.util.List.class, + java.util.ArrayList.class, + java.util.Map.class, + java.util.HashMap.class, + java.util.concurrent.CopyOnWriteArrayList.class, + java.util.concurrent.ConcurrentHashMap.class, + }); String whitelistProp = GeoWebCacheExtensions.getProperty("GEOWEBCACHE_XSTREAM_WHITELIST"); if (whitelistProp != null) { @@ -279,8 +267,7 @@ protected void setupConverters() { registerConverter(new ColorConverter(), PRIORITY_NORMAL); } if (JVM.isSwingAvailable()) { - registerConverter( - new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL); + registerConverter(new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); @@ -297,49 +284,25 @@ protected void setupConverters() { new Class[] {ConverterLookup.class}, new Object[] {converterLookup}); registerConverterDynamically( - "com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.extended.CurrencyConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.extended.RegexPatternConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.extended.CharsetConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.extended.CharsetConverter", PRIORITY_NORMAL, null, null); // late bound converters - allows XStream to be compiled on earlier JDKs if (JVM.loadClassForName("javax.xml.datatype.Duration") != null) { registerConverterDynamically( - "com.thoughtworks.xstream.converters.extended.DurationConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.extended.DurationConverter", PRIORITY_NORMAL, null, null); } registerConverterDynamically( - "com.thoughtworks.xstream.converters.enums.EnumConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.basic.StringBuilderConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.basic.StringBuilderConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.basic.UUIDConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.basic.UUIDConverter", PRIORITY_NORMAL, null, null); if (JVM.loadClassForName("javax.activation.ActivationDataFlavor") != null) { registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.ActivationDataFlavorConverter", @@ -348,91 +311,43 @@ protected void setupConverters() { null); } registerConverterDynamically( - "com.thoughtworks.xstream.converters.extended.PathConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.extended.PathConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.ChronologyConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.ChronologyConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.DurationConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.DurationConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.HijrahDateConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.HijrahDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.JapaneseDateConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.JapaneseDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.JapaneseEraConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.JapaneseEraConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.InstantConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.InstantConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.LocalDateConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.LocalDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.LocalDateTimeConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.LocalDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.LocalTimeConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.LocalTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.MinguoDateConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.MinguoDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.MonthDayConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.MonthDayConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.OffsetDateTimeConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.OffsetDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.OffsetTimeConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.OffsetTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.PeriodConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.PeriodConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( "com.thoughtworks.xstream.converters.time.SystemClockConverter", PRIORITY_NORMAL, new Class[] {Mapper.class}, new Object[] {mapper}); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.ThaiBuddhistDateConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.ThaiBuddhistDateConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( "com.thoughtworks.xstream.converters.time.ValueRangeConverter", PRIORITY_NORMAL, @@ -444,25 +359,13 @@ protected void setupConverters() { new Class[] {Mapper.class}, new Object[] {mapper}); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.YearConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.YearConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.YearMonthConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.YearMonthConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.ZonedDateTimeConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.ZonedDateTimeConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( - "com.thoughtworks.xstream.converters.time.ZoneIdConverter", - PRIORITY_NORMAL, - null, - null); + "com.thoughtworks.xstream.converters.time.ZoneIdConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( "com.thoughtworks.xstream.converters.reflection.LambdaConverter", PRIORITY_NORMAL, @@ -477,10 +380,7 @@ protected void setupConverters() { * will be removed if XStream relaxes access control */ private void registerConverterDynamically( - String className, - int priority, - Class[] constructorParamTypes, - Object[] constructorParamValues) { + String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, getClassLoaderReference().getReference()); diff --git a/geowebcache/core/src/main/java/org/geowebcache/io/TreeMapConverter.java b/geowebcache/core/src/main/java/org/geowebcache/io/TreeMapConverter.java index ffc83d21f1..7886c4556b 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/io/TreeMapConverter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/io/TreeMapConverter.java @@ -68,23 +68,17 @@ public TreeMapConverter(Mapper mapper) { } @Override - public void marshal( - Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { SortedMap sortedMap = (SortedMap) source; marshalComparator(mapper(), sortedMap.comparator(), writer, context); super.marshal(source, writer, context); } protected static void marshalComparator( - Mapper mapper, - Comparator comparator, - HierarchicalStreamWriter writer, - MarshallingContext context) { + Mapper mapper, Comparator comparator, HierarchicalStreamWriter writer, MarshallingContext context) { if (comparator != null) { writer.startNode("comparator"); - writer.addAttribute( - mapper.aliasForSystemAttribute("class"), - mapper.serializedClass(comparator.getClass())); + writer.addAttribute(mapper.aliasForSystemAttribute("class"), mapper.serializedClass(comparator.getClass())); context.convertAnother(comparator); writer.endNode(); } @@ -94,8 +88,7 @@ protected static void marshalComparator( public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { TreeMap result = null; @SuppressWarnings("unchecked") - final Comparator comparator = - unmarshalComparator(mapper(), reader, context, result); + final Comparator comparator = unmarshalComparator(mapper(), reader, context, result); if (result == null) { result = comparator == null ? new TreeMap<>() : new TreeMap<>(comparator); } @@ -104,10 +97,7 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co } protected static Comparator unmarshalComparator( - Mapper mapper, - HierarchicalStreamReader reader, - UnmarshallingContext context, - TreeMap result) { + Mapper mapper, HierarchicalStreamReader reader, UnmarshallingContext context, TreeMap result) { final Comparator comparator; if (reader.hasMoreChildren()) { reader.moveDown(); @@ -128,17 +118,13 @@ protected static Comparator unmarshalComparator( } protected void populateTreeMap( - HierarchicalStreamReader reader, - UnmarshallingContext context, - TreeMap result, - Comparator comparator) { + HierarchicalStreamReader reader, UnmarshallingContext context, TreeMap result, Comparator comparator) { boolean inFirstElement = comparator == NULL_MARKER; if (inFirstElement) { comparator = null; } SortedMap sortedMap = - new PresortedMap( - comparator != null && JVM.hasOptimizedTreeMapPutAll() ? comparator : null); + new PresortedMap(comparator != null && JVM.hasOptimizedTreeMapPutAll() ? comparator : null); if (inFirstElement) { // we are already within the first entry putCurrentEntryIntoMap(reader, context, result, sortedMap); diff --git a/geowebcache/core/src/main/java/org/geowebcache/io/TreeSetConverter.java b/geowebcache/core/src/main/java/org/geowebcache/io/TreeSetConverter.java index 2cdc4a5913..01f858873e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/io/TreeSetConverter.java +++ b/geowebcache/core/src/main/java/org/geowebcache/io/TreeSetConverter.java @@ -54,8 +54,7 @@ public TreeSetConverter(Mapper mapper) { } @Override - public void marshal( - Object source, HierarchicalStreamWriter writer, MarshallingContext context) { + public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { SortedSet sortedSet = (SortedSet) source; TreeMapConverter.marshalComparator(mapper(), sortedSet.comparator(), writer, context); super.marshal(source, writer, context); diff --git a/geowebcache/core/src/main/java/org/geowebcache/io/XMLBuilder.java b/geowebcache/core/src/main/java/org/geowebcache/io/XMLBuilder.java index d44714909e..db6da0db78 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/io/XMLBuilder.java +++ b/geowebcache/core/src/main/java/org/geowebcache/io/XMLBuilder.java @@ -152,8 +152,7 @@ public XMLBuilder endElement(@Nullable String name) throws IOException { * * @throws IOException thrown if the underlying Appendable throws IOException */ - public XMLBuilder simpleElement(String name, @Nullable String text, boolean indent) - throws IOException { + public XMLBuilder simpleElement(String name, @Nullable String text, boolean indent) throws IOException { return startElement(name, indent).text(text).endElement(); } @@ -232,8 +231,7 @@ public XMLBuilder bboxAttributes(T minx, T miny, T maxx, T maxy) throws IOEx } /** Add a BoundingBox element */ - public XMLBuilder boundingBox(@Nullable String srs, T minx, T miny, T maxx, T maxy) - throws IOException { + public XMLBuilder boundingBox(@Nullable String srs, T minx, T miny, T maxx, T maxy) throws IOException { indentElement("BoundingBox"); if (srs != null) attribute("SRS", srs); bboxAttributes(minx, miny, maxx, maxy); diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java b/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java index edc5a026df..fcae5f94b1 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java @@ -49,7 +49,8 @@ public abstract class AbstractTileLayer extends TileLayer { private static final int[] DEFAULT_METATILING_FACTORS = {1, 1}; - @Nullable protected String blobStoreId; + @Nullable + protected String blobStoreId; protected Boolean enabled; diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/MetaTile.java b/geowebcache/core/src/main/java/org/geowebcache/layer/MetaTile.java index 3ea06a896b..3379475ee6 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/MetaTile.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/MetaTile.java @@ -140,9 +140,7 @@ public MetaTile( this.metaY = metaY; this.gutterConfig = responseFormat.isVector() || gutter == null ? 0 : gutter.intValue(); - metaGridCov = - calculateMetaTileGridBounds( - gridSubset.getCoverage((int) tileGridPosition[2]), tileGridPosition); + metaGridCov = calculateMetaTileGridBounds(gridSubset.getCoverage((int) tileGridPosition[2]), tileGridPosition); tilesGridPositions = calculateTilesGridPositions(); calculateEdgeGutter(); int tileHeight = gridSubset.getTileHeight(); @@ -259,21 +257,15 @@ public void setImageBytes(Resource buffer) throws GeoWebCacheException { try { // ImageIO.read closes the stream, and the stream throws exception on second close call @SuppressWarnings("PMD.CloseResource") - ImageInputStream imgStream = - new ResourceImageInputStream(((ByteArrayResource) buffer).getInputStream()); + ImageInputStream imgStream = new ResourceImageInputStream(((ByteArrayResource) buffer).getInputStream()); RenderedImage metaTiledImage = ImageIO.read(imgStream); // read closes the stream for us setImage(metaTiledImage); } catch (IOException ioe) { throw new GeoWebCacheException( - "WMSMetaTile.setImageBytes() " - + "failed on ImageIO.read(byte[" - + buffer.getSize() - + "])", - ioe); + "WMSMetaTile.setImageBytes() " + "failed on ImageIO.read(byte[" + buffer.getSize() + "])", ioe); } if (metaTileImage == null) { - throw new GeoWebCacheException( - "ImageIO.read(InputStream) returned null. Unable to read image."); + throw new GeoWebCacheException("ImageIO.read(InputStream) returned null. Unable to read image."); } } @@ -313,26 +305,23 @@ private Rectangle[] createTiles(int tileHeight, int tileWidth) { * @param tileHeight height of the tile * @return a rendered image of the specified meta tile region */ - public RenderedImage createTile( - final int minX, final int minY, final int tileWidth, final int tileHeight) { + public RenderedImage createTile(final int minX, final int minY, final int tileWidth, final int tileHeight) { // optimize if we get a bufferedimage if (metaTileImage instanceof BufferedImage) { - BufferedImage subimage = - ((BufferedImage) metaTileImage).getSubimage(minX, minY, tileWidth, tileHeight); + BufferedImage subimage = ((BufferedImage) metaTileImage).getSubimage(minX, minY, tileWidth, tileHeight); return new BufferedImageAdapter(subimage); } // do a crop, and then turn it into a buffered image so that we can release // the image chain - PlanarImage cropped = - CropDescriptor.create( - metaTileImage, - Float.valueOf(minX), - Float.valueOf(minY), - Float.valueOf(tileWidth), - Float.valueOf(tileHeight), - NO_CACHE); + PlanarImage cropped = CropDescriptor.create( + metaTileImage, + Float.valueOf(minX), + Float.valueOf(minY), + Float.valueOf(tileWidth), + Float.valueOf(tileHeight), + NO_CACHE); if (nativeAccelAvailable()) { log.finer("created cropped tile"); return cropped; @@ -364,8 +353,7 @@ public boolean writeTileToStream(final int tileIdx, Resource target) throws IOEx } Rectangle tileRegion = tiles[tileIdx]; - RenderedImage tile = - createTile(tileRegion.x, tileRegion.y, tileRegion.width, tileRegion.height); + RenderedImage tile = createTile(tileRegion.x, tileRegion.y, tileRegion.width, tileRegion.height); disposeLater(tile); // TODO should we recycle the writers ? @@ -398,12 +386,7 @@ protected void disposeLater(RenderedImage tile) { } public String debugString() { - return " metaX: " - + metaX - + " metaY: " - + metaY - + " metaGridCov: " - + Arrays.toString(metaGridCov); + return " metaX: " + metaX + " metaY: " + metaY + " metaGridCov: " + Arrays.toString(metaGridCov); } /** diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java index dc069bff5e..9ba085523c 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java @@ -153,16 +153,14 @@ public abstract ConveyorTile getTile(ConveyorTile tile) public abstract ConveyorTile getNoncachedTile(ConveyorTile tile) throws GeoWebCacheException; /** */ - public abstract void seedTile(ConveyorTile tile, boolean tryCache) - throws GeoWebCacheException, IOException; + public abstract void seedTile(ConveyorTile tile, boolean tryCache) throws GeoWebCacheException, IOException; /** * This is a more direct way of requesting a tile without invoking metatiling, and should not be * used in general. The method was exposed to let the KML service traverse the tree ahead of the * client, to avoid linking to empty tiles. */ - public abstract ConveyorTile doNonMetatilingRequest(ConveyorTile tile) - throws GeoWebCacheException; + public abstract ConveyorTile doNonMetatilingRequest(ConveyorTile tile) throws GeoWebCacheException; public abstract List getFormatModifiers(); @@ -279,16 +277,13 @@ public boolean supportsFormat(String strFormat) throws GeoWebCacheException { } // REVISIT: why not simply return false if this is a query method?! - throw new GeoWebCacheException( - "Format " + strFormat + " is not supported by " + this.getName()); + throw new GeoWebCacheException("Format " + strFormat + " is not supported by " + this.getName()); } /** GetFeatureInfo template, throws exception, subclasses must override if supported. */ - public Resource getFeatureInfo( - ConveyorTile convTile, BoundingBox bbox, int height, int width, int x, int y) + public Resource getFeatureInfo(ConveyorTile convTile, BoundingBox bbox, int height, int width, int x, int y) throws GeoWebCacheException { - throw new GeoWebCacheException( - "GetFeatureInfo is not supported by this layer (" + getName() + ")"); + throw new GeoWebCacheException("GetFeatureInfo is not supported by this layer (" + getName() + ")"); } /** @return the resolutions (units/pixel) for the layer */ @@ -328,8 +323,7 @@ public MimeType getDefaultMimeType() { * Converts the given bounding box into the closest location on the grid supported by the * reference system. */ - public long[] indexFromBounds(String gridSetId, BoundingBox tileBounds) - throws GridMismatchException { + public long[] indexFromBounds(String gridSetId, BoundingBox tileBounds) throws GridMismatchException { return getGridSubset(gridSetId).closestIndex(tileBounds); } @@ -418,8 +412,7 @@ public Map getModifiableParameters(Map map, String en final String[] keys = parameterFilters.stream().map(ParameterFilter::getKey).toArray(i -> new String[i]); - final Map requestValues = - ServletUtils.selectedStringsFromMap(map, encoding, keys); + final Map requestValues = ServletUtils.selectedStringsFromMap(map, encoding, keys); final Map defaultValues = getDefaultParameterFilters(); @@ -429,9 +422,7 @@ public Map getModifiableParameters(Map map, String en value = decodeDimensionValue(value); String defaultValue = defaultValues.get(key); - if (value == null - || value.length() == 0 - || (defaultValue != null && defaultValue.equals(value))) { + if (value == null || value.length() == 0 || (defaultValue != null && defaultValue.equals(value))) { fullParameters.put(key, defaultValue); } else { String appliedValue = parameterFilter.apply(value); @@ -489,8 +480,7 @@ protected ByteArrayResource getImageBuffer(ThreadLocal tl) { } /** Loops over the gridPositions, generates cache keys and saves to cache */ - protected void saveTiles(MetaTile metaTile, ConveyorTile tileProto, long requestTime) - throws GeoWebCacheException { + protected void saveTiles(MetaTile metaTile, ConveyorTile tileProto, long requestTime) throws GeoWebCacheException { final long[][] gridPositions = metaTile.getTilesGridPositions(); final long[] gridLoc = tileProto.getTileIndex(); @@ -523,21 +513,18 @@ protected void saveTiles(MetaTile metaTile, ConveyorTile tileProto, long request try { boolean completed = metaTile.writeTileToStream(i, resource); if (!completed) { - log.log( - Level.SEVERE, - "metaTile.writeTileToStream returned false, no tiles saved"); + log.log(Level.SEVERE, "metaTile.writeTileToStream returned false, no tiles saved"); } if (store) { long[] idx = {gridPos[0], gridPos[1], gridPos[2]}; - TileObject tile = - TileObject.createCompleteTileObject( - this.getName(), - idx, - tileProto.getGridSetId(), - tileProto.getMimeType().getFormat(), - tileProto.getParameters(), - resource); + TileObject tile = TileObject.createCompleteTileObject( + this.getName(), + idx, + tileProto.getGridSetId(), + tileProto.getMimeType().getFormat(), + tileProto.getParameters(), + resource); tile.setCreated(requestTime); try { @@ -552,10 +539,7 @@ protected void saveTiles(MetaTile metaTile, ConveyorTile tileProto, long request } } } catch (IOException ioe) { - log.log( - Level.SEVERE, - "Unable to write image tile to " + "ByteArrayOutputStream", - ioe); + log.log(Level.SEVERE, "Unable to write image tile to " + "ByteArrayOutputStream", ioe); } } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayerDispatcher.java b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayerDispatcher.java index df82f2e3f6..89efbf049f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayerDispatcher.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayerDispatcher.java @@ -81,8 +81,7 @@ public TileLayerDispatcher( this.tileLayerDispatcherFilter = tileLayerDispatcherFilter; } - public TileLayerDispatcher( - GridSetBroker gridSetBroker, TileLayerDispatcherFilter tileLayerDispatcherFilter) { + public TileLayerDispatcher(GridSetBroker gridSetBroker, TileLayerDispatcherFilter tileLayerDispatcherFilter) { this.gridSetBroker = gridSetBroker; this.tileLayerDispatcherFilter = tileLayerDispatcherFilter; } @@ -111,13 +110,12 @@ public TileLayer getTileLayer(final String layerName) throws GeoWebCacheExceptio return layer.get(); } } - throw new GeoWebCacheException( - "Thread " - + Thread.currentThread().getName() - + " Unknown layer " - + layerName - + ". Check the logfiles," - + " it may not have loaded properly."); + throw new GeoWebCacheException("Thread " + + Thread.currentThread().getName() + + " Unknown layer " + + layerName + + ". Check the logfiles," + + " it may not have loaded properly."); } public int getLayerCount() { @@ -165,9 +163,8 @@ public Iterable getLayerList() { public Iterable getLayerListFiltered() { Iterable result = getLayerList(); if (tileLayerDispatcherFilter != null) { - Stream s = - StreamSupport.stream(result.spliterator(), false) - .filter(x -> !tileLayerDispatcherFilter.exclude(x)); + Stream s = StreamSupport.stream(result.spliterator(), false) + .filter(x -> !tileLayerDispatcherFilter.exclude(x)); result = s::iterator; } return result; @@ -249,20 +246,17 @@ public TileLayerConfiguration getConfiguration(TileLayer tl) throws IllegalArgum return getConfiguration(tl.getName()); } - public TileLayerConfiguration getConfiguration(final String tileLayerName) - throws IllegalArgumentException { + public TileLayerConfiguration getConfiguration(final String tileLayerName) throws IllegalArgumentException { Assert.notNull(tileLayerName, "tileLayerName is null"); for (TileLayerConfiguration c : configs) { if (c.containsLayer(tileLayerName)) { return c; } } - throw new IllegalArgumentException( - "No configuration found containing layer " + tileLayerName); + throw new IllegalArgumentException("No configuration found containing layer " + tileLayerName); } - public synchronized void addGridSet(final GridSet gridSet) - throws IllegalArgumentException, IOException { + public synchronized void addGridSet(final GridSet gridSet) throws IllegalArgumentException, IOException { if (null != gridSetBroker.get(gridSet.getName())) { throw new IllegalArgumentException("GridSet " + gridSet.getName() + " already exists"); } @@ -276,8 +270,7 @@ private void saveGridSet(final GridSet gridSet) throws IOException { 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"); + throw new IllegalStateException("Can not remove gridset " + gridsetToRemove + " as it is used by layers"); } gridSetBroker.removeGridSet(gridsetToRemove); } @@ -292,10 +285,8 @@ public synchronized void removeGridSetRecursive(String gridsetToRemove) { } } } catch (NoSuchElementException e) { - IllegalStateException wrappedException = - new IllegalStateException( - "Layer was found referencing gridset but was missing during recursive delete", - e); + IllegalStateException wrappedException = new IllegalStateException( + "Layer was found referencing gridset but was missing during recursive delete", e); try { deletedLayers.forEach(this::addLayer); } catch (RuntimeException exceptionOnRestore) { @@ -322,26 +313,19 @@ public List getConfigurations(Cl if (clazz == TileLayerConfiguration.class) { return (List) Collections.unmodifiableList(configs); } else { - return configs.stream() - .filter(clazz::isInstance) - .map(clazz::cast) - .collect(Collectors.toList()); + return configs.stream().filter(clazz::isInstance).map(clazz::cast).collect(Collectors.toList()); } } @Override public void afterPropertiesSet() throws Exception { - this.configs = - GeoWebCacheExtensions.configurations( - TileLayerConfiguration.class, applicationContext); + this.configs = GeoWebCacheExtensions.configurations(TileLayerConfiguration.class, applicationContext); - Map config = - applicationContext.getBeansOfType(BaseConfiguration.class); + Map config = applicationContext.getBeansOfType(BaseConfiguration.class); if (config != null && !config.isEmpty()) { for (Entry e : config.entrySet()) { if (ServerConfiguration.class.isAssignableFrom(e.getValue().getClass())) { - setServiceInformation( - ((ServerConfiguration) e.getValue()).getServiceInformation()); + setServiceInformation(((ServerConfiguration) e.getValue()).getServiceInformation()); } } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/meta/LayerMetaInformation.java b/geowebcache/core/src/main/java/org/geowebcache/layer/meta/LayerMetaInformation.java index 454e12fec6..a322aa9fce 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/meta/LayerMetaInformation.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/meta/LayerMetaInformation.java @@ -31,10 +31,7 @@ public class LayerMetaInformation { } public LayerMetaInformation( - String title, - String description, - List keywords, - List contacts) { + String title, String description, List keywords, List contacts) { this.title = title; this.description = description; this.keywords = keywords; diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSHttpHelper.java b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSHttpHelper.java index 782c9bad21..3fc8f6c344 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSHttpHelper.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSHttpHelper.java @@ -79,14 +79,8 @@ HttpClient getHttpClient() { return client; } - HttpClientBuilder builder = - new HttpClientBuilder( - null, - getBackendTimeout(), - httpUsername, - httpPassword, - proxyUrl, - getConcurrency()); + HttpClientBuilder builder = new HttpClientBuilder( + null, getBackendTimeout(), httpUsername, httpPassword, proxyUrl, getConcurrency()); client = builder.buildClient(); } @@ -118,8 +112,7 @@ protected void makeRequest( try { wmsBackendUrl = URLs.of(requestUrl); } catch (MalformedURLException maue) { - throw new GeoWebCacheException( - "Malformed URL: " + requestUrl + " " + maue.getMessage()); + throw new GeoWebCacheException("Malformed URL: " + requestUrl + " " + maue.getMessage()); } try { connectAndCheckHeaders( @@ -142,13 +135,10 @@ protected void makeRequest( if (fetchException != null) { msg += " Reason: " + fetchException.getMessage() + ". "; } - msg += - " Last request: '" - + wmsBackendUrl.toString() - + "'. " - + (tileRespRecv.getErrorMessage() == null - ? "" - : tileRespRecv.getErrorMessage()); + msg += " Last request: '" + + wmsBackendUrl.toString() + + "'. " + + (tileRespRecv.getErrorMessage() == null ? "" : tileRespRecv.getErrorMessage()); tileRespRecv.setError(); tileRespRecv.setErrorMessage(msg); @@ -176,16 +166,15 @@ private void connectAndCheckHeaders( responseCode = method.getStatusLine().getStatusCode(); if (responseCode == 200) { if (method.getFirstHeader("length") != null) { - responseLength = Integer.parseInt(method.getFirstHeader("length").getValue()); - } else if (method.getFirstHeader("Content-Length") != null) { responseLength = - Integer.parseInt(method.getFirstHeader("Content-Length").getValue()); + Integer.parseInt(method.getFirstHeader("length").getValue()); + } else if (method.getFirstHeader("Content-Length") != null) { + responseLength = Integer.parseInt( + method.getFirstHeader("Content-Length").getValue()); } else if (method.getEntity() != null) { responseLength = Math.toIntExact(method.getEntity().getContentLength()); } else { - throw new ServiceException( - "Unable to determine response length from: " - + wmsBackendUrl.toString()); + throw new ServiceException("Unable to determine response length from: " + wmsBackendUrl.toString()); } } // Do not set error at this stage @@ -201,17 +190,12 @@ private void connectAndCheckHeaders( if (responseCode != 200 && responseCode != 204) { tileRespRecv.setError(); throw new ServiceException( - "Unexpected response code from backend: " - + responseCode - + " for " - + wmsBackendUrl.toString()); + "Unexpected response code from backend: " + responseCode + " for " + wmsBackendUrl.toString()); } // Check that we're not getting an error MIME back. String responseMime = method.getFirstHeader("Content-Type").getValue(); - if (responseCode != 204 - && responseMime != null - && !requestMimeType.isCompatible(responseMime)) { + if (responseCode != 204 && responseMime != null && !requestMimeType.isCompatible(responseMime)) { String message = null; if (responseMime.equalsIgnoreCase(ErrorMime.vnd_ogc_se_inimage.getFormat())) { // TODO: revisit: I don't understand why it's trying to create a String message @@ -223,22 +207,20 @@ private void connectAndCheckHeaders( } catch (IOException ioe) { // Do nothing } - } else if (responseMime != null - && responseMime.toLowerCase().startsWith("application/vnd.ogc.se_xml")) { + } else if (responseMime != null && responseMime.toLowerCase().startsWith("application/vnd.ogc.se_xml")) { try (InputStream stream = method.getEntity().getContent()) { message = IOUtils.toString(stream, StandardCharsets.UTF_8); } catch (IOException e) { // } } - String msg = - "MimeType mismatch, expected " - + requestMimeType - + " but got " - + responseMime - + " from " - + wmsBackendUrl.toString() - + (message == null ? "" : (":\n" + message)); + String msg = "MimeType mismatch, expected " + + requestMimeType + + " but got " + + responseMime + + " from " + + wmsBackendUrl.toString() + + (message == null ? "" : (":\n" + message)); tileRespRecv.setError(); tileRespRecv.setErrorMessage(msg); log.warning(msg); @@ -267,22 +249,17 @@ private void connectAndCheckHeaders( int readAccu = (int) target.getSize(); if (readAccu != responseLength) { tileRespRecv.setError(); - throw new GeoWebCacheException( - "Responseheader advertised " - + responseLength - + " bytes, but only received " - + readAccu - + " from " - + wmsBackendUrl.toString()); + throw new GeoWebCacheException("Responseheader advertised " + + responseLength + + " bytes, but only received " + + readAccu + + " from " + + wmsBackendUrl.toString()); } } } catch (IOException ioe) { tileRespRecv.setError(); - log.severe( - "Caught IO exception, " - + wmsBackendUrl.toString() - + " " - + ioe.getMessage()); + log.severe("Caught IO exception, " + wmsBackendUrl.toString() + " " + ioe.getMessage()); } } } @@ -346,16 +323,12 @@ public HttpResponse executeRequest( return getHttpClient().execute(method); } - private String processRequestParameters(Map parameters) - throws UnsupportedEncodingException { + private String processRequestParameters(Map parameters) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); for (String parameterName : parameters.keySet()) { sb.append(parameterName) .append('=') - .append( - URLEncoder.encode( - parameters.get(parameterName), - StandardCharsets.UTF_8.toString())) + .append(URLEncoder.encode(parameters.get(parameterName), StandardCharsets.UTF_8.toString())) .append('&'); } return sb.substring(0, sb.length() - 1); diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSLayer.java b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSLayer.java index cae8e4ebb2..bca902a667 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSLayer.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSLayer.java @@ -184,9 +184,8 @@ protected boolean initializeInternal(GridSetBroker gridSetBroker) { } if (null == this.sourceHelper) { - log.config( - this.name - + " is configured without a source, which is a bug unless you're running tests that don't care."); + log.config(this.name + + " is configured without a source, which is a bug unless you're running tests that don't care."); } curWmsURL = 0; @@ -234,8 +233,7 @@ protected boolean initializeInternal(GridSetBroker gridSetBroker) { } @Override - public Resource getFeatureInfo( - ConveyorTile convTile, BoundingBox bbox, int height, int width, int x, int y) + public Resource getFeatureInfo(ConveyorTile convTile, BoundingBox bbox, int height, int width, int x, int y) throws GeoWebCacheException { return sourceHelper.makeFeatureInfoRequest(convTile, bbox, height, width, x, y); } @@ -252,8 +250,7 @@ public Resource getFeatureInfo( * @return The resulting tile request */ @Override - public ConveyorTile getTile(ConveyorTile tile) - throws GeoWebCacheException, IOException, OutsideCoverageException { + public ConveyorTile getTile(ConveyorTile tile) throws GeoWebCacheException, IOException, OutsideCoverageException { MimeType mime = tile.getMimeType(); if (mime == null) { @@ -261,8 +258,7 @@ public ConveyorTile getTile(ConveyorTile tile) } if (!formats.contains(mime)) { - throw new GeoWebCacheException( - mime.getFormat() + " is not a supported format for " + name); + throw new GeoWebCacheException(mime.getFormat() + " is not a supported format for " + name); } String tileGridSetId = tile.getGridSetId(); @@ -295,12 +291,10 @@ public ConveyorTile getTile(ConveyorTile tile) /** Used for seeding */ @Override - public void seedTile(ConveyorTile tile, boolean tryCache) - throws GeoWebCacheException, IOException { + public void seedTile(ConveyorTile tile, boolean tryCache) throws GeoWebCacheException, IOException { GridSubset gridSubset = getGridSubset(tile.getGridSetId()); if (gridSubset.shouldCacheAtZoom(tile.getTileIndex()[2])) { - if (tile.getMimeType().supportsTiling() - && (metaWidthHeight[0] > 1 || metaWidthHeight[1] > 1)) { + if (tile.getMimeType().supportsTiling() && (metaWidthHeight[0] > 1 || metaWidthHeight[1] > 1)) { getMetatilingReponse(tile, tryCache); } else { getNonMetatilingReponse(tile, tryCache); @@ -314,8 +308,7 @@ public void seedTile(ConveyorTile tile, boolean tryCache) * @param tile the Tile with all the information * @param tryCache whether to try the cache, or seed */ - private ConveyorTile getMetatilingReponse(ConveyorTile tile, boolean tryCache) - throws GeoWebCacheException { + private ConveyorTile getMetatilingReponse(ConveyorTile tile, boolean tryCache) throws GeoWebCacheException { // int idx = this.getSRSIndex(tile.getSRS()); long[] gridLoc = tile.getTileIndex(); @@ -329,16 +322,15 @@ private ConveyorTile getMetatilingReponse(ConveyorTile tile, boolean tryCache) if (filteringParameters.isEmpty()) { filteringParameters = getDefaultParameterFilters(); } - WMSMetaTile metaTile = - new WMSMetaTile( - this, - gridSubset, - mimeType, - this.getFormatModifier(tile.getMimeType()), - gridLoc, - metaWidthHeight[0], - metaWidthHeight[1], - filteringParameters); + WMSMetaTile metaTile = new WMSMetaTile( + this, + gridSubset, + mimeType, + this.getFormatModifier(tile.getMimeType()), + gridLoc, + metaWidthHeight[0], + metaWidthHeight[1], + filteringParameters); // Leave a hint to save expiration, if necessary if (saveExpirationHeaders) { @@ -372,8 +364,7 @@ private ConveyorTile getMetatilingReponse(ConveyorTile tile, boolean tryCache) sourceHelper.makeRequest(metaTile, buffer); if (metaTile.getError()) { - throw new GeoWebCacheException( - "Empty metatile, error message: " + metaTile.getErrorMessage()); + throw new GeoWebCacheException("Empty metatile, error message: " + metaTile.getErrorMessage()); } if (saveExpirationHeaders) { @@ -427,8 +418,7 @@ private String buildLockKey(ConveyorTile tile, WMSMetaTile metaTile) { * @param tile the Tile with all the information * @param tryCache whether to try the cache, or seed */ - private ConveyorTile getNonMetatilingReponse(ConveyorTile tile, boolean tryCache) - throws GeoWebCacheException { + private ConveyorTile getNonMetatilingReponse(ConveyorTile tile, boolean tryCache) throws GeoWebCacheException { // String debugHeadersStr = null; long[] gridLoc = tile.getTileIndex(); @@ -453,8 +443,7 @@ private ConveyorTile getNonMetatilingReponse(ConveyorTile tile, boolean tryCache tile = doNonMetatilingRequest(tile); - if (tile.getStatus() > 299 - || this.getExpireCache((int) gridLoc[2]) != GWCVars.CACHE_DISABLE_CACHE) { + if (tile.getStatus() > 299 || this.getExpireCache((int) gridLoc[2]) != GWCVars.CACHE_DISABLE_CACHE) { tile.persist(); } @@ -653,8 +642,7 @@ protected String nextWmsURL() { return wmsUrl[curWmsURL]; } - public long[][] getZoomedInGridLoc(String gridSetId, long[] gridLoc) - throws GeoWebCacheException { + public long[][] getZoomedInGridLoc(String gridSetId, long[] gridLoc) throws GeoWebCacheException { return null; } @@ -811,13 +799,11 @@ public void proxyRequest(ConveyorTile tile) throws GeoWebCacheException { WMSSourceHelper helper = getSourceHelper(); if (!(helper instanceof WMSHttpHelper)) { - throw new GeoWebCacheException( - "Can only proxy if WMS Layer is backed by an HTTP backend"); + throw new GeoWebCacheException("Can only proxy if WMS Layer is backed by an HTTP backend"); } httpResponse = - ((WMSHttpHelper) helper) - .executeRequest(url, null, getBackendTimeout(), getHttpRequestMode()); + ((WMSHttpHelper) helper).executeRequest(url, null, getBackendTimeout(), getHttpRequestMode()); HttpEntity entity = httpResponse.getEntity(); try (InputStream is = entity.getContent()) { HttpServletResponse response = tile.servletResp; @@ -859,8 +845,7 @@ public Map getLayerLegendsInf String layerName = wmsLayers == null ? getName() : wmsLayers; return legends == null ? super.getLayerLegendsInfo() - : legends.getLegendsInfo( - layerName, wmsUrl != null && wmsUrl.length > 0 ? wmsUrl[0] : null); + : legends.getLegendsInfo(layerName, wmsUrl != null && wmsUrl.length > 0 ? wmsUrl[0] : null); } /** diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSMetaTile.java b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSMetaTile.java index 7a19e1970c..a71540e4c0 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSMetaTile.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSMetaTile.java @@ -51,8 +51,7 @@ protected WMSMetaTile( } protected Map getWMSParams() throws GeoWebCacheException { - Map params = - wmsLayer.getWMSRequestTemplate(this.getResponseFormat(), WMSLayer.RequestType.MAP); + Map params = wmsLayer.getWMSRequestTemplate(this.getResponseFormat(), WMSLayer.RequestType.MAP); // Fill in the blanks String format; diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSSourceHelper.java b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSSourceHelper.java index 922f17c255..48fcd47f47 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSSourceHelper.java +++ b/geowebcache/core/src/main/java/org/geowebcache/layer/wms/WMSSourceHelper.java @@ -58,8 +58,7 @@ public void makeRequest(ConveyorTile tile, Resource target) throws GeoWebCacheEx GridSubset gridSubset = layer.getGridSubset(tile.getGridSetId()); - Map wmsParams = - layer.getWMSRequestTemplate(tile.getMimeType(), WMSLayer.RequestType.MAP); + Map wmsParams = layer.getWMSRequestTemplate(tile.getMimeType(), WMSLayer.RequestType.MAP); wmsParams.put("FORMAT", tile.getMimeType().getFormat()); wmsParams.put("SRS", layer.backendSRSOverride(gridSubset.getSRS())); @@ -88,8 +87,7 @@ public void makeRequest(ConveyorTile tile, Resource target) throws GeoWebCacheEx makeRequest(tile, layer, wmsParams, mimeType, target); } - public Resource makeFeatureInfoRequest( - ConveyorTile tile, BoundingBox bbox, int height, int width, int x, int y) + public Resource makeFeatureInfoRequest(ConveyorTile tile, BoundingBox bbox, int height, int width, int x, int y) throws GeoWebCacheException { WMSLayer layer = (WMSLayer) tile.getLayer(); @@ -117,11 +115,8 @@ public Resource makeFeatureInfoRequest( String featureCount; { - Map values = - ServletUtils.selectedStringsFromMap( - tile.servletReq.getParameterMap(), - tile.servletReq.getCharacterEncoding(), - "feature_count"); + Map values = ServletUtils.selectedStringsFromMap( + tile.servletReq.getParameterMap(), tile.servletReq.getCharacterEncoding(), "feature_count"); featureCount = values.get("feature_count"); } if (featureCount != null) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/locks/MemoryLockProvider.java b/geowebcache/core/src/main/java/org/geowebcache/locks/MemoryLockProvider.java index d3d15e248d..416914480d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/locks/MemoryLockProvider.java +++ b/geowebcache/core/src/main/java/org/geowebcache/locks/MemoryLockProvider.java @@ -63,16 +63,13 @@ public Lock getLock(String lockKey) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Acquiring lock key " + lockKey); // Atomically create a new LockAndCounter, or increment the existing one - LockAndCounter lockAndCounter = - lockAndCounters.compute( - lockKey, - (key, internalLockAndCounter) -> { - if (internalLockAndCounter == null) { - internalLockAndCounter = new LockAndCounter(); - } - internalLockAndCounter.counter.incrementAndGet(); - return internalLockAndCounter; - }); + LockAndCounter lockAndCounter = lockAndCounters.compute(lockKey, (key, internalLockAndCounter) -> { + if (internalLockAndCounter == null) { + internalLockAndCounter = new LockAndCounter(); + } + internalLockAndCounter.counter.incrementAndGet(); + return internalLockAndCounter; + }); lockAndCounter.lock.lock(); @@ -97,15 +94,12 @@ public void release() { // "compute" // so that we know it hasn't been incremented since the if-statement above // was evaluated - lockAndCounters.compute( - lockKey, - (key, existingLockAndCounter) -> { - if (existingLockAndCounter == null - || existingLockAndCounter.counter.get() == 0) { - return null; - } - return existingLockAndCounter; - }); + lockAndCounters.compute(lockKey, (key, existingLockAndCounter) -> { + if (existingLockAndCounter == null || existingLockAndCounter.counter.get() == 0) { + return null; + } + return existingLockAndCounter; + }); } if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Released lock key " + lockKey); diff --git a/geowebcache/core/src/main/java/org/geowebcache/locks/NIOLockProvider.java b/geowebcache/core/src/main/java/org/geowebcache/locks/NIOLockProvider.java index cdedf4aa7f..e556512587 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/locks/NIOLockProvider.java +++ b/geowebcache/core/src/main/java/org/geowebcache/locks/NIOLockProvider.java @@ -51,8 +51,7 @@ public NIOLockProvider(DefaultStorageFinder storageFinder) throws ConfigurationE this(storageFinder.getDefaultPath()); } - public NIOLockProvider( - DefaultStorageFinder storageFinder, int waitBeforeRetry, int maxLockAttempts) + public NIOLockProvider(DefaultStorageFinder storageFinder, int waitBeforeRetry, int maxLockAttempts) throws ConfigurationException { this.root = storageFinder.getDefaultPath(); this.waitBeforeRetry = waitBeforeRetry; @@ -103,21 +102,16 @@ public LockProvider.Lock getLock(final String lockKey) throws GeoWebCacheExcepti // verify we managed to get the FS lock if (count >= maxLockAttempts) { throw new GeoWebCacheException( - "Failed to get a lock on key " - + lockKey - + " after " - + count - + " attempts"); + "Failed to get a lock on key " + lockKey + " after " + count + " attempts"); } if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.fine( - "Lock " - + lockKey - + " acquired by thread " - + Thread.currentThread().getName() - + " on file " - + file); + LOGGER.fine("Lock " + + lockKey + + " acquired by thread " + + Thread.currentThread().getName() + + " on file " + + file); } // store the results in a final variable for the inner class to use @@ -164,18 +158,16 @@ public void release() throws GeoWebCacheException { lockFile.delete(); if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.fine( - "Lock " - + lockKey - + " on file " - + lockFile - + " released by thread " - + Thread.currentThread().getName()); + LOGGER.fine("Lock " + + lockKey + + " on file " + + lockFile + + " released by thread " + + Thread.currentThread().getName()); } } catch (IOException e) { throw new GeoWebCacheException( - "Failure while trying to release lock for key " + lockKey, - e); + "Failure while trying to release lock for key " + lockKey, e); } } finally { memoryLock.release(); @@ -194,8 +186,7 @@ public void release() throws GeoWebCacheException { } } } catch (IOException e) { - throw new GeoWebCacheException( - "Failure while trying to get lock for key " + lockKey, e); + throw new GeoWebCacheException("Failure while trying to get lock for key " + lockKey, e); } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/mime/ApplicationMime.java b/geowebcache/core/src/main/java/org/geowebcache/mime/ApplicationMime.java index b282c1abef..6a3779605f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/mime/ApplicationMime.java +++ b/geowebcache/core/src/main/java/org/geowebcache/mime/ApplicationMime.java @@ -23,8 +23,7 @@ public class ApplicationMime extends MimeType { - public static final String MAPBOX_TILES_LEGACY_MIME = - "application/x-protobuf;type=mapbox-vector"; + public static final String MAPBOX_TILES_LEGACY_MIME = "application/x-protobuf;type=mapbox-vector"; protected boolean vector; @@ -38,61 +37,37 @@ public class ApplicationMime extends MimeType { new ApplicationMime("application/json", "json", "json", "application/json", false); public static final ApplicationMime topojson = - new ApplicationMime( - "application/json", - "topojson", - "topojson", - "application/json;type=topojson", - true); + new ApplicationMime("application/json", "topojson", "topojson", "application/json;type=topojson", true); public static final ApplicationMime geojson = - new ApplicationMime( - "application/json", - "geojson", - "geojson", - "application/json;type=geojson", - true); + new ApplicationMime("application/json", "geojson", "geojson", "application/json;type=geojson", true); public static final ApplicationMime utfgrid = - new ApplicationMime( - "application/json", - "utfgrid", - "utfgrid", - "application/json;type=utfgrid", - true); - - public static final ApplicationMime mapboxVector = - new ApplicationMime( - "application/vnd.mapbox-vector-tile", - "pbf", - "mapbox-vectortile", - "application/vnd.mapbox-vector-tile", - true); - - static Set ALL = - ImmutableSet.of(bil16, bil32, json, topojson, geojson, utfgrid, mapboxVector); + new ApplicationMime("application/json", "utfgrid", "utfgrid", "application/json;type=utfgrid", true); + + public static final ApplicationMime mapboxVector = new ApplicationMime( + "application/vnd.mapbox-vector-tile", + "pbf", + "mapbox-vectortile", + "application/vnd.mapbox-vector-tile", + true); + + static Set ALL = ImmutableSet.of(bil16, bil32, json, topojson, geojson, utfgrid, mapboxVector); private static final List BINARY_FORMATS = Arrays.asList(bil16.mimeType, bil32.mimeType, mapboxVector.mimeType, utfgrid.mimeType); - private static Map BY_FORMAT = - Maps.uniqueIndex(ALL, mimeType -> mimeType.getFormat()); + private static Map BY_FORMAT = Maps.uniqueIndex(ALL, mimeType -> mimeType.getFormat()); private static Map BY_EXTENSION = Maps.uniqueIndex(ALL, mimeType -> mimeType.getFileExtension()); - private ApplicationMime( - String mimeType, - String fileExtension, - String internalName, - String format, - boolean vector) { + private ApplicationMime(String mimeType, String fileExtension, String internalName, String format, boolean vector) { super(mimeType, fileExtension, internalName, format, false); this.vector = vector; } - public ApplicationMime( - String mimeType, String fileExtension, String internalName, String format) + public ApplicationMime(String mimeType, String fileExtension, String internalName, String format) throws MimeException { super(mimeType, fileExtension, internalName, format, false); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/mime/ErrorMime.java b/geowebcache/core/src/main/java/org/geowebcache/mime/ErrorMime.java index d7a43937f5..8b902b6c95 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/mime/ErrorMime.java +++ b/geowebcache/core/src/main/java/org/geowebcache/mime/ErrorMime.java @@ -21,15 +21,13 @@ public class ErrorMime extends MimeType { private static Logger log = Logging.getLogger(ErrorMime.class.getName()); - public static final ErrorMime vnd_ogc_se_inimage = - new ErrorMime("application/vnd.ogc.se_inimage"); + public static final ErrorMime vnd_ogc_se_inimage = new ErrorMime("application/vnd.ogc.se_inimage"); private ErrorMime(String mimeType) { super(mimeType, null, null, mimeType, false); } - public ErrorMime(String mimeType, String fileExtension, String internalName, String format) - throws MimeException { + public ErrorMime(String mimeType, String fileExtension, String internalName, String format) throws MimeException { super(mimeType, fileExtension, internalName, format, false); // Check for trouble @@ -44,9 +42,7 @@ public static ErrorMime createFromMimeType(String mimeType) throws MimeException } else { log.log( Level.SEVERE, - "Unsupported MIME type: " - + mimeType - + ", falling back to application/vnd.ogc.se_inimage."); + "Unsupported MIME type: " + mimeType + ", falling back to application/vnd.ogc.se_inimage."); return vnd_ogc_se_inimage; } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/mime/ImageMime.java b/geowebcache/core/src/main/java/org/geowebcache/mime/ImageMime.java index 790b23af8f..479056e622 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/mime/ImageMime.java +++ b/geowebcache/core/src/main/java/org/geowebcache/mime/ImageMime.java @@ -51,103 +51,76 @@ public class ImageMime extends MimeType { JAIExt.initJAIEXT(false, false); } - public static final ImageMime png = - new ImageMime("image/png", "png", "png", "image/png", true, true, true) { - - /** Any response mime starting with image/png will do */ - @Override - public boolean isCompatible(String otherMimeType) { - return super.isCompatible(otherMimeType) - || otherMimeType.startsWith("image/png"); + public static final ImageMime png = new ImageMime("image/png", "png", "png", "image/png", true, true, true) { + + /** Any response mime starting with image/png will do */ + @Override + public boolean isCompatible(String otherMimeType) { + return super.isCompatible(otherMimeType) || otherMimeType.startsWith("image/png"); + } + }; + + public static final ImageMime jpeg = new ImageMime("image/jpeg", "jpeg", "jpeg", "image/jpeg", true, false, false) { + + /** Shave off the alpha band, JPEG cannot write it out */ + @Override + public RenderedImage preprocess(RenderedImage ri) { + if (ri.getColorModel().hasAlpha()) { + final int numBands = ri.getSampleModel().getNumBands(); + // handle both gray-alpha and RGBA (same code as in GeoTools ImageWorker) + final int[] bands = new int[numBands - 1]; + for (int i = 0; i < bands.length; i++) { + bands[i] = i; } - }; - - public static final ImageMime jpeg = - new ImageMime("image/jpeg", "jpeg", "jpeg", "image/jpeg", true, false, false) { - - /** Shave off the alpha band, JPEG cannot write it out */ - @Override - public RenderedImage preprocess(RenderedImage ri) { - if (ri.getColorModel().hasAlpha()) { - final int numBands = ri.getSampleModel().getNumBands(); - // handle both gray-alpha and RGBA (same code as in GeoTools ImageWorker) - final int[] bands = new int[numBands - 1]; - for (int i = 0; i < bands.length; i++) { - bands[i] = i; - } - // ParameterBlock creation + // ParameterBlock creation + ParameterBlock pb = new ParameterBlock(); + pb.setSource(ri, 0); + pb.set(bands, 0); + final RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, new ImageLayout(ri)); + ri = JAI.create("BandSelect", pb, hints); + } + return ri; + } + }; + + public static final ImageMime gif = new ImageMime("image/gif", "gif", "gif", "image/gif", true, false, true); + + public static final ImageMime tiff = new ImageMime("image/tiff", "tiff", "tiff", "image/tiff", true, true, true); + + public static final ImageMime png8 = new ImageMime("image/png", "png8", "png", "image/png8", true, false, true) { + + /** Quantize if the source did not do so already */ + @Override + public RenderedImage preprocess(RenderedImage canvas) { + if (!(canvas.getColorModel() instanceof IndexColorModel)) { + if (canvas.getColorModel() instanceof ComponentColorModel + && canvas.getSampleModel().getDataType() == DataBuffer.TYPE_BYTE) { + ColorIndexer indexer = new Quantizer(256).subsample().buildColorIndexer(canvas); + if (indexer != null) { ParameterBlock pb = new ParameterBlock(); - pb.setSource(ri, 0); - pb.set(bands, 0); - final RenderingHints hints = - new RenderingHints(JAI.KEY_IMAGE_LAYOUT, new ImageLayout(ri)); - ri = JAI.create("BandSelect", pb, hints); + pb.setSource(canvas, 0); // The source image. + pb.set(indexer, 0); + canvas = JAI.create( + "ColorIndexer", pb, JAI.getDefaultInstance().getRenderingHints()); } - return ri; } - }; - - public static final ImageMime gif = - new ImageMime("image/gif", "gif", "gif", "image/gif", true, false, true); - - public static final ImageMime tiff = - new ImageMime("image/tiff", "tiff", "tiff", "image/tiff", true, true, true); - - public static final ImageMime png8 = - new ImageMime("image/png", "png8", "png", "image/png8", true, false, true) { - - /** Quantize if the source did not do so already */ - @Override - public RenderedImage preprocess(RenderedImage canvas) { - if (!(canvas.getColorModel() instanceof IndexColorModel)) { - if (canvas.getColorModel() instanceof ComponentColorModel - && canvas.getSampleModel().getDataType() == DataBuffer.TYPE_BYTE) { - ColorIndexer indexer = - new Quantizer(256).subsample().buildColorIndexer(canvas); - if (indexer != null) { - ParameterBlock pb = new ParameterBlock(); - pb.setSource(canvas, 0); // The source image. - pb.set(indexer, 0); - canvas = - JAI.create( - "ColorIndexer", - pb, - JAI.getDefaultInstance().getRenderingHints()); - } - } - } - return canvas; - } - }; + } + return canvas; + } + }; - public static final ImageMime png24 = - new ImageMime("image/png", "png24", "png", "image/png24", true, true, true); + public static final ImageMime png24 = new ImageMime("image/png", "png24", "png", "image/png24", true, true, true); public static final ImageMime png_24 = - new ImageMime( - "image/png; mode=24bit", - "png_24", - "png", - "image/png;%20mode=24bit", - true, - true, - true); - - public static final ImageMime dds = - new ImageMime("image/dds", "dds", "dds", "image/dds", false, false, false); + new ImageMime("image/png; mode=24bit", "png_24", "png", "image/png;%20mode=24bit", true, true, true); + + public static final ImageMime dds = new ImageMime("image/dds", "dds", "dds", "image/dds", false, false, false); public static final ImageMime jpegPng = - new JpegPngMime( - "image/vnd.jpeg-png", "jpeg-png", "jpeg-png", "image/vnd.jpeg-png", jpeg, png); + new JpegPngMime("image/vnd.jpeg-png", "jpeg-png", "jpeg-png", "image/vnd.jpeg-png", jpeg, png); public static final ImageMime jpegPng8 = - new JpegPngMime( - "image/vnd.jpeg-png8", - "jpeg-png8", - "jpeg-png8", - "image/vnd.jpeg-png8", - jpeg, - png8); + new JpegPngMime("image/vnd.jpeg-png8", "jpeg-png8", "jpeg-png8", "image/vnd.jpeg-png8", jpeg, png8); private ImageMime( String mimeType, @@ -204,8 +177,7 @@ protected static ImageMime checkForFormat(String formatStr) throws MimeException protected static ImageMime checkForExtension(String fileExtension) throws MimeException { if (fileExtension.equalsIgnoreCase("png")) { return png; - } else if (fileExtension.equalsIgnoreCase("jpeg") - || fileExtension.equalsIgnoreCase("jpg")) { + } else if (fileExtension.equalsIgnoreCase("jpeg") || fileExtension.equalsIgnoreCase("jpg")) { return jpeg; } else if (fileExtension.equalsIgnoreCase("gif")) { return gif; @@ -250,9 +222,7 @@ public ImageWriter getImageWriter(RenderedImage image) { || this.internalName.equals(ImageMime.png8.internalName)) { int bitDepth = image.getSampleModel().getSampleSize(0); - if (bitDepth > 1 - && bitDepth < 8 - && writer.getClass().getName().equals(NATIVE_PNG_WRITER_CLASS_NAME)) { + if (bitDepth > 1 && bitDepth < 8 && writer.getClass().getName().equals(NATIVE_PNG_WRITER_CLASS_NAME)) { writer = it.next(); } @@ -292,15 +262,14 @@ public JpegPngMime( boolean isBestFormatJpeg(RenderedImage renderedImage) { int numBands = renderedImage.getSampleModel().getNumBands(); if (numBands == 4 || numBands == 2) { - RenderedOp extremaOp = - ExtremaDescriptor.create( - renderedImage, - null, - 1, - 1, - false, - 1, - JAI.getDefaultInstance().getRenderingHints()); + RenderedOp extremaOp = ExtremaDescriptor.create( + renderedImage, + null, + 1, + 1, + false, + 1, + JAI.getDefaultInstance().getRenderingHints()); double[][] extrema = (double[][]) extremaOp.getProperty("Extrema"); double[] mins = extrema[0]; @@ -340,8 +309,7 @@ public String getMimeType(org.geowebcache.io.Resource resource) throws IOExcepti @Override public boolean isCompatible(String otherMimeType) { - return jpegDelegate.isCompatible(otherMimeType) - || pngDelegate.isCompatible(otherMimeType); + return jpegDelegate.isCompatible(otherMimeType) || pngDelegate.isCompatible(otherMimeType); } @Override diff --git a/geowebcache/core/src/main/java/org/geowebcache/mime/MimeType.java b/geowebcache/core/src/main/java/org/geowebcache/mime/MimeType.java index c3a30a81f5..fc8a40d88c 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/mime/MimeType.java +++ b/geowebcache/core/src/main/java/org/geowebcache/mime/MimeType.java @@ -33,11 +33,7 @@ public class MimeType { private static Logger log = Logging.getLogger(MimeType.class.getName()); protected MimeType( - String mimeType, - String fileExtension, - String internalName, - String format, - boolean supportsTiling) { + String mimeType, String fileExtension, String internalName, String format, boolean supportsTiling) { this.mimeType = mimeType; this.fileExtension = fileExtension; this.internalName = internalName; @@ -194,8 +190,7 @@ public int hashCode() { */ public boolean isCompatible(String otherMimeType) { return mimeType.equalsIgnoreCase(otherMimeType) - || (otherMimeType != null - && otherMimeType.toLowerCase().startsWith(mimeType.toLowerCase())); + || (otherMimeType != null && otherMimeType.toLowerCase().startsWith(mimeType.toLowerCase())); } @Override diff --git a/geowebcache/core/src/main/java/org/geowebcache/mime/TextMime.java b/geowebcache/core/src/main/java/org/geowebcache/mime/TextMime.java index 579fa13c1c..a05d17b3c6 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/mime/TextMime.java +++ b/geowebcache/core/src/main/java/org/geowebcache/mime/TextMime.java @@ -18,25 +18,17 @@ public class TextMime extends MimeType { public static final TextMime txt = new TextMime("text/plain", "txt", "txt", "text/plain", true); - public static final TextMime txtHtml = - new TextMime("text/html", "txt.html", "html", "text/html", true); + public static final TextMime txtHtml = new TextMime("text/html", "txt.html", "html", "text/html", true); - public static final TextMime txtMapml = - new TextMime("text/mapml", "mapml", "mapml", "text/mapml", true); + public static final TextMime txtMapml = new TextMime("text/mapml", "mapml", "mapml", "text/mapml", true); public static final TextMime txtXml = new TextMime("text/xml", "xml", "xml", "text/xml", true); public static final TextMime txtCss = new TextMime("text/css", "css", "css", "text/css", true); - public static final TextMime txtJs = - new TextMime("text/javascript", "js", "javascript", "text/javascript", true); + public static final TextMime txtJs = new TextMime("text/javascript", "js", "javascript", "text/javascript", true); - private TextMime( - String mimeType, - String fileExtension, - String internalName, - String format, - boolean noop) { + private TextMime(String mimeType, String fileExtension, String internalName, String format, boolean noop) { super(mimeType, fileExtension, internalName, format, false); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/mime/XMLMime.java b/geowebcache/core/src/main/java/org/geowebcache/mime/XMLMime.java index b208a39f69..72b5847073 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/mime/XMLMime.java +++ b/geowebcache/core/src/main/java/org/geowebcache/mime/XMLMime.java @@ -17,46 +17,21 @@ public class XMLMime extends MimeType { public static final XMLMime ogcxml = - new XMLMime( - "application/vnd.ogc.se_xml", - "ogc-xml", - "ogc-xml", - "application/vnd.ogc.se_xml", - false); + new XMLMime("application/vnd.ogc.se_xml", "ogc-xml", "ogc-xml", "application/vnd.ogc.se_xml", false); - public static final XMLMime kml = - new XMLMime( - "application/vnd.google-earth.kml+xml", - "kml", - "kml", - "application/vnd.google-earth.kml+xml", - false); + public static final XMLMime kml = new XMLMime( + "application/vnd.google-earth.kml+xml", "kml", "kml", "application/vnd.google-earth.kml+xml", false); public static final XMLMime kmz = - new XMLMime( - "application/vnd.google-earth.kmz", - "kmz", - "kmz", - "application/vnd.google-earth.kmz", - false); + new XMLMime("application/vnd.google-earth.kmz", "kmz", "kmz", "application/vnd.google-earth.kmz", false); public static final XMLMime gml = new XMLMime("application/vnd.ogc.gml", "gml", "gml", "application/vnd.ogc.gml", false); public static final XMLMime gml3 = - new XMLMime( - "application/vnd.ogc.gml/3.1.1", - "gml3", - "gml3", - "application/vnd.ogc.gml/3.1.1", - false); + new XMLMime("application/vnd.ogc.gml/3.1.1", "gml3", "gml3", "application/vnd.ogc.gml/3.1.1", false); - private XMLMime( - String mimeType, - String fileExtension, - String internalName, - String format, - boolean noop) { + private XMLMime(String mimeType, String fileExtension, String internalName, String format, boolean noop) { super(mimeType, fileExtension, internalName, format, false); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/proxy/ProxyDispatcher.java b/geowebcache/core/src/main/java/org/geowebcache/proxy/ProxyDispatcher.java index 000d385e1a..d5190140bb 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/proxy/ProxyDispatcher.java +++ b/geowebcache/core/src/main/java/org/geowebcache/proxy/ProxyDispatcher.java @@ -32,8 +32,8 @@ public class ProxyDispatcher extends AbstractController { private static long lastRequest = System.currentTimeMillis(); @Override - protected ModelAndView handleRequestInternal( - HttpServletRequest request, HttpServletResponse response) throws Exception { + protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) + throws Exception { String methStr = request.getMethod(); if (!methStr.equalsIgnoreCase("POST")) { diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/GWCTask.java b/geowebcache/core/src/main/java/org/geowebcache/seed/GWCTask.java index e8a29535b2..d02eee4d78 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/GWCTask.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/GWCTask.java @@ -80,14 +80,8 @@ public final void doAction() throws GeoWebCacheException, InterruptedException { dispose(); int membersRemaining = this.sharedThreadCount.decrementAndGet(); if (0 == membersRemaining) { - double groupTotalTimeSecs = - (System.currentTimeMillis() - (double) groupStartTime) / 1000; - log.info( - "Thread group finished " - + parsedType - + " task after " - + groupTotalTimeSecs - + " seconds"); + double groupTotalTimeSecs = (System.currentTimeMillis() - (double) groupStartTime) / 1000; + log.info("Thread group finished " + parsedType + " task after " + groupTotalTimeSecs + " seconds"); } } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/MassTruncateRequest.java b/geowebcache/core/src/main/java/org/geowebcache/seed/MassTruncateRequest.java index 4f69c8b099..169d834d5d 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/MassTruncateRequest.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/MassTruncateRequest.java @@ -34,8 +34,7 @@ public interface MassTruncateRequest { * @param breeder The tile breeder storing information about the affected layers * @return {@literal true} if successful, {@literal false} otherwise */ - public boolean doTruncate(StorageBroker sb, TileBreeder breeder) - throws StorageException, GeoWebCacheException; + public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws StorageException, GeoWebCacheException; public default ResponseEntity getResponse(String contentType) { return new ResponseEntity<>(HttpStatus.OK); diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/SeedRequest.java b/geowebcache/core/src/main/java/org/geowebcache/seed/SeedRequest.java index eb223ad436..9607c7e18f 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/SeedRequest.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/SeedRequest.java @@ -42,8 +42,7 @@ public class SeedRequest { private String format = null; - private String type = - null; // TODO: This appears to do nothing as it is never changed from being null + private String type = null; // TODO: This appears to do nothing as it is never changed from being null private TYPE enumType = null; diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/SeedTask.java b/geowebcache/core/src/main/java/org/geowebcache/seed/SeedTask.java index 9a52a447a6..b74fa624d7 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/SeedTask.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/SeedTask.java @@ -56,15 +56,11 @@ class SeedTask extends GWCTask { private AtomicLong sharedFailureCounter; - @VisibleForTesting Sleeper sleeper = Thread::sleep; + @VisibleForTesting + Sleeper sleeper = Thread::sleep; /** Constructs a SeedTask */ - public SeedTask( - StorageBroker sb, - TileRangeIterator trIter, - TileLayer tl, - boolean reseed, - boolean doFilterUpdate) { + public SeedTask(StorageBroker sb, TileRangeIterator trIter, TileLayer tl, boolean reseed, boolean doFilterUpdate) { this.storageBroker = sb; this.trIter = trIter; this.tl = tl; @@ -122,16 +118,8 @@ protected void doActionInternal() throws GeoWebCacheException, InterruptedExcept checkInterrupted(); Map fullParameters = tr.getParameters(); - ConveyorTile tile = - new ConveyorTile( - storageBroker, - layerName, - tr.getGridSetId(), - gridLoc, - tr.getMimeType(), - fullParameters, - null, - null); + ConveyorTile tile = new ConveyorTile( + storageBroker, layerName, tr.getGridSetId(), gridLoc, tr.getMimeType(), fullParameters, null, null); for (int fetchAttempt = 0; fetchAttempt <= tileFailureRetryCount || tileFailureRetryCount < 0; @@ -152,27 +140,24 @@ protected void doActionInternal() throws GeoWebCacheException, InterruptedExcept long sharedFailureCount = sharedFailureCounter.incrementAndGet(); if (sharedFailureCount >= totalFailuresBeforeAborting) { - log.info( - "Aborting seed thread " - + getThreadName() - + ". Error count reached configured maximum of " - + totalFailuresBeforeAborting); + log.info("Aborting seed thread " + + getThreadName() + + ". Error count reached configured maximum of " + + totalFailuresBeforeAborting); super.state = GWCTask.STATE.DEAD; return; } - String logMsg = - "Seed failed at " - + tile.toString() - + " after " - + (fetchAttempt + 1) - + " of " - + (tileFailureRetryCount + 1) - + " attempts."; + String logMsg = "Seed failed at " + + tile.toString() + + " after " + + (fetchAttempt + 1) + + " of " + + (tileFailureRetryCount + 1) + + " attempts."; if (fetchAttempt < tileFailureRetryCount) { log.fine(logMsg); if (tileFailureRetryWaitTime > 0) { - log.finer( - "Waiting " + tileFailureRetryWaitTime + " before trying again"); + log.finer("Waiting " + tileFailureRetryWaitTime + " before trying again"); waitToRetry(); } } else { @@ -194,8 +179,7 @@ protected void doActionInternal() throws GeoWebCacheException, InterruptedExcept // note: computing the # of tiles processed by this thread instead of by the whole group // also reduces thread contention as the trIter methods are synchronized and profiler // shows 16 threads block on synchronization about 40% the time - final long tilesCompletedByThisThread = - seedCalls * metaTilingFactorX * metaTilingFactorY; + final long tilesCompletedByThisThread = seedCalls * metaTilingFactorX * metaTilingFactorY; updateStatusInfo(tl, tilesCompletedByThisThread, START_TIME); @@ -205,22 +189,16 @@ protected void doActionInternal() throws GeoWebCacheException, InterruptedExcept } if (this.terminate) { - log.info( - "Job on " - + getThreadName() - + " was terminated after " - + this.tilesDone - + " tiles"); + log.info("Job on " + getThreadName() + " was terminated after " + this.tilesDone + " tiles"); } else { - log.info( - getThreadName() - + " completed (re)seeding layer " - + layerName - + " after " - + this.tilesDone - + " tiles and " - + this.timeSpent - + " seconds."); + log.info(getThreadName() + + " completed (re)seeding layer " + + layerName + + " after " + + this.tilesDone + + " tiles and " + + this.timeSpent + + " seconds."); } checkInterrupted(); @@ -232,8 +210,7 @@ protected void doActionInternal() throws GeoWebCacheException, InterruptedExcept } private void reprioritize() { - Thread.currentThread() - .setPriority((java.lang.Thread.NORM_PRIORITY + java.lang.Thread.MIN_PRIORITY) / 2); + Thread.currentThread().setPriority((java.lang.Thread.NORM_PRIORITY + java.lang.Thread.MIN_PRIORITY) / 2); } private void waitToRetry() throws InterruptedException { @@ -303,8 +280,7 @@ private void runFilterUpdates(String gridSetId) { if (reqFilter.update(tl, gridSetId)) { log.info("Updated request filter " + reqFilter.getName()); } else { - log.fine( - "Request filter " + reqFilter.getName() + " returned false on update."); + log.fine("Request filter " + reqFilter.getName() + " returned false on update."); } } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/TileBreeder.java b/geowebcache/core/src/main/java/org/geowebcache/seed/TileBreeder.java index 3ddbaef203..38771ce48e 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/TileBreeder.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/TileBreeder.java @@ -173,10 +173,9 @@ public void setApplicationContext(ApplicationContext applicationContext) throws @SuppressWarnings("serial") private void checkPositive(long value, String variable) { if (value < 0) { - throw new BeanInitializationException( - "Invalid configuration value for environment variable " - + variable - + ". It should be a positive integer.") {}; + throw new BeanInitializationException("Invalid configuration value for environment variable " + + variable + + ". It should be a positive integer.") {}; } } @@ -187,13 +186,12 @@ private long toLong(String varName, String paramVal, long defaultVal) { try { return Long.valueOf(paramVal); } catch (NumberFormatException e) { - log.warning( - "Invalid environment parameter for " - + varName - + ": '" - + paramVal - + "'. Using default value: " - + defaultVal); + log.warning("Invalid environment parameter for " + + varName + + ": '" + + paramVal + + "'. Using default value: " + + defaultVal); } return defaultVal; } @@ -207,8 +205,7 @@ public void seed(final String layerName, final SeedRequest sr) throws GeoWebCach TileRange tr = createTileRange(sr, tl); - GWCTask[] tasks = - createTasks(tr, tl, sr.getType(), sr.getThreadCount(), sr.getFilterUpdate()); + GWCTask[] tasks = createTasks(tr, tl, sr.getType(), sr.getThreadCount(), sr.getFilterUpdate()); dispatchTasks(tasks); } @@ -223,8 +220,7 @@ public void seed(final String layerName, final SeedRequest sr) throws GeoWebCach * @param filterUpdate // TODO: What does this do? * @return Array of tasks. Will have length threadCount or 1. */ - public GWCTask[] createTasks( - TileRange tr, GWCTask.TYPE type, int threadCount, boolean filterUpdate) + public GWCTask[] createTasks(TileRange tr, GWCTask.TYPE type, int threadCount, boolean filterUpdate) throws GeoWebCacheException { String layerName = tr.getLayerName(); @@ -232,8 +228,7 @@ public GWCTask[] createTasks( return createTasks(tr, tileLayer, type, threadCount, filterUpdate); } - public GWCTask[] createTasks( - TileRange tr, TileLayer tl, GWCTask.TYPE type, int threadCount, boolean filterUpdate) + public GWCTask[] createTasks(TileRange tr, TileLayer tl, GWCTask.TYPE type, int threadCount, boolean filterUpdate) throws GeoWebCacheException { return createTasks( tr, @@ -289,10 +284,7 @@ public GWCTask[] createTasks( } else { SeedTask task = (SeedTask) createSeedTask(type, trIter, tl, filterUpdate); task.setFailurePolicy( - tileFailureRetryCount, - tileFailureRetryWaitTime, - totalFailuresBeforeAborting, - failureCounter); + tileFailureRetryCount, tileFailureRetryWaitTime, totalFailuresBeforeAborting, failureCounter); tasks[i] = task; } tasks[i].setThreadInfo(sharedThreadCount, i); @@ -323,8 +315,7 @@ public void dispatchTasks(GWCTask[] tasks) { } /** Find the tile range for a Seed Request. */ - public static TileRange createTileRange(SeedRequest req, TileLayer tl) - throws GeoWebCacheException { + public static TileRange createTileRange(SeedRequest req, TileLayer tl) throws GeoWebCacheException { int zoomStart = req.getZoomStart().intValue(); int zoomStop = req.getZoomStop().intValue(); @@ -349,10 +340,9 @@ public static TileRange createTileRange(SeedRequest req, TileLayer tl) if (crsMatches.size() == 1) { gridSetId = crsMatches.get(0).getName(); } else { - throw new IllegalArgumentException( - "More than one GridSubet matches the requested SRS " - + srs - + ". gridSetId must be specified"); + throw new IllegalArgumentException("More than one GridSubet matches the requested SRS " + + srs + + ". gridSetId must be specified"); } } } @@ -381,8 +371,7 @@ public static TileRange createTileRange(SeedRequest req, TileLayer tl) String layerName = tl.getName(); Map parameters = req.getParameters(); - return new TileRange( - layerName, gridSetId, zoomStart, zoomStop, coveredGridLevels, mimeType, parameters); + return new TileRange(layerName, gridSetId, zoomStart, zoomStop, coveredGridLevels, mimeType, parameters); } /** @@ -392,8 +381,7 @@ public static TileRange createTileRange(SeedRequest req, TileLayer tl) * @param trIter a collection of tile ranges * @param tl the layer */ - private GWCTask createSeedTask( - TYPE type, TileRangeIterator trIter, TileLayer tl, boolean doFilterUpdate) + private GWCTask createSeedTask(TYPE type, TileRangeIterator trIter, TileLayer tl, boolean doFilterUpdate) throws IllegalArgumentException { switch (type) { @@ -406,8 +394,7 @@ private GWCTask createSeedTask( } } - private GWCTask createTruncateTask( - TileRangeIterator trIter, TileLayer tl, boolean doFilterUpdate) { + private GWCTask createTruncateTask(TileRangeIterator trIter, TileLayer tl, boolean doFilterUpdate) { return new TruncateTask(storageBroker, trIter.getTileRange(), tl, doFilterUpdate); } @@ -484,7 +471,8 @@ private void drain() { try { dispatchesWithoutDrain = 0; threadPool.purge(); - for (Iterator> it = this.currentPool.entrySet().iterator(); + for (Iterator> it = + this.currentPool.entrySet().iterator(); it.hasNext(); ) { if (it.next().getValue().future.isDone()) { it.remove(); diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateAllRequest.java b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateAllRequest.java index b11c579f78..8a10a66179 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateAllRequest.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateAllRequest.java @@ -37,11 +37,11 @@ public class TruncateAllRequest implements MassTruncateRequest, Serializable { private static final Logger log = Logging.getLogger(TruncateAllRequest.class.getName()); - @XStreamOmitField private StringBuilder trucatedLayers = new StringBuilder(); + @XStreamOmitField + private StringBuilder trucatedLayers = new StringBuilder(); @Override - public boolean doTruncate(StorageBroker sb, TileBreeder breeder) - throws StorageException, GeoWebCacheException { + public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws StorageException, GeoWebCacheException { Iterator iterator = breeder.getLayers().iterator(); TileLayer toTruncate; Iterator gridSetIterator; @@ -87,17 +87,15 @@ public String getTrucatedLayersList() { private StringBuilder getResponsePage() { StringBuilder doc = new StringBuilder(); - String content = - "

Truncated All Layers

\n" - + "

Truncated Layers:" - + getTrucatedLayersList().toString() - + "

"; + String content = "

Truncated All Layers

\n" + + "

Truncated Layers:" + + getTrucatedLayersList().toString() + + "

"; - doc.append( - "\n" - + ServletUtils.gwcHtmlHeader("../", "GWC Seed Form") - + "\n" - + ServletUtils.gwcHtmlLogoLink("../")); + doc.append("\n" + + ServletUtils.gwcHtmlHeader("../", "GWC Seed Form") + + "\n" + + ServletUtils.gwcHtmlLogoLink("../")); doc.append("

" + content + "

"); doc.append("

Go back

"); return doc; diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateBboxRequest.java b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateBboxRequest.java index 2504c47c2d..e86797806c 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateBboxRequest.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateBboxRequest.java @@ -51,8 +51,7 @@ public TruncateBboxRequest(String layerName, BoundingBox bounds, String gridSetI } @Override - public boolean doTruncate(StorageBroker sb, TileBreeder breeder) - throws StorageException, GeoWebCacheException { + public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws StorageException, GeoWebCacheException { final Set> allParams = sb.getCachedParameters(layerName); final TileLayer tileLayer = breeder.findTileLayer(layerName); final Collection allFormats = tileLayer.getMimeTypes(); @@ -60,40 +59,32 @@ public boolean doTruncate(StorageBroker sb, TileBreeder breeder) final int minZ = Optional.fromNullable(subSet.getMinCachedZoom()).or(subSet.getZoomStart()); final int maxZ = Optional.fromNullable(subSet.getMaxCachedZoom()).or(subSet.getZoomStop()); // Create seed request for each combination of params and format - Function, Stream> seedRequestMapper = - params -> - allFormats.stream() - .map( - format -> - new SeedRequest( - layerName, - bounds, - gridSetId, - 1, - minZ, - maxZ, - format.getMimeType(), - GWCTask.TYPE.TRUNCATE, - params)); + Function, Stream> seedRequestMapper = params -> allFormats.stream() + .map(format -> new SeedRequest( + layerName, + bounds, + gridSetId, + 1, + minZ, + maxZ, + format.getMimeType(), + GWCTask.TYPE.TRUNCATE, + params)); try { - int taskCount = - Stream.concat( - allParams.stream(), - Stream.of( - (Map) - null)) // Add null for the default parameters - .flatMap(seedRequestMapper) - .map( - request -> { - try { - breeder.seed(layerName, request); - return 1; - } catch (GeoWebCacheException e) { - throw new UncheckedGeoWebCacheException(e); - } - }) - .reduce((x, y) -> x + y) - .orElse(0); + int taskCount = Stream.concat( + allParams.stream(), + Stream.of((Map) null)) // Add null for the default parameters + .flatMap(seedRequestMapper) + .map(request -> { + try { + breeder.seed(layerName, request); + return 1; + } catch (GeoWebCacheException e) { + throw new UncheckedGeoWebCacheException(e); + } + }) + .reduce((x, y) -> x + y) + .orElse(0); return taskCount > 0; } catch (UncheckedGeoWebCacheException e) { throw e.getCause(); diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateOrphansRequest.java b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateOrphansRequest.java index fc96faba06..5b2f04af25 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateOrphansRequest.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateOrphansRequest.java @@ -31,8 +31,7 @@ public class TruncateOrphansRequest implements MassTruncateRequest { String layerName; @Override - public boolean doTruncate(StorageBroker sb, TileBreeder breeder) - throws GeoWebCacheException, StorageException { + public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws GeoWebCacheException, StorageException { final TileLayer layer = breeder.findTileLayer(layerName); return sb.purgeOrphans(layer); } diff --git a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateTask.java b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateTask.java index 0e76d2acdc..d9db329d59 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateTask.java +++ b/geowebcache/core/src/main/java/org/geowebcache/seed/TruncateTask.java @@ -79,9 +79,7 @@ private void runFilterUpdates() { if (reqFilter.update(tl, tr.getGridSetId())) { log.log(Level.FINE, "Updated request filter " + reqFilter.getName()); } else { - log.log( - Level.FINE, - "Request filter " + reqFilter.getName() + " returned false on update."); + log.log(Level.FINE, "Request filter " + reqFilter.getName() + " returned false on update."); } } } diff --git a/geowebcache/core/src/main/java/org/geowebcache/service/OWSException.java b/geowebcache/core/src/main/java/org/geowebcache/service/OWSException.java index 948b3b2943..456ff5e90c 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/service/OWSException.java +++ b/geowebcache/core/src/main/java/org/geowebcache/service/OWSException.java @@ -56,12 +56,7 @@ public String toString() { str.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"); str.append( " xsi:schemaLocation=\"http://www.opengis.net/ows/1.1 http://geowebcache.org/schema/ows/1.1.0/owsExceptionReport.xsd\">\n"); - str.append( - " \n"); + str.append(" \n"); str.append(" " + exceptionText + "\n"); str.append(" \n"); str.append("\n"); diff --git a/geowebcache/core/src/main/java/org/geowebcache/service/Service.java b/geowebcache/core/src/main/java/org/geowebcache/service/Service.java index 8413b0329d..687d441aab 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/service/Service.java +++ b/geowebcache/core/src/main/java/org/geowebcache/service/Service.java @@ -49,25 +49,19 @@ public String getPathName() { // TODO these should be renamed / removed public Conveyor getConveyor(HttpServletRequest request, HttpServletResponse response) throws GeoWebCacheException, OWSException { - throw new ServiceException( - "Service for " - + pathName - + " needs to override " - + "getConveyor(HttpSerlvetRequest,HttpServletResponse)"); + throw new ServiceException("Service for " + + pathName + + " needs to override " + + "getConveyor(HttpSerlvetRequest,HttpServletResponse)"); } public void handleRequest(Conveyor conv) throws GeoWebCacheException, OWSException { throw new RuntimeException( - "Service for " - + pathName - + " needs to override " - + "handleRequest(TileLayerDispatcher, Tile)"); + "Service for " + pathName + " needs to override " + "handleRequest(TileLayerDispatcher, Tile)"); } protected String getLayersParameter(HttpServletRequest request) throws ServiceException { - String layers = - ServletUtils.stringFromMap( - request.getParameterMap(), request.getCharacterEncoding(), "layers"); + String layers = ServletUtils.stringFromMap(request.getParameterMap(), request.getCharacterEncoding(), "layers"); if (layers == null) { throw new ServiceException("Unable to parse layers parameter from request."); } @@ -96,10 +90,7 @@ protected static void writeTileResponse(ConveyorTile conv, boolean writeExpirati } protected static void writeTileResponse( - ConveyorTile conv, - boolean writeExpiration, - RuntimeStats stats, - String mimeTypeOverride) { + ConveyorTile conv, boolean writeExpiration, RuntimeStats stats, String mimeTypeOverride) { HttpServletResponse response = conv.servletResp; Resource data = conv.getBlob(); diff --git a/geowebcache/core/src/main/java/org/geowebcache/stats/RuntimeStats.java b/geowebcache/core/src/main/java/org/geowebcache/stats/RuntimeStats.java index 00f460865b..8822f6aa10 100644 --- a/geowebcache/core/src/main/java/org/geowebcache/stats/RuntimeStats.java +++ b/geowebcache/core/src/main/java/org/geowebcache/stats/RuntimeStats.java @@ -82,8 +82,7 @@ public RuntimeStats(int pollInterval, List intervals, List inte * @param intervalDescs the description for each of the previously defined intervals * @param clock the clock to use to keep track of the time */ - public RuntimeStats( - int pollInterval, List intervals, List intervalDescs, Clock clock) { + public RuntimeStats(int pollInterval, List intervals, List intervalDescs, Clock clock) { this.clock = clock; this.startTime = this.clock.millis(); @@ -103,10 +102,7 @@ public RuntimeStats( if (curVal % pollInterval != 0) { log.log( Level.SEVERE, - "The interval (" - + curVal - + ") must be a multiple of the poll interval " - + pollInterval); + "The interval (" + curVal + ") must be a multiple of the poll interval " + pollInterval); curVal = curVal - (curVal % pollInterval); } this.intervals[i] = curVal; @@ -177,16 +173,11 @@ public String getHTMLStats() { if (runningTime > 0) { str.append("
Started:"); - str.append( - ServletUtils.formatTimestamp(this.startTime) - + " (" - + formatTimeDiff(runningTime) - + ") "); + str.append(ServletUtils.formatTimestamp(this.startTime) + " (" + formatTimeDiff(runningTime) + ") "); str.append("
Total number of requests:" - + totalRequests); + str.append("
Total number of requests:" + + totalRequests); str.append(" (" + totalRequests / (runningTime) + "/s ) "); str.append("
Total number of bytes:" - + totalBytes); + str.append("
Total number of bytes:" + + totalBytes); str.append(" (" + formatBits((totalBytes * 8.0) / (runningTime)) + ") "); str.append("
Cache hit ratio:"); + str.append("
Cache hit ratio:"); if (totalHits + totalMisses > 0) { double hitPercentage = (totalHits * 100.0) / (totalHits + totalMisses); int rounded = (int) Math.round(hitPercentage * 100.0); @@ -225,18 +214,13 @@ public String getHTMLStats() { str.append("
Blank/KML/HTML:"); + str.append("
Blank/KML/HTML:"); 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 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"); @@ -249,8 +233,7 @@ public String getHTMLStats() { str.append("
Peak request rate:"); + str.append("
Peak request rate:"); if (totalRequests > 0) { str.append(formatRequests((peakRequests * 1.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); @@ -259,8 +242,7 @@ public String getHTMLStats() { } str.append("
Peak bandwidth:"); + str.append("
Peak bandwidth:"); if (totalRequests > 0) { str.append(formatBits((peakBytes * 8.0) / pollInterval)); str.append(" (" + ServletUtils.formatTimestamp(peakRequestsTime) + ") "); @@ -284,31 +266,28 @@ public String getHTMLStats() { String[] bits = calculateBits(intervals[i]); - str.append( - "
" - + intervalDescs[i] - + "" - + requests[0] - + "" - + requests[1] - + "" - + bits[0] - + "" - + bits[1] - + "" - + "
" + + intervalDescs[i] + + "" + + requests[0] + + "" + + requests[1] + + "" + + bits[0] + + "" + + bits[1] + + "" + + "
All figures are " - + pollInterval - + " second(s) delayed and do not include HTTP overhead
All figures are " + + pollInterval + + " second(s) delayed and do not include HTTP overhead
The cache hit ratio does not account for metatiling
The cache hit ratio does not account for metatiling