Skip to content

Commit

Permalink
Fix PMD errors in core when run with Java 21
Browse files Browse the repository at this point in the history
* `Thread.getId()` is deprecated. Since it's only used for reporting
  errors, use `Thread.getName()` instead
* `new URL(String)` is deprecated. Use `new URI(String).toURL()`
  instead, throwing `MalformedURLException` to preserve the old
  behavior in methods that throw `IOException`. This is centralized in
  the new utility class/method `org.geowebcache.util.URLs.of(String
url)`
* `ExecutorService` implements `AutoCloseable` in Java 21, add
`@SuppressWarnings("PMD.CloseResource")` in the test classes that use it
* Add `@SuppressFBWarnings` for new rules
  • Loading branch information
groldan authored and aaime committed Jan 22, 2024
1 parent 9e9438e commit 9b55d9a
Show file tree
Hide file tree
Showing 27 changed files with 111 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Proxy;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.annotation.Nullable;
import org.geowebcache.storage.StorageException;
import org.geowebcache.util.URLs;
import org.springframework.http.HttpStatus;

class AzureClient implements Closeable {
Expand Down Expand Up @@ -86,7 +86,7 @@ public AzureClient(AzureBlobStoreData configuration) throws StorageException {
PipelineOptions options = new PipelineOptions().withClient(client);
ServiceURL serviceURL =
new ServiceURL(
new URL(getServiceURL(configuration)),
URLs.of(getServiceURL(configuration)),
StorageURL.createPipeline(creds, options));

String containerName = configuration.getContainer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
import org.geowebcache.storage.UnsuitableStorageException;
import org.geowebcache.util.ApplicationContextProvider;
import org.geowebcache.util.ExceptionUtils;
import org.geowebcache.util.URLs;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
Expand Down Expand Up @@ -266,10 +267,10 @@ public void setDefaultValues(TileLayer layer) {
URL proxyUrl = null;
try {
if (getGwcConfig().getProxyUrl() != null) {
proxyUrl = new URL(getGwcConfig().getProxyUrl());
proxyUrl = URLs.of(getGwcConfig().getProxyUrl());
log.fine("Using proxy " + proxyUrl.getHost() + ":" + proxyUrl.getPort());
} else if (wl.getProxyUrl() != null) {
proxyUrl = new URL(wl.getProxyUrl());
proxyUrl = URLs.of(wl.getProxyUrl());
log.fine("Using proxy " + proxyUrl.getHost() + ":" + proxyUrl.getPort());
}
} catch (MalformedURLException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,19 @@
import org.geowebcache.grid.GridSubset;
import org.geowebcache.grid.GridSubsetFactory;
import org.geowebcache.grid.SRS;
import org.geowebcache.util.SuppressFBWarnings;

/**
* This class exists mainly to parse the old XML objects using XStream
*
* <p>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"
}) // field assignment done by XStream
public class XMLOldGrid implements Serializable {

private static final long serialVersionUID = 1413422643636728997L;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.geowebcache.layer.wms.WMSLayer;
import org.geowebcache.mime.ImageMime;
import org.geowebcache.util.ServletUtils;
import org.geowebcache.util.URLs;

public class WMSRasterFilter extends RasterFilter {

Expand Down Expand Up @@ -110,7 +111,7 @@ protected BufferedImage loadMatrix(TileLayer tlayer, String gridSetId, int z)
+ ") , "
+ urlStr);

URL wmsUrl = new URL(urlStr);
URL wmsUrl = URLs.of(urlStr);

if (backendTimeout == null) {
backendTimeout = 120;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public TileLayer getTileLayer(final String layerName) throws GeoWebCacheExceptio
}
throw new GeoWebCacheException(
"Thread "
+ Thread.currentThread().getId()
+ Thread.currentThread().getName()
+ " Unknown layer "
+ layerName
+ ". Check the logfiles,"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import org.geowebcache.util.GWCVars;
import org.geowebcache.util.HttpClientBuilder;
import org.geowebcache.util.ServletUtils;
import org.geowebcache.util.URLs;
import org.springframework.util.Assert;

/** This class is a wrapper for HTTP interaction with WMS backend */
Expand Down Expand Up @@ -115,7 +116,7 @@ protected void makeRequest(
String requestUrl = layer.nextWmsURL();

try {
wmsBackendUrl = new URL(requestUrl);
wmsBackendUrl = URLs.of(requestUrl);
} catch (MalformedURLException maue) {
throw new GeoWebCacheException(
"Malformed URL: " + requestUrl + " " + maue.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import org.geowebcache.mime.MimeType;
import org.geowebcache.mime.XMLMime;
import org.geowebcache.util.GWCVars;
import org.geowebcache.util.URLs;

/** A tile layer backed by a WMS server */
public class WMSLayer extends AbstractTileLayer implements ProxyLayer {
Expand Down Expand Up @@ -803,9 +804,9 @@ public void proxyRequest(ConveyorTile tile) throws GeoWebCacheException {
try {
URL url;
if (serverStr.contains("?")) {
url = new URL(serverStr + "&" + queryStr);
url = URLs.of(serverStr + "&" + queryStr);
} else {
url = new URL(serverStr + queryStr);
url = URLs.of(serverStr + queryStr);
}

WMSSourceHelper helper = getSourceHelper();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public LockProvider.Lock getLock(final String lockKey) throws GeoWebCacheExcepti
"Lock "
+ lockKey
+ " acquired by thread "
+ Thread.currentThread().getId()
+ Thread.currentThread().getName()
+ " on file "
+ file);
}
Expand Down Expand Up @@ -151,7 +151,7 @@ public void release() throws GeoWebCacheException {
+ " for releasing lock is unkonwn, it means "
+ "this lock was never acquired, or was released twice. "
+ "Current thread is: "
+ Thread.currentThread().getId()
+ Thread.currentThread().getName()
+ ". "
+ "Are you running two GWC instances in the same JVM using NIO locks? "
+ "This case is not supported and will generate exactly this error message");
Expand All @@ -170,7 +170,7 @@ public void release() throws GeoWebCacheException {
+ " on file "
+ lockFile
+ " released by thread "
+ Thread.currentThread().getId());
+ Thread.currentThread().getName());
}
} catch (IOException e) {
throw new GeoWebCacheException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.geotools.util.logging.Logging;
import org.geowebcache.util.URLs;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

Expand Down Expand Up @@ -62,7 +63,7 @@ protected ModelAndView handleRequestInternal(
}
String decodedUrl = URLDecoder.decode(urlStr, charEnc);

URL url = new URL(decodedUrl);
URL url = URLs.of(decodedUrl);
HttpURLConnection wmsBackendCon = (HttpURLConnection) url.openConnection();

if (wmsBackendCon.getContentEncoding() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public BlobStoreInfo getBlobStore(final String blobStoreName) throws GeoWebCache
() ->
new GeoWebCacheException(
"Thread "
+ Thread.currentThread().getId()
+ Thread.currentThread().getName()
+ " Unknown blob store "
+ blobStoreName
+ ". Check the logfiles,"
Expand Down
54 changes: 54 additions & 0 deletions geowebcache/core/src/main/java/org/geowebcache/util/URLs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* <p>This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* <p>You should have received a copy of the GNU Lesser General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Gabriel Roldan, Camptocamp, Copyright 2023
*/
package org.geowebcache.util;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/** Utilities for manipulating and converting to and from {@link URL}s. */
public class URLs {

private URLs() {
// private constructor signaling this is a pure-utility class
}

/**
* Creates a {@code URL} object from the {@code String} representation.
*
* <p>Prefer this method to {@code new URL(String)}, which is <a
* href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/net/URL.html#constructor-deprecation">deprecated
* in Java 21</a>.
*
* <p>Note a {@link URISyntaxException} will be rethrown as {@link MalformedURLException} to
* preserve the behavior of code that used to call {@code new URL(String)} and expected either a
* {@code MalformedURLException} or its super type {@code java.io.IOException}.
*
* @param url a URL string to build a {@link URL} from
* @return the URL built from the argument
* @throws MalformedURLException if {code}url{code} is not a valid {@link URI} nor a valid
* {@link URL} as per {@link URI#toURL()}
*/
public static URL of(String url) throws MalformedURLException {
try {
return new URI(url).toURL();
} catch (URISyntaxException orig) {
MalformedURLException e = new MalformedURLException(orig.getMessage());
e.initCause(orig);
throw e;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public void createTestUnit() throws Exception {
private void putLayerMetadataConcurrently(
final int srcStoreKey, final FileBlobStore srcStore, int numberOfThreads)
throws InterruptedException {
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
Expand All @@ -75,6 +76,7 @@ private void putLayerMetadataConcurrently(

private void executeStoresConcurrently(int numberOfStores, int numberOfThreads)
throws InterruptedException {
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService service = Executors.newFixedThreadPool(numberOfStores);
CountDownLatch latch = new CountDownLatch(numberOfStores);
for (int i = 0; i < numberOfStores; i++) {
Expand Down Expand Up @@ -106,6 +108,7 @@ public void testMetadataWithPointInKey() throws Exception {
public void testConcurrentMetadataWithPointInKey() throws InterruptedException {
assertThat(store.getLayerMetadata("testLayer", "test.Key"), nullValue());
int numberOfThreads = 2;
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@ public void testConcurrentAdds() throws Exception {
defaultCount + 10,
getInfoNames(config).size());
// get a thread pool
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService pool =
Executors.newFixedThreadPool(
16, (Runnable r) -> new Thread(r, "Info Concurrency Test for ADD"));
Expand Down Expand Up @@ -389,6 +390,7 @@ public void testConcurrentDeletes() throws Exception {
defaultCount + 100,
getInfoNames(config).size());
// get a thread pool
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService pool =
Executors.newFixedThreadPool(
16, (Runnable r) -> new Thread(r, "Info Concurrency Test for DELETE"));
Expand Down Expand Up @@ -431,6 +433,7 @@ public void testConcurrentModifies() throws Exception {
defaultCount + 100,
getInfoNames(config).size());
// get a thread pool
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService pool =
Executors.newFixedThreadPool(
16, (Runnable r) -> new Thread(r, "Info Concurrency Test for MODIFY"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.geowebcache.layer.TileLayer;
import org.geowebcache.layer.wms.WMSHttpHelper;
import org.geowebcache.layer.wms.WMSLayer;
import org.geowebcache.util.URLs;
import org.junit.Test;

public class DefaultingConfigurationTest {
Expand Down Expand Up @@ -111,9 +112,9 @@ public void setDefaultValues(TileLayer layer) {
URL proxyUrl = null;
try {
if (getGwcConfig().getProxyUrl() != null) {
proxyUrl = new URL(getGwcConfig().getProxyUrl());
proxyUrl = URLs.of(getGwcConfig().getProxyUrl());
} else if (wl.getProxyUrl() != null) {
proxyUrl = new URL(wl.getProxyUrl());
proxyUrl = URLs.of(wl.getProxyUrl());
}
} catch (MalformedURLException e) {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,7 @@ private List<ConveyorTile> getTiles(
long[] gridLoc = trIter.nextMetaGridLocation(new long[3]);

// six concurrent requests max
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService requests = Executors.newFixedThreadPool(6);
ExecutorCompletionService<ConveyorTile> completer =
new ExecutorCompletionService<>(requests);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ private long traverseTileRangeIter(
final int[] metaTilingFactors)
throws Exception {

@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
final ExecutorService executorService = Executors.newFixedThreadPool(nThreads);

final TileRange tileRange;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import org.geowebcache.grid.GridSubset;
Expand Down Expand Up @@ -84,7 +83,7 @@ public PageLevelInfo(

@Override
public String toString() {
NumberFormat nf = NumberFormat.getInstance(new Locale("es"));
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(true);

return "Pages: "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import org.geotools.util.logging.Logging;
import org.geowebcache.config.DefaultGridsets;
Expand Down Expand Up @@ -76,7 +75,7 @@ public void testCalculatePageInfo() {
}

private void printPyramid(int zoomStart, int zoomStop, PagePyramid pp) {
NumberFormat nf = NumberFormat.getInstance(new Locale("es"));
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(true);

long totalPages = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import org.geowebcache.storage.DiscontinuousTileRange;
import org.geowebcache.storage.RasterMask;
import org.geowebcache.storage.StorageBroker;
import org.geowebcache.util.URLs;

/**
* A task to run a GeoRSS feed poll and launch the seeding process
Expand Down Expand Up @@ -128,7 +129,7 @@ private void runPollAndLaunchSeed() throws IOException {
final String previousUpdatedEntry = storageBroker.getLayerMetadata(layerName, LAST_UPDATED);

final String gridSetId = pollDef.getGridSetId();
final URL feedUrl = new URL(templateFeedUrl(pollDef.getFeedUrl(), previousUpdatedEntry));
URL feedUrl = URLs.of(templateFeedUrl(pollDef.getFeedUrl(), previousUpdatedEntry));
final String httpUsername = pollDef.getHttpUsername();
final String httpPassword = pollDef.getHttpUsername();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ private void genericMultiThreadsTest(
int threadsNumber, int workersNumber, long poolSize, File... files) throws Exception {
SqliteConnectionManager connectionManager = new SqliteConnectionManager(poolSize, 10);
connectionManagersToClean.add(connectionManager);
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService executor = Executors.newFixedThreadPool(threadsNumber);
Random random = new Random();
List<Future<Tuple<File, String>>> results = new ArrayList<>();
Expand Down
Loading

0 comments on commit 9b55d9a

Please sign in to comment.