<commit_before>package org.geotools.map;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.grid.GridGeometry2D;
import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.data.ows.CRSEnvelope;
import org.geotools.data.ows.Layer;
import org.geotools.data.wms.WebMapServer;
import org.geotools.data.wms.request.GetFeatureInfoRequest;
import org.geotools.data.wms.request.GetMapRequest;
import org.geotools.data.wms.response.GetFeatureInfoResponse;
import org.geotools.data.wms.response.GetMapResponse;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.ows.ServiceException;
import org.geotools.referencing.CRS;
import org.geotools.renderer.lite.RendererUtilities;
import org.opengis.coverage.grid.Format;
import org.opengis.geometry.Envelope;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.parameter.ParameterValue;
import org.opengis.referencing.ReferenceIdentifier;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

/**
 * A grid coverage readers backing onto a WMS server by issuing GetMap
 */
class WMSCoverageReader extends AbstractGridCoverage2DReader {
    
    /** The logger for the map module. */
    static public final Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geotools.map");
    
    static GridCoverageFactory gcf = new GridCoverageFactory();

    /**
     * The WMS server
     */
    WebMapServer wms;

    /**
     * The layer
     */
    List<Layer> layers = new ArrayList<Layer>();

    /**
     * The chosen SRS name
     */
    String srsName;

    /**
     * The format to use for requests
     */
    String format;

    /**
     * The last GetMap request
     */
    GetMapRequest mapRequest;

    /**
     * The last GetMap response
     */
    GridCoverage2D grid;

    /**
     * The set of SRS common to all layers
     */
    Set<String> validSRS;

    /**
     * The cached layer bounds
     */
    ReferencedEnvelope bounds;

    /**
     * The last request envelope
     */
    ReferencedEnvelope requestedEnvelope;

    /**
     * Last request width
     */
    int width;

    /**
     * Last request height
     */
    int height;

    /**
     * Last request CRS (used for reprojected GetFeatureInfo)
     */
    CoordinateReferenceSystem requestCRS;

    /**
     * Builds a new WMS coverage reader
     * 
     * @param wms
     * @param layer
     */
    public WMSCoverageReader(WebMapServer wms, Layer layer) {
        this.wms = wms;
        addLayer(layer);

        // best guess at the format with a preference for PNG (since it's normally transparent)
        List<String> formats = wms.getCapabilities().getRequest().getGetMap().getFormats();
        this.format = formats.iterator().next();
        for (String format : formats) {
            if ("image/png".equals(format) || "image/png24".equals(format)
                    || "png".equals(format) || "png24".equals(format)
                    || "image/png; mode=24bit".equals(format)) {
                this.format = format;
                break;
            }
        }
    }

