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
This commit is contained in:
Francesco Mangiacrapa 2016-01-22 14:19:10 +00:00
parent f524f7712b
commit 59fbadc62a
29 changed files with 2669 additions and 0 deletions

36
.classpath Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry including="**/*.java" kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

42
.project Normal file
View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>geo-utility</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

13
.settings/.jsdtscope Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry kind="src" path="target/m2e-wtp/web-resources"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>

View File

@ -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/<project>=UTF-8

View File

@ -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

View File

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="geo-utility">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<property name="context-root" value="geo-utility"/>
<property name="java-output-path" value="/geo-utility/target/geo-utility-1.0.0-SNAPSHOT/WEB-INF/classes"/>
</wb-module>
</project-modules>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="1.7"/>
<installed facet="jst.web" version="2.3"/>
<installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>

View File

@ -0,0 +1 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

View File

@ -0,0 +1 @@
Window

View File

@ -0,0 +1,2 @@
disabled=06target
eclipse.preferences.version=1

142
pom.xml Normal file
View File

@ -0,0 +1,142 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.gcube.spatial.data</groupId>
<artifactId>geo-utility</artifactId>
<packaging>jar</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>A library with several utility class to work with geo-spatial data: WmsUrlValidator, GeoGetStylesUtils, etc..</name>
<properties>
<distroDirectory>distro</distroDirectory>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- DOM -->
<dependency>
<groupId>org.w3c</groupId>
<artifactId>dom</artifactId>
<version>2.3.0-jaxb-1.0.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.2</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.apache.commons</groupId> -->
<!-- <artifactId>commons-csv</artifactId> -->
<!-- <version>1.2</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>copy-profile</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target</outputDirectory>
<resources>
<resource>
<directory>${distroDirectory}</directory>
<filtering>true</filtering>
<includes>
<include>profile.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>install</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -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<String, String> 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<String> 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<String, String>(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<String> 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<String, String> 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();
}
}

View File

@ -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<String> supportedStyles;
private List<String> 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<String> supportedStyles, List<String> 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<String> getSupportedStyles() {
return supportedStyles;
}
/**
* Gets the palettes.
*
* @return the palettes
*/
public List<String> 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<String> 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<String> 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();
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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));
}
}

View File

