added d4science project configurations

This commit is contained in:
Francesco Mangiacrapa 2022-01-28 15:02:42 +01:00
parent d84cfefa4f
commit 1072b5c10f
26 changed files with 3357 additions and 73 deletions

View File

@ -6,23 +6,20 @@
<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"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" 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">
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target/

View File

@ -1,8 +1,11 @@
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.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

26
CHANGELOG.md Normal file
View File

@ -0,0 +1,26 @@
# Changelog for geo-utility
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1-1-2] - 2019-10-24
- [#17831#change-92733] Bug fixed
## [v1-1-1] - 2016-04-27
- Updated comment in WMSGetStyles class
- Bug fixing for method getValueOfParameter
## [v1-1-0] - 2016-02-09
- [Feature #2191] Updated NcWmsGetMetadata to retrieve z-axis
## [v1-0-0] - 2016-01-26
- [#2054] First release

311
LICENSE.md Normal file
View File

@ -0,0 +1,311 @@
#European Union Public Licence V.1.1
##*EUPL © the European Community 2007*
This **European Union Public Licence** (the **“EUPL”**) applies to the Work or Software
(as defined below) which is provided under the terms of this Licence. Any use of
the Work, other than as authorised under this Licence is prohibited (to the
extent such use is covered by a right of the copyright holder of the Work).
The Original Work is provided under the terms of this Licence when the Licensor
(as defined below) has placed the following notice immediately following the
copyright notice for the Original Work:
**Licensed under the EUPL V.1.1**
or has expressed by any other mean his willingness to license under the EUPL.
##1. Definitions
In this Licence, the following terms have the following meaning:
- The Licence: this Licence.
- The Original Work or the Software: the software distributed and/or
communicated by the Licensor under this Licence, available as Source Code and
also as Executable Code as the case may be.
- Derivative Works: the works or software that could be created by the Licensee,
based upon the Original Work or modifications thereof. This Licence does not
define the extent of modification or dependence on the Original Work required
in order to classify a work as a Derivative Work; this extent is determined by
copyright law applicable in the country mentioned in Article 15.
- The Work: the Original Work and/or its Derivative Works.
- The Source Code: the human-readable form of the Work which is the most
convenient for people to study and modify.
- The Executable Code: any code which has generally been compiled and which is
meant to be interpreted by a computer as a program.
- The Licensor: the natural or legal person that distributes and/or communicates
the Work under the Licence.
- Contributor(s): any natural or legal person who modifies the Work under the
Licence, or otherwise contributes to the creation of a Derivative Work.
- The Licensee or “You”: any natural or legal person who makes any usage of the
Software under the terms of the Licence.
- Distribution and/or Communication: any act of selling, giving, lending,
renting, distributing, communicating, transmitting, or otherwise making
available, on-line or off-line, copies of the Work or providing access to its
essential functionalities at the disposal of any other natural or legal
person.
##2. Scope of the rights granted by the Licence
The Licensor hereby grants You a world-wide, royalty-free, non-exclusive,
sub-licensable licence to do the following, for the duration of copyright vested
in the Original Work:
- use the Work in any circumstance and for all usage, reproduce the Work, modify
- the Original Work, and make Derivative Works based upon the Work, communicate
- to the public, including the right to make available or display the Work or
- copies thereof to the public and perform publicly, as the case may be, the
- Work, distribute the Work or copies thereof, lend and rent the Work or copies
- thereof, sub-license rights in the Work or copies thereof.
Those rights can be exercised on any media, supports and formats, whether now
known or later invented, as far as the applicable law permits so.
In the countries where moral rights apply, the Licensor waives his right to
exercise his moral right to the extent allowed by law in order to make effective
the licence of the economic rights here above listed.
The Licensor grants to the Licensee royalty-free, non exclusive usage rights to
any patents held by the Licensor, to the extent necessary to make use of the
rights granted on the Work under this Licence.
##3. Communication of the Source Code
The Licensor may provide the Work either in its Source Code form, or as
Executable Code. If the Work is provided as Executable Code, the Licensor
provides in addition a machine-readable copy of the Source Code of the Work
along with each copy of the Work that the Licensor distributes or indicates, in
a notice following the copyright notice attached to the Work, a repository where
the Source Code is easily and freely accessible for as long as the Licensor
continues to distribute and/or communicate the Work.
##4. Limitations on copyright
Nothing in this Licence is intended to deprive the Licensee of the benefits from
any exception or limitation to the exclusive rights of the rights owners in the
Original Work or Software, of the exhaustion of those rights or of other
applicable limitations thereto.
##5. Obligations of the Licensee
The grant of the rights mentioned above is subject to some restrictions and
obligations imposed on the Licensee. Those obligations are the following:
Attribution right: the Licensee shall keep intact all copyright, patent or
trademarks notices and all notices that refer to the Licence and to the
disclaimer of warranties. The Licensee must include a copy of such notices and a
copy of the Licence with every copy of the Work he/she distributes and/or
communicates. The Licensee must cause any Derivative Work to carry prominent
notices stating that the Work has been modified and the date of modification.
Copyleft clause: If the Licensee distributes and/or communicates copies of the
Original Works or Derivative Works based upon the Original Work, this
Distribution and/or Communication will be done under the terms of this Licence
or of a later version of this Licence unless the Original Work is expressly
distributed only under this version of the Licence. The Licensee (becoming
Licensor) cannot offer or impose any additional terms or conditions on the Work
or Derivative Work that alter or restrict the terms of the Licence.
Compatibility clause: If the Licensee Distributes and/or Communicates Derivative
Works or copies thereof based upon both the Original Work and another work
licensed under a Compatible Licence, this Distribution and/or Communication can
be done under the terms of this Compatible Licence. For the sake of this clause,
“Compatible Licence” refers to the licences listed in the appendix attached to
this Licence. Should the Licensees obligations under the Compatible Licence
conflict with his/her obligations under this Licence, the obligations of the
Compatible Licence shall prevail.
Provision of Source Code: When distributing and/or communicating copies of the
Work, the Licensee will provide a machine-readable copy of the Source Code or
indicate a repository where this Source will be easily and freely available for
as long as the Licensee continues to distribute and/or communicate the Work.
Legal Protection: This Licence does not grant permission to use the trade names,
trademarks, service marks, or names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the copyright notice.
##6. Chain of Authorship
The original Licensor warrants that the copyright in the Original Work granted
hereunder is owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each Contributor warrants that the copyright in the modifications he/she brings
to the Work are owned by him/her or licensed to him/her and that he/she has the
power and authority to grant the Licence.
Each time You accept the Licence, the original Licensor and subsequent
Contributors grant You a licence to their contributions to the Work, under the
terms of this Licence.
##7. Disclaimer of Warranty
The Work is a work in progress, which is continuously improved by numerous
contributors. It is not a finished work and may therefore contain defects or
“bugs” inherent to this type of software development.
For the above reason, the Work is provided under the Licence on an “as is” basis
and without warranties of any kind concerning the Work, including without
limitation merchantability, fitness for a particular purpose, absence of defects
or errors, accuracy, non-infringement of intellectual property rights other than
copyright as stated in Article 6 of this Licence.
This disclaimer of warranty is an essential part of the Licence and a condition
for the grant of any rights to the Work.
##8. Disclaimer of Liability
Except in the cases of wilful misconduct or damages directly caused to natural
persons, the Licensor will in no event be liable for any direct or indirect,
material or moral, damages of any kind, arising out of the Licence or of the use
of the Work, including without limitation, damages for loss of goodwill, work
stoppage, computer failure or malfunction, loss of data or any commercial
damage, even if the Licensor has been advised of the possibility of such
damage. However, the Licensor will be liable under statutory product liability
laws as far such laws apply to the Work.
##9. Additional agreements
While distributing the Original Work or Derivative Works, You may choose to
conclude an additional agreement to offer, and charge a fee for, acceptance of
support, warranty, indemnity, or other liability obligations and/or services
consistent with this Licence. However, in accepting such obligations, You may
act only on your own behalf and on your sole responsibility, not on behalf of
the original Licensor or any other Contributor, and only if You agree to
indemnify, defend, and hold each Contributor harmless for any liability incurred
by, or claims asserted against such Contributor by the fact You have accepted
any such warranty or additional liability.
##10. Acceptance of the Licence
The provisions of this Licence can be accepted by clicking on an icon “I agree”
placed under the bottom of a window displaying the text of this Licence or by
affirming consent in any other similar way, in accordance with the rules of
applicable law. Clicking on that icon indicates your clear and irrevocable
acceptance of this Licence and all of its terms and conditions.
Similarly, you irrevocably accept this Licence and all of its terms and
conditions by exercising any rights granted to You by Article 2 of this Licence,
such as the use of the Work, the creation by You of a Derivative Work or the
Distribution and/or Communication by You of the Work or copies thereof.
##11. Information to the public
In case of any Distribution and/or Communication of the Work by means of
electronic communication by You (for example, by offering to download the Work
from a remote location) the distribution channel or media (for example, a
website) must at least provide to the public the information requested by the
applicable law regarding the Licensor, the Licence and the way it may be
accessible, concluded, stored and reproduced by the Licensee.
##12. Termination of the Licence
The Licence and the rights granted hereunder will terminate automatically upon
any breach by the Licensee of the terms of the Licence.
Such a termination will not terminate the licences of any person who has
received the Work from the Licensee under the Licence, provided such persons
remain in full compliance with the Licence.
##13. Miscellaneous
Without prejudice of Article 9 above, the Licence represents the complete
agreement between the Parties as to the Work licensed hereunder.
If any provision of the Licence is invalid or unenforceable under applicable
law, this will not affect the validity or enforceability of the Licence as a
whole. Such provision will be construed and/or reformed so as necessary to make
it valid and enforceable.
The European Commission may publish other linguistic versions and/or new
versions of this Licence, so far this is required and reasonable, without
reducing the scope of the rights granted by the Licence. New versions of the
Licence will be published with a unique version number.
All linguistic versions of this Licence, approved by the European Commission,
have identical value. Parties can take advantage of the linguistic version of
their choice.
##14. Jurisdiction
Any litigation resulting from the interpretation of this License, arising
between the European Commission, as a Licensor, and any Licensee, will be
subject to the jurisdiction of the Court of Justice of the European Communities,
as laid down in article 238 of the Treaty establishing the European Community.
Any litigation arising between Parties, other than the European Commission, and
resulting from the interpretation of this License, will be subject to the
exclusive jurisdiction of the competent court where the Licensor resides or
conducts its primary business.
##15. Applicable Law
This Licence shall be governed by the law of the European Union country where
the Licensor resides or has his registered office.
This licence shall be governed by the Belgian law if:
- a litigation arises between the European Commission, as a Licensor, and any
- Licensee; the Licensor, other than the European Commission, has no residence
- or registered office inside a European Union country.
---
##Appendix
**“Compatible Licences”** according to article 5 EUPL are:
- GNU General Public License (GNU GPL) v. 2
- Open Software License (OSL) v. 2.1, v. 3.0
- Common Public License v. 1.0
- Eclipse Public License v. 1.0
- Cecill v. 2.0

55
README.md Normal file
View File

@ -0,0 +1,55 @@
# gCube URI Resolver
The URI Resolver is a RESTful service which gives access via HTTP(s) to different gCube Resolver services and gCube Applications
## Built With
* [OpenJDK](https://openjdk.java.net/) - The JDK used
* [Maven](https://maven.apache.org/) - Dependency Management
## Documentation
You can find the URI Resolver documentation at [URI Resolver Wiki Page](https://wiki.gcube-system.org/gcube/URI_Resolver)
## Change log
See the [URI Resolver Releases](https://code-repo.d4science.org/gCubeSystem/uri-resolver/releases)
## Authors
* **Francesco Mangiacrapa** ([ORCID](https://orcid.org/0000-0002-6528-664X)) Computer Scientist at [ISTI-CNR Infrascience Group](http://nemis.isti.cnr.it/groups/infrascience)
## License
This project is licensed under the EUPL V.1.1 License - see the [LICENSE.md](LICENSE.md) file for details.
## About the gCube Framework
This software is part of the [gCubeFramework](https://www.gcube-system.org/ "gCubeFramework"): an
open-source software toolkit used for building and operating Hybrid Data
Infrastructures enabling the dynamic deployment of Virtual Research Environments
by favouring the realisation of reuse oriented policies.
The projects leading to this software have received funding from a series of European Union programmes including:
- the Sixth Framework Programme for Research and Technological Development
- DILIGENT (grant no. 004260).
- the Seventh Framework Programme for research, technological development and demonstration
- D4Science (grant no. 212488);
- D4Science-II (grant no.239019);
- ENVRI (grant no. 283465);
- EUBrazilOpenBio (grant no. 288754);
- iMarine(grant no. 283644).
- the H2020 research and innovation programme
- BlueBRIDGE (grant no. 675680);
- EGIEngage (grant no. 654142);
- ENVRIplus (grant no. 654182);
- PARTHENOS (grant no. 654119);
- SoBigData (grant no. 654024);
- DESIRA (grant no. 818194);
- ARIADNEplus (grant no. 823914);
- RISIS2 (grant no. 824091);
- PerformFish (grant no. 727610);
- AGINFRAplus (grant no. 731001).

32
descriptor.xml Normal file
View File

@ -0,0 +1,32 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README.md</include>
<include>LICENSE.md</include>
<include>profile.xml</include>
<include>CHANGELOG.md</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
</fileSets>
<files>
<file>
<source>target/${build.finalName}.${project.packaging}</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
</files>
</assembly>

69
pom.xml
View File

@ -1,33 +1,35 @@
<?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">
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.0.0</version>
<version>1.1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.gcube.spatial.data</groupId>
<artifactId>geo-utility</artifactId>
<packaging>jar</packaging>
<version>1.1.2-SNAPSHOT</version>
<name>geo-utility</name>
<description>A library with several utility classes to work with geo-spatial data: WmsUrlValidator, GeoGetStyles, etc..</description>
<description>A library with utility classes to interact with geo-spatial data: WmsUrlValidator, GeoGetStyles, etc..</description>
<scm>
<connection>scm:git:https://code-repo.d4science.org/gCubeSystem/${project.artifactId}.git</connection>
<developerConnection>scm:git:https://code-repo.d4science.org/gCubeSystem/${project.artifactId}.git</developerConnection>
<url>https://code-repo.d4science.org/gCubeSystem/${project.artifactId}</url>
</scm>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<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>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
@ -72,6 +74,13 @@
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -92,39 +101,22 @@
</resource>
</resources>
<!-- <finalName>${artifactId}</finalName> -->
<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>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
<descriptor>descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
@ -138,6 +130,5 @@
</executions>
</plugin>
</plugins>
</build>
</project>

34
profile.xml Normal file
View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:p1="http://schemas.xmlsoap.org/wsdl/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID/>
<Type>Service</Type>
<Profile>
<Description>${project.description}</Description>
<Class>SpatialData</Class>
<Name>${project.artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>${project.artifactId}</Name>
<Description>${project.description}</Description>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
</MavenCoordinates>
<MultiVersion value="true"/>
<Mandatory level="GHN"/>
<Shareable level="VO"/>
<GHNRequirements>
<Requirement category="Site" operator="ge" requirement="string" value="java1.5"/>
</GHNRequirements>
<SpecificData>text</SpecificData>
<Type>service</Type>
<Files>
<File>${project.build.finalName}.${project.packaging}</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

View File

@ -0,0 +1,336 @@
/**
*
*/
package org.gcube.spatial.data.geoutility;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.gcube.spatial.data.geoutility.bean.LayerStyles;
import org.gcube.spatial.data.geoutility.bean.LayerZAxis;
import org.gcube.spatial.data.geoutility.bean.NcWmsLayerMetadata;
import org.gcube.spatial.data.geoutility.bean.NcWmsLayerMetadata.METADATA;
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 GeoNcWMSMetadataUtility.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 9, 2016
*/
public class GeoNcWMSMetadataUtility {
public static Logger logger = Logger.getLogger(GeoNcWMSMetadataUtility.class);
public static final String COLORSCALERANGE = "COLORSCALERANGE";
public static final String COLORSCALERANGE_DEFAULT_VALUE = "auto";
private String wmsRequest;
private WmsUrlValidator validator;
private int connectionTimeout;
private NcWmsLayerMetadata ncMetadata;
private LayerZAxis zAxis = null;
private LayerStyles layerStyles;
/** The Constant CONNECTION_TIMEOUT. */
public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; //DEFAULT CONNECTION TIMEOUT
/**
* Instantiates a new geo get styles utility.
*
* @param wmsRequest the wms request
* @throws Exception the exception
*/
public GeoNcWMSMetadataUtility(String wmsRequest) throws Exception{
this(wmsRequest, DEFAULT_CONNECTION_TIMEOUT);
}
/**
* Instantiates a new geo get styles utility.
*
* @param wmsRequest the wms request
* @param connectionTimeout the connection timeout sets a specified timeout value, in milliseconds, to be used when opening URLConnection.
* @throws Exception the exception
*/
public GeoNcWMSMetadataUtility(String wmsRequest, int connectionTimeout) throws Exception{
this.wmsRequest = wmsRequest;
this.connectionTimeout = connectionTimeout;
this.validator = new WmsUrlValidator(wmsRequest);
validator.parseWmsRequest(true, false);
validateConnectionTimeout();
loadMetadata();
}
/**
* Instantiates a new geo get styles utility.
*
* @param validator the validator
* @throws Exception the exception
*/
public GeoNcWMSMetadataUtility(WmsUrlValidator validator) throws Exception{
this(validator, DEFAULT_CONNECTION_TIMEOUT);
}
/**
* Instantiates a new geo get styles utility.
*
* @param validator the validator
* @param connectionTimeout the connection timeout sets a specified timeout value, in milliseconds, to be used when opening URLConnection.
* @throws Exception the exception
*/
public GeoNcWMSMetadataUtility(WmsUrlValidator validator, int connectionTimeout) throws Exception{
this.wmsRequest = validator.getWmsRequest();
this.validator = validator;
this.connectionTimeout = connectionTimeout;
validateConnectionTimeout();
loadMetadata();
}
/**
* Validate connection timeout.
*/
private void validateConnectionTimeout(){
if(this.connectionTimeout<=0)
this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
}
/**
* Load metadata.
*
* @throws Exception the exception
*/
private void loadMetadata() throws Exception{
String uriWMSService = validator.getBaseWmsServiceUrl();
String layerName = validator.getValueOfParsedWMSParameter(WmsParameters.LAYERS);
this.ncMetadata = NcWmsGetMetadata.getMetadata(uriWMSService, layerName, connectionTimeout, METADATA.values());
}
/**
* Load styles for a layer (WMS or ncWMS). This method puts styles for a layer into List {@link LayerStyles#getGeoStyles()}
* and override the value of {@link NcWmsGetMetadataRequest#COLORSCALERANGE} for ncWMS styles and put it into Map {@link LayerStyles#getMapNcWmsStyles()}
*
* @return the styles
*/
public LayerStyles loadStyles(){
String uriWMSService = validator.getBaseWmsServiceUrl();
String layerName = validator.getValueOfParsedWMSParameter(WmsParameters.LAYERS);
String versionWms = validator.getValueOfParsedWMSParameter(WmsParameters.VERSION);
String crs = validator.getValueOfParsedWMSParameter(WmsParameters.CRS);
layerStyles = new LayerStyles();
Map<String, String> mapNcWmsStyles = null;
List<String> styles;
boolean isNcWms = false;
try {
//OVERRIDE ncWMS COLORSCALERANGE='auto'
if(validator.getMapWmsNoStandardParams()!=null){
mapNcWmsStyles = new HashMap<String, String>(validator.getMapWmsNoStandardParams().size());
// mapNcWmsStyles.putAll(validator.getMapWmsNotStandardParams());
if(validator.getMapWmsNoStandardParams().containsKey(NcWmsGetMetadataRequest.COLORSCALERANGE) || validator.getMapWmsNoStandardParams().containsKey(NcWmsGetMetadataRequest.COLORSCALERANGE.toLowerCase())){
isNcWms = true;
logger.debug("Ovveriding "+NcWmsGetMetadataRequest.COLORSCALERANGE +"?");
String value = validator.getMapWmsNoStandardParams().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),connectionTimeout);
if(minmax!=null && minmax.length==2 && minmax[0]!=null && minmax[1]!=null){
String valueMinMax = minmax[0]+","+minmax[1];
mapNcWmsStyles.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),connectionTimeout);
if(minmax!=null && minmax.length==2 && minmax[0]!=null && minmax[1]!=null){
isNcWms = true;
logger.debug(NcWmsGetMetadataRequest.GET_METADATA +" works, adding "+NcWmsGetMetadataRequest.COLORSCALERANGE + " with minmax");
String valueMinMax = minmax[0]+","+minmax[1];
mapNcWmsStyles.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);
//VALIDATION STYLES
if(stylesRead==null || stylesRead.isEmpty()){
logger.trace("styles are empty or null - Trying to get styles by 'WMS Get Style'");
WmsGetStyles wmsGetStyles = new WmsGetStyles(connectionTimeout);
styles = wmsGetStyles.getStylesFromWms(uriWMSService, layerName);
if(wmsGetStyles.getResponseCode()==200){
logger.debug("WMS Get Style found: "+styles);
}else{
logger.debug("Wms GetStyles not found, Trying to get styles by 'NcWmsGetMetadata'");
isNcWms = true;
try{
if(ncMetadata==null){
METADATA[] meta = new METADATA[3];
meta[0] = METADATA.SUPPORTEDSTYLES;
meta[1] = METADATA.DEFAULTPALETTE;
meta[2] = METADATA.PALETTES;
this.ncMetadata = NcWmsGetMetadata.getMetadata(uriWMSService, layerName, connectionTimeout, meta);
}
if(ncMetadata!=null && ncMetadata.getResponseCode()==200){
//STYLES
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();
}
logger.trace("returning style: "+styles);
layerStyles.setGeoStyles(styles);
layerStyles.setMapNcWmsStyles(mapNcWmsStyles);
layerStyles.setNcWms(isNcWms);
return layerStyles;
// this.geoStyles = styles;
}
/**
* Load z-axis values for a ncWMS layer and put it into {@link #getZAxis()}
* @return
*
* @return the z axis
* @throws Exception
*/
public LayerZAxis loadZAxis() throws Exception{
if(ncMetadata==null){
String uriWMSService = validator.getBaseWmsServiceUrl();
String layerName = validator.getValueOfParsedWMSParameter(WmsParameters.LAYERS);
METADATA[] meta = new METADATA[1];
meta[0] = METADATA.Z_AXIS;
this.ncMetadata = NcWmsGetMetadata.getMetadata(uriWMSService, layerName, connectionTimeout, meta);
}
if(this.ncMetadata==null)
this.zAxis = null;
else
this.zAxis = this.ncMetadata.getZAxis();
return this.zAxis;
}
/**
* @return the zAxis
*/
public LayerZAxis getZAxis() {
return zAxis;
}
/**
* @return the layerStyles
*/
public LayerStyles getLayerStyles() {
return layerStyles;
}
/**
* Gets the wms request.
*
* @return the wmsRequest
*/
public String getWmsRequest() {
return wmsRequest;
}
/**
* Gets the map wms no standard parameters.
*
* @return the map wms no standard parameters
*/
public Map<String, String> getMapWmsNoStandardParameters(){
return validator.getMapWmsNoStandardParams();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GeoNcWMSMetadataUtility [wmsRequest=");
builder.append(wmsRequest);
builder.append(", validator=");
builder.append(validator);
builder.append(", connectionTimeout=");
builder.append(connectionTimeout);
builder.append(", ncMetadata=");
builder.append(ncMetadata);
builder.append(", zAxis=");
builder.append(zAxis);
builder.append(", layerStyles=");
builder.append(layerStyles);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,63 @@
/**
*
*/
package org.gcube.spatial.data.geoutility;
/**
* The Class GeoWmsServiceUtility.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 25, 2016
*/
public class GeoWmsServiceUtility {
public static final String OWS = "ows";
public static final String SERVICE_WMS = "service=wms";
/**
* Instantiates a new geo service wms utility.
*/
public GeoWmsServiceUtility() {
}
/**
* Checks if is WMS service.
*
* @param wmsRequest the wms request
* @return true, if is WMS service
* @throws Exception the exception
*/
public static boolean isWMSService(String wmsRequest) throws Exception{
validateWmsRequest(wmsRequest);
return wmsRequest.toLowerCase().lastIndexOf(SERVICE_WMS)>-1;
}
/**
* Validate wms request.
*
* @param wmsRequest the wms request
* @throws Exception the exception
*/
private static void validateWmsRequest(String wmsRequest) throws Exception{
if(wmsRequest==null || wmsRequest.isEmpty())
throw new Exception("Wms Request is null or empty!");
}
/**
* Checks if is OWS serice.
*
* @param wmsRequest the wms request
* @return true, if is OWS serice
* @throws Exception the exception
*/
public static boolean isOWSSerice(String wmsRequest) throws Exception{
validateWmsRequest(wmsRequest);
return wmsRequest.toLowerCase().contains(OWS);
}
}

View File

@ -0,0 +1,130 @@
/**
*
*/
package org.gcube.spatial.data.geoutility.bean;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* The Class LayerStyles.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 10, 2016
*/
public class LayerStyles implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2322122044504571474L;
private List<String> geoStyles;
private Map<String, String> mapNcWmsStyles;
boolean isNcWms = false;
/**
* Instantiates a new layer styles.
*/
public LayerStyles() {
}
/**
* Instantiates a new layer styles.
*
* @param geoStyles the geo styles
* @param mapNcWmsStyles the map nc wms styles
* @param isNcWms the is nc wms
*/
public LayerStyles(List<String> geoStyles, Map<String, String> mapNcWmsStyles,boolean isNcWms) {
this.geoStyles = geoStyles;
this.mapNcWmsStyles = mapNcWmsStyles;
this.isNcWms = isNcWms;
}
/**
* Gets the geo styles.
*
* @return the geoStyles
*/
public List<String> getGeoStyles() {
return geoStyles;
}
/**
* Gets the map nc wms styles.
*
* @return the mapNcWmsStyles
*/
public Map<String, String> getMapNcWmsStyles() {
return mapNcWmsStyles;
}
/**
* Checks if is nc wms.
*
* @return the isNcWms
*/
public boolean isNcWms() {
return isNcWms;
}
/**
* Sets the geo styles.
*
* @param geoStyles the geoStyles to set
*/
public void setGeoStyles(List<String> geoStyles) {
this.geoStyles = geoStyles;
}
/**
* Sets the map nc wms styles.
*
* @param mapNcWmsStyles the mapNcWmsStyles to set
*/
public void setMapNcWmsStyles(Map<String, String> mapNcWmsStyles) {
this.mapNcWmsStyles = mapNcWmsStyles;
}
/**
* Sets the nc wms.
*
* @param isNcWms the isNcWms to set
*/
public void setNcWms(boolean isNcWms) {
this.isNcWms = isNcWms;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("LayerStyles [geoStyles=");
builder.append(geoStyles);
builder.append(", mapNcWmsStyles=");
builder.append(mapNcWmsStyles);
builder.append(", isNcWms=");
builder.append(isNcWms);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,131 @@
/**
*
*/
package org.gcube.spatial.data.geoutility.bean;
import java.io.Serializable;
import java.util.List;
/**
* The Class LayerZAxis.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 10, 2016
*/
public class LayerZAxis implements Serializable{
/**
*
*/
private static final long serialVersionUID = 7559936591822228182L;
public static final String UNITS = "units";
public static final String POSITIVE = "positive";
public static final String VALUES = "values";
private String units;
private boolean positive;
private List<Double> values;
/**
* Instantiates a new layer z axis.
*/
public LayerZAxis() {
}
/**
* Instantiates a new layer z axis.
*
* @param units the units
* @param positive the positive
* @param values the values
*/
public LayerZAxis(String units, boolean positive, List<Double> values) {
this.units = units;
this.positive = positive;
this.values = values;
}
/**
* Gets the units.
*
* @return the units
*/
public String getUnits() {
return units;
}
/**
* Checks if is positive.
*
* @return the positive
*/
public boolean isPositive() {
return positive;
}
/**
* Gets the values.
*
* @return the values
*/
public List<Double> getValues() {
return values;
}
/**
* Sets the units.
*
* @param units the units to set
*/
public void setUnits(String units) {
this.units = units;
}
/**
* Sets the positive.
*
* @param positive the positive to set
*/
public void setPositive(boolean positive) {
this.positive = positive;
}
/**
* Sets the values.
*
* @param values the values to set
*/
public void setValues(List<Double> values) {
this.values = values;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ZAxis [units=");
builder.append(units);
builder.append(", positive=");
builder.append(positive);
builder.append(", values=");
builder.append(values);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,213 @@
/**
*
*/
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;
public static enum METADATA {
SUPPORTEDSTYLES("supportedStyles"),
PALETTES("palettes"),
DEFAULTPALETTE("defaultPalette"),
Z_AXIS("zaxis");
private String key;
METADATA(String key){
this.key = key;
}
public String getKey() {
return key;
}
};
private String defaultPalette;
private List<String> supportedStyles;
private List<String> palettes;
private int responseCode;
private LayerZAxis zAxis;
private String rawJson;
/**
* Instantiates a new nc wms layer metadata.
*/
public NcWmsLayerMetadata() {
}
/**
* 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
* @param zAxis the z axis
* @param json the json
*/
public NcWmsLayerMetadata(int responseCode, String defaultPalette, List<String> supportedStyles, List<String> palettes, LayerZAxis zAxis, String json) {
this.responseCode = responseCode;
this.defaultPalette = defaultPalette;
this.supportedStyles = supportedStyles;
this.palettes = palettes;
this.zAxis = zAxis;
this.rawJson = json;
}
/**
* Sets the raw json.
*
* @param jsonTxt the new raw json
*/
public void setRawJson(String jsonTxt) {
this.rawJson =jsonTxt;
}
/**
* Gets the raw json.
*
* @return the rawJson
*/
public String getRawJson() {
return rawJson;
}
/**
* 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;
}
/**
* Gets the z axis.
*
* @return the zAxis
*/
public LayerZAxis getZAxis() {
return zAxis;
}
/**
* Sets the z axis.
*
* @param zAxis the zAxis to set
*/
public void setZAxis(LayerZAxis zAxis) {
this.zAxis = zAxis;
}
/**
* 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;
}
/**
* Gets the response code.
*
* @return the responseCode
*/
public int getResponseCode() {
return responseCode;
}
/**
* Sets the response code.
*
* @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(", responseCode=");
builder.append(responseCode);
builder.append(", zAxis=");
builder.append(zAxis);
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,125 @@
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,195 @@
/**
*
*/
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,97 @@
/**
*
*/
package org.gcube.spatial.data.geoutility.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* The Class UrlEncoderUtil.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 25, 2016
*/
public class UrlEncoderUtil {
public static String charset = "UTF-8";
public static Logger logger = Logger.getLogger(UrlEncoderUtil.class);
/**
* Encode query.
*
* @param parameters the parameters
* @return the string
*/
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);
}
/**
* Encode query.
*
* @param parameters the parameters
* @return the string
*/
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);
}
/**
* Removes the last char.
*
* @param string the string
* @return the string
*/
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,249 @@
/**
*
*/
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.Arrays;
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.LayerZAxis;
import org.gcube.spatial.data.geoutility.bean.NcWmsLayerMetadata;
import org.gcube.spatial.data.geoutility.bean.NcWmsLayerMetadata.METADATA;
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 {
/** The Constant CONNECTION_TIMEOUT. */
protected static final int CONNECTION_TIMEOUT = 1000; //DEFAULT CONNECTION TIMEOUT
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 {
return getMetadata(wmsServerUri, layerName, CONNECTION_TIMEOUT, METADATA.values());
}
/**
* Gets the metadata.
*
* @param wmsServerUri the wms server uri
* @param layerName the layer name
* @param connectionTimeout the connection timeout
* @param meta the meta
* @return the metadata
* @throws Exception the exception
*/
public static NcWmsLayerMetadata getMetadata(String wmsServerUri, String layerName, int connectionTimeout, NcWmsLayerMetadata.METADATA...meta) 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, connectionTimeout, meta);
}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
* @param connectionTimeout the connection timeout sets a specified timeout value, in milliseconds, to be used when opening URLConnection.
* @param meta the meta
* @return the nc wms layer metadata
*/
private static NcWmsLayerMetadata openConnectionGetMetadata(String urlConn, String query, int connectionTimeout, NcWmsLayerMetadata.METADATA...meta) {
URL url;
NcWmsLayerMetadata metadata = null;
try {
url = new URL(urlConn + "?" + query);
URLConnection connection = url.openConnection();
if(connectionTimeout<0)
connectionTimeout = CONNECTION_TIMEOUT;
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(connectionTimeout + connectionTimeout);
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, meta);
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
* @param meta the meta
* @return the metadata
* @throws IOException Signals that an I/O exception has occurred.
*/
private static NcWmsLayerMetadata getMetadata(HttpURLConnection httpConnection, METADATA[] meta) throws IOException{
InputStream source = null;
NcWmsLayerMetadata metadata = new NcWmsLayerMetadata();
try{
source = httpConnection.getInputStream();
String jsonTxt = IOUtils.toString(source);
metadata.setRawJson(jsonTxt);
if(meta==null)
meta = METADATA.values();
List<METADATA> listMeta = Arrays.asList(meta);
JSONObject json = new JSONObject(jsonTxt);
if(listMeta.contains(NcWmsLayerMetadata.METADATA.SUPPORTEDSTYLES)){
JSONArray supportedStyles = json.getJSONArray(NcWmsLayerMetadata.METADATA.SUPPORTEDSTYLES.getKey());
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);
}
}
if(listMeta.contains(NcWmsLayerMetadata.METADATA.PALETTES)){
JSONArray palettes = json.getJSONArray(NcWmsLayerMetadata.METADATA.PALETTES.getKey());
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);
}
}
if(listMeta.contains(NcWmsLayerMetadata.METADATA.DEFAULTPALETTE)){
metadata.setDefaultPalette(json.getString(NcWmsLayerMetadata.METADATA.DEFAULTPALETTE.getKey()));
}
if(listMeta.contains(NcWmsLayerMetadata.METADATA.Z_AXIS)){
JSONObject zaxis = json.getJSONObject(NcWmsLayerMetadata.METADATA.Z_AXIS.getKey());
if(zaxis!=null){
logger.trace("z-axis: "+zaxis.toString());
LayerZAxis zAxis = new LayerZAxis();
zAxis.setUnits(zaxis.getString(LayerZAxis.UNITS));
zAxis.setPositive(zaxis.getBoolean(LayerZAxis.POSITIVE));
JSONArray values = zaxis.getJSONArray(LayerZAxis.VALUES);
if(values!=null){
List<Double> s = new ArrayList<Double>(values.length());
for (int i=0; i<values.length(); i++) {
s.add(values.getDouble(i));
}
zAxis.setValues(s);
}
metadata.setZAxis(zAxis);
}
}
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 {
System.out.println(NcWmsGetMetadata.getMetadata("http://thredds.research-infrastructures.eu/thredds/wms/public/netcdf/WOA2005TemperatureAnnual_CLIMATOLOGY_METEOROLOGY_ATMOSPHERE_.nc", "t00an1"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,221 @@
/**
*
*/
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
* @param connectionTimeout the connection timeout
* @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, int connectionTimeout) 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, connectionTimeout);
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
* @param connectionTimeout the connection timeout
* @return the string[] an array with 2 elements witch contains min, max value for the COLORSCALERANGE
*/
private static String[] openConnectionGetColorScaleRange(String urlConn, String query, int connectionTimeout) {
URL url;
String[] colorScaleRange = null;
try {
url = new URL(urlConn + "?" + query);
URLConnection connection = url.openConnection();
if(connectionTimeout<0)
connectionTimeout = CONNECTION_TIMEOUT;
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(connectionTimeout*2);
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", 2000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,341 @@
/**
*
*/
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 {
private int CONNECTION_TIMEOUT = 1000; //DEFAULT CONNECTION TIMEOUT
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);
}
/**
* Instantiates a new wms get styles.
*
* @param connectionTimeout the connection timeout sets a specified timeout value, in milliseconds, to be used when opening WMS GetStyles request.
*/
public WmsGetStyles(int connectionTimeout) {
this();
if(connectionTimeout>0)
CONNECTION_TIMEOUT = connectionTimeout;
}
/**
* 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>();
String query = "";
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");
query = UrlEncoderUtil.encodeQuery(parameters);
WmsServiceBaseUri geosever = foundWmsServiceBaseUri(urlConn);
if(query==null || query.isEmpty())
return new ArrayList<String>();
logger.info("tentative get styles.. with query: " + query);
styles = openConnectionGetStyles(urlConn, query);
if(styles==null || styles.isEmpty()){
if(geosever.getScope()!=null && !geosever.getScope().isEmpty()){
logger.trace("trying to get styles with scope: "+geosever.getScope());
String newUrlConn = urlConn.replace("/"+geosever.getScope(), "");
logger.trace("new tentative get styles as base url without scope");
styles = openConnectionGetStyles(newUrlConn, query);
}
}
logger.info("WMS GetStyles returning: "+styles.toString());
return styles;
}catch (Exception e) {
logger.error("Error Exception getStylesFromWms from url: " + urlConn + ", query: "+query, e);
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,418 @@
package org.gcube.spatial.data.geoutility.wms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.gcube.spatial.data.geoutility.bean.WmsParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class WmsUrlValidator.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Jan 25, 2016
*/
public class WmsUrlValidator {
private HashMap<String, String> mapWmsParameters = new HashMap<String, String>();
private String wmsRequest;
private String baseWmsServiceUrl;
private String wmsParameters;
private String wmsNoStandardParameters = "";
private Map<String, String> mapWmsNoStandardParams;
public static Logger logger = LoggerFactory.getLogger(WmsUrlValidator.class);
/**
* Instantiates a new wms url validator.
*
* @param wmsRequest the wms request
*/
public WmsUrlValidator(String wmsRequest){
this.wmsRequest = wmsRequest;
logger.debug("The wms request is: "+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 the wms request uri builded
* @throws Exception the 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);
mapWmsParameters.put(wmsParam.getParameter(), value);
}
if(wmsParam.equals(WmsParameters.FORMAT)){
String value = validateValueOfParameter(WmsParameters.FORMAT, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), value);
}
if(wmsParam.equals(WmsParameters.HEIGHT)){
String value = validateValueOfParameter( WmsParameters.HEIGHT, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), value);
}
if(wmsParam.equals(WmsParameters.CRS)){
String crs = validateValueOfParameter(WmsParameters.CRS, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), crs);
}
if(wmsParam.equals(WmsParameters.WIDTH)){
String value = validateValueOfParameter(WmsParameters.WIDTH, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), value);
}
if(wmsParam.equals(WmsParameters.REQUEST)){
String value = validateValueOfParameter(WmsParameters.REQUEST, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), value);
}
if(wmsParam.equals(WmsParameters.SERVICE)){
String value = validateValueOfParameter(WmsParameters.SERVICE, wmsParameters,fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), value);
}
if(wmsParam.equals(WmsParameters.SRS)){
String value = validateValueOfParameter(WmsParameters.SRS, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), value);
}
if(wmsParam.equals(WmsParameters.STYLES)){
String styles = validateValueOfParameter(WmsParameters.STYLES, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), styles);
}
if(wmsParam.equals(WmsParameters.VERSION)){
String version = validateValueOfParameter(WmsParameters.VERSION, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), version);
}
if(wmsParam.equals(WmsParameters.LAYERS)){
String layers = validateValueOfParameter(WmsParameters.LAYERS, wmsParameters, fillEmptyParameterAsDefaultValue);
mapWmsParameters.put(wmsParam.getParameter(), layers);
}
}
String parsedWmsRequest = baseWmsServiceUrl+"?";
String[] params = wmsParameters.split("&");
//CREATING MAP TO RETURN WMS PARAMETERS NOT STANDARD
mapWmsNoStandardParams = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
if(params.length>0) {
logger.debug("Params are: "+Arrays.asList(params));
for (String param : params) {
if(param!=null && !param.isEmpty()) {
int ei = param.indexOf("=");
String key = param.substring(0, ei);
String value = param.substring(ei+1, param.length());
mapWmsNoStandardParams.put(key, value);
}
}
}
//CREATE WMS REQUEST
for (String key : mapWmsParameters.keySet()) {
String value = mapWmsParameters.get(key);
if(returnEmptyParameter || !(value==null) && !value.isEmpty()){
parsedWmsRequest+=key+"="+value;
parsedWmsRequest+="&";
}
/*if(!returnEmptyParameter && (value==null || value.isEmpty())){
}else{
fullWmsRequest+=key+"="+value;
fullWmsRequest+="&";
}*/
String exist = mapWmsParameters.get(key);
if(exist!=null)
mapWmsNoStandardParams.remove(key); //REMOVE WMS STANDARD PARAMETER FROM MAP
}
for (String key : mapWmsNoStandardParams.keySet()) {
wmsNoStandardParameters+=key+"="+mapWmsNoStandardParams.get(key) + "&";
}
if(wmsNoStandardParameters.length()>0)
wmsNoStandardParameters = wmsNoStandardParameters.substring(0, wmsNoStandardParameters.length()-1); //REMOVE LAST &
logger.trace("wmsNotStandardParameters: "+wmsNoStandardParameters);
String fullWmsUrlBuilded;
if(!wmsNoStandardParameters.isEmpty()){
fullWmsUrlBuilded = parsedWmsRequest + wmsNoStandardParameters; //remove last &
logger.trace("full wms url builded + wms no standard parameters: "+fullWmsUrlBuilded);
}else{
fullWmsUrlBuilded = parsedWmsRequest.substring(0, parsedWmsRequest.length()-1); //remove last &
logger.trace("WmsUrlValidator parseWmsRequest returning, full wms url builded: "+fullWmsUrlBuilded);
}
return fullWmsUrlBuilded;
}
/**
* Gets the map wms parameters.
*
* @return the map wms parameters
*/
public HashMap<String, String> getMapWmsParameters() {
return mapWmsParameters;
}
/**
* Gets the wms request.
*
* @return the wmsRequest
*/
public String getWmsRequest() {
return wmsRequest;
}
/**
* Gets the base wms service url.
*
* @return the baseWmsServiceUrl
*/
public String getBaseWmsServiceUrl() {
return baseWmsServiceUrl;
}
/**
* Gets the wms no standard parameters.
*
* @return the wms no standard parameters like a query string (param1=value1&param2=value2&...)
*/
public String getWmsNoStandardParameters() {
return wmsNoStandardParameters;
}
/**
* 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 mapWmsParameters.get(parameter.getParameter());
}
/**
* Validate value of parameter.
*
* @param wmsParam the wms param
* @param queryStringParameters the value of parameter
* @param fillEmptyParameterAsDefaultValue the fill empty parameter as default value
* @return the string
*/
public static String validateValueOfParameter(WmsParameters wmsParam, String queryStringParameters, boolean fillEmptyParameterAsDefaultValue){
try{
logger.trace("validateValueOfParameter wmsParam "+wmsParam+" with queryStringParameters " +queryStringParameters);
String value = getValueOfParameter(wmsParam, queryStringParameters);
logger.trace("validateValueOfParameter wmsParam "+wmsParam+" value " +value);
if(fillEmptyParameterAsDefaultValue && (value==null || value.isEmpty())){
logger.trace("setting empty value for 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()+"="); //ADDING CHAR "=" IN TAIL TO BE SECURE IT IS A PARAMETER
// 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+"="); //END WITH CHAR "=" TO BE SECURE IT IS A 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 no standard params.
*
* @return an empty map if WMS no standard parameters don't exist
*/
public Map<String, String> getMapWmsNoStandardParams() {
return mapWmsNoStandardParams==null?new HashMap<String, String>(1):mapWmsNoStandardParams;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("WmsUrlValidator [mapWmsParameters=");
builder.append(mapWmsParameters);
builder.append(", wmsRequest=");
builder.append(wmsRequest);
builder.append(", baseWmsServiceUrl=");
builder.append(baseWmsServiceUrl);
builder.append(", wmsParameters=");
builder.append(wmsParameters);
builder.append(", wmsNotStandardParameters=");
builder.append(wmsNoStandardParameters);
builder.append(", mapWmsNoStandardParams=");
builder.append(mapWmsNoStandardParams);
builder.append("]");
return builder.toString();
}
/**
* 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://www.fao.org/figis/geoserver/species/ows?CRS=EPSG:4326&BBOX=-180,-90,180,90&VERSION=1.1.0&FORMAT=image/png&SERVICE=WMS&HEIGHT=230&LAYERS=&REQUEST=GetMap&STYLES=&SRS=EPSG:4326&WIDTH=676";
// fullPath = WmsUrlValidator.setValueOfParameter(WmsParameters.LAYERS, fullPath, "123", true);
// System.out.println(fullPath);
String wmsRequest = "http://geoserver-dev.d4science-ii.research-infrastructures.eu/geoserver/wms?CRS=EPSG:4326&BBOX=-85.5,-180.0,90.0,180.0&VERSION=1.1.0&FORMAT=application/openlayers&SERVICE=wms&HEIGHT=330&LAYERS=aquamaps:lsoleasolea20130716162322254cest&REQUEST=GetMap&STYLES=Species_prob&SRS=EPSG:4326&WIDTH=676";
// 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";
WmsUrlValidator wms;
try {
wms = new WmsUrlValidator(wmsRequest);
System.out.println("Returned wms: "+wms.toString());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
}

View File

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID></ID>
<Type>Library</Type>
<Profile>
<Description>{description}</Description>
<Class>SpatialData</Class>
<Name>geo-utility</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>geo-utility</Name>
<Version>1.1.1-SNAPSHOT</Version>
<MavenCoordinates>
<groupId>org.gcube.spatial.data</groupId>
<artifactId>geo-utility</artifactId>
<version>1.1.1-SNAPSHOT</version>
</MavenCoordinates>
<Files>
<File>geo-utility-1.1.1-SNAPSHOT.jar</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

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