    void addLayer(Layer layer) {
        this.layers.add(layer);

        if (srsName == null) {
            // initialize from first layer
            if (layer.getBoundingBoxes().size() > 0) {
                // we assume the layer is declared in its native bounding box
                CRSEnvelope envelope = layer.getBoundingBoxes().get(
                        layer.getBoundingBoxes().keySet().iterator().next());
                srsName = envelope.getEPSGCode();
            } else if (layer.getSrs().contains("EPSG:4326")) {
                // otherwise we try 4326
                srsName = "EPSG:4326";
            } else {
                // if not even that works we just take the first...
                srsName = (String) layer.getSrs().iterator().next();
            }
            validSRS = layer.getSrs();
        } else {
            Set<String> intersection = new HashSet<String>(validSRS);
            intersection.retainAll(layer.getSrs());

            // can we reuse what we have?
            if (!intersection.contains(srsName)) {
                if (intersection.size() == 0) {
                    throw new IllegalArgumentException("The layer being appended does "
                            + "not have any SRS in common with the ones already "
                            + "included in the WMS request, cannot be merged");
                } else if (intersection.contains("EPSG:4326")) {<commit_msg>[GEOT-3528] WMSLayer fails against systems publishing data using unkonwn EPSG codes<commit_after>package org.geotools.map;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.grid.GridGeometry2D;
import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.data.ows.Layer;
import org.geotools.data.wms.WebMapServer;
import org.geotools.data.wms.request.GetFeatureInfoRequest;
import org.geotools.data.wms.request.GetMapRequest;
import org.geotools.data.wms.response.GetFeatureInfoResponse;
import org.geotools.data.wms.response.GetMapResponse;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.ows.ServiceException;
import org.geotools.referencing.CRS;
import org.geotools.renderer.lite.RendererUtilities;
import org.opengis.coverage.grid.Format;
import org.opengis.geometry.Envelope;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.parameter.ParameterValue;
import org.opengis.referencing.ReferenceIdentifier;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

/**
 * A grid coverage readers backing onto a WMS server by issuing GetMap
 */
class WMSCoverageReader extends AbstractGridCoverage2DReader {
    
    /** The logger for the map module. */
    static public final Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geotools.map");
    
    static GridCoverageFactory gcf = new GridCoverageFactory();

    /**
     * The WMS server
     */
    WebMapServer wms;

    /**
     * The layer
     */
    List<Layer> layers = new ArrayList<Layer>();

    /**
     * The chosen SRS name
     */
    String srsName;

    /**
     * The format to use for requests
     */
    String format;

    /**
     * The last GetMap request
     */
    GetMapRequest mapRequest;

    /**
     * The last GetMap response
     */
    GridCoverage2D grid;

    /**
     * The set of SRS common to all layers
     */
    Set<String> validSRS;

    /**
     * The cached layer bounds
     */
    ReferencedEnvelope bounds;

    /**
     * The last request envelope
     */
    ReferencedEnvelope requestedEnvelope;

    /**
     * Last request width
     */
    int width;

    /**
     * Last request height
     */
    int height;

    /**
     * Last request CRS (used for reprojected GetFeatureInfo)
     */
    CoordinateReferenceSystem requestCRS;

    /**
     * Builds a new WMS coverage reader
     * 
     * @param wms
     * @param layer
     */
    public WMSCoverageReader(WebMapServer wms, Layer layer) {
        this.wms = wms;
        addLayer(layer);

        // best guess at the format with a preference for PNG (since it's normally transparent)
        List<String> formats = wms.getCapabilities().getRequest().getGetMap().getFormats();
        this.format = formats.iterator().next();
        for (String format : formats) {
            if ("image/png".equals(format) || "image/png24".equals(format)
                    || "png".equals(format) || "png24".equals(format)
                    || "image/png; mode=24bit".equals(format)) {
                this.format = format;
                break;
            }
        }
    }

    void addLayer(Layer layer) {
        this.layers.add(layer);

        if (srsName == null) {
            // initialize from first layer
            for(String srs : layer.getBoundingBoxes().keySet()) {
                try {
                    // check it's valid, if not we crap out and move to the next
                    CRS.decode(srs);
                    srsName = srs;
                    break;
                } catch(Exception e) {
                    // it's fine, we could not decode that code
                }
            }
            
            if(srsName == null) {
                if (layer.getSrs().contains("EPSG:4326")) {
                    // otherwise we try 4326
                    srsName = "EPSG:4326";
                } else {
                    // if not even that works we just take the first...
                    srsName = (String) layer.getSrs().iterator().next();
                }
            }
            validSRS = layer.getSrs();
        } else {
            Set<String> intersection = new HashSet<String>(validSRS);
            intersection.retainAll(layer.getSrs());

            // can we reuse what we have?
            if (!intersection.contains(srsName)) {
                if (intersection.size() == 0) {
                    throw new IllegalArgumentException("The layer being appended does "
                            + "not have any SRS in common with the ones already "
                            + "included in the WMS request, cannot be merged");
                } else if (intersection.contains("EPSG:4326")) {
{'fraction_non_alphanumeric': 0.10513516041530259, 'fraction_numerical': 0.006079880273126929, 'mean_word_length': 2.337078651685393, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 1, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6963311', 'n_tokens_mistral': 3223, 'n_tokens_neox': 3093, 'n_words': 716}