@ -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<String, String> prefixMap;
private final Map<String, Set<String>> 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<String, String> 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<String, String> toMap(String... mappingPairs) {
Map<String, String> prefixMappings = new HashMap<String, String>(
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<String, String> createPrefixMap(
Map<String, String> prefixMappings) {
Map<String, String> prefixMap = new HashMap<String, String>(
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<String, String> 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<String, Set<String>> createNamespaceMap(
Map<String, String> prefixMap) {
Map<String, Set<String>> nsMap = new HashMap<String, Set<String>>();
for (Map.Entry<String, String> entry : prefixMap.entrySet()) {
String nsURI = entry.getValue();
Set<String> prefixes = nsMap.get(nsURI);
if (prefixes == null) {
prefixes = new HashSet<String>();
nsMap.put(nsURI, prefixes);
}
prefixes.add(entry.getKey());
}
for (Map.Entry<String, Set<String>> entry : nsMap.entrySet()) {
Set<String> 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<String> 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<String> getPrefixes(String namespaceURI) {
checkNotNull(namespaceURI);
Set<String> 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<String, String> 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();
}
}

View File

@ -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<String, String> 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<String, String> parameters = new HashMap<String, String>();
parameters.put("request", "GetStyles");
parameters.put("layers", "test Name");
parameters.put("version", "1.1.1");
System.out.println(UrlEncoderUtil.encodeQuery(parameters));
}
}

View File

@ -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<String> getTextFromXPathExpression(NamespaceContextMap context, InputStream source, String xpathExpression){
List<String> list = new ArrayList<String>();
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<nodes.getLength(); i++) {
Node node = nodes.item(i);
list.add(node.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 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<String> getTextFromXPathExpression(NamespaceContextMap context, String source, String xpathExpression){
List<String> list = new ArrayList<String>();
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<nodes.getLength(); i++) {
Node node = nodes.item(i);
list.add(node.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* String to input stream.
*
* @param text the text
* @return the input stream
*/
public static InputStream stringToInputStream(String text){
return IOUtils.toInputStream(text);
}
/**
* The main method.
*
* @param args the arguments
* @throws IOException Signals that an I/O exception has occurred.
*/
/*public static void main(String[] args) throws IOException {
HashMap<String, String> mappings = new HashMap<String, String>();
// 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<String> listStylesNames = new ArrayList<String>();
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<String> defaultStylesList = XpathParserUtil.getTextFromXPathExpression(context, xmlGetStyles, xpathExpression);
LinkedHashMap<String, String> exclusiveStyles = new LinkedHashMap<String, String>();
//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<String> 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);
}
}*/
}

View File

@ -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<String, String> parameters = new HashMap<String, String>();
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<String> s = new ArrayList<String>(supportedStyles.length());
for (int i=0; i<supportedStyles.length(); i++) {
s.add(supportedStyles.getString(i));
}
metadata.setSupportedStyles(s);
}
JSONArray palettes = json.getJSONArray("palettes");
if(palettes!=null){
List<String> s = new ArrayList<String>(palettes.length());
for (int i=0; i<palettes.length(); i++) {
s.add(palettes.getString(i));
}
metadata.setPalettes(s);
}
metadata.setDefaultPalette(json.getString("defaultPalette"));
logger.trace("returning: "+metadata.toString());
}catch (JSONException e){
logger.warn("JSONException occurred when converting stream to JSON");
}catch (IOException e) {
logger.warn("IOException occurred when converting stream to JSON");
}
return metadata;
}
/**
* 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 {
NcWmsGetMetadata.getMetadata("http://thredds-d-d4s.d4science.org/thredds/wms/public/netcdf/test20.nc", "analyzed_field");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,216 @@
/**
*
*/
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.Arrays;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.gcube.spatial.data.geoutility.bean.WmsParameters;
import org.gcube.spatial.data.geoutility.util.UrlEncoderUtil;
import org.json.JSONException;
import org.json.JSONObject;
/**
* The Class NcWmsGetColorScaleRange.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Dec 1, 2015
*/
public class NcWmsGetMetadataRequest {
/**
*
*/
public static final String GET_METADATA = "GetMetadata";
public static final int CONNECTION_TIMEOUT = 1000;
public static Logger logger = Logger.getLogger(NcWmsGetMetadataRequest.class);
public static final String COLORSCALERANGE = "COLORSCALERANGE";
public static final String WMS_VERSION_1_3_0 = "1.3.0";
public static final String COLORSCALERANGE_DEFAULT_VALUE = "auto";
/**
* Gets the color scale range
* Calls a ncWMS GetMetadata request with item = minmax.
* Returns minmax if GetMedatada works, a null array otherwise.
*
* @param wmsServerUri the WMS Server Uri
* @param wmsVersion the wms version
* @param bbox the bbox
* @param layerName the layer name
* @param crs the crs
* @param width the width
* @param height the height
* @return the color scale range - an array of 2 elements that contains min and max value for the COLORSCALERANGE
* @throws Exception the exception
*/
public static String[] getColorScaleRange(String wmsServerUri, String wmsVersion, String bbox, String layerName, String crs, String width, String height) throws Exception {
logger.trace(NcWmsGetMetadataRequest.class.getName()+".getColorScaleRange working...");
String[] colorScaleMinMax = null;
// 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
if(wmsServerUri==null || wmsServerUri.isEmpty())
throw new Exception("Invalid wms server uri");
HashMap<String, String> parameters = new HashMap<String, String>();
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();
}
}
}

View File

@ -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<String, String> mappings;
protected NamespaceContextMap context;
private int responseCode;
private static final String GEOSERVER = "/geoserver";
/**
* Instantiates a new wms get styles.
*/
public WmsGetStyles() {
mappings = new HashMap<String, String>();
// 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<String> getStylesFromWms(String urlConn, String layerName) {
List<String> styles = new ArrayList<String>();
try {
HashMap<String, String> parameters = new HashMap<String, String>();
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<String>();
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<String> getStyles(HttpURLConnection httpConnection) throws IOException{
List<String> listStylesNames = new ArrayList<String>();
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<String> defaultStylesList = XpathParserUtil.getTextFromXPathExpression(context, xmlGetStyles, xpathExpression);
LinkedHashMap<String, String> exclusiveStyles = new LinkedHashMap<String, String>();
//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<String> 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<String> openConnectionGetStyles(String urlConn, String query) {
URL url;
List<String> styles = new ArrayList<String>();
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<endUrl?includeGeoserverString+1:endUrl; //INCLUDE SLASH
String scope = wmsServiceUri.substring(startScope, endUrl);
logger.trace("geoserver url include scope: "+wmsServiceUri.substring(includeGeoserverString, endUrl));
geoserverBaseUri.setBaseUrl(wmsServiceUri.substring(0, endUrl));
geoserverBaseUri.setScope(scope);
return geoserverBaseUri;
}
else{
logger.trace("the string "+GEOSERVER+" not found in "+wmsServiceUri);
// GET LAST INDEX OF '/' AND CONCATENATE GEOSERVER
String urlConn = wmsServiceUri.substring(0, wmsServiceUri.lastIndexOf("/"))+GEOSERVER;
logger.trace("tentative concatenating string "+GEOSERVER+" at http url "+urlConn);
try {
if(HttpRequestUtil.urlExists(urlConn, false)){
logger.trace("url: "+urlConn+" - open a connection, return "+urlConn);
geoserverBaseUri.setBaseUrl(urlConn);
return geoserverBaseUri;
}
else
logger.trace("url: "+urlConn+" - not open a connection");
} catch (Exception e) {
logger.error("url connection is wrong at :"+urlConn);
}
String uriWithoutParameters = uri.substring(0, end);
logger.trace("url connection, returned: "+uriWithoutParameters);
geoserverBaseUri.setBaseUrl(uriWithoutParameters);
return geoserverBaseUri;
}
}
/**
* Gets the response code.
*
* @return the responseCode
*/
public int getResponseCode() {
return responseCode;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("WmsGetStyles [mappings=");
builder.append(mappings);
builder.append(", context=");
builder.append(context);
builder.append("]");
return builder.toString();
}
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
WmsGetStyles wmsStyles = new WmsGetStyles();
try {
List<String> 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();
}
}
}

View File

@ -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<String, String> parameterValues = new HashMap<String, String>();
private String wmsRequest;
private String baseWmsServiceUrl;
private String wmsParameters;
private String wmsNotStandardParameters = "";
private Map<String, String> 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, String>(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<String, String> 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<String> getStylesAsList() {
List<String> listStyles = new ArrayList<String>();
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<String, String> 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);
//
}*/
}

