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`
* `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 committed Jan 5, 2024
1 parent 4ee9e3e commit 5fb1ad3
Show file tree
Hide file tree
Showing 26 changed files with 92 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Proxy;
import java.net.URL;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
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)),
new URI(getServiceURL(configuration)).toURL(),
StorageURL.createPipeline(creds, options));

String containerName = configuration.getContainer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -266,13 +268,13 @@ public void setDefaultValues(TileLayer layer) {
URL proxyUrl = null;
try {
if (getGwcConfig().getProxyUrl() != null) {
proxyUrl = new URL(getGwcConfig().getProxyUrl());
proxyUrl = new URI(getGwcConfig().getProxyUrl()).toURL();
log.fine("Using proxy " + proxyUrl.getHost() + ":" + proxyUrl.getPort());
} else if (wl.getProxyUrl() != null) {
proxyUrl = new URL(wl.getProxyUrl());
proxyUrl = new URI(wl.getProxyUrl()).toURL();
log.fine("Using proxy " + proxyUrl.getHost() + ":" + proxyUrl.getPort());
}
} catch (MalformedURLException e) {
} catch (MalformedURLException | URISyntaxException e) {
log.log(
Level.SEVERE,
"could not parse proxy URL "
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 @@ -18,6 +18,9 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -110,7 +113,13 @@ protected BufferedImage loadMatrix(TileLayer tlayer, String gridSetId, int z)
+ ") , "
+ urlStr);

URL wmsUrl = new URL(urlStr);
URL wmsUrl;
try {
wmsUrl = new URI(urlStr).toURL();
} catch (URISyntaxException e) {
// preserve behavior from when new URL(urlStr) was used
throw new MalformedURLException(e.getMessage());
}

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 @@ -18,6 +18,8 @@
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.channels.Channels;
Expand Down Expand Up @@ -115,8 +117,8 @@ protected void makeRequest(
String requestUrl = layer.nextWmsURL();

try {
wmsBackendUrl = new URL(requestUrl);
} catch (MalformedURLException maue) {
wmsBackendUrl = new URI(requestUrl).toURL();
} catch (URISyntaxException | MalformedURLException maue) {
throw new GeoWebCacheException(
"Malformed URL: " + requestUrl + " " + maue.getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
Expand Down Expand Up @@ -803,9 +805,9 @@ public void proxyRequest(ConveyorTile tile) throws GeoWebCacheException {
try {
URL url;
if (serverStr.contains("?")) {
url = new URL(serverStr + "&" + queryStr);
url = new URI(serverStr + "&" + queryStr).toURL();
} else {
url = new URL(serverStr + queryStr);
url = new URI(serverStr + queryStr).toURL();
}

WMSSourceHelper helper = getSourceHelper();
Expand Down Expand Up @@ -839,7 +841,7 @@ public void proxyRequest(ConveyorTile tile) throws GeoWebCacheException {
}
}
}
} catch (IOException ioe) {
} catch (IOException | URISyntaxException ioe) {
tile.servletResp.setStatus(500);
log.log(Level.SEVERE, ioe.getMessage());
}
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 @@ -15,6 +15,7 @@
package org.geowebcache.proxy;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.logging.Logger;
Expand Down Expand Up @@ -62,7 +63,7 @@ protected ModelAndView handleRequestInternal(
}
String decodedUrl = URLDecoder.decode(urlStr, charEnc);

URL url = new URL(decodedUrl);
URL url = new URI(decodedUrl).toURL();
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
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 @@ -19,6 +19,8 @@
import static org.junit.Assert.assertNull;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.Set;
Expand Down Expand Up @@ -111,11 +113,11 @@ public void setDefaultValues(TileLayer layer) {
URL proxyUrl = null;
try {
if (getGwcConfig().getProxyUrl() != null) {
proxyUrl = new URL(getGwcConfig().getProxyUrl());
proxyUrl = new URI(getGwcConfig().getProxyUrl()).toURL();
} else if (wl.getProxyUrl() != null) {
proxyUrl = new URL(wl.getProxyUrl());
proxyUrl = new URI(wl.getProxyUrl()).toURL();
}
} catch (MalformedURLException e) {
} catch (MalformedURLException | URISyntaxException e) {
}

final WMSHttpHelper sourceHelper;
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 @@ -17,6 +17,9 @@
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
Expand Down Expand Up @@ -128,7 +131,12 @@ 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;
try {
feedUrl = new URI(templateFeedUrl(pollDef.getFeedUrl(), previousUpdatedEntry)).toURL();
} catch (URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
}
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
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ private static void rawSqlitle(File rootDirectory, File seedFile, long[][] tiles
}
FileUtils.copyFile(seedFile, databaseFile);
// submitting the select tasks
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService executor = Executors.newFixedThreadPool(WORKERS);
long startTime = System.currentTimeMillis();
try (Connection connection =
Expand Down Expand Up @@ -124,6 +125,7 @@ private static void pooledSqlitle(File rootDirectory, File seedFile, long[][] ti
}
FileUtils.copyFile(seedFile, databaseFile);
// submitting the select tasks
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService executor = Executors.newFixedThreadPool(WORKERS);
SqliteConnectionManager connectionManager = new SqliteConnectionManager(10, 2000);
long startTime = System.currentTimeMillis();
Expand Down Expand Up @@ -179,6 +181,7 @@ private static void mbtilesStore(File rootDirectory, File seedFile, long[][] til
}
FileUtils.copyFile(seedFile, databaseFile);
// submitting the select tasks
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService executor = Executors.newFixedThreadPool(WORKERS);
long startTime = System.currentTimeMillis();
// mbtiles store configuration
Expand Down Expand Up @@ -240,6 +243,7 @@ private static void fileStore(File seedDirectory, long[][] tiles) throws Excepti
LOGGER.info(String.format("Start reading from directory'%s'.", seedDirectory));
}
// submitting the read tasks
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ExecutorService executor = Executors.newFixedThreadPool(WORKERS);
long startTime = System.currentTimeMillis();
// instantiate the file blobstore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,7 @@ public void deleteByParametersId() {
@Ignore // unreliable test timing
public void deleteWhenUploadExists() throws Exception {
BlockingQueue<Runnable> taskQueue = spy(new LinkedBlockingQueue<>(1000));
@SuppressWarnings("PMD.CloseResource") // implements AutoCloseable in Java 21
ThreadPoolExecutor executor =
spy(
new ThreadPoolExecutor(
Expand Down
Loading

0 comments on commit 5fb1ad3

Please sign in to comment.