diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 05a4d99cc1..ec00c754ba 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -31,6 +31,11 @@ jobs: with: fetch-depth: 0 + - uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: '21' + - uses: actions/setup-python@v6 with: python-version: '3.13' diff --git a/core/src/main/java/org/mapfish/print/FontTools.java b/core/src/main/java/org/mapfish/print/FontTools.java index 426aac60a7..94259dadd8 100644 --- a/core/src/main/java/org/mapfish/print/FontTools.java +++ b/core/src/main/java/org/mapfish/print/FontTools.java @@ -4,6 +4,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -62,7 +63,7 @@ public static List listFontConfigFonts(final String famil String[] commands = {"fc-list", "-b", family}; Process process = Runtime.getRuntime().exec(commands); - inputStreamReader = new InputStreamReader(process.getInputStream(), "utf-8"); + inputStreamReader = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8); stdInput = new BufferedReader(inputStreamReader); String inputLine; FontConfigDescription description = null; diff --git a/core/src/main/java/org/mapfish/print/SvgUtil.java b/core/src/main/java/org/mapfish/print/SvgUtil.java index 2072d7b23d..71589ce6b2 100644 --- a/core/src/main/java/org/mapfish/print/SvgUtil.java +++ b/core/src/main/java/org/mapfish/print/SvgUtil.java @@ -42,8 +42,7 @@ private static class BufferedImageTranscoder extends ImageTranscoder { @Override public BufferedImage createImage(final int w, final int h) { - BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - return bi; + return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } @Override diff --git a/core/src/main/java/org/mapfish/print/URIUtils.java b/core/src/main/java/org/mapfish/print/URIUtils.java index 2636133e43..174edeea4f 100644 --- a/core/src/main/java/org/mapfish/print/URIUtils.java +++ b/core/src/main/java/org/mapfish/print/URIUtils.java @@ -9,6 +9,7 @@ import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Map; import java.util.Set; @@ -54,13 +55,8 @@ public static Multimap getParameters(final String rawQuery) { key = pair; value = ""; } else { - - try { - key = URLDecoder.decode(pair.substring(0, pos), "UTF-8"); - value = URLDecoder.decode(pair.substring(pos + 1), "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new PrintException("Failed to get parameters for query " + rawQuery, e); - } + key = URLDecoder.decode(pair.substring(0, pos), StandardCharsets.UTF_8); + value = URLDecoder.decode(pair.substring(pos + 1), StandardCharsets.UTF_8); } result.put(key, value); @@ -214,7 +210,7 @@ public static URI setQueryParams( final URI initialUri, final Multimap queryParams) { StringBuilder queryString = new StringBuilder(); for (Map.Entry entry : queryParams.entries()) { - if (queryString.length() > 0) { + if (!queryString.isEmpty()) { queryString.append("&"); } queryString.append(entry.getKey()).append("=").append(entry.getValue()); diff --git a/core/src/main/java/org/mapfish/print/attribute/StringArrayAttribute.java b/core/src/main/java/org/mapfish/print/attribute/StringArrayAttribute.java index 34998ba16c..c4719a11ef 100644 --- a/core/src/main/java/org/mapfish/print/attribute/StringArrayAttribute.java +++ b/core/src/main/java/org/mapfish/print/attribute/StringArrayAttribute.java @@ -3,7 +3,6 @@ /** An attribute that can contain an array of strings. [[examples=verboseExample]] */ public class StringArrayAttribute extends PrimitiveAttribute { /** Constructor. */ - @SuppressWarnings("unchecked") public StringArrayAttribute() { super(String[].class); } diff --git a/core/src/main/java/org/mapfish/print/attribute/StringAttribute.java b/core/src/main/java/org/mapfish/print/attribute/StringAttribute.java index e3236b453f..4d0d25f831 100644 --- a/core/src/main/java/org/mapfish/print/attribute/StringAttribute.java +++ b/core/src/main/java/org/mapfish/print/attribute/StringAttribute.java @@ -39,8 +39,7 @@ public final void setMaxLength(final int maxLength) { @Override public final void validateValue(final Object value) { - if (this.maxLength >= 0 && value instanceof String) { - String text = (String) value; + if (this.maxLength >= 0 && value instanceof String text) { if (text.length() > this.maxLength) { throw new IllegalArgumentException( "text contains more than " + this.maxLength + " characters"); diff --git a/core/src/main/java/org/mapfish/print/attribute/map/CenterScaleMapBounds.java b/core/src/main/java/org/mapfish/print/attribute/map/CenterScaleMapBounds.java index 368cd390c5..71e228dc53 100644 --- a/core/src/main/java/org/mapfish/print/attribute/map/CenterScaleMapBounds.java +++ b/core/src/main/java/org/mapfish/print/attribute/map/CenterScaleMapBounds.java @@ -2,7 +2,9 @@ import static org.mapfish.print.Constants.PDF_DPI; +import com.google.common.annotations.VisibleForTesting; import java.awt.Rectangle; +import java.util.Objects; import org.geotools.api.referencing.crs.CoordinateReferenceSystem; import org.geotools.api.referencing.operation.TransformException; import org.geotools.geometry.Position2D; @@ -179,12 +181,21 @@ private ReferencedEnvelope computeGeodeticBBox( } } - private double rollLongitude(final double x) { - return x - (((int) (x + Math.signum(x) * 180)) / 360) * 360.0; + @VisibleForTesting + double rollLongitude(final double x) { + return modulo(x + 180, 360.0) - 180; } - private double rollLatitude(final double y) { - return y - (((int) (y + Math.signum(y) * 90)) / 180) * 180.0; + private static double modulo(final double a, final double b) { + return b - ((-a % b) + b) % b; + } + + @VisibleForTesting + double rollLatitude(final double y) { + if (y > 90 || y < -90) { + throw new IllegalArgumentException("Latitude must be between -90 and 90"); + } + return y; } @Override @@ -201,10 +212,10 @@ public boolean equals(final Object o) { final CenterScaleMapBounds that = (CenterScaleMapBounds) o; - if (this.center != null ? !this.center.equals(that.center) : that.center != null) { + if (!Objects.equals(this.center, that.center)) { return false; } - return this.scale != null ? this.scale.equals(that.scale) : that.scale == null; + return Objects.equals(this.scale, that.scale); } @Override diff --git a/core/src/main/java/org/mapfish/print/attribute/map/MapAttribute.java b/core/src/main/java/org/mapfish/print/attribute/map/MapAttribute.java index cd6157d387..ece30c7e07 100644 --- a/core/src/main/java/org/mapfish/print/attribute/map/MapAttribute.java +++ b/core/src/main/java/org/mapfish/print/attribute/map/MapAttribute.java @@ -30,7 +30,6 @@ public final class MapAttribute extends GenericMapAttribute { ZoomLevelSnapStrategy.CLOSEST_LOWER_SCALE_ON_TIE; private static final boolean DEFAULT_SNAP_GEODETIC = false; - @SuppressWarnings("unchecked") @Override public Class getValueType() { return MapAttributeValues.class; diff --git a/core/src/main/java/org/mapfish/print/attribute/map/MapfishMapContext.java b/core/src/main/java/org/mapfish/print/attribute/map/MapfishMapContext.java index 0a79fa4384..8f49dc173a 100644 --- a/core/src/main/java/org/mapfish/print/attribute/map/MapfishMapContext.java +++ b/core/src/main/java/org/mapfish/print/attribute/map/MapfishMapContext.java @@ -301,7 +301,7 @@ public AffineTransform getTransform() { final AffineTransform transform = AffineTransform.getTranslateInstance(0.0, 0.0); // move to the center of the original map rectangle (this is the actual // size of the graphic) - transform.translate(this.mapSize.width / 2, this.mapSize.height / 2); + transform.translate(this.mapSize.width / 2.0, this.mapSize.height / 2.0); // then rotate around this center transform.rotate(this.rotation); @@ -309,7 +309,7 @@ public AffineTransform getTransform() { // then move to an artificial origin (0,0) which might be outside the actual // painting area. this origin still keeps the center of the original map area // at the center of the rotated map area. - transform.translate(-rotatedMapSize.width / 2, -rotatedMapSize.height / 2); + transform.translate(-rotatedMapSize.width / 2.0, -rotatedMapSize.height / 2.0); return transform; } diff --git a/core/src/main/java/org/mapfish/print/attribute/map/OverviewMapAttribute.java b/core/src/main/java/org/mapfish/print/attribute/map/OverviewMapAttribute.java index eda775d609..0082316bd5 100644 --- a/core/src/main/java/org/mapfish/print/attribute/map/OverviewMapAttribute.java +++ b/core/src/main/java/org/mapfish/print/attribute/map/OverviewMapAttribute.java @@ -41,7 +41,6 @@ public void setStyle(final String style) { this.style = style; } - @SuppressWarnings("unchecked") @Override public Class getValueType() { return OverviewMapAttributeValues.class; diff --git a/core/src/main/java/org/mapfish/print/cli/Main.java b/core/src/main/java/org/mapfish/print/cli/Main.java index 5ed5b29fff..4ab21d8ad0 100644 --- a/core/src/main/java/org/mapfish/print/cli/Main.java +++ b/core/src/main/java/org/mapfish/print/cli/Main.java @@ -123,22 +123,13 @@ private static void printUsage(final int exitCode) { private static void configureLogs(final String verbose) { final ClassLoader classLoader = Main.class.getClassLoader(); - URL logfile; - switch (Integer.parseInt(verbose)) { - case LOGLEVEL_QUIET: - logfile = classLoader.getResource("shell-quiet-log.xml"); - break; - case LOGLEVEL_INFO: - logfile = classLoader.getResource("shell-info-log.xml"); - break; - case LOGLEVEL_VERBOSE: - logfile = classLoader.getResource("shell-verbose-log.xml"); - break; - case LOGLEVEL_DEFAULT: - default: - logfile = classLoader.getResource("shell-default-log.xml"); - break; - } + URL logfile = + switch (Integer.parseInt(verbose)) { + case LOGLEVEL_QUIET -> classLoader.getResource("shell-quiet-log.xml"); + case LOGLEVEL_INFO -> classLoader.getResource("shell-info-log.xml"); + case LOGLEVEL_VERBOSE -> classLoader.getResource("shell-verbose-log.xml"); + default -> classLoader.getResource("shell-default-log.xml"); + }; LoggerContext loggerContext = getLoggerContext(logfile); new StatusPrinter2().printInCaseOfErrorsOrWarnings(loggerContext); diff --git a/core/src/main/java/org/mapfish/print/config/ConfigurationFactory.java b/core/src/main/java/org/mapfish/print/config/ConfigurationFactory.java index 58e5e30a52..9cee27330a 100644 --- a/core/src/main/java/org/mapfish/print/config/ConfigurationFactory.java +++ b/core/src/main/java/org/mapfish/print/config/ConfigurationFactory.java @@ -77,7 +77,7 @@ public final Configuration getConfig(final File configFile, final InputStream co errors.append("\n\t* ").append(throwable.getMessage()); LOGGER.error("Configuration Error found", throwable); } - throw new Error(errors.toString(), validate.get(0)); + throw new Error(errors.toString(), validate.getFirst()); } } return config; diff --git a/core/src/main/java/org/mapfish/print/config/PDFConfig.java b/core/src/main/java/org/mapfish/print/config/PDFConfig.java index 1bfc268581..3b6196d205 100644 --- a/core/src/main/java/org/mapfish/print/config/PDFConfig.java +++ b/core/src/main/java/org/mapfish/print/config/PDFConfig.java @@ -102,7 +102,7 @@ public String getKeywordsAsString() { public void setKeywords(final List keywords) { StringBuilder builder = new StringBuilder(); for (String keyword : keywords) { - if (builder.length() > 0) { + if (!builder.isEmpty()) { builder.append(','); } builder.append(keyword.trim()); diff --git a/core/src/main/java/org/mapfish/print/config/access/RoleAccessAssertion.java b/core/src/main/java/org/mapfish/print/config/access/RoleAccessAssertion.java index f7d9c1d406..c5607311b1 100644 --- a/core/src/main/java/org/mapfish/print/config/access/RoleAccessAssertion.java +++ b/core/src/main/java/org/mapfish/print/config/access/RoleAccessAssertion.java @@ -43,11 +43,10 @@ public AccessAssertion setRequiredRoles(final Collection assertionRequir if (assertionRequiredRoles == null) { this.requiredRoles = Collections.unmodifiableSet(Collections.emptySet()); } else { - if (assertionRequiredRoles instanceof Set) { - Set roles = (Set) assertionRequiredRoles; + if (assertionRequiredRoles instanceof Set roles) { this.requiredRoles = Collections.unmodifiableSet(roles); } else { - this.requiredRoles = Collections.unmodifiableSet(new HashSet<>(assertionRequiredRoles)); + this.requiredRoles = Set.copyOf(assertionRequiredRoles); } } return this; @@ -135,7 +134,7 @@ public int hashCode() { @Override public AccessAssertion copy() { RoleAccessAssertion assertion = new RoleAccessAssertion(); - assertion.requiredRoles = Collections.unmodifiableSet(new HashSet<>(this.requiredRoles)); + assertion.requiredRoles = Set.copyOf(this.requiredRoles); return assertion; } } diff --git a/core/src/main/java/org/mapfish/print/http/ConfigFileResolvingRequest.java b/core/src/main/java/org/mapfish/print/http/ConfigFileResolvingRequest.java index fe136e19f6..304f1590e5 100644 --- a/core/src/main/java/org/mapfish/print/http/ConfigFileResolvingRequest.java +++ b/core/src/main/java/org/mapfish/print/http/ConfigFileResolvingRequest.java @@ -258,14 +258,8 @@ public URI getURI() { return this.uri; } - private static class ConfigFileResolverHttpResponse implements ClientHttpResponse { - private final InputStream is; - private final HttpHeaders headers; - - ConfigFileResolverHttpResponse(final InputStream is, final HttpHeaders headers) { - this.headers = headers; - this.is = is; - } + private record ConfigFileResolverHttpResponse(InputStream is, HttpHeaders headers) + implements ClientHttpResponse { @Override @Nonnull diff --git a/core/src/main/java/org/mapfish/print/http/MfClientHttpRequestFactoryImpl.java b/core/src/main/java/org/mapfish/print/http/MfClientHttpRequestFactoryImpl.java index 8d88a68bb6..50c04b769c 100644 --- a/core/src/main/java/org/mapfish/print/http/MfClientHttpRequestFactoryImpl.java +++ b/core/src/main/java/org/mapfish/print/http/MfClientHttpRequestFactoryImpl.java @@ -218,9 +218,7 @@ protected Response executeInternal(@Nonnull final HttpHeaders headers) throws IO } } } - if (this.request instanceof HttpEntityEnclosingRequest) { - final HttpEntityEnclosingRequest entityEnclosingRequest = - (HttpEntityEnclosingRequest) this.request; + if (this.request instanceof HttpEntityEnclosingRequest entityEnclosingRequest) { final HttpEntity requestEntity = new ByteArrayEntity(this.outputStream.toByteArray()); entityEnclosingRequest.setEntity(requestEntity); } diff --git a/core/src/main/java/org/mapfish/print/http/UserAgentCreator.java b/core/src/main/java/org/mapfish/print/http/UserAgentCreator.java index e2b9a0a91a..6d1ca88a2b 100644 --- a/core/src/main/java/org/mapfish/print/http/UserAgentCreator.java +++ b/core/src/main/java/org/mapfish/print/http/UserAgentCreator.java @@ -39,7 +39,6 @@ public static String getUserAgent() { LOGGER.error("Error getting MapFishPrint version", e); } - final String userAgent = String.format("%s/%s %s", AGENT_NAME, mfpRelease, httpClientUserAgent); - return userAgent; + return String.format("%s/%s %s", AGENT_NAME, mfpRelease, httpClientUserAgent); } } diff --git a/core/src/main/java/org/mapfish/print/http/Utils.java b/core/src/main/java/org/mapfish/print/http/Utils.java index d42a385d88..3ad7b8642a 100644 --- a/core/src/main/java/org/mapfish/print/http/Utils.java +++ b/core/src/main/java/org/mapfish/print/http/Utils.java @@ -18,7 +18,7 @@ private Utils() {} * @param headers The headers */ public static List getPrintableHeadersList(final Map> headers) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); for (String header : headers.keySet()) { List value = headers.get(header); if (AUTH_HEADERS.contains(header.toLowerCase())) { diff --git a/core/src/main/java/org/mapfish/print/jasperreports/HumanAlphaSerie.java b/core/src/main/java/org/mapfish/print/jasperreports/HumanAlphaSerie.java index a7c7e618fe..459e80ff45 100644 --- a/core/src/main/java/org/mapfish/print/jasperreports/HumanAlphaSerie.java +++ b/core/src/main/java/org/mapfish/print/jasperreports/HumanAlphaSerie.java @@ -59,7 +59,6 @@ private static char numberToChar(final int number) { if (number > 26 || number < 0) { return '\0'; } - char c = (char) ('A' + number - 1); - return c; + return (char) ('A' + number - 1); } } diff --git a/core/src/main/java/org/mapfish/print/map/geotools/AbstractFeatureSourceLayer.java b/core/src/main/java/org/mapfish/print/map/geotools/AbstractFeatureSourceLayer.java index c83b8f3d11..2b2ee847ab 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/AbstractFeatureSourceLayer.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/AbstractFeatureSourceLayer.java @@ -92,20 +92,14 @@ public final List getLayers( public final void setFeatureCollection(final SimpleFeatureCollection featureCollection) { this.featureSourceSupplier = - new FeatureSourceSupplier() { - @Nonnull - @Override - public FeatureSource load( - @Nonnull final MfClientHttpRequestFactory requestFactory, - @Nonnull final MapfishMapContext mapContext) { - // GeoTools is not always thread safe. In particular the - // DefaultFeatureCollection.getBounds - // method. If multiple maps are sharing the same features, this would cause - // zoomToFeature - // to result in funky bboxes. To avoid that, we use a copy of the featureCollection - final SimpleFeatureCollection copy = DataUtilities.collection(featureCollection); - return new CollectionFeatureSource(copy); - } + (requestFactory, mapContext) -> { + // GeoTools is not always thread safe. In particular the + // DefaultFeatureCollection.getBounds + // method. If multiple maps are sharing the same features, this would cause + // zoomToFeature + // to result in funky bboxes. To avoid that, we use a copy of the featureCollection + final SimpleFeatureCollection copy = DataUtilities.collection(featureCollection); + return new CollectionFeatureSource(copy); }; } diff --git a/core/src/main/java/org/mapfish/print/map/geotools/AbstractGeotoolsLayer.java b/core/src/main/java/org/mapfish/print/map/geotools/AbstractGeotoolsLayer.java index 24988c8e37..aaafe50318 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/AbstractGeotoolsLayer.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/AbstractGeotoolsLayer.java @@ -183,8 +183,7 @@ protected abstract List getLayers( MfClientHttpRequestFactory httpRequestFactory, MapfishMapContext transformer, Processor.ExecutionContext context, - LayerContext layerContext) - throws Exception; + LayerContext layerContext); @Override public boolean supportsNativeRotation() { diff --git a/core/src/main/java/org/mapfish/print/map/geotools/AbstractGridCoverageLayerPlugin.java b/core/src/main/java/org/mapfish/print/map/geotools/AbstractGridCoverageLayerPlugin.java index 1b7e3cb821..e5fdeafe16 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/AbstractGridCoverageLayerPlugin.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/AbstractGridCoverageLayerPlugin.java @@ -2,10 +2,8 @@ import static org.mapfish.print.Constants.Style.Raster.NAME; -import org.geotools.api.style.Style; import org.mapfish.print.OptionalUtils; import org.mapfish.print.config.Template; -import org.mapfish.print.http.MfClientHttpRequestFactory; import org.mapfish.print.map.style.StyleParser; import org.springframework.beans.factory.annotation.Autowired; @@ -25,15 +23,12 @@ public abstract class AbstractGridCoverageLayerPlugin { */ protected final StyleSupplier createStyleSupplier( final Template template, final String styleRef) { - return new StyleSupplier() { - @Override - public Style load(final MfClientHttpRequestFactory requestFactory, final T featureSource) { - final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser; - return OptionalUtils.or( - () -> template.getStyle(styleRef), - () -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef)) - .orElse(template.getConfiguration().getDefaultStyle(NAME)); - } + return (requestFactory, featureSource) -> { + final StyleParser parser = AbstractGridCoverageLayerPlugin.this.styleParser; + return OptionalUtils.or( + () -> template.getStyle(styleRef), + () -> parser.loadStyle(template.getConfiguration(), requestFactory, styleRef)) + .orElse(template.getConfiguration().getDefaultStyle(NAME)); }; } } diff --git a/core/src/main/java/org/mapfish/print/map/geotools/FeaturesParser.java b/core/src/main/java/org/mapfish/print/map/geotools/FeaturesParser.java index cc3b88e148..65f9d93755 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/FeaturesParser.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/FeaturesParser.java @@ -100,7 +100,13 @@ static CoordinateReferenceSystem parseCoordinateReferenceSystem( return CRS.parseWKT(wkt); } catch (FactoryException e) { LOGGER.warn( - "Unable to load linked CRS from geojson: \n{}\n\nWKT loaded" + " from:\n{}", + """ + Unable to load linked CRS from geojson:\s + {} + + WKT loaded from: + {}\ + """, crsJson, wkt); } @@ -120,7 +126,7 @@ static CoordinateReferenceSystem parseCoordinateReferenceSystem( "Error reading the required elements to parse crs of the geojson: \n{}", geojson, e); } try { - if (code.length() > 0) { + if (!code.isEmpty()) { crs = CRS.decode(code.toString(), forceLongitudeFirst); } } catch (NoSuchAuthorityCodeException e) { diff --git a/core/src/main/java/org/mapfish/print/map/geotools/GeoJsonLayer.java b/core/src/main/java/org/mapfish/print/map/geotools/GeoJsonLayer.java index 64815f1aab..e926f6e5f2 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/GeoJsonLayer.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/GeoJsonLayer.java @@ -81,21 +81,15 @@ public GeoJsonLayer parse(@Nonnull final Template template, @Nonnull final GeoJs private FeatureSourceSupplier createFeatureSourceSupplier( final Template template, final String geoJsonString) { - return new FeatureSourceSupplier() { - @Nonnull - @Override - public FeatureSource load( - @Nonnull final MfClientHttpRequestFactory requestFactory, - @Nonnull final MapfishMapContext mapContext) { - final FeaturesParser parser = - new FeaturesParser(requestFactory, mapContext.isForceLongitudeFirst()); - SimpleFeatureCollection featureCollection; - try { - featureCollection = parser.autoTreat(template, geoJsonString); - return new CollectionFeatureSource(featureCollection); - } catch (IOException e) { - throw new PrintException("Failed to load " + mapContext, e); - } + return (requestFactory, mapContext) -> { + final FeaturesParser parser = + new FeaturesParser(requestFactory, mapContext.isForceLongitudeFirst()); + SimpleFeatureCollection featureCollection; + try { + featureCollection = parser.autoTreat(template, geoJsonString); + return new CollectionFeatureSource(featureCollection); + } catch (IOException e) { + throw new PrintException("Failed to load " + mapContext, e); } }; } diff --git a/core/src/main/java/org/mapfish/print/map/geotools/GmlLayer.java b/core/src/main/java/org/mapfish/print/map/geotools/GmlLayer.java index 2324d970aa..fc38c5dc60 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/GmlLayer.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/GmlLayer.java @@ -96,23 +96,17 @@ public GmlLayer parse(@Nonnull final Template template, @Nonnull final GmlParam private FeatureSourceSupplier createFeatureSourceSupplier( final Template template, final String url) { - return new FeatureSourceSupplier() { - @Nonnull - @Override - public FeatureSource load( - @Nonnull final MfClientHttpRequestFactory requestFactory, - @Nonnull final MapfishMapContext mapContext) { - SimpleFeatureCollection featureCollection; - try { - featureCollection = createFeatureSource(template, requestFactory, url); - } catch (IOException e) { - throw new PrintException("Failed to create feature source for " + url, e); - } - if (featureCollection == null) { - throw new IllegalArgumentException(url + " does not reference a GML file"); - } - return new CollectionFeatureSource(featureCollection); + return (requestFactory, mapContext) -> { + SimpleFeatureCollection featureCollection; + try { + featureCollection = createFeatureSource(template, requestFactory, url); + } catch (IOException e) { + throw new PrintException("Failed to create feature source for " + url, e); + } + if (featureCollection == null) { + throw new IllegalArgumentException(url + " does not reference a GML file"); } + return new CollectionFeatureSource(featureCollection); }; } diff --git a/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLabel.java b/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLabel.java index 4eba426563..45c3ed7996 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLabel.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLabel.java @@ -1,17 +1,7 @@ package org.mapfish.print.map.geotools.grid; /** Represents text, position and rotation of a label. */ -class GridLabel { - final String text; - final int x, y; - final Side side; - - GridLabel(final String text, final int x, final int y, final Side side) { - this.text = text; - this.x = x; - this.y = y; - this.side = side; - } +record GridLabel(String text, int x, int y, Side side) { @Override public String toString() { diff --git a/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLayer.java b/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLayer.java index 9116e3e543..449bd1f8d3 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLayer.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/grid/GridLayer.java @@ -101,16 +101,19 @@ public void render( for (GridLabel label : this.labels) { Shape textShape = - baseFont.createGlyphVector(graphics2D.getFontRenderContext(), label.text).getOutline(); + baseFont + .createGlyphVector(graphics2D.getFontRenderContext(), label.text()) + .getOutline(); Rectangle2D textBounds = textShape.getBounds2D(); AffineTransform transform = new AffineTransform(baseTransform); - transform.translate(label.x, label.y); + transform.translate(label.x(), label.y()); - applyOffset(transform, label.side); + applyOffset(transform, label.side()); RotationQuadrant.getQuadrant(transformer.getRotation(), this.params.rotateLabels) - .updateTransform(transform, this.params.indent, label.side, halfCharHeight, textBounds); + .updateTransform( + transform, this.params.indent, label.side(), halfCharHeight, textBounds); graphics2D.setTransform(transform); if (haloRadius > 0.0f) { diff --git a/core/src/main/java/org/mapfish/print/map/geotools/grid/LineGridStrategy.java b/core/src/main/java/org/mapfish/print/map/geotools/grid/LineGridStrategy.java index e283c89083..51dd7d6542 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/grid/LineGridStrategy.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/grid/LineGridStrategy.java @@ -2,7 +2,6 @@ import java.awt.geom.AffineTransform; import javax.annotation.Nonnull; -import org.geotools.api.data.FeatureSource; import org.geotools.api.feature.simple.SimpleFeature; import org.geotools.api.feature.simple.SimpleFeatureType; import org.geotools.api.referencing.crs.CoordinateReferenceSystem; @@ -20,7 +19,6 @@ import org.mapfish.print.Constants.Style.Grid; import org.mapfish.print.attribute.map.MapfishMapContext; import org.mapfish.print.config.Template; -import org.mapfish.print.http.MfClientHttpRequestFactory; import org.mapfish.print.map.geotools.FeatureSourceSupplier; /** Strategy for creating the style and features for the grid when the grid consists of lines. */ @@ -33,23 +31,16 @@ public Style defaultStyle(final Template template, final GridParam layerData) { @Override public FeatureSourceSupplier createFeatureSource( final Template template, final GridParam layerData, final LabelPositionCollector labels) { - return new FeatureSourceSupplier() { - @Nonnull - @Override - public FeatureSource load( - @Nonnull final MfClientHttpRequestFactory requestFactory, - @Nonnull final MapfishMapContext mapContext) { - SimpleFeatureType featureType = - GridUtils.createGridFeatureType(mapContext, LineString.class); - SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); - final DefaultFeatureCollection features; - if (layerData.numberOfLines != null) { - features = createFeaturesFromNumberOfLines(mapContext, featureBuilder, layerData, labels); - } else { - features = createFeaturesFromSpacing(mapContext, featureBuilder, layerData, labels); - } - return new CollectionFeatureSource(features); + return (requestFactory, mapContext) -> { + SimpleFeatureType featureType = GridUtils.createGridFeatureType(mapContext, LineString.class); + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); + final DefaultFeatureCollection features; + if (layerData.numberOfLines != null) { + features = createFeaturesFromNumberOfLines(mapContext, featureBuilder, layerData, labels); + } else { + features = createFeaturesFromSpacing(mapContext, featureBuilder, layerData, labels); } + return new CollectionFeatureSource(features); }; } @@ -227,17 +218,5 @@ private SimpleFeature createFeature( return featureBuilder.buildFeature("grid." + (ordinate == 1 ? 'x' : 'y') + "." + i); } - private static final class SpacesAndMins { - public final double xSpace; - public final double ySpace; - public final double minX; - public final double minY; - - SpacesAndMins(final double xSpace, final double ySpace, final double minX, final double minY) { - this.xSpace = xSpace; - this.ySpace = ySpace; - this.minX = minX; - this.minY = minY; - } - } + private record SpacesAndMins(double xSpace, double ySpace, double minX, double minY) {} } diff --git a/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStrategy.java b/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStrategy.java index c05b7f62be..a1fa4d858c 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStrategy.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStrategy.java @@ -1,8 +1,6 @@ package org.mapfish.print.map.geotools.grid; import java.awt.geom.AffineTransform; -import javax.annotation.Nonnull; -import org.geotools.api.data.FeatureSource; import org.geotools.api.feature.simple.SimpleFeatureType; import org.geotools.api.referencing.crs.CoordinateReferenceSystem; import org.geotools.api.referencing.operation.MathTransform; @@ -19,7 +17,6 @@ import org.mapfish.print.Constants.Style.Grid; import org.mapfish.print.attribute.map.MapfishMapContext; import org.mapfish.print.config.Template; -import org.mapfish.print.http.MfClientHttpRequestFactory; import org.mapfish.print.map.geotools.FeatureSourceSupplier; /** Strategy for creating the style and features for the grid when the grid consists of lines. */ @@ -33,22 +30,16 @@ public Style defaultStyle(final Template template, final GridParam layerData) { @Override public FeatureSourceSupplier createFeatureSource( final Template template, final GridParam layerData, final LabelPositionCollector labels) { - return new FeatureSourceSupplier() { - @Nonnull - @Override - public FeatureSource load( - @Nonnull final MfClientHttpRequestFactory requestFactory, - @Nonnull final MapfishMapContext mapContext) { - SimpleFeatureType featureType = GridUtils.createGridFeatureType(mapContext, Point.class); - SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); - final DefaultFeatureCollection features; - if (layerData.numberOfLines != null) { - features = createFeaturesFromNumberOfLines(mapContext, featureBuilder, layerData, labels); - } else { - features = createFeaturesFromSpacing(mapContext, featureBuilder, layerData, labels); - } - return new CollectionFeatureSource(features); + return (requestFactory, mapContext) -> { + SimpleFeatureType featureType = GridUtils.createGridFeatureType(mapContext, Point.class); + SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); + final DefaultFeatureCollection features; + if (layerData.numberOfLines != null) { + features = createFeaturesFromNumberOfLines(mapContext, featureBuilder, layerData, labels); + } else { + features = createFeaturesFromSpacing(mapContext, featureBuilder, layerData, labels); } + return new CollectionFeatureSource(features); }; } diff --git a/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStyle.java b/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStyle.java index a618477ecd..3970223305 100644 --- a/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStyle.java +++ b/core/src/main/java/org/mapfish/print/map/geotools/grid/PointGridStyle.java @@ -26,12 +26,12 @@ static Style get(final GridParam params) { crossSymbolizer("shape://plus", builder, CROSS_SIZE, params.gridColor); final Style style = builder.createStyle(pointSymbolizer); final List symbolizers = - style.featureTypeStyles().get(0).rules().get(0).symbolizers(); + style.featureTypeStyles().getFirst().rules().getFirst().symbolizers(); if (params.haloRadius > 0.0) { Symbolizer halo = crossSymbolizer("cross", builder, CROSS_SIZE + params.haloRadius * 2.0, params.haloColor); - symbolizers.add(0, halo); + symbolizers.addFirst(halo); } return style; diff --git a/core/src/main/java/org/mapfish/print/map/image/AbstractSingleImageLayer.java b/core/src/main/java/org/mapfish/print/map/image/AbstractSingleImageLayer.java index 2f86853c5a..f7a7c43fb2 100644 --- a/core/src/main/java/org/mapfish/print/map/image/AbstractSingleImageLayer.java +++ b/core/src/main/java/org/mapfish/print/map/image/AbstractSingleImageLayer.java @@ -182,7 +182,7 @@ private static String getInvalidResponseBody( throws IOException { if (contentType == null || contentType.size() != 1) { LOGGER.debug("The image {} didn't return a valid content type header.", request.getURI()); - } else if (!contentType.get(0).startsWith("image/")) { + } else if (!contentType.getFirst().startsWith("image/")) { final byte[] data; try (InputStream body = httpResponse.getBody()) { data = IOUtils.toByteArray(body); @@ -201,8 +201,13 @@ private boolean isResponseStatusCodeValid( if (httpResponse.getRawStatusCode() != HttpStatus.OK.value()) { String message = String.format( - "Invalid status code for %s (%d!=%d), status: %s. With request headers:\n%s\n" - + "The response was: '%s'\nWith response headers:\n%s", + """ + Invalid status code for %s (%d!=%d), status: %s. With request headers: + %s + The response was: '%s' + With response headers: + %s\ + """, request.getURI(), httpResponse.getRawStatusCode(), HttpStatus.OK.value(), @@ -233,11 +238,11 @@ private boolean isResponseBodyValid( LOGGER.debug( "We get a wrong image for {}, content type: {}\nresult:\n{}", request.getURI(), - contentType.get(0), + contentType.getFirst(), responseBody); this.registry.counter(MetricRegistry.name(baseMetricName, "error")).inc(); if (getFailOnError()) { - throw new RuntimeException("Wrong content-type : " + contentType.get(0)); + throw new RuntimeException("Wrong content-type : " + contentType.getFirst()); } else { return false; } diff --git a/core/src/main/java/org/mapfish/print/map/style/SLDParserPlugin.java b/core/src/main/java/org/mapfish/print/map/style/SLDParserPlugin.java index a8f9fa4564..2ce1680ff1 100644 --- a/core/src/main/java/org/mapfish/print/map/style/SLDParserPlugin.java +++ b/core/src/main/java/org/mapfish/print/map/style/SLDParserPlugin.java @@ -6,6 +6,7 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; +import java.util.Objects; import java.util.Optional; import java.util.function.Function; import javax.annotation.Nonnull; @@ -152,11 +153,7 @@ public URL locateResource(final String uri) { styles.length)); } - if (styleIndex == null) { - return Optional.of(styles[0]); - } else { - return Optional.of(styles[styleIndex]); - } + return Optional.of(styles[Objects.requireNonNullElse(styleIndex, 0)]); } private static boolean isNonXml(final byte[] bytes) { diff --git a/core/src/main/java/org/mapfish/print/map/style/json/JsonStyleParserHelper.java b/core/src/main/java/org/mapfish/print/map/style/json/JsonStyleParserHelper.java index f7e1fadc96..a5ef7a12fe 100644 --- a/core/src/main/java/org/mapfish/print/map/style/json/JsonStyleParserHelper.java +++ b/core/src/main/java/org/mapfish/print/map/style/json/JsonStyleParserHelper.java @@ -296,9 +296,8 @@ private String validateURL(final String externalGraphicUrl) { * * @param styleJson The old style. */ - @VisibleForTesting @Nullable - protected LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) { + LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) { final Stroke stroke = createStroke(styleJson, true); if (stroke == null) { return null; @@ -313,8 +312,7 @@ protected LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) { * @param styleJson The old style. */ @Nullable - @VisibleForTesting - protected PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) { + PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) { if (this.allowNullSymbolizer && !styleJson.has(JSON_FILL_COLOR)) { return null; } @@ -332,8 +330,7 @@ protected PolygonSymbolizer createPolygonSymbolizer(final PJsonObject styleJson) * * @param styleJson The old style. */ - @VisibleForTesting - protected TextSymbolizer createTextSymbolizer(final PJsonObject styleJson) { + TextSymbolizer createTextSymbolizer(final PJsonObject styleJson) { final TextSymbolizer textSymbolizer = this.styleBuilder.createTextSymbolizer(); // make sure that labels are also rendered if a part of the text would be outside @@ -426,7 +423,7 @@ private Font createFont(final Font defaultFont, final PJsonObject styleJson) { Expression fontFamily = parseExpression(null, styleJson, JSON_FONT_FAMILY, fontFamily1 -> fontFamily1); if (fontFamily == null) { - fontFamily = defaultFont.getFamily().get(0); + fontFamily = defaultFont.getFamily().getFirst(); } List fontFamilies = getFontExpressions(fontFamily, fontWeight); @@ -440,7 +437,8 @@ private Font createFont(final Font defaultFont, final PJsonObject styleJson) { fontStyle = defaultFont.getStyle(); } - Font font = this.styleBuilder.createFont(fontFamilies.get(0), fontStyle, fontWeight, fontSize); + Font font = + this.styleBuilder.createFont(fontFamilies.getFirst(), fontStyle, fontWeight, fontSize); if (fontFamilies.size() > 1) { // add remaining "fallback" fonts for (int i = 1; i < fontFamilies.size(); i++) { @@ -600,20 +598,20 @@ private AnchorPoint createAnchorPoint(final PJsonObject styleJson) { String yAlign = labelAlign.substring(1, 2); final double anchorInMiddle = 0.5; - if ("l".equals(xAlign)) { - anchorX = this.styleBuilder.literalExpression(0.0); - } else if ("c".equals(xAlign)) { - anchorX = this.styleBuilder.literalExpression(anchorInMiddle); - } else if ("r".equals(xAlign)) { - anchorX = this.styleBuilder.literalExpression(1.0); - } - if ("b".equals(yAlign)) { - anchorY = this.styleBuilder.literalExpression(0.0); - } else if ("m".equals(yAlign)) { - anchorY = this.styleBuilder.literalExpression(anchorInMiddle); - } else if ("t".equals(yAlign)) { - anchorY = this.styleBuilder.literalExpression(1.0); - } + anchorX = + switch (xAlign) { + case "l" -> this.styleBuilder.literalExpression(0.0); + case "c" -> this.styleBuilder.literalExpression(anchorInMiddle); + case "r" -> this.styleBuilder.literalExpression(1.0); + default -> anchorX; + }; + anchorY = + switch (yAlign) { + case "b" -> this.styleBuilder.literalExpression(0.0); + case "m" -> this.styleBuilder.literalExpression(anchorInMiddle); + case "t" -> this.styleBuilder.literalExpression(1.0); + default -> anchorY; + }; } boolean returnNull = true; if (anchorX == null) { @@ -705,8 +703,7 @@ Stroke createStroke(final PJsonObject styleJson, final boolean allowNull) { if (styleJson.has(JSON_STROKE_DASHSTYLE) && !STROKE_DASHSTYLE_SOLID.equals(styleJson.getString(JSON_STROKE_DASHSTYLE))) { double width = 1.0; - if (widthExpression instanceof Literal) { - Literal expression = (Literal) widthExpression; + if (widthExpression instanceof Literal expression) { width = ((Number) expression.getValue()).doubleValue(); } final Expression defaultDashSpacingE = this.styleBuilder.literalExpression(0.1f); @@ -815,7 +812,7 @@ private String getMimeTypeFromHttpResponse(final String externalGraphicFile) { } if (contentTypes != null && contentTypes.size() == 1) { - String contentType = contentTypes.get(0); + String contentType = contentTypes.getFirst(); int index = contentType.lastIndexOf(";"); return index >= 0 ? contentType.substring(0, index) : contentType; } diff --git a/core/src/main/java/org/mapfish/print/map/style/json/MapfishStyleParserPlugin.java b/core/src/main/java/org/mapfish/print/map/style/json/MapfishStyleParserPlugin.java index b3e868ba23..1d895180f4 100644 --- a/core/src/main/java/org/mapfish/print/map/style/json/MapfishStyleParserPlugin.java +++ b/core/src/main/java/org/mapfish/print/map/style/json/MapfishStyleParserPlugin.java @@ -452,12 +452,11 @@ public Optional