From 59fbadc62a7434fca760d8a2eca48868f238adaf Mon Sep 17 00:00:00 2001 From: "francesco.mangiacrapa" Date: Fri, 22 Jan 2016 14:19:10 +0000 Subject: [PATCH] 2034: Gcube GisViewer: get gcube token for WPS service Task-Url: https://support.d4science.org/issues/show/2034 git-svn-id: https://svn.research-infrastructures.eu/d4science/gcube/trunk/spatial-data/geo-utility@122457 82a268e6-3cf1-43bd-a215-b396298e98cf --- .classpath | 36 ++ .project | 42 ++ .settings/.jsdtscope | 13 + .settings/org.eclipse.core.resources.prefs | 6 + .settings/org.eclipse.jdt.core.prefs | 8 + .settings/org.eclipse.m2e.core.prefs | 4 + .settings/org.eclipse.wst.common.component | 10 + ....eclipse.wst.common.project.facet.core.xml | 7 + ...rg.eclipse.wst.jsdt.ui.superType.container | 1 + .../org.eclipse.wst.jsdt.ui.superType.name | 1 + .settings/org.eclipse.wst.validation.prefs | 2 + pom.xml | 142 +++++++ .../spatial/data/geoutility/GeoGetStyles.java | 224 +++++++++++ .../geoutility/bean/NcWmsLayerMetadata.java | 144 +++++++ .../data/geoutility/bean/WmsParameters.java | 69 ++++ .../geoutility/bean/WmsServiceBaseUri.java | 91 +++++ .../data/geoutility/util/HttpRequestUtil.java | 126 ++++++ .../geoutility/util/NamespaceContextMap.java | 198 ++++++++++ .../data/geoutility/util/UrlEncoderUtil.java | 103 +++++ .../data/geoutility/util/XpathParserUtil.java | 160 ++++++++ .../data/geoutility/wms/NcWmsGetMetadata.java | 193 ++++++++++ .../wms/NcWmsGetMetadataRequest.java | 216 +++++++++++ .../data/geoutility/wms/WmsGetStyles.java | 337 ++++++++++++++++ .../data/geoutility/wms/WmsUrlValidator.java | 363 ++++++++++++++++++ src/main/webapp/GeoUtility.css | 34 ++ src/main/webapp/GeoUtility.html | 63 +++ src/main/webapp/WEB-INF/web.xml | 24 ++ .../spatial/data/geoutility/GeoJUnitTest.java | 32 ++ .../spatial/data/geoutility/log4j.properties | 20 + 29 files changed, 2669 insertions(+) create mode 100644 .classpath create mode 100644 .project create mode 100644 .settings/.jsdtscope create mode 100644 .settings/org.eclipse.core.resources.prefs create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.m2e.core.prefs create mode 100644 .settings/org.eclipse.wst.common.component create mode 100644 .settings/org.eclipse.wst.common.project.facet.core.xml create mode 100644 .settings/org.eclipse.wst.jsdt.ui.superType.container create mode 100644 .settings/org.eclipse.wst.jsdt.ui.superType.name create mode 100644 .settings/org.eclipse.wst.validation.prefs create mode 100644 pom.xml create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/GeoGetStyles.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/bean/NcWmsLayerMetadata.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/bean/WmsParameters.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/bean/WmsServiceBaseUri.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/util/HttpRequestUtil.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/util/NamespaceContextMap.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/util/UrlEncoderUtil.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/util/XpathParserUtil.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/wms/NcWmsGetMetadata.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/wms/NcWmsGetMetadataRequest.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/wms/WmsGetStyles.java create mode 100644 src/main/java/org/gcube/spatial/data/geoutility/wms/WmsUrlValidator.java create mode 100644 src/main/webapp/GeoUtility.css create mode 100644 src/main/webapp/GeoUtility.html create mode 100644 src/main/webapp/WEB-INF/web.xml create mode 100644 src/test/java/org/gcube/spatial/data/geoutility/GeoJUnitTest.java create mode 100644 src/test/resources/org/gcube/spatial/data/geoutility/log4j.properties diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..750b6b3 --- /dev/null +++ b/.classpath @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..021438a --- /dev/null +++ b/.project @@ -0,0 +1,42 @@ + + + geo-utility + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope new file mode 100644 index 0000000..b72a6a4 --- /dev/null +++ b/.settings/.jsdtscope @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..29abf99 --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,6 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding//src/test/resources=UTF-8 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..443e085 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..3dcba20 --- /dev/null +++ b/.settings/org.eclipse.wst.common.component @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..735eb31 --- /dev/null +++ b/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/.settings/org.eclipse.wst.validation.prefs b/.settings/org.eclipse.wst.validation.prefs new file mode 100644 index 0000000..04cad8c --- /dev/null +++ b/.settings/org.eclipse.wst.validation.prefs @@ -0,0 +1,2 @@ +disabled=06target +eclipse.preferences.version=1 diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..9b1ff74 --- /dev/null +++ b/pom.xml @@ -0,0 +1,142 @@ + + + + maven-parent + org.gcube.tools + 1.0.0 + + + 4.0.0 + org.gcube.spatial.data + geo-utility + jar + 1.0.0-SNAPSHOT + A library with several utility class to work with geo-spatial data: WmsUrlValidator, GeoGetStylesUtils, etc.. + + + distro + UTF-8 + + + + + + junit + junit + 4.8.2 + test + + + + commons-lang + commons-lang + 2.6 + + + + + org.w3c + dom + 2.3.0-jaxb-1.0.6 + compile + + + + commons-io + commons-io + 1.2 + + + + + + + + + + org.json + json + 20140107 + compile + + + + log4j + log4j + 1.2.16 + + + org.slf4j + slf4j-log4j12 + 1.6.4 + + + + + + + + src/main/java + + **/*.* + + + + + src/main/resources + + **/*.* + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.5 + + + copy-profile + install + + copy-resources + + + target + + + ${distroDirectory} + true + + profile.xml + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + ${distroDirectory}/descriptor.xml + + + + + servicearchive + install + + single + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/spatial/data/geoutility/GeoGetStyles.java b/src/main/java/org/gcube/spatial/data/geoutility/GeoGetStyles.java new file mode 100644 index 0000000..f634a48 --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/GeoGetStyles.java @@ -0,0 +1,224 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility; + +import java.util.HashMap; +import java.util.List; + +import org.apache.log4j.Logger; +import org.gcube.spatial.data.geoutility.bean.NcWmsLayerMetadata; +import org.gcube.spatial.data.geoutility.bean.WmsParameters; +import org.gcube.spatial.data.geoutility.wms.NcWmsGetMetadata; +import org.gcube.spatial.data.geoutility.wms.NcWmsGetMetadataRequest; +import org.gcube.spatial.data.geoutility.wms.WmsGetStyles; +import org.gcube.spatial.data.geoutility.wms.WmsUrlValidator; + +/** + * The Class GeoGetStyles. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2016 + * + * return list of styles from a OGC compliant WMS/ncWMS map service like Geoserver, Thredds, Mapsever. + */ +public class GeoGetStyles { + + public static Logger logger = Logger.getLogger(GeoGetStyles.class); + public static final String COLORSCALERANGE = "COLORSCALERANGE"; + public static final String COLORSCALERANGE_DEFAULT_VALUE = "auto"; + boolean isNcWms = false; + private String wmsRequest; + + private HashMap mapWmsNotStandard; + private WmsUrlValidator validator; + + /** + * Instantiates a new geo get styles. + * + * @param wmsRequest the wms request + * @throws Exception + */ + public GeoGetStyles(String wmsRequest) throws Exception{ + this.wmsRequest = wmsRequest; + this.validator = new WmsUrlValidator(wmsRequest); + validator.parseWmsRequest(true, false); + } + + /** + * Gets the styles. + * + * @return the styles + */ + public List getStyles(){ + + String uriWMSService = validator.getBaseWmsServiceUrl(); + String layerName = validator.getValueOfParsedWMSParameter(WmsParameters.LAYERS); + String versionWms = validator.getValueOfParsedWMSParameter(WmsParameters.VERSION); + String crs = validator.getValueOfParsedWMSParameter(WmsParameters.CRS); + + System.out.println(validator.getParameterValues().toString()); + + try { + + if(validator.getMapWmsNotStandardParams()!=null){ + mapWmsNotStandard = new HashMap(validator.getMapWmsNotStandardParams().size()); + mapWmsNotStandard.putAll(validator.getMapWmsNotStandardParams()); + + if(mapWmsNotStandard.containsKey(NcWmsGetMetadataRequest.COLORSCALERANGE) || mapWmsNotStandard.containsKey(NcWmsGetMetadataRequest.COLORSCALERANGE.toLowerCase())){ + logger.debug("Ovveriding "+NcWmsGetMetadataRequest.COLORSCALERANGE +"?"); + String value = mapWmsNotStandard.get(NcWmsGetMetadataRequest.COLORSCALERANGE); + + if(value.compareToIgnoreCase(NcWmsGetMetadataRequest.COLORSCALERANGE_DEFAULT_VALUE)==0){ //COLORSCALERANGE == 'auto'? + logger.trace(NcWmsGetMetadataRequest.COLORSCALERANGE +" found like 'auto'.."); + String[] minmax = NcWmsGetMetadataRequest.getColorScaleRange(uriWMSService, + versionWms, + validator.getValueOfParsedWMSParameter(WmsParameters.BBOX), + layerName, + crs, + validator.getValueOfParsedWMSParameter(WmsParameters.WIDTH), + validator.getValueOfParsedWMSParameter(WmsParameters.HEIGHT)); + + if(minmax!=null && minmax.length==2 && minmax[0]!=null && minmax[1]!=null){ + String valueMinMax = minmax[0]+","+minmax[1]; + mapWmsNotStandard.put(NcWmsGetMetadataRequest.COLORSCALERANGE, valueMinMax); + logger.debug("Overrided "+NcWmsGetMetadataRequest.COLORSCALERANGE +" min,max value: "+valueMinMax); + } + }else{ + logger.debug(NcWmsGetMetadataRequest.COLORSCALERANGE +" is not \'auto', skipping override"); + } + }else{ //NcWmsGetColorScaleRange.COLORSCALERANGE not found + logger.debug(NcWmsGetMetadataRequest.COLORSCALERANGE +" not found"); + + String[] minmax = NcWmsGetMetadataRequest.getColorScaleRange(uriWMSService, + versionWms, + validator.getValueOfParsedWMSParameter(WmsParameters.BBOX), + layerName, + crs, + validator.getValueOfParsedWMSParameter(WmsParameters.WIDTH), + validator.getValueOfParsedWMSParameter(WmsParameters.HEIGHT)); + + if(minmax!=null && minmax.length==2 && minmax[0]!=null && minmax[1]!=null){ + logger.debug(NcWmsGetMetadataRequest.GET_METADATA +" works, adding "+NcWmsGetMetadataRequest.COLORSCALERANGE + " with minmax"); + String valueMinMax = minmax[0]+","+minmax[1]; + mapWmsNotStandard.put(NcWmsGetMetadataRequest.COLORSCALERANGE, valueMinMax); + logger.debug("Added "+NcWmsGetMetadataRequest.COLORSCALERANGE +" min,max value: "+valueMinMax); + }else{ + logger.debug(NcWmsGetMetadataRequest.GET_METADATA +" failed, skip "+NcWmsGetMetadataRequest.COLORSCALERANGE +" management, is not raster?"); + } + } + } + }catch (Exception e) { + logger.error("Exception during ncWMS get style: "+e); + } + + logger.trace("versionWms found: "+versionWms); + logger.trace("crs found: "+crs); + + String stylesRead = validator.getValueOfParsedWMSParameter(WmsParameters.STYLES); + logger.trace("styles found: "+stylesRead); + + List styles; + //VALIDATION STYLES + if(stylesRead==null || stylesRead.isEmpty()){ + + logger.trace("styles is empty - validator styles "+stylesRead); + WmsGetStyles wmsGetStyles = new WmsGetStyles(); + + styles = wmsGetStyles.getStylesFromWms(uriWMSService, layerName); + + if(wmsGetStyles.getResponseCode()==200){ + logger.debug("wms GetStyles found: "+styles); + }else{ + logger.debug("Tentative to get styles from NcWmsGetMetadata..."); + isNcWms = true; + try{ + NcWmsLayerMetadata ncMetadata = NcWmsGetMetadata.getMetadata(uriWMSService, layerName); + + if(ncMetadata!=null && ncMetadata.getResponseCode()==200){ + if(ncMetadata.getSupportedStyles().size()>0){ + styles.add(ncMetadata.getSupportedStyles().get(0)+"/"+ncMetadata.getDefaultPalette()); //DEFAULT STYLE + logger.debug("added ncWms default style: "+ncMetadata.getSupportedStyles().get(0)+"/"+ncMetadata.getDefaultPalette()); + + for (String s : ncMetadata.getSupportedStyles()) { + for (String p : ncMetadata.getPalettes()) { + String as = s+"/"+p; + if(!styles.contains(as)){ + styles.add(as); + logger.trace("added ncWms style: "+as); + } + } + } + } + } + }catch(Exception e){ + logger.error(e); + styles = validator.getStylesAsList(); + } + } + }else{ + styles = validator.getStylesAsList(); + } + + return styles; + } + + /** + * Checks if is nc wms. + * + * @return the isNcWms + */ + public boolean isNcWms() { + + return isNcWms; + } + + /** + * Gets the wms request. + * + * @return the wmsRequest + */ + public String getWmsRequest() { + + return wmsRequest; + } + + /** + * Gets the map wms not standard. + * + * @return the mapWmsNotStandard + */ + public HashMap getMapWmsNotStandard() { + + return mapWmsNotStandard; + } + + /** + * Gets the validator. + * + * @return the validator + */ + public WmsUrlValidator getValidator() { + + return validator; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + StringBuilder builder = new StringBuilder(); + builder.append("GetStylesUtils [isNcWms="); + builder.append(isNcWms); + builder.append(", wmsRequest="); + builder.append(wmsRequest); + builder.append(", mapWmsNotStandard="); + builder.append(mapWmsNotStandard); + builder.append(", validator="); + builder.append(validator); + builder.append("]"); + return builder.toString(); + } +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/bean/NcWmsLayerMetadata.java b/src/main/java/org/gcube/spatial/data/geoutility/bean/NcWmsLayerMetadata.java new file mode 100644 index 0000000..2a454cc --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/bean/NcWmsLayerMetadata.java @@ -0,0 +1,144 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility.bean; + +import java.io.Serializable; +import java.util.List; + + +/** + * The Class NcWmsLayerMetadata. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Dec 18, 2015 + */ +public class NcWmsLayerMetadata implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5111586382138532571L; + + //GET PARAMETERS + public static final String SUPPORTEDSTYLES = "supportedStyles"; + public static final String PALETTES = "palettes"; + public static final String DEFAULTPALETTE = "defaultPalette"; + private String defaultPalette; + private List supportedStyles; + private List palettes; + private int responseCode; + + /** + * Instantiates a new nc wms layer metadata. + */ + public NcWmsLayerMetadata() { + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new nc wms layer metadata. + * + * @param responseCode the response code + * @param defaultPalette the default palette + * @param supportedStyles the supported styles + * @param palettes the palettes + */ + public NcWmsLayerMetadata(int responseCode, String defaultPalette, List supportedStyles, List palettes) { + this.responseCode = responseCode; + this.defaultPalette = defaultPalette; + this.supportedStyles = supportedStyles; + this.palettes = palettes; + } + + + /** + * Gets the default palette. + * + * @return the defaultPalette + */ + public String getDefaultPalette() { + return defaultPalette; + } + + + /** + * Gets the supported styles. + * + * @return the supportedStyles + */ + public List getSupportedStyles() { + return supportedStyles; + } + + + /** + * Gets the palettes. + * + * @return the palettes + */ + public List getPalettes() { + return palettes; + } + + + /** + * Sets the default palette. + * + * @param defaultPalette the defaultPalette to set + */ + public void setDefaultPalette(String defaultPalette) { + this.defaultPalette = defaultPalette; + } + + + /** + * Sets the supported styles. + * + * @param supportedStyles the supportedStyles to set + */ + public void setSupportedStyles(List supportedStyles) { + this.supportedStyles = supportedStyles; + } + + /** + * @return the responseCode + */ + public int getResponseCode() { + return responseCode; + } + + /** + * @param responseCode the responseCode to set + */ + public void setResponseCode(int responseCode) { + this.responseCode = responseCode; + } + + + + /** + * Sets the palettes. + * + * @param palettes the palettes to set + */ + public void setPalettes(List palettes) { + this.palettes = palettes; + } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("NcWmsLayerMetadata [defaultPalette="); + builder.append(defaultPalette); + builder.append(", supportedStyles="); + builder.append(supportedStyles); + builder.append(", palettes="); + builder.append(palettes); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/bean/WmsParameters.java b/src/main/java/org/gcube/spatial/data/geoutility/bean/WmsParameters.java new file mode 100644 index 0000000..588c95a --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/bean/WmsParameters.java @@ -0,0 +1,69 @@ +package org.gcube.spatial.data.geoutility.bean; + + +/** + * + * Param Mandatory + * service Yes Service name. Value is WMS. + * version Yes Service version. Value is one of 1.0.0, 1.1.0, 1.1.1, 1.3. + * request Yes Operation name. Value is GetMap. + * layers Yes Layers to display on map. Value is a comma-separated list of layer names. + * styles Yes Styles in which layers are to be rendered. Value is a comma-separated list of style names, or empty if default styling is required. Style names may be empty in the list, to use default layer styling. + * srs or crs Yes Spatial Reference System for map output. Value is in form EPSG:nnn. crs is the parameter key used in WMS 1.3.0. + * bbox Yes Bounding box for map extent. Value is minx,miny,maxx,maxy in units of the SRS. + * width Yes Width of map output, in pixels. + * height Yes Height of map output, in pixels. + * format Yes Format for the map output. See WMS output formats for supported values. + * transparent No Whether the map background should be transparent. Values are true or false. Default is false + * bgcolor No Background color for the map image. Value is in the form RRGGBB. Default is FFFFFF (white). + * exceptions No Format in which to report exceptions. Default value is application/vnd.ogc.se_xml. + * time No Time value or range for map data. See Time Support in Geoserver WMS for more information. + * sld No A URL referencing a StyledLayerDescriptor XML file which controls or enhances map layers and styling + * sld_body No A URL-encoded StyledLayerDescriptor XML document which controls or enhances map layers and styling + * + */ +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * @Apr 26, 2013 + * + */ +public enum WmsParameters { + + SERVICE("SERVICE", "WMS"), + VERSION("VERSION", "1.1.0"), + REQUEST("REQUEST", "GetMap"), + LAYERS("LAYERS", ""), + STYLES("STYLES",""), + BBOX("BBOX","-180,-90,180,90"), + WIDTH("WIDTH","676"), + HEIGHT("HEIGHT","230"), + SRS("SRS","EPSG:4326"), + CRS("CRS","EPSG:4326"), //WMS 1.3.0 COMPLIANT + FORMAT("FORMAT","image/png"), + TRANSPARENT("TRANSPARENT","true"); + + private String parameter; + private String value; + + WmsParameters(String parameter, String value){ + this.parameter = parameter; + this.value = value; + } + + public String getParameter() { + return parameter; + } + + public void setParameter(String parameter) { + this.parameter = parameter; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/bean/WmsServiceBaseUri.java b/src/main/java/org/gcube/spatial/data/geoutility/bean/WmsServiceBaseUri.java new file mode 100644 index 0000000..7999dd9 --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/bean/WmsServiceBaseUri.java @@ -0,0 +1,91 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility.bean; + +import java.io.Serializable; + +/** + * The Class WmsServiceBaseUri. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2016 + */ +public class WmsServiceBaseUri implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = -5557778286412179122L; + + private String baseUrl = ""; + private String scope = ""; + + /** + * Instantiates a new geoserver base uri. + */ + public WmsServiceBaseUri() { + } + + /** + * Instantiates a new geoserver base uri. + * + * @param baseUrl the base url + * @param scope the scope + */ + public WmsServiceBaseUri(String baseUrl, String scope) { + this.baseUrl = baseUrl; + this.scope = scope; + } + + /** + * Gets the base url. + * + * @return the base url + */ + public String getBaseUrl() { + return baseUrl; + } + + /** + * Sets the base url. + * + * @param baseUrl the new base url + */ + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + /** + * Gets the scope. + * + * @return the scope + */ + public String getScope() { + return scope; + } + + /** + * Sets the scope. + * + * @param scope the new scope + */ + public void setScope(String scope) { + this.scope = scope; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("GeoserverBaseUri [baseUrl="); + builder.append(baseUrl); + builder.append(", scope="); + builder.append(scope); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/util/HttpRequestUtil.java b/src/main/java/org/gcube/spatial/data/geoutility/util/HttpRequestUtil.java new file mode 100644 index 0000000..26e58bc --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/util/HttpRequestUtil.java @@ -0,0 +1,126 @@ +package org.gcube.spatial.data.geoutility.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLConnection; + +import org.apache.log4j.Logger; + +/** + * The Class HttpRequestUtil. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2016 + */ +public class HttpRequestUtil { + + private static final String SERVICE_EXCEPTION_REPORT = "ServiceExceptionReport"; //WMS Exception + private static final String OWS_EXCEPTION_REPORT = "ows:ExceptionReport"; //OWS Exception + private static final int CONNECTION_TIMEOUT = 1000; + public static Logger logger = Logger.getLogger(HttpRequestUtil.class); + + /** + * Url exists. + * + * @param urlConn the url conn + * @param verifyIsWmsGeoserver the verify is wms geoserver + * @return true, if successful + * @throws Exception the exception + */ + public static boolean urlExists(String urlConn, boolean verifyIsWmsGeoserver) throws Exception { + + URL url; + try { + url = new URL(urlConn); + + URLConnection connection = url.openConnection(); + connection.setConnectTimeout(CONNECTION_TIMEOUT); + connection.setReadTimeout(CONNECTION_TIMEOUT+CONNECTION_TIMEOUT); + + logger.trace("open connection on: " + url); + + // Cast to a HttpURLConnection + if (connection instanceof HttpURLConnection) { + HttpURLConnection httpConnection = (HttpURLConnection) connection; + + httpConnection.setRequestMethod("GET"); + + int code = httpConnection.getResponseCode(); + + if(verifyIsWmsGeoserver) + return isGeoserver(httpConnection); + + httpConnection.disconnect(); + + if (code == 200) + return true; + } else { + logger.error("error - not a http request!"); + } + + return false; + + } catch (SocketTimeoutException e) { + logger.error("Error SocketTimeoutException with url " +urlConn); + throw new Exception("Error SocketTimeoutException"); + } catch (MalformedURLException e) { + logger.error("Error MalformedURLException with url " +urlConn); + throw new Exception("Error MalformedURLException"); + } catch (IOException e) { + logger.error("Error IOException with url " +urlConn); + throw new Exception("Error IOException"); + }catch (Exception e) { + logger.error("Error Exception with url " +urlConn); + throw new Exception("Error Exception"); + } + } + + + /** + * Checks if is geoserver. + * + * @param httpConnection the http connection + * @return true, if is geoserver + * @throws IOException Signals that an I/O exception has occurred. + */ + private static boolean isGeoserver(HttpURLConnection httpConnection) throws IOException{ + + BufferedReader rd = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); + String line; + String result = ""; + + int code = httpConnection.getResponseCode(); + + if (code == 200) { + while ((line = rd.readLine()) != null) { + result += line; + } + } + else{ + rd.close(); + return false; + } + if(result.contains(OWS_EXCEPTION_REPORT) || result.contains(SERVICE_EXCEPTION_REPORT)){ + rd.close(); + return true; + } + rd.close(); + return false; + + } + + /** + * The main method. + * + * @param args the arguments + * @throws Exception the exception + */ + public static void main(String[] args) throws Exception { + System.out.println(HttpRequestUtil.urlExists("http://geoserver2.d4science.research-infrastructures.eu/geoserver/wms", true)); + } +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/util/NamespaceContextMap.java b/src/main/java/org/gcube/spatial/data/geoutility/util/NamespaceContextMap.java new file mode 100644 index 0000000..6a8dd1f --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/util/NamespaceContextMap.java @@ -0,0 +1,198 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility.util; + +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * @May 7, 2013 + * + */ +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import javax.xml.XMLConstants; +import javax.xml.namespace.NamespaceContext; + + +/** + * The Class NamespaceContextMap. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2016 + */ +public final class NamespaceContextMap implements NamespaceContext { + + private final Map prefixMap; + private final Map> nsMap; + + /** + * Constructor that takes a map of XML prefix-namespaceURI values. A + * defensive copy is made of the map. An IllegalArgumentException will be + * thrown if the map attempts to remap the standard prefixes defined in the + * NamespaceContext contract. + * + * @param prefixMappings + * a map of prefix:namespaceURI values + */ + public NamespaceContextMap(Map prefixMappings) { + prefixMap = createPrefixMap(prefixMappings); + nsMap = createNamespaceMap(prefixMap); + } + + /** + * Convenience constructor. + * + * @param mappingPairs + * pairs of prefix-namespaceURI values + */ + public NamespaceContextMap(String... mappingPairs) { + this(toMap(mappingPairs)); + } + + /** + * To map. + * + * @param mappingPairs the mapping pairs + * @return the map + */ + private static Map toMap(String... mappingPairs) { + Map prefixMappings = new HashMap( + mappingPairs.length / 2); + for (int i = 0; i < mappingPairs.length; i++) { + prefixMappings.put(mappingPairs[i], mappingPairs[++i]); + } + return prefixMappings; + } + + /** + * Creates the prefix map. + * + * @param prefixMappings the prefix mappings + * @return the map + */ + private Map createPrefixMap( + Map prefixMappings) { + Map prefixMap = new HashMap( + prefixMappings); + addConstant(prefixMap, XMLConstants.XML_NS_PREFIX, + XMLConstants.XML_NS_URI); + addConstant(prefixMap, XMLConstants.XMLNS_ATTRIBUTE, + XMLConstants.XMLNS_ATTRIBUTE_NS_URI); + return Collections.unmodifiableMap(prefixMap); + } + + /** + * Adds the constant. + * + * @param prefixMap the prefix map + * @param prefix the prefix + * @param nsURI the ns uri + */ + private void addConstant(Map prefixMap, String prefix, + String nsURI) { + String previous = prefixMap.put(prefix, nsURI); + if (previous != null && !previous.equals(nsURI)) { + throw new IllegalArgumentException(prefix + " -> " + previous + + "; see NamespaceContext contract"); + } + } + + /** + * Creates the namespace map. + * + * @param prefixMap the prefix map + * @return the map + */ + private Map> createNamespaceMap( + Map prefixMap) { + Map> nsMap = new HashMap>(); + for (Map.Entry entry : prefixMap.entrySet()) { + String nsURI = entry.getValue(); + Set prefixes = nsMap.get(nsURI); + if (prefixes == null) { + prefixes = new HashSet(); + nsMap.put(nsURI, prefixes); + } + prefixes.add(entry.getKey()); + } + for (Map.Entry> entry : nsMap.entrySet()) { + Set readOnly = Collections + .unmodifiableSet(entry.getValue()); + entry.setValue(readOnly); + } + return nsMap; + } + + /* (non-Javadoc) + * @see javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String) + */ + @Override + public String getNamespaceURI(String prefix) { + checkNotNull(prefix); + String nsURI = prefixMap.get(prefix); + return nsURI == null ? XMLConstants.NULL_NS_URI : nsURI; + } + + /* (non-Javadoc) + * @see javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String) + */ + @Override + public String getPrefix(String namespaceURI) { + checkNotNull(namespaceURI); + Set set = nsMap.get(namespaceURI); + return set == null ? null : set.iterator().next(); + } + + /* (non-Javadoc) + * @see javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String) + */ + @Override + public Iterator getPrefixes(String namespaceURI) { + checkNotNull(namespaceURI); + Set set = nsMap.get(namespaceURI); + return set.iterator(); + } + + /** + * Check not null. + * + * @param value the value + */ + private void checkNotNull(String value) { + if (value == null) { + throw new IllegalArgumentException("null"); + } + } + + /** + * Gets the map. + * + * @return an unmodifiable map of the mappings in the form + * prefix-namespaceURI + */ + public Map getMap() { + return prefixMap; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("NamespaceContextMap [prefixMap="); + builder.append(prefixMap); + builder.append(", nsMap="); + builder.append(nsMap); + builder.append("]"); + return builder.toString(); + } + + + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/spatial/data/geoutility/util/UrlEncoderUtil.java b/src/main/java/org/gcube/spatial/data/geoutility/util/UrlEncoderUtil.java new file mode 100644 index 0000000..c4cac77 --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/util/UrlEncoderUtil.java @@ -0,0 +1,103 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility.util; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * @Jun 4, 2013 + * + */ +public class UrlEncoderUtil { + + public static String charset = "UTF-8"; + + public static Logger logger = Logger.getLogger(UrlEncoderUtil.class); + /** + * + * @param url + * @param parameters + * @return + */ + public static String encodeQuery(String... parameters){ + + String query = ""; + for (String string : parameters) { + + try { + query+=URLEncoder.encode(string, charset)+"&"; + } catch (UnsupportedEncodingException e) { + logger.error(e); + return query; + } + + } + return removeLastChar(query); + } + + + + /** + * + * @param url + * @param parameters + * @return + */ + public static String encodeQuery(Map parameters){ + + String query = ""; + + if(parameters==null) + return query; + + for (String key : parameters.keySet()) { + + try { + + query+=String.format(key+"=%s", URLEncoder.encode(parameters.get(key), charset))+"&"; + } catch (UnsupportedEncodingException e) { + logger.error(e); + return query; + } + + } + + return removeLastChar(query); + + } + + public static String removeLastChar(String string){ + + if(string == null) + return null; + + if(string.length()>0) + return string.substring(0, string.length()-1); + + return string; + } + + public static void main(String[] args) { + +// System.out.println(UrlEncoderUtil.encodeQuery("request=GetStyles", "layers=test Name", "service=WMS", "version=1.1.1")); + + HashMap parameters = new HashMap(); + + parameters.put("request", "GetStyles"); + parameters.put("layers", "test Name"); + parameters.put("version", "1.1.1"); + + System.out.println(UrlEncoderUtil.encodeQuery(parameters)); + + + } + + +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/util/XpathParserUtil.java b/src/main/java/org/gcube/spatial/data/geoutility/util/XpathParserUtil.java new file mode 100644 index 0000000..1083985 --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/util/XpathParserUtil.java @@ -0,0 +1,160 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility.util; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathFactory; + +import org.apache.commons.io.IOUtils; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/** + * The Class XpathParserUtil. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 21, 2016 + */ +public class XpathParserUtil { + + /** + * Gets the text from x path expression. + * + * @param context the context + * @param source the source + * @param xpathExpression the xpath expression + * @return the text from x path expression + */ + public static List getTextFromXPathExpression(NamespaceContextMap context, InputStream source, String xpathExpression){ + + List list = new ArrayList(); + try { + + XPath xpath = XPathFactory.newInstance().newXPath(); + xpath.setNamespaceContext(context); + XPathExpression xPathExpression = xpath.compile(xpathExpression); + InputSource inputSource = new InputSource(source); + +// System.out.println(xml); +// System.out.println(xpathExpression); +// System.out.println(inputSource.toString()); + + NodeList nodes = (NodeList) xPathExpression.evaluate(inputSource, XPathConstants.NODESET); + + for (int i = 0; i getTextFromXPathExpression(NamespaceContextMap context, String source, String xpathExpression){ + + List list = new ArrayList(); + try { + + XPath xpath = XPathFactory.newInstance().newXPath(); + xpath.setNamespaceContext(context); + XPathExpression xPathExpression = xpath.compile(xpathExpression); + InputSource inputSource = new InputSource(IOUtils.toInputStream(source)); + + NodeList nodes = (NodeList) xPathExpression.evaluate(inputSource, XPathConstants.NODESET); + + for (int i = 0; i mappings = new HashMap(); +// mappings.put("xmlns", "http://www.opengis.net/sld"); + mappings.put("sld", "http://www.opengis.net/sld"); + mappings.put("ogc", "http://www.opengis.net/ogc"); + mappings.put("gml", "http://www.opengis.net/gml"); + mappings.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); + NamespaceContextMap context = new NamespaceContextMap(mappings); + + List listStylesNames = new ArrayList(); + + InputStream inputStream = XpathParserUtil.class.getResourceAsStream("styles.sld+xml"); + + + String xmlGetStyles = IOUtils.toString(inputStream); + + String xpathExpression = "//sld:UserStyle[sld:IsDefault=1]/sld:Name"; //FIND DEFAULT STYLE NAME + + List defaultStylesList = XpathParserUtil.getTextFromXPathExpression(context, xmlGetStyles, xpathExpression); + + + LinkedHashMap exclusiveStyles = new LinkedHashMap(); + + //DEFAULT STYLE IS FOUND + if(defaultStylesList.size()>0 || !defaultStylesList.get(0).isEmpty()){ + + String defaultStyle = defaultStylesList.get(0); + exclusiveStyles.put(defaultStyle, defaultStyle); + } + + xpathExpression = "//sld:UserStyle/sld:Name"; //FIND OTHER STYLES NAMES AND ADD INTO LIST + List allStyles = XpathParserUtil.getTextFromXPathExpression(context, xmlGetStyles, xpathExpression); + + for (String style : allStyles) { + exclusiveStyles.put(style, style); + } + + listStylesNames.addAll(exclusiveStyles.keySet()); + + + for (String string : listStylesNames) { + System.out.println("style: "+string); + } + + }*/ + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/spatial/data/geoutility/wms/NcWmsGetMetadata.java b/src/main/java/org/gcube/spatial/data/geoutility/wms/NcWmsGetMetadata.java new file mode 100644 index 0000000..523bd27 --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/wms/NcWmsGetMetadata.java @@ -0,0 +1,193 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility.wms; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.apache.log4j.Logger; +import org.gcube.spatial.data.geoutility.bean.NcWmsLayerMetadata; +import org.gcube.spatial.data.geoutility.bean.WmsParameters; +import org.gcube.spatial.data.geoutility.util.UrlEncoderUtil; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * The Class NcWmsGetMetadata. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Dec 18, 2015 + */ +public class NcWmsGetMetadata { + + protected static final int CONNECTION_TIMEOUT = 1000; + public static Logger logger = Logger.getLogger(NcWmsGetMetadata.class); + + + /** + * Gets the metadata. + * + * @param wmsServerUri the wms server uri + * @param layerName the layer name + * @return the metadata + * @throws Exception the exception + */ + public static NcWmsLayerMetadata getMetadata(String wmsServerUri, String layerName) throws Exception { + + if(wmsServerUri==null || wmsServerUri.isEmpty()) + throw new Exception("Invalid wms server uri"); + + HashMap parameters = new HashMap(); + parameters.put(WmsParameters.REQUEST.getParameter(), "GetMetadata"); + parameters.put("layerName", layerName); + parameters.put("item", "layerDetails"); + parameters.put(WmsParameters.SERVICE.getParameter(), "WMS"); + + try { + + String query = UrlEncoderUtil.encodeQuery(parameters); + return openConnectionGetMetadata(wmsServerUri, query); + + }catch (Exception e) { + logger.error("Error Exception with url " + wmsServerUri); + return null; + } + } + + /** + * Open connection get metadata. + * + * @param urlConn the url conn + * @param query the query + * @return the nc wms layer metadata + */ + private static NcWmsLayerMetadata openConnectionGetMetadata(String urlConn, String query) { + + URL url; + NcWmsLayerMetadata metadata = null; + + try { + url = new URL(urlConn + "?" + query); + URLConnection connection = url.openConnection(); + + connection.setConnectTimeout(CONNECTION_TIMEOUT); + connection.setReadTimeout(CONNECTION_TIMEOUT + CONNECTION_TIMEOUT); + + logger.trace("openConnectionGetMetadata on: " + url); + + // Cast to a HttpURLConnection + if (connection instanceof HttpURLConnection) { + HttpURLConnection httpConnection = (HttpURLConnection) connection; + + httpConnection.setRequestMethod("GET"); + int code = httpConnection.getResponseCode(); + + if (code == 200) { + metadata = getMetadata(httpConnection); + metadata.setResponseCode(code); + }else{ + logger.warn("openConnectionGetMetadata error, code = " + code +", returning"); + } + + httpConnection.disconnect(); + + } else { + logger.error("error - not a http request!"); + } + + return metadata; + + } catch (SocketTimeoutException e) { + logger.error("Error SocketTimeoutException with url " + urlConn); + return metadata; + } catch (MalformedURLException e) { + logger.error("Error MalformedURLException with url " + urlConn); + return metadata; + } catch (IOException e) { + logger.error("Error IOException with url " + urlConn); + return metadata; + } catch (Exception e) { + logger.error("Error Exception with url " + urlConn); + return metadata; + } + + } + + /** + * Gets the metadata. + * + * @param httpConnection the http connection + * @return the metadata + * @throws IOException Signals that an I/O exception has occurred. + */ + private static NcWmsLayerMetadata getMetadata(HttpURLConnection httpConnection) throws IOException{ + + InputStream source = null; + NcWmsLayerMetadata metadata = new NcWmsLayerMetadata(); + + try{ + source = httpConnection.getInputStream(); + String jsonTxt = IOUtils.toString(source); + JSONObject json = new JSONObject(jsonTxt); + + JSONArray supportedStyles = json.getJSONArray("supportedStyles"); + + if(supportedStyles!=null){ + List s = new ArrayList(supportedStyles.length()); + for (int i=0; i s = new ArrayList(palettes.length()); + for (int i=0; i parameters = new HashMap(); + parameters.put(WmsParameters.REQUEST.getParameter(), GET_METADATA); + parameters.put(WmsParameters.LAYERS.getParameter(), layerName); + parameters.put("item", "minmax"); + + parameters.put(WmsParameters.CRS.getParameter(), crs); + parameters.put(WmsParameters.WIDTH.getParameter(), width); + parameters.put(WmsParameters.HEIGHT.getParameter(), height); + + if(wmsVersion.compareTo(WMS_VERSION_1_3_0)==0){ + String[] values = bbox.split(","); + String newbbox = values[1] +","+values[0]+","+values[3]+","+values[2]; + logger.trace("inverted bbox to wms 1.3.0: "+newbbox); + parameters.put(WmsParameters.BBOX.getParameter(), newbbox); + + }else + parameters.put(WmsParameters.BBOX.getParameter(), bbox); + + try { + + String query = UrlEncoderUtil.encodeQuery(parameters); + colorScaleMinMax = openConnectionGetColorScaleRange(wmsServerUri, query); + return colorScaleMinMax; + + }catch (Exception e) { + logger.error("Error Exception with url " + wmsServerUri); + return colorScaleMinMax; + } + } + + /** + * Open connection get color scale range. + * + * @param urlConn the url conn + * @param query the query + * @return the string[] an array with 2 elements witch contains min, max value for the COLORSCALERANGE + */ + private static String[] openConnectionGetColorScaleRange(String urlConn, String query) { + + URL url; + String[] colorScaleRange = null; + + try { + url = new URL(urlConn + "?" + query); + URLConnection connection = url.openConnection(); + + connection.setConnectTimeout(CONNECTION_TIMEOUT); + connection.setReadTimeout(CONNECTION_TIMEOUT + CONNECTION_TIMEOUT); + + logger.trace("openConnectionGetColorScaleRange on: " + url); + + // Cast to a HttpURLConnection + if (connection instanceof HttpURLConnection) { + HttpURLConnection httpConnection = (HttpURLConnection) connection; + + httpConnection.setRequestMethod("GET"); + int code = httpConnection.getResponseCode(); + + if (code == 200) { + colorScaleRange = getColorScaleRange(httpConnection); + }else + logger.warn("openConnectionGetColorScaleRange error, code = " + code +", returning"); + + httpConnection.disconnect(); + + } else { + logger.error("error - not a http request!"); + } + + return colorScaleRange; + + } catch (SocketTimeoutException e) { + logger.error("Error SocketTimeoutException with url " + urlConn); + return colorScaleRange; + } catch (MalformedURLException e) { + logger.error("Error MalformedURLException with url " + urlConn); + return colorScaleRange; + } catch (IOException e) { + logger.error("Error IOException with url " + urlConn); + return colorScaleRange; + } catch (Exception e) { + logger.error("Error Exception with url " + urlConn); + return colorScaleRange; + } + + } + + + + /** + * Gets the color scale range. + * + * @param httpConnection the http connection + * @return the color scale range + * @throws IOException Signals that an I/O exception has occurred. + */ + private static String[] getColorScaleRange(HttpURLConnection httpConnection) throws IOException{ + + String[] minmax = new String[2]; + InputStream source = null; + + int code = httpConnection.getResponseCode(); + + logger.trace("response code is " + code); + + if (code == 200) { + try{ + source = httpConnection.getInputStream(); + String jsonTxt = IOUtils.toString(source); + JSONObject json = new JSONObject(jsonTxt); + + String min = json.getString("min"); + + if(min!=null && !min.isEmpty()) + minmax[0]=min; + + String max = json.getString("max"); + + if(max!=null && !max.isEmpty()) + minmax[1]=max; + + logger.trace("returning: "+Arrays.toString(minmax)); + }catch (JSONException e){ + logger.warn("JSONException occurred when converting stream to JSON"); + + }catch (IOException e) { + logger.warn("IOException occurred when converting stream to JSON"); + } + + } else + return minmax; + + return minmax; + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + +// http://thredds-d-d4s.d4science.org/thredds/wms/public/netcdf/test20.nc?item=minmax&layers=analyzed_field&bbox=-180.0,-85.0,180.0,85.0&crs=EPSG%3A4326&request=GetMetadata&width=640&height=480 + + try { + NcWmsGetMetadataRequest.getColorScaleRange("http://thredds-d-d4s.d4science.org/thredds/wms/public/netcdf/test20.nc", "1.1.1", "-85.0,-180.0,85.0,180.0", "analyzed_field", "EPSG:4326", "640", "480"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/wms/WmsGetStyles.java b/src/main/java/org/gcube/spatial/data/geoutility/wms/WmsGetStyles.java new file mode 100644 index 0000000..a055a3b --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/wms/WmsGetStyles.java @@ -0,0 +1,337 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility.wms; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +import javax.xml.XMLConstants; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathFactory; + +import org.apache.commons.io.IOUtils; +import org.apache.log4j.Logger; +import org.gcube.spatial.data.geoutility.bean.WmsServiceBaseUri; +import org.gcube.spatial.data.geoutility.util.HttpRequestUtil; +import org.gcube.spatial.data.geoutility.util.NamespaceContextMap; +import org.gcube.spatial.data.geoutility.util.UrlEncoderUtil; +import org.gcube.spatial.data.geoutility.util.XpathParserUtil; + + + +/** + * The Class WmsGetStyles. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2016 + */ +public class WmsGetStyles { + + protected static final int CONNECTION_TIMEOUT = 1000; + public static Logger logger = Logger.getLogger(WmsGetStyles.class); + protected HashMap mappings; + protected NamespaceContextMap context; + private int responseCode; + private static final String GEOSERVER = "/geoserver"; + + /** + * Instantiates a new wms get styles. + */ + public WmsGetStyles() { + + mappings = new HashMap(); +// mappings.put("xmlns", "http://www.opengis.net/sld"); + mappings.put("sld", "http://www.opengis.net/sld"); + mappings.put("ogc", "http://www.opengis.net/ogc"); + mappings.put("gml", "http://www.opengis.net/gml"); + mappings.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); + context = new NamespaceContextMap(mappings); + } + + /** + * Gets the styles from wms. + * + * @param urlConn the url conn + * @param layerName the layer name + * @return the styles from wms + */ + public List getStylesFromWms(String urlConn, String layerName) { + + List styles = new ArrayList(); + + try { + + HashMap parameters = new HashMap(); + parameters.put("request", "GetStyles"); + parameters.put("layers", layerName); + parameters.put("service", "wms"); + parameters.put("version", "1.1.1"); + + String query = UrlEncoderUtil.encodeQuery(parameters); + WmsServiceBaseUri geosever = foundWmsServiceBaseUri(urlConn); + + if(query==null || query.isEmpty()) + return new ArrayList(); + + logger.trace("tentative get styles..with query:" + geosever.getScope()); + styles = openConnectionGetStyles(urlConn, query); + + + if(geosever.getScope()!=null && geosever.getScope().length()>0){ + logger.trace("tentative get styles with scope " + geosever.getScope()); + styles = openConnectionGetStyles(urlConn, query); + + if(styles.size()==0){ + + logger.trace("tentative get styles with scope: "+geosever.getScope()+", has returned empty styles"); + String newUrlConn = urlConn.replace("/"+geosever.getScope(), ""); + logger.trace("new tentative get styles as base url without scope"); + return openConnectionGetStyles(newUrlConn, query); + + }else + return styles; + } + else + return openConnectionGetStyles(urlConn, query); + + }catch (Exception e) { + logger.error("Error Exception with url " + urlConn); + return styles; + } + + } + + /** + * Gets the styles. + * + * @param httpConnection the http connection + * @return a list of styles. The first element of list is default style if exists + * @throws IOException Signals that an I/O exception has occurred. + */ + + private List getStyles(HttpURLConnection httpConnection) throws IOException{ + + List listStylesNames = new ArrayList(); + InputStream source = null; + int code = httpConnection.getResponseCode(); + logger.trace("response code is " + code); + + if (code == 200) { + + source = httpConnection.getInputStream(); + XPathFactory factory = XPathFactory.newInstance(); + XPath xPath = factory.newXPath(); + xPath.setNamespaceContext(context); + + try{ + + String xmlGetStyles = IOUtils.toString(source); + String xpathExpression = "//sld:UserStyle[sld:IsDefault=1]/sld:Name"; //FIND DEFAULT STYLE NAME + List defaultStylesList = XpathParserUtil.getTextFromXPathExpression(context, xmlGetStyles, xpathExpression); + LinkedHashMap exclusiveStyles = new LinkedHashMap(); + + //DEFAULT STYLE IS FOUND + if(defaultStylesList.size()>0 || !defaultStylesList.get(0).isEmpty()){ + String defaultStyle = defaultStylesList.get(0); + exclusiveStyles.put(defaultStyle, defaultStyle); + } + + xpathExpression = "//sld:UserStyle/sld:Name"; //FIND OTHER STYLES NAMES AND ADD INTO LIST + List allStyles = XpathParserUtil.getTextFromXPathExpression(context, xmlGetStyles, xpathExpression); + + for (String style : allStyles) { + exclusiveStyles.put(style, style); + } + + listStylesNames.addAll(exclusiveStyles.keySet()); + + }catch (IOException e) { + logger.warn("IOException occurred when converting stream get styles"); + } + + } else { + + return listStylesNames; + } + + return listStylesNames; + + } + + /** + * Open connection get styles. + * + * @param urlConn the url conn + * @param query the query + * @return the list + */ + private List openConnectionGetStyles(String urlConn, String query) { + + URL url; + List styles = new ArrayList(); + + try { + url = new URL(urlConn + "?" + query); + URLConnection connection = url.openConnection(); + connection.setConnectTimeout(CONNECTION_TIMEOUT); + connection.setReadTimeout(CONNECTION_TIMEOUT + CONNECTION_TIMEOUT); + logger.trace("openConnectionGetStyles: " + url); + + // Cast to a HttpURLConnection + if (connection instanceof HttpURLConnection) { + + HttpURLConnection httpConnection = (HttpURLConnection) connection; + httpConnection.setRequestMethod("GET"); + responseCode= httpConnection.getResponseCode(); + + if (responseCode == 200) { + styles = getStyles(httpConnection); + }else{ + logger.warn("openConnectionGetStyles error, code = " + responseCode +", returning"); + } + + httpConnection.disconnect(); + + } else { + logger.error("error - not a http request!"); + } + + return styles; + } catch (SocketTimeoutException e) { + logger.error("Error SocketTimeoutException with url " + urlConn); + return styles; + } catch (MalformedURLException e) { + logger.error("Error MalformedURLException with url " + urlConn); + return styles; + } catch (IOException e) { + logger.error("Error IOException with url " + urlConn); + return styles; + } catch (Exception e) { + logger.error("Error Exception with url " + urlConn); + return styles; + } + + } + + /** + * Gets the geoserver base uri. + * + * @param uri the uri + * @return the input uri without the parameters, (the uri substring from start to index of '?' char (if exists)) if geoserver base url not found, + * geoserver url otherwise + */ + public WmsServiceBaseUri foundWmsServiceBaseUri(String uri){ + + WmsServiceBaseUri geoserverBaseUri = new WmsServiceBaseUri(); + + if(uri==null) + return geoserverBaseUri; //uri is empty + + int end = uri.toLowerCase().lastIndexOf("?"); + + if(end==-1){ + logger.trace("char ? not found in geoserver uri, return: "+uri); + return geoserverBaseUri; //uri is empty + } + + String wmsServiceUri = uri.substring(0, uri.toLowerCase().lastIndexOf("?")); + int index = wmsServiceUri.lastIndexOf(GEOSERVER); + + if(index>-1){ //FOUND the string GEOSERVER into URL + logger.trace("found geoserver string: "+GEOSERVER+" in "+wmsServiceUri); + + //THERE IS SCOPE? + int lastSlash = wmsServiceUri.lastIndexOf("/"); + int includeGeoserverString = index+GEOSERVER.length(); + int endUrl = lastSlash>includeGeoserverString?lastSlash:includeGeoserverString; + logger.trace("indexs - lastSlash: ["+lastSlash+"], includeGeoserverString: ["+includeGeoserverString+"], endUrl: ["+endUrl+"]"); + int startScope = includeGeoserverString+1 list = wmsStyles.getStylesFromWms("http://www.fao.org/figis/geoserver/area/ows", "FAO_AREAS"); + for (String string : list) { + System.out.println(string); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/org/gcube/spatial/data/geoutility/wms/WmsUrlValidator.java b/src/main/java/org/gcube/spatial/data/geoutility/wms/WmsUrlValidator.java new file mode 100644 index 0000000..7c9677e --- /dev/null +++ b/src/main/java/org/gcube/spatial/data/geoutility/wms/WmsUrlValidator.java @@ -0,0 +1,363 @@ +package org.gcube.spatial.data.geoutility.wms; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.log4j.Logger; +import org.gcube.spatial.data.geoutility.bean.WmsParameters; + + + +/** + * The Class WmsUrlValidator. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Dec 4, 2015 + */ +public class WmsUrlValidator { + + private HashMap parameterValues = new HashMap(); + private String wmsRequest; + private String baseWmsServiceUrl; + private String wmsParameters; + private String wmsNotStandardParameters = ""; + private Map mapWmsNotStandardParams; + public static Logger logger = Logger.getLogger(WmsUrlValidator.class); + /** + * Instantiates a new wms url validator. + * + * @param wmsRequest the wms request + */ + public WmsUrlValidator(String wmsRequest){ + this.wmsRequest = wmsRequest; + int indexStart = wmsRequest.indexOf("?"); + if(indexStart==-1){ + this.baseWmsServiceUrl = wmsRequest; + this.wmsParameters = null; + }else{ + this.baseWmsServiceUrl=wmsRequest.substring(0, indexStart); + this.baseWmsServiceUrl.trim(); + this.wmsParameters = wmsRequest.substring(indexStart+1, this.wmsRequest.length()); + this.wmsParameters.trim(); + } + } + + /** + * Parses the wms request. + * + * @param returnEmptyParameter the return empty parameter + * @param fillEmptyParameterAsDefaultValue the fill empty parameter as default + * @return + * @throws Exception + */ + public String parseWmsRequest(boolean returnEmptyParameter, boolean fillEmptyParameterAsDefaultValue) throws Exception{ + + if(wmsParameters==null || wmsParameters.isEmpty()){ + String msg = "IT IS NOT POSSIBLE TO PARSE WMS URL, 'WMS PARAMETERS' not found!"; +// logger.trace(msg); + throw new Exception(msg); + } + + for (WmsParameters wmsParam : WmsParameters.values()) { + + if(wmsParam.equals(WmsParameters.BBOX)){ + String value = validateValueOfParameter(WmsParameters.BBOX, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), value); + } + + if(wmsParam.equals(WmsParameters.FORMAT)){ + String value = validateValueOfParameter(WmsParameters.FORMAT, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), value); + } + + if(wmsParam.equals(WmsParameters.HEIGHT)){ + String value = validateValueOfParameter( WmsParameters.HEIGHT, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), value); + } + + if(wmsParam.equals(WmsParameters.CRS)){ + String crs = validateValueOfParameter(WmsParameters.CRS, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), crs); + } + + if(wmsParam.equals(WmsParameters.WIDTH)){ + String value = validateValueOfParameter(WmsParameters.WIDTH, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), value); + } + + if(wmsParam.equals(WmsParameters.REQUEST)){ + String value = validateValueOfParameter(WmsParameters.REQUEST, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), value); + } + + if(wmsParam.equals(WmsParameters.SERVICE)){ + String value = validateValueOfParameter(WmsParameters.SERVICE, wmsParameters,fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), value); + } + + if(wmsParam.equals(WmsParameters.SRS)){ + String value = validateValueOfParameter(WmsParameters.SRS, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), value); + } + + if(wmsParam.equals(WmsParameters.STYLES)){ + String styles = validateValueOfParameter(WmsParameters.STYLES, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), styles); + } + + if(wmsParam.equals(WmsParameters.VERSION)){ + String version = validateValueOfParameter(WmsParameters.VERSION, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), version); + } + + if(wmsParam.equals(WmsParameters.LAYERS)){ + String layers = validateValueOfParameter(WmsParameters.LAYERS, wmsParameters, fillEmptyParameterAsDefaultValue); + parameterValues.put(wmsParam.getParameter(), layers); + } + } + + String parsedWmsRequest = baseWmsServiceUrl+"?"; + + String[] params = wmsParameters.split("&"); + + //CREATING MAP TO RETURN WMS PARAMETERS NOT STANDARD + mapWmsNotStandardParams = new TreeMap(String.CASE_INSENSITIVE_ORDER); + + for (String param : params) { + String key = param.substring(0, param.indexOf("=")); + String value = param.substring(param.indexOf("=")+1, param.length()); + mapWmsNotStandardParams.put(key, value); + } + + //CREATE WMS REQUEST + for (String key : parameterValues.keySet()) { + + String value = parameterValues.get(key); + if(returnEmptyParameter && value!=null && value.isEmpty()){ + parsedWmsRequest+=key+"="+value; + //not add the parameter + }else{ + parsedWmsRequest+=key+"="+value; + parsedWmsRequest+="&"; + String exist = mapWmsNotStandardParams.get(key); + + if(exist!=null) + mapWmsNotStandardParams.remove(key); //REMOVE WMS STANDARD PARAMETER FROM MAP + } + } + + for (String key : mapWmsNotStandardParams.keySet()) { + wmsNotStandardParameters+=key+"="+mapWmsNotStandardParams.get(key) + "&"; + } + + if(wmsNotStandardParameters.length()>0) + wmsNotStandardParameters = wmsNotStandardParameters.substring(0, wmsNotStandardParameters.length()-1); //REMOVE LAST & + + logger.trace("wmsNotStandardParameters: "+wmsNotStandardParameters); + + String fullWmsUrlBuilded; + + if(!wmsNotStandardParameters.isEmpty()){ + fullWmsUrlBuilded = parsedWmsRequest + wmsNotStandardParameters; //remove last & + logger.trace("full wms url builded + not wms standard parameters: "+fullWmsUrlBuilded); + }else{ + fullWmsUrlBuilded = parsedWmsRequest.substring(0, parsedWmsRequest.length()-1); //remove last & + logger.trace("full wms url builded: "+fullWmsUrlBuilded); + } + + return fullWmsUrlBuilded; + } + + /** + * @return the parameterValues + */ + public HashMap getParameterValues() { + return parameterValues; + } + + /** + * @return the wmsRequest + */ + public String getWmsRequest() { + return wmsRequest; + } + + /** + * @return the baseWmsServiceUrl + */ + public String getBaseWmsServiceUrl() { + return baseWmsServiceUrl; + } + + /** + * Gets the wms not standard parameters. + * + * @return the wms not standard parameters + */ + public String getWmsNotStandardParameters() { + return wmsNotStandardParameters; + } + + + /** + * Gets the value of parsed wms parameter. + * + * @param parameter the parameter + * @return the value of parsed wms parameter parsed from wms request. + */ + public String getValueOfParsedWMSParameter(WmsParameters parameter){ + return parameterValues.get(parameter.getParameter()); + } + + + /** + * Validate value of parameter. + * + * @param wmsParam the wms param + * @param valueOfParameter the value of parameter + * @param fillEmptyParameterAsDefaultValue the fill empty parameter as default value + * @return the string + */ + public static String validateValueOfParameter(WmsParameters wmsParam, String valueOfParameter, boolean fillEmptyParameterAsDefaultValue){ + + try{ + + String value = getValueOfParameter(wmsParam, valueOfParameter); + + if(fillEmptyParameterAsDefaultValue && (value==null || value.isEmpty())){ + logger.trace("setting empty value to wms parameter: "+wmsParam.getParameter() +", as default value: "+wmsParam.getValue()); + value = wmsParam.getValue(); + } + return value; + }catch(Exception e){ + //silent + return null; + } + } + + /** + * Gets the value of parameter. + * + * @param wmsParam the wms param + * @param wmsRequestParamaters the url wms parameters + * @return the value of parameter or null if parameter not exists + */ + public static String getValueOfParameter(WmsParameters wmsParam, String wmsRequestParamaters) { +// logger.trace("finding: "+wmsParam +" into "+url); + int index = wmsRequestParamaters.toLowerCase().indexOf(wmsParam.getParameter().toLowerCase()); +// logger.trace("start index of "+wmsParam+ " is: "+index); + String value = ""; + if(index > -1){ + + int start = index + wmsParam.getParameter().length()+1; //add +1 for char '=' + String sub = wmsRequestParamaters.substring(start, wmsRequestParamaters.length()); + int indexOfSeparator = sub.indexOf("&"); + int end = indexOfSeparator!=-1?indexOfSeparator:sub.length(); + value = sub.substring(0, end); + }else + return null; + +// logger.trace("return value: "+value); + return value; + } + + + /** + * Sets the value of parameter. + * + * @param wmsParam the wms param + * @param wmsRequestParameters the wms url parameters + * @param newValue the new value + * @param addIfNotExists add the parameter if not exists + * @return the string + */ + public static String setValueOfParameter(WmsParameters wmsParam, String wmsRequestParameters, String newValue, boolean addIfNotExists){ + String toLowerWmsUrlParameters = wmsRequestParameters.toLowerCase(); + String toLowerWmsParam = wmsParam.getParameter().toLowerCase(); + + int index = toLowerWmsUrlParameters.indexOf(toLowerWmsParam+"="); //+ "=" SECURE TO BE PARAMETER +// logger.trace("start index of "+wmsParam+ " is: "+index); + if(index > -1){ + int indexStartValue = index + toLowerWmsParam.length()+1; //add +1 for char '=' + int indexOfSeparator = toLowerWmsUrlParameters.indexOf("&", indexStartValue); //GET THE FIRST "&" STARTING FROM INDEX VALUE +// logger.trace("indexOfSeparator index of "+wmsParam+ " is: "+indexOfSeparator); + int indexEndValue = indexOfSeparator!=-1?indexOfSeparator:toLowerWmsUrlParameters.length(); +// logger.trace("end: "+indexEndValue); + return wmsRequestParameters.substring(0, indexStartValue) + newValue +wmsRequestParameters.substring(indexEndValue, wmsRequestParameters.length()); + }else if (addIfNotExists){ + wmsRequestParameters+="&"+wmsParam.getParameter()+"="+newValue; + } +// logger.trace("return value: "+value); + return wmsRequestParameters; + } + + /** + * Gets the styles as list. + * + * @return the styles as list + */ + public List getStylesAsList() { + + List listStyles = new ArrayList(); + String styles = getValueOfParsedWMSParameter(WmsParameters.STYLES); + + if(styles!=null && !styles.isEmpty()){ + + String[] arrayStyle = styles.split(","); + for (String style : arrayStyle) { + if(style!=null && !style.isEmpty()) + listStyles.add(style); + } + } + return listStyles; + } + + /** + * Gets the map wms not standard params. + * + * @return the mapWmsNotStandardParams + */ + public Map getMapWmsNotStandardParams() { + return mapWmsNotStandardParams; + } + + + /** + * The main method. + * + * @param args the arguments + */ + /*public static void main(String[] args) { + +// String baseGeoserverUrl = "http://repoigg.services.iit.cnr.it:8080/geoserver/IGG/ows"; +// String baseGeoserverUrl = "http://www.fao.org/figis/geoserver/species"; +// String fullPath = "http://www.fao.org/figis/geoserver/species?SERVICE=WMS&BBOX=-176.0,-90.0,180.0,90&styles=Species_prob, puppa&layers=layerName&FORMAT=image/gif"; +// String fullPath = "http://repoigg.services.iit.cnr.it:8080/geoserver/IGG/ows?service=wms&version=1.1.0&request=GetMap&layers==IGG:area_temp_1000&width=676&height=330&srs=EPSG:4326&crs=EPSG:4326&format=application/openlayers&bbox=-85.5,-180.0,90.0,180.0"; +// String baseGeoserverUrl = "http://thredds-d-d4s.d4science.org/thredds/wms/public/netcdf/test20.nc"; +// String fullPath = "http://thredds-d-d4s.d4science.org/thredds/wms/public/netcdf/test20.nc?service=wms&version=1.3.0&request=GetMap&layers=analyzed_field&bbox=-85.0,-180.0,85.0,180.0&styles=&width=640&height=480&srs=EPSG:4326&CRS=EPSG:4326&format=image/png&COLORSCALERANGE=auto"; +// WmsUrlValidator validator = new WmsUrlValidator(baseGeoserverUrl, fullPath , "", false); +// logger.trace("base wms service url: "+validator.getBaseWmsServiceUrl()); +// logger.trace("layer name: "+validator.getLayerName()); +// logger.trace("full wms url: "+validator.getFullWmsUrlRequest(false, true)); +// logger.trace("style: "+validator.getStyles()); +// logger.trace("not standard parameter: "+validator.getWmsNotStandardParameters()); +// String[] arrayStyle = validator.getStyles().split(","); +// +// if(arrayStyle!=null && arrayStyle.length>0){ +// +// for (String style : arrayStyle) { +// if(style!=null && !style.isEmpty()) +// +// System.out.println("Style: "+style.trim()); +// } +// } +// +// String fullPath = "http://thredds-d-d4s.d4science.org/thredds/wms/public/netcdf/test20.nc?service=wms&version=1.3.0&request=GetMap&layers=analyzed_field&styles=&width=640&height=480&srs=EPSG:4326&CRS=EPSG:4326&format=image/png&COLORSCALERANGE=auto&bbox=-85.0,-180.0,85.0,180.0"; +// fullPath = WmsUrlValidator.setValueOfParameter(WmsParameters.STYLES, fullPath, "123", true); +// + }*/ + +} diff --git a/src/main/webapp/GeoUtility.css b/src/main/webapp/GeoUtility.css new file mode 100644 index 0000000..7aca7ac --- /dev/null +++ b/src/main/webapp/GeoUtility.css @@ -0,0 +1,34 @@ +/** Add css rules here for your application. */ + + +/** Example rules used by the template application (remove for your app) */ +h1 { + font-size: 2em; + font-weight: bold; + color: #777777; + margin: 40px 0px 70px; + text-align: center; +} + +.sendButton { + display: block; + font-size: 16pt; +} + +/** Most GWT widgets already have a style name defined */ +.gwt-DialogBox { + width: 400px; +} + +.dialogVPanel { + margin: 5px; +} + +.serverResponseLabelError { + color: red; +} + +/** Set ids using widget.getElement().setId("idOfElement") */ +#closeButton { + margin: 15px 6px 6px; +} diff --git a/src/main/webapp/GeoUtility.html b/src/main/webapp/GeoUtility.html new file mode 100644 index 0000000..1c25517 --- /dev/null +++ b/src/main/webapp/GeoUtility.html @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + Web Application Starter Project + + + + + + + + + + + + + + + + + + + + + + +