View File

@ -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;
}

View File

@ -0,0 +1,63 @@
<!doctype html>
<!-- The DOCTYPE declaration above will set the -->
<!-- browser's rendering engine into -->
<!-- "Standards Mode". Replacing this declaration -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout. -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- -->
<!-- Consider inlining CSS to reduce the number of requested files -->
<!-- -->
<link type="text/css" rel="stylesheet" href="GeoUtility.css">
<!-- -->
<!-- Any title is fine -->
<!-- -->
<title>Web Application Starter Project</title>
<!-- -->
<!-- This script loads your compiled module. -->
<!-- If you add any GWT meta tags, they must -->
<!-- be added before this line. -->
<!-- -->
<script type="text/javascript" language="javascript" src="GeoUtility/GeoUtility.nocache.js"></script>
</head>
<!-- -->
<!-- The body can have arbitrary html, or -->
<!-- you can leave the body empty if you want -->
<!-- to create a completely dynamic UI. -->
<!-- -->
<body>
<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>
<h1>Web Application Starter Project</h1>
<table align="center">
<tr>
<td colspan="2" style="font-weight:bold;">Please enter your name:</td>
</tr>
<tr>
<td id="nameFieldContainer"></td>
<td id="sendButtonContainer"></td>
</tr>
<tr>
<td colspan="2" style="color:red;" id="errorLabelContainer"></td>
</tr>
</table>
</body>
</html>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- Servlets -->
<servlet>
<servlet-name>greetServlet</servlet-name>
<servlet-class>org.gcube.spatial.data.geoutility.server.GreetingServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>greetServlet</servlet-name>
<url-pattern>/GeoUtility/greet</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>GeoUtility.html</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -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();
}
}
}

View File

@ -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