Web Application Starter Project

+ + + + + + + + + + + + +
Please enter your name:
+ + diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..1f82d7c --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + + + + + greetServlet + org.gcube.spatial.data.geoutility.server.GreetingServiceImpl + + + + greetServlet + /GeoUtility/greet + + + + + GeoUtility.html + + + diff --git a/src/test/java/org/gcube/spatial/data/geoutility/GeoJUnitTest.java b/src/test/java/org/gcube/spatial/data/geoutility/GeoJUnitTest.java new file mode 100644 index 0000000..8762537 --- /dev/null +++ b/src/test/java/org/gcube/spatial/data/geoutility/GeoJUnitTest.java @@ -0,0 +1,32 @@ +/** + * + */ +package org.gcube.spatial.data.geoutility; + +import org.junit.Test; + + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jan 22, 2016 + */ +public class GeoJUnitTest { + + @Test + public void testGetStyles() { +// String wmsRequest = "http://repoigg.services.iit.cnr.it:8080/geoserver/IGG/ows?service=wms&version=1.1.0&request=GetMap&layers==IGG:area_temp_1000&width=676&height=330&srs=EPSG:4326&crs=EPSG:4326&format=application/openlayers&bbox=-85.5,-180.0,90.0,180.0"; + String wmsRequest = "http://thredds-d-d4s.d4science.org/thredds/wms/public/netcdf/test20.nc?service=wms&version=1.3.0&request=GetMap&layers=analyzed_field&styles=&width=640&height=480&srs=EPSG:4326&CRS=EPSG:4326&format=image/png&COLORSCALERANGE=auto&bbox=-85.0,-180.0,85.0,180.0"; +// String wmsRequest = "http://www.fao.org/figis/geoserver/species?SERVICE=WMS&BBOX=-176.0,-90.0,180.0,90&styles=&layers=layerName&FORMAT=image/gif"; + GeoGetStyles geo; + try { + geo = new GeoGetStyles(wmsRequest); + System.out.println("Returned styles: "+geo.getStyles().toString()); + } + catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } +} diff --git a/src/test/resources/org/gcube/spatial/data/geoutility/log4j.properties b/src/test/resources/org/gcube/spatial/data/geoutility/log4j.properties new file mode 100644 index 0000000..a00acb0 --- /dev/null +++ b/src/test/resources/org/gcube/spatial/data/geoutility/log4j.properties @@ -0,0 +1,20 @@ +# Created by Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + +log4j.rootCategory=ERROR, A1 + +log4j.appender.A1=org.apache.log4j.ConsoleAppender + + +# A1 uses PatternLayout. +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} [%t,%M:%L] %m%n + + +# Display any warnings generated by our code +#log4j.category.org.gcube=trace +#log4j.category.org.globus=trace +#log4j.category.isclient=INFO +#log4j.category.org.gcube.common.homelibrary.jcr=TRACE + +##GCube +log4j.category.org.gcube=TRACE