Compare commits

..

54 Commits

Author SHA1 Message Date
mbarto
b8ecffaa0b Merge pull request #156 from xandros6/v1.5.1-patch
Added additional WCS informations to publish GeoTIFF
2015-11-23 17:03:04 +01:00
Xandros
b4c2ab8d3d Added additional WCS informations to publish GeoTIFF 2015-11-20 12:52:21 +01:00
Carlo Cancellieri
545acc425a Merge pull request #117 from eblondel/1.5.x-114-GSLayerEncoder21-fix
1.5.x -  #114 - GSLayerEncoder21 fix
2013-11-22 13:35:05 -08:00
eblondel
6fc77c7936 1.5.x #114 - fix GSLayerEncoder21 (identifiers) 2013-11-21 13:36:16 +01:00
Carlo Cancellieri
5c1569c129 Merge pull request #113 from eblondel/1.5.x-102-GSLayer-AuthorityURL-Identifier-advertise
#102 - 1.5.x - support for AuthorityURL/Identifier/advertise + tests
2013-10-21 09:42:09 -07:00
eblondel
9d72c4665d #102 - 1.5.x - support for AuthorityURL/Identifier/advertise + tests 2013-10-21 17:38:21 +02:00
Carlo Cancellieri
cb6fc418f2 Merge pull request #111 from geosolutions-it/1.5.x-110-IllegalArgument-getVersion
close 110. IllegalArgument on getVersion on Geoserver 2.1
2013-10-21 06:50:00 -07:00
carlo cancellieri
6979d0d435 close 110. IllegalArgument on getVersion on Geoserver 2.1 2013-10-21 11:19:07 +02:00
Carlo Cancellieri
7f232a1168 Merge pull request #108 from wumpz/1.5.x-FeatureTypeList-backport
1.5.x feature type list backport this time with the right target branch
2013-10-19 10:50:42 -07:00
wumpz
500043ba1f FeatureTypeList included 2013-10-18 22:11:33 +02:00
wumpz
47acfa9f1a FeatureTypeList included 2013-10-18 22:11:24 +02:00
carlo cancellieri
11a75c3ae4 fix commit for #105. add integration tests 2013-10-18 16:09:09 +02:00
carlo cancellieri
0c6823057b close #105. add getVersion capabilities 2013-10-18 14:35:50 +02:00
etj
a610bc3de9 RESTLayer: provide workspace info in default style. Close #100. 2013-10-08 11:49:56 +02:00
Carlo Cancellieri
71b46e2745 Merge pull request #99 from geosolutions-it/1.5.x-RESTFeatureTypes-attributes
fix inheritance for RESTFeatureTyle getAttribute methods
2013-09-30 08:00:31 -07:00
carlo cancellieri
8414e18ee5 fix inheritance for RESTFeatureTyle getAttribute methods
Conflicts:

	src/main/java/it/geosolutions/geoserver/rest/decoder/RESTFeatureType.java
	src/main/java/it/geosolutions/geoserver/rest/decoder/RESTResource.java
2013-09-30 16:34:21 +02:00
Carlo Cancellieri
539edf5429 Merge pull request #97 from eblondel/1.5.x-95-keywords-decoder
1.5.x - #95 - keywords decoder
2013-09-30 05:25:46 -07:00
eblondel
fca8dd65bc #95 - add keyword decoder + ResourceDecoderTest 2013-09-30 14:13:38 +02:00
Carlo Cancellieri
cc206bc730 Merge pull request #86 from eblondel/1.5.x-84-GSLayerEncoder-multiple-styles
#84 - 1.5.x - support encoding of multiple styles + tests
2013-07-05 00:27:00 -07:00
eblondel
93b4aa8041 #84 - 1.5.x - support encoding of multiple styles + tests 2013-07-05 08:21:54 +02:00
carlo cancellieri
c61a5055cd port: simplify the publisher 2013-07-02 16:49:31 +02:00
Carlo Cancellieri
124b2b9aca Merge pull request #83 from eblondel/1.5.x-81-DatastoreEncoder-EstimatedExtends-fix
#81 - 1.5.x - fix PostGIS / OracleNG Estimated extends param
2013-06-25 06:26:00 -07:00
eblondel
ee6b428e63 #81 - 1.5.x - fix PostGIS / OracleNG Estimated extends param 2013-06-25 14:04:20 +02:00
etj
c9d181e473 Back to SNAPSHOT version 2013-06-18 15:18:03 +02:00
etj
645d79c2cb Release 1.5.2 2013-06-18 15:08:42 +02:00
carlo cancellieri
be329f8a55 Merge branch '1.5.x' of https://github.com/geosolutions-it/geoserver-manager into 1.5.x 2013-06-13 08:00:51 +02:00
carlo cancellieri
71132e3b9e fix #80: Considering several layers with the same name 2013-06-13 08:00:31 +02:00
Carlo Cancellieri
89e049baf7 Merge pull request #79 from geosolutions-it/77-1.5.x-missing-support-jp2k
fix: missing jp2k support. close 77
2013-06-12 03:57:37 -07:00
carlo cancellieri
f76434ea82 fix: missing jp2k support. close 77 2013-06-12 11:41:06 +02:00
mbarto
51fac5a674 Merge pull request #73 from eblondel/1.5.x-71-OracleNGDatastore-fix
#71 - 1.5.x - GSOracleNGDatastoreEncoder fix & tests (backport)
2013-05-02 23:59:57 -07:00
eblondel
695877041a #71 - 1.5.x - GSOracleNGDatastoreEncoder fix & tests (backport) 2013-05-02 20:15:24 +02:00
carlo cancellieri
75f03072d1 deprecate GSResourceEncoder.setMetadata in flavour of specializations 2013-04-15 16:31:59 +02:00
Carlo Cancellieri
b32ec90405 Merge pull request #70 from eblondel/1.5.x-65-VirtualTable-support
#65 VirtualTable support (1.5.x) - add encoder/decode + tests
2013-04-15 06:33:44 -07:00
eblondel
aba9f6b7e0 #65 VirtualTable support (1.5.x) - add encoder/decode + tests 2013-04-15 15:21:14 +02:00
Carlo Cancellieri
958485263f Merge pull request #69 from eblondel/1.5.x-62-MetadataLink-refactor
#62 - MetadataLinkInfo (1.5.x) - refactor encoder/decoder
2013-04-15 05:51:03 -07:00
eblondel
6332769557 MetadataLinkInfo (1.5.x) - refactor encoder/decoder 2013-04-15 14:43:55 +02:00
carlo cancellieri
2e6a972f28 clean GeoserverRESTDatastoreManagerTest license 2013-04-15 10:05:52 +02:00
Carlo Cancellieri
5158cd940c Merge pull request #66 from eblondel/1.5.x-62-Metadatalink-support
#62 MetadataLink support (1.5.x branch)
2013-04-12 00:30:09 -07:00
eblondel
54df100ea6 #62 MetadataLink support (1.5.x branch) - add encoder/decoder & tests 2013-04-11 19:40:18 +02:00
carlo cancellieri
ea6976dc19 fix: #61 LayerGroup tests are failing on master 2013-04-10 21:30:01 +02:00
ccancellieri
a96ecf4f1c added links to the mailing list on the README 2013-02-01 15:33:14 +01:00
Davide Savazzi
7760354b81 changed pom version 2013-01-24 11:48:56 +01:00
Davide Savazzi
c88fec8530 changed pom version 2013-01-24 11:32:50 +01:00
Davide Savazzi
a49473f542 Merge pull request #55 from svzdvd/1.5.1-release
fixed LayerGroup Encoder tests
2013-01-24 01:43:04 -08:00
Davide Savazzi
4e0ebffa3c fixed LayerGroup Encoder tests 2013-01-24 10:39:09 +01:00
Davide Savazzi
aef225d60e Merge pull request #54 from svzdvd/1.5.1-release
Backport of LayerGroup patch for branch 1.5.x
2013-01-23 13:06:55 -08:00
Davide Savazzi
a67e10dab3 fixed name of GeoServerRESTDatastoreManager file 2013-01-23 22:00:20 +01:00
Davide Savazzi
d00ad470e4 added LayerGroup encoder for GeoServer 2.2 and GeoServer 2.3 2013-01-23 21:55:04 +01:00
Davide Savazzi
552edbc9fe updated LayerGroup reader to support GeoServer 2.3.x 2013-01-23 21:54:45 +01:00
Carlo Cancellieri
4fc0a8dd99 Merge pull request #51 from geosolutions-it/1.5.x-StoreManager-improvements
1.5.x store manager improvements
2013-01-22 06:40:13 -08:00
ccancellieri
550f982701 refine backport 2013-01-22 14:43:44 +01:00
ccancellieri
0978997f9f backport to the 1.5.x branch 2013-01-21 19:03:10 +01:00
ccancellieri
46fbce4393 Remove specific datastore methods from manager implementing a generic StoreManager. Improving Store encoders and integration tests. 2013-01-21 18:35:42 +01:00
Damiano
0097264d42 changed pom version 2013-01-14 18:51:06 +01:00
117 changed files with 2412 additions and 9091 deletions

View File

@ -1,15 +0,0 @@
sudo: false
cache:
directories:
- "$HOME/.m2"
language: java
jdk:
- oraclejdk7
- openjdk7
script:
- mvn -B -T2 -fae clean install
notifications:
email: false
on_failure: never
after_success:
- mvn clean cobertura:cobertura coveralls:report

View File

@ -1,4 +1,4 @@
Copyright (c) 20007-2016 GeoSolutions Copyright (c) 20007-2011 GeoSolutions
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

16
README Normal file
View File

@ -0,0 +1,16 @@
REST client library to interact with GeoServer (http://www.geoserver.org)
The purpose of this project is to hold a REST client library to interact with GeoServer; a requirement for this library is to depend as less as possible on external libraries. This library aims at being lean and mean.
For general questions about this project feel free to use the mailing lists.
Mailing Lists
USERS
https://groups.google.com/forum/?fromgroups#!forum/geoserver-manager-users
DEVELOPERS
https://groups.google.com/forum/?fromgroups#!forum/geoserver-manager-devs
For more information see this page:
https://github.com/geosolutions-it/geoserver-manager

View File

@ -1,68 +0,0 @@
# geoserver-manager
## Status
* Master on travis [![Build Status](https://travis-ci.org/geosolutions-it/geoserver-manager.svg?branch=master)](https://travis-ci.org/geosolutions-it/geoserver-manager)
* Master on Linux + OracleJDK7 [![Build Status](http://build.geo-solutions.it/jenkins/view/GeoServer-manager/job/GeoServer-Manager-Master/badge/icon)](http://build.geo-solutions.it/jenkins/view/GeoServer-manager/job/GeoServer-Manager-Master/)
* Master on Windows + OracleJDK7 [![Build Status](http://winbuild.geo-solutions.it/jenkins/buildStatus/icon?job=GeoServer-Manager-Master)](http://winbuild.geo-solutions.it/jenkins/view/GeoServer-Manager/job/GeoServer-Manager-Master/)
* Stable on Linux + OracleJDK7 [![Build Status](http://build.geo-solutions.it/jenkins/view/GeoServer-manager/job/GeoServer-Manager-Stable/badge/icon)](http://build.geo-solutions.it/jenkins/view/GeoServer-manager/job/GeoServer-Manager-Stable/)
* Stable on Windows + OracleJDK7 [![Build Status](http://winbuild.geo-solutions.it/jenkins/buildStatus/icon?job=GeoServer-Manager-Stable)](http://winbuild.geo-solutions.it/jenkins/view/GeoServer-Manager/job/GeoServer-Manager-Stable/)
## Intro
Client library written in Java to interact with [GeoServer](http://www.geoserver.org) through its [ReST administration interface](http://docs.geoserver.org/stable/en/user/rest/api/index.html).
The purpose of this project is to hold a ReST client library to interact with GeoServer; a requirement for this library is to depend as less as possible on external libraries. This library aims at being lean and mean.
For general questions about this project feel free to use the mailing lists.
## Using the library
### Working with Maven
In order to include the lib and its dependencies in a Maven project, the repository to point at is this one:
```xml
<repository>
<id>GeoSolutions</id>
<url>http://maven.geo-solutions.it/</url>
</repository>
```
and the dependency tag for your pom is as follows:
```xml
<dependency>
<groupId>it.geosolutions</groupId>
<artifactId>geoserver-manager</artifactId>
<version>1.7.0</version>
</dependency>
```
### Direct Link to JAR
If you are simply looking for the JAR to download and use you can find it [here](http://maven.geo-solutions.it/it/geosolutions/geoserver-manager/1.7.0/geoserver-manager-1.7.0.jar).
### GeoServer Compatibility Matrix
**GeoServer-Manager/GeoServer** | **2.6.x** |**2.7.x** |**2.8.x** |**2.9.x**
-------------------------------- | ----------|----------|----------|---------
**1.6.0** | Y | Y | P | P
**1.7.0** | N | P | Y | Y
### Documentation
You can find some examples in the wiki.
## License
geoserver-manager is released under a permissive [MIT](https://opensource.org/licenses/MIT) license. See [wikipedia](https://en.wikipedia.org/wiki/MIT_License) for more information.
## Mailing Lists
* [USERS](https://groups.google.com/group/geoserver-manager-users)
* [DEVELOPERS](https://groups.google.com/forum/?fromgroups#!forum/geoserver-manager-devs)
For more information see [this](https://github.com/geosolutions-it/geoserver-manager/wiki) page.
## Version
Current stable version is [1.7.0](https://github.com/geosolutions-it/geoserver-manager/releases/tag/v1.7.0) ([Changelog](https://github.com/geosolutions-it/geoserver-manager/wiki/Changelog)).
## Credits
The work on this library has been initiated by GeoSolutions. Over the years it has been funded by various organizations like UN FAO, German Space Agency (DLR) and others.

144
pom.xml
View File

@ -1,50 +1,38 @@
<!-- <!-- * GeoServer-Manager - Simple Manager Library for GeoServer * * Copyright
* GeoServer-Manager - Simple Manager Library for GeoServer (C) 2007,2011 GeoSolutions S.A.S. * http://www.geo-solutions.it * * Permission
* is hereby granted, free of charge, to any person obtaining a copy * of this
* Copyright (C) 2007 - 2016 GeoSolutions S.A.S. http://www.geo-solutions.it software and associated documentation files (the "Software"), to deal * in
* the Software without restriction, including without limitation the rights
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions: * * The above copyright
* notice and this permission notice shall be included in * all copies or substantial
* The above copyright notice and this permission notice shall be included in portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
* all copies or substantial portions of the Software. OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER DEALINGS IN * THE SOFTWARE. -->
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
-->
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>it.geosolutions</groupId> <groupId>it.geosolutions</groupId>
<artifactId>geoserver-manager</artifactId> <artifactId>geoserver-manager</artifactId>
<version>1.8-SNAPSHOT</version> <version>1.5-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>GeoServer Manager - REST based</name> <name>GeoServer 2 Manager - REST based</name>
<description> <description>
GeoServer Manager is a library to interact with GeoServer GeoServer Manager is a library to interact with GeoServer 2.x.
The scope of this library is to have a simple API, and use as few external The scope of this library is to have a simple API, and use as few external
libs as possible. libs as possible.
</description> </description>
<inceptionYear>2007</inceptionYear> <inceptionYear>2007</inceptionYear>
<url>https://github.com/geosolutions-it/geoserver-manager</url>
<organization> <organization>
<name>GeoSolutions</name> <name>GeoSolutions</name>
<url>http://www.geo-solutions.it</url> <url>http://www.geo-solutions.it</url>
@ -85,9 +73,11 @@
</license> </license>
</licenses> </licenses>
<url>http://code.google.com/p/geoserver-manager/</url>
<issueManagement> <issueManagement>
<system>GitHub</system> <system>googlecode</system>
<url>https://github.com/geosolutions-it/geoserver-manager/issues</url> <url>http://code.google.com/p/geoserver-manager/issues/list</url>
</issueManagement> </issueManagement>
<mailingLists> <mailingLists>
@ -100,61 +90,16 @@
<scm> <scm>
<connection>scm:git:[fetch=]https://github.com/geosolutions-it/geoserver-manager.git[push=]git@github.com:geosolutions-it/geoserver-manager.git</connection> <connection>scm:git:[fetch=]https://github.com/geosolutions-it/geoserver-manager.git[push=]git@github.com:geosolutions-it/geoserver-manager.git</connection>
<!--developerConnection>scm:git</developerConnection -->
<!--tag>master</tag -->
<url>https://github.com/geosolutions-it/geoserver-manager</url> <url>https://github.com/geosolutions-it/geoserver-manager</url>
</scm> </scm>
<ciManagement> <ciManagement>
<system>jenkins</system> <system>jenkins</system>
<url>http://build.geo-solutions.it/jenkins/view/GeoServer-manager/</url> <url>http://ci.geo-solutions.it/</url>
</ciManagement> </ciManagement>
<repositories>
<repository>
<id>boundless</id>
<name>Boundless Maven Repository</name>
<url>https://repo.boundlessgeo.com/main/</url>
<!-- contains snapshot and release (including third-party-dependences) -->
<!-- Restlet maven Repository (http://maven.restlet.org) -->
<!-- ucar (https://artifacts.unidata.ucar.edu/content/repositories/unidata-releases) -->
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
<repository>
<id>osgeo</id>
<name>Open Source Geospatial Foundation Repository</name>
<url>http://download.osgeo.org/webdav/geotools/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>maven-restlet</id>
<name>Restlet Maven Repository</name>
<url>http://maven.restlet.org</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>geosolutions</id>
<name>geosolutions repository</name>
<url>http://maven.geo-solutions.it/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<distributionManagement> <distributionManagement>
<downloadUrl>http://maven.geo-solutions.it</downloadUrl> <downloadUrl>http://maven.geo-solutions.it</downloadUrl>
<repository> <repository>
@ -164,7 +109,7 @@
</repository> </repository>
<site> <site>
<id>demo.geosolutions</id> <id>demo.geosolutions</id>
<url>scp://demo.geo-solutions.it/var/www/share/github/gsman</url> <url>scp://demo.geo-solutions.it/var/www/share/javadoc/gsman</url>
</site> </site>
</distributionManagement> </distributionManagement>
@ -232,7 +177,7 @@
<extension> <extension>
<groupId>org.apache.maven.wagon</groupId> <groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId> <artifactId>wagon-ftp</artifactId>
<version>2.6</version> <version>1.0-beta-7</version>
</extension> </extension>
</extensions> </extensions>
</build> </build>
@ -251,6 +196,8 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId>
<version>2.2</version> </plugin> -->
</plugins> </plugins>
</reporting> </reporting>
@ -284,19 +231,6 @@
<version>1.1</version> <version>1.1</version>
</dependency> </dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.apache.servicemix.bundles</groupId>
<artifactId>org.apache.servicemix.bundles.restlet</artifactId>
<version>1.1.10_3</version>
</dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
@ -310,21 +244,13 @@
<!-- commons-logging can be rather simply and conveniently excluded as <!-- commons-logging can be rather simply and conveniently excluded as
a dependency by declaring it in the provided scope within the pom.xml file a dependency by declaring it in the provided scope within the pom.xml file
of your project. The actual commons-logging classes would be provided by of your project. The actual commons-logging classes would be provided by
jcl-over-slf4j. jcl-over-slf4j. This translates into the following pom file snippet: -->
This translates into the following pom file snippet: --> <!-- <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId>
<!-- <dependency> <version>1.1.1</version> <scope>provided</scope> </dependency> <dependency>
<groupId>commons-logging</groupId> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependency>-->
</dependency>-->
<!--================================================================= --> <!--================================================================= -->
<!-- TEST --> <!-- TEST -->
<!--================================================================= --> <!--================================================================= -->

View File

@ -1,39 +0,0 @@
#!/bin/sh
if [ "$#" -ne 3 ]; then
echo "
Generates git log report between two tags:
USAGE:
$0 {START_TAG} {STOP_TAG|HEAD} {MESSAGE DESCRIPTION}"
exit 1
fi
echo "What's new?
===========
$3
Where can I get it?
===================
* Home:
https://github.com/geosolutions-it/geoserver-manager
* Download:
https://github.com/geosolutions-it/geoserver-manager/releases
* Documentation:
https://github.com/geosolutions-it/geoserver-manager/wiki
Who contributed to this release?
================================
* List authors of this release
"
git log $1..$2 --pretty="format:* %aN" | sort | uniq
echo "
========================
CHANGES IN THIS RELEASE:
========================
"
git log $1..$2 --no-merges --pretty=oneline --reverse --grep fix --grep improve --grep close --grep "#" --grep add --format='* %s' .
exit $?

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007,2016 GeoSolutions S.A.S. * Copyright (C) 2007,2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest; package it.geosolutions.geoserver.rest;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTAbstractManager; import it.geosolutions.geoserver.rest.manager.GeoServerRESTAbstractManager;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTDatastoreManager;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStoreManager; import it.geosolutions.geoserver.rest.manager.GeoServerRESTStoreManager;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStructuredGridCoverageReaderManager;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStyleManager;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
@ -48,12 +47,10 @@ import java.net.URL;
public class GeoServerRESTManager extends GeoServerRESTAbstractManager { public class GeoServerRESTManager extends GeoServerRESTAbstractManager {
private final GeoServerRESTPublisher publisher; private final GeoServerRESTPublisher publisher;
private final GeoServerRESTReader reader; private final GeoServerRESTReader reader;
private final GeoServerRESTStoreManager storeManager; private final GeoServerRESTStoreManager store;
private final GeoServerRESTStyleManager styleManager;
private final GeoServerRESTStructuredGridCoverageReaderManager structuredGridCoverageReader;
/** /**
* Default constructor. * Default constructor.
@ -67,15 +64,13 @@ public class GeoServerRESTManager extends GeoServerRESTAbstractManager {
* @throws IllegalArgumentException {@link GeoServerRESTAbstractManager#GeoServerRESTAbstractManager(URL, String, String)} * @throws IllegalArgumentException {@link GeoServerRESTAbstractManager#GeoServerRESTAbstractManager(URL, String, String)}
*/ */
public GeoServerRESTManager(URL restURL, String username, String password) public GeoServerRESTManager(URL restURL, String username, String password)
throws IllegalArgumentException { throws IllegalArgumentException, MalformedURLException {
super(restURL, username, password); super(restURL, username, password);
// Internal publisher and reader, provide simple access methods. // Internal publisher and reader, provide simple access methods.
publisher = new GeoServerRESTPublisher(restURL.toString(), username, password); publisher = new GeoServerRESTPublisher(restURL.toString(), username, password);
reader = new GeoServerRESTReader(restURL, username, password); reader = new GeoServerRESTReader(restURL, username, password);
structuredGridCoverageReader = new GeoServerRESTStructuredGridCoverageReaderManager(restURL, username, password); store = new GeoServerRESTStoreManager(restURL, gsuser, gspass);
storeManager = new GeoServerRESTStoreManager(restURL, gsuser, gspass);
styleManager = new GeoServerRESTStyleManager(restURL, gsuser, gspass);
} }
public GeoServerRESTPublisher getPublisher() { public GeoServerRESTPublisher getPublisher() {
@ -87,15 +82,15 @@ public class GeoServerRESTManager extends GeoServerRESTAbstractManager {
} }
public GeoServerRESTStoreManager getStoreManager() { public GeoServerRESTStoreManager getStoreManager() {
return storeManager; return store;
} }
public GeoServerRESTStyleManager getStyleManager() { /**
return styleManager; *
} * @Deprecated use {GeoServerRESTManager#getStoreManager()}
*/
public GeoServerRESTStructuredGridCoverageReaderManager getStructuredGridCoverageReader() { public GeoServerRESTDatastoreManager getDatastoreManager() {
return structuredGridCoverageReader; return (GeoServerRESTDatastoreManager) store;
} }
} }

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007,2013 GeoSolutions S.A.S. * Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -41,23 +41,14 @@ import it.geosolutions.geoserver.rest.decoder.RESTLayerList;
import it.geosolutions.geoserver.rest.decoder.RESTNamespace; import it.geosolutions.geoserver.rest.decoder.RESTNamespace;
import it.geosolutions.geoserver.rest.decoder.RESTNamespaceList; import it.geosolutions.geoserver.rest.decoder.RESTNamespaceList;
import it.geosolutions.geoserver.rest.decoder.RESTResource; import it.geosolutions.geoserver.rest.decoder.RESTResource;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageGranulesList;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageIndexSchema;
import it.geosolutions.geoserver.rest.decoder.RESTStyle;
import it.geosolutions.geoserver.rest.decoder.RESTStyleList; import it.geosolutions.geoserver.rest.decoder.RESTStyleList;
import it.geosolutions.geoserver.rest.decoder.RESTWms;
import it.geosolutions.geoserver.rest.decoder.RESTWmsList;
import it.geosolutions.geoserver.rest.decoder.RESTWmsStore;
import it.geosolutions.geoserver.rest.decoder.RESTWmsStoreList;
import it.geosolutions.geoserver.rest.decoder.RESTWorkspaceList; import it.geosolutions.geoserver.rest.decoder.RESTWorkspaceList;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder; import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStructuredGridCoverageReaderManager;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStyleManager;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -77,23 +68,23 @@ import org.slf4j.LoggerFactory;
public class GeoServerRESTReader { public class GeoServerRESTReader {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoServerRESTReader.class); private final static Logger LOGGER = LoggerFactory.getLogger(GeoServerRESTReader.class);
private final String baseurl; private final String baseurl;
private String username; private String username;
private String password; private String password;
private GeoServerRESTStyleManager styleManager;
/** /**
* Creates a <TT>GeoServerRESTReader</TT> for a given GeoServer instance and * Creates a <TT>GeoServerRESTReader</TT> for a given GeoServer instance and
* no auth credentials. * no auth credentials.
* <P><B><I>Note that GeoServer 2.0 REST interface requires username/password credentials by * <P><B><I>Note that GeoServer 2.0 REST interface requires username/password credentials by
* default, if not otherwise configured. </I></B>. * default, if not otherwise configured. </I></B>.
* *
* @param gsUrl the base GeoServer URL(e.g.: <TT>http://localhost:8080/geoserver</TT>) * @param restUrl the base GeoServer URL(e.g.: <TT>http://localhost:8080/geoserver</TT>)
*/ */
public GeoServerRESTReader(URL gsUrl) { public GeoServerRESTReader(URL restUrl) {
baseurl = init(gsUrl, null, null); String extForm = restUrl.toExternalForm();
this.baseurl = extForm.endsWith("/") ?
extForm.substring(0, extForm.length()-1) :
extForm;
} }
/** /**
@ -102,63 +93,65 @@ public class GeoServerRESTReader {
* <P><B><I>Note that GeoServer 2.0 REST interface requires username/password credentials by * <P><B><I>Note that GeoServer 2.0 REST interface requires username/password credentials by
* default, if not otherwise configured. </I></B>. * default, if not otherwise configured. </I></B>.
* *
* @param gsUrl the base GeoServer URL (e.g.: <TT>http://localhost:8080/geoserver</TT>) * @param restUrl the base GeoServer URL (e.g.: <TT>http://localhost:8080/geoserver</TT>)
*/ */
public GeoServerRESTReader(String gsUrl) throws MalformedURLException { public GeoServerRESTReader(String restUrl)
baseurl = init(gsUrl, null, null); throws MalformedURLException {
} new URL(restUrl); // check URL correctness
this.baseurl = restUrl.endsWith("/") ?
/**
* Creates a <TT>GeoServerRESTReader</TT> for a given GeoServer instance
* with the given auth credentials.
*
* @param gsUrl the base GeoServer URL (e.g.: <TT>http://localhost:8080/geoserver</TT>)
* @param username username auth credential
* @param password password auth credential
*/
public GeoServerRESTReader(String gsUrl, String username, String password) throws MalformedURLException {
baseurl = init(gsUrl, username, password);
}
/**
* Creates a <TT>GeoServerRESTReader</TT> for a given GeoServer instance
* with the given auth credentials.
*
* @param gsUrl the base GeoServer URL (e.g.: <TT>http://localhost:8080/geoserver</TT>)
* @param username username auth credential
* @param password password auth credential
*/
public GeoServerRESTReader(URL gsUrl, String username, String password) {
baseurl = init(gsUrl, username, password);
}
private String init(String gsUrl, String username, String password) throws MalformedURLException {
return init(new URL(gsUrl), username, password);
}
private String init(URL gsUrl, String username, String password) {
String restUrl = gsUrl.toExternalForm();
String cleanUrl = restUrl.endsWith("/") ?
restUrl.substring(0, restUrl.length()-1) : restUrl.substring(0, restUrl.length()-1) :
restUrl; restUrl;
}
/**
* Creates a <TT>GeoServerRESTReader</TT> for a given GeoServer instance
* with the given auth credentials.
*
* @param restUrl the base GeoServer URL (e.g.: <TT>http://localhost:8080/geoserver</TT>)
* @param username username auth credential
* @param password password auth credential
*/
public GeoServerRESTReader(String restUrl, String username, String password) throws MalformedURLException {
this(restUrl);
this.username = username; this.username = username;
this.password = password; this.password = password;
}
styleManager = new GeoServerRESTStyleManager(gsUrl, username, password); /**
* Creates a <TT>GeoServerRESTReader</TT> for a given GeoServer instance
return cleanUrl; * with the given auth credentials.
*
* @param restUrl the base GeoServer URL (e.g.: <TT>http://localhost:8080/geoserver</TT>)
* @param username username auth credential
* @param password password auth credential
*/
public GeoServerRESTReader(URL restUrl, String username, String password) {
this(restUrl);
this.username = username;
this.password = password;
} }
private String load(String url) { private String load(String url) {
LOGGER.info("Loading from REST path " + url); LOGGER.info("Loading from REST path " + url);
try {
String response = HTTPUtils.get(baseurl + url, username, password); String response = HTTPUtils.get(baseurl + url, username, password);
return response; return response;
} catch (MalformedURLException ex) {
LOGGER.warn("Bad URL", ex);
}
return null;
} }
private String loadFullURL(String url) { private String loadFullURL(String url) {
LOGGER.info("Loading from REST path " + url); LOGGER.info("Loading from REST path " + url);
try {
String response = HTTPUtils.get(url, username, password); String response = HTTPUtils.get(url, username, password);
return response; return response;
} catch (MalformedURLException ex) {
LOGGER.warn("Bad URL", ex);
}
return null;
} }
/** /**
@ -203,42 +196,8 @@ public class GeoServerRESTReader {
* @throws RuntimeException if any other HTTP code than 200 or 404 was retrieved. * @throws RuntimeException if any other HTTP code than 200 or 404 was retrieved.
*/ */
public boolean existsStyle(String styleName) throws RuntimeException { public boolean existsStyle(String styleName) throws RuntimeException {
return styleManager.existsStyle(styleName); String url = baseurl + "/rest/styles/" + styleName + ".xml";
} return HTTPUtils.exists(url, username, password);
/**
* Check if a Style exists in the configured GeoServer instance.
* @param styleName the name of the style to check for.
* @param quietOnNotFound if true, mute exception if false is returned
* @return <TT>true</TT> on HTTP 200, <TT>false</TT> on HTTP 404
* @throws RuntimeException if any other HTTP code than 200 or 404 was retrieved.
*/
public boolean existsStyle(String styleName, boolean quietOnNotFound) throws RuntimeException {
return styleManager.existsStyle(styleName, quietOnNotFound);
}
/**
* @see GeoServerRESTStyleManager#existsStyle(java.lang.String, java.lang.String)
* @since GeoServer 2.2
*/
public boolean existsStyle(String workspace, String styleName) throws RuntimeException {
return styleManager.existsStyle(workspace, styleName);
}
/**
* @see GeoServerRESTStyleManager#getStyle(java.lang.String)
* @since GeoServer 2.2
*/
public RESTStyle getStyle(String name) {
return styleManager.getStyle(name);
}
/**
* @see GeoServerRESTStyleManager#getStyle(java.lang.String, java.lang.String)
* @since GeoServer 2.2
*/
public RESTStyle getStyle(String workspace, String name) {
return styleManager.getStyle(workspace, name);
} }
/** /**
@ -247,30 +206,22 @@ public class GeoServerRESTReader {
* @return summary info about Styles as a {@link RESTStyleList} * @return summary info about Styles as a {@link RESTStyleList}
*/ */
public RESTStyleList getStyles() { public RESTStyleList getStyles() {
return styleManager.getStyles(); String url = "/rest/styles.xml";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving Styles list from " + url);
} }
return RESTStyleList.build(load(url));
/**
* @see GeoServerRESTStyleManager#getStyles(java.lang.String)
* @since GeoServer 2.2
*/
public RESTStyleList getStyles(String workspace) {
return styleManager.getStyles(workspace);
} }
/** /**
* Get the SLD body of a Style. * Get the SLD body of a Style.
*/ */
public String getSLD(String styleName) { public String getSLD(String styleName) {
return styleManager.getSLD(styleName); String url = "/rest/styles/"+styleName+".sld";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving SLD body from " + url);
} }
return load(url);
/**
* @see GeoServerRESTStyleManager#getSLD(java.lang.String, java.lang.String)
* @since GeoServer 2.2
*/
public String getSLD(String workspace, String styleName) {
return styleManager.getSLD(workspace, styleName);
} }
//========================================================================== //==========================================================================
@ -325,31 +276,6 @@ public class GeoServerRESTReader {
return RESTDataStore.build(response); return RESTDataStore.build(response);
} }
/**
* Checks if the selected DataStore is present
*
* @param workspace workspace of the datastore
* @param dsName name of the datastore
* @return boolean indicating if the datastore exists
*/
public boolean existsDatastore(String workspace, String dsName){
return existsDatastore(workspace, dsName, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
/**
* Checks if the selected DataStore is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the datastore
* @param dsName name of the datastore
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the datastore exists
*/
public boolean existsDatastore(String workspace, String dsName, boolean quietOnNotFound){
String url = baseurl + "/rest/workspaces/" + workspace + "/datastores/" + dsName + ".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
//========================================================================== //==========================================================================
//=== FEATURETYPES //=== FEATURETYPES
//========================================================================== //==========================================================================
@ -369,33 +295,6 @@ public class GeoServerRESTReader {
return RESTFeatureType.build(response); return RESTFeatureType.build(response);
} }
/**
* Checks if the selected FeatureType is present.
*
* @param workspace workspace of the datastore
* @param dsName name of the datastore
* @param ftName name of the featuretype
* @return boolean indicating if the featuretype exists
*/
public boolean existsFeatureType(String workspace, String dsName, String ftName){
return existsFeatureType(workspace, dsName, ftName, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
/**
* Checks if the selected FeatureType is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the datastore
* @param dsName name of the datastore
* @param ftName name of the featuretype
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the featuretype exists
*/
public boolean existsFeatureType(String workspace, String dsName, String ftName, boolean quietOnNotFound){
String url = baseurl + "/rest/workspaces/" + workspace + "/datastores/" + dsName + "/featuretypes/" + ftName +".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
//========================================================================== //==========================================================================
//=== COVERAGESTORES //=== COVERAGESTORES
//========================================================================== //==========================================================================
@ -446,31 +345,6 @@ public class GeoServerRESTReader {
return RESTCoverageStore.build(response); return RESTCoverageStore.build(response);
} }
/**
* Checks if the selected Coverage store is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the coveragestore
* @param dsName name of the coveragestore
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the coveragestore exists
*/
public boolean existsCoveragestore(String workspace, String csName, boolean quietOnNotFound){
String url = baseurl + "/rest/workspaces/" + workspace + "/coveragestores/" + csName + ".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected Coverage store is present.
*
* @param workspace workspace of the coveragestore
* @param dsName name of the coveragestore
* @return boolean indicating if the coveragestore exists
*/
public boolean existsCoveragestore(String workspace, String csName){
return existsCoveragestore(workspace, csName, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
//========================================================================== //==========================================================================
//=== COVERAGES //=== COVERAGES
//========================================================================== //==========================================================================
@ -507,33 +381,6 @@ public class GeoServerRESTReader {
return RESTCoverage.build(load(url)); return RESTCoverage.build(load(url));
} }
/**
* Checks if the selected Coverage is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the coveragestore
* @param dsName name of the coveragestore
* @param name name of the coverage
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the coverage exists
*/
public boolean existsCoverage(String workspace, String store, String name, boolean quietOnNotFound){
String url = baseurl + "/rest/workspaces/" + workspace + "/coveragestores/" + store + "/coverages/"+name+".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected Coverage is present.
*
* @param workspace workspace of the coveragestore
* @param store name of the coveragestore
* @param name name of the coverage
* @return boolean indicating if the coverage exists
*/
public boolean existsCoverage(String workspace, String store, String name){
return existsCoverage(workspace, store, name, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
/** /**
* Get detailed info about a Coverage given the Layer where it's published with. * Get detailed info about a Coverage given the Layer where it's published with.
* *
@ -548,153 +395,6 @@ public class GeoServerRESTReader {
return RESTCoverage.build(response); return RESTCoverage.build(response);
} }
//==========================================================================
//=== WMSSTORES
//==========================================================================
/**
* Get summary info about all WmsStore in a WorkSpace.
*
* @param workspace The name of the workspace
*
* @return summary info about CoverageStores as a {@link RESTWmsStoreList}
*/
public RESTWmsStoreList getWmsStores(String workspace) {
String url = "/rest/workspaces/" + workspace + "/wmsstores.xml";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving CS list from " + url);
}
return RESTWmsStoreList.build(load(url));
}
/**
* Get detailed info about a given WmsStore in a given Workspace.
*
* @param workspace The name of the workspace
* @param wsName The name of the WmsStore
* @return WmsStore details as a {@link RESTWmsStore}
*/
public RESTWmsStore getWmsStore(String workspace, String wsName) {
String url = "/rest/workspaces/" + workspace + "/wmsstores/" + wsName + ".xml";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving CS from " + url);
}
return RESTWmsStore.build(load(url));
}
/**
* Get detailed info about a Wms's Datastore.
*
* @param wms the RESTWms
* @return wmsStore details as a {@link RESTWmsStore}
*/
public RESTWmsStore getWmsStore(RESTWms wms) {
String url = wms.getStoreUrl();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving CS from fullurl " + url);
}
String response = loadFullURL(url);
return RESTWmsStore.build(response);
}
/**
* Checks if the selected Wms store is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the wmsstore
* @param wsName name of the wmsstore
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the wmsstore exists
*/
public boolean existsWmsstore(String workspace, String wsName, boolean quietOnNotFound){
String url = baseurl + "/rest/workspaces/" + workspace + "/wmsstores/" + wsName + ".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected wms store is present.
*
* @param workspace workspace of the wmsstore
* @param wsName name of the wmsstore
* @return boolean indicating if the wmsstore exists
*/
public boolean existsWmsstore(String workspace, String wsName){
return existsCoveragestore(workspace, wsName, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
//==========================================================================
//=== WMSS
//==========================================================================
/**
* Get list of wmss (usually only one).
*
* @param workspace The name of the workspace
* @param wsName The name of the WmsStore
* @return wms list as a {@link RESTWmsList}
*/
public RESTWmsList getWms(String workspace, String wsName) {
String url = "/rest/workspaces/" + workspace + "/wmsstores/" + wsName + "/wmslayers.xml";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving Wmss from " + url);
}
return RESTWmsList.build(load(url));
}
/**
* Get detailed info about a given Wms.
*
* @param workspace The name of the workspace
* @param store The name of the WmsStore
* @param name The name of the Wms
* @return wms details as a {@link RESTwms}
*/
public RESTWms getWms(String workspace, String store, String name) {
String url = "/rest/workspaces/" + workspace + "/wmsstores/" + store + "/wmslayers/"+name+".xml";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving Wmss from " + url);
}
return RESTWms.build(load(url));
}
/**
* Checks if the selected Wms is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the wmsstore
* @param wsName name of the wmsstore
* @param name name of the wms
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the coverage exists
*/
public boolean existsWms(String workspace, String store, String name, boolean quietOnNotFound){
String url = baseurl + "/rest/workspaces/" + workspace + "/wmsstores/" + store + "/wmslayers/"+name+".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected wms is present.
*
* @param workspace workspace of the wmsstore
* @param store name of the wmsstore
* @param name name of the wms
* @return boolean indicating if the coverage exists
*/
public boolean existsWms(String workspace, String store, String name){
return existsWms(workspace, store, name, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
/**
* Get detailed info about a Wms given the Layer where it's published with.
*
* @param layer A layer publishing the wmsStore
* @return Wms details as a {@link RESTWms}
*/
public RESTWms getWms(RESTLayer layer) {
String response = loadFullURL(layer.getResourceUrl());
return RESTWms.build(response);
}
//========================================================================== //==========================================================================
//========================================================================== //==========================================================================
@ -773,35 +473,7 @@ public class GeoServerRESTReader {
return getLayerGroup(null, name); return getLayerGroup(null, name);
} }
/**
* Checks if the selected LayerGroup is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the LayerGroup
* @param name name of the LayerGroup
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the LayerGroup exists
*/
public boolean existsLayerGroup(String workspace, String name, boolean quietOnNotFound){
String url;
if (workspace == null) {
url = baseurl + "/rest/layergroups/" + name + ".xml";
} else {
url = baseurl + "/rest/workspaces/" + workspace + "/layergroups/" + name + ".xml";
}
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected LayerGroup is present.
*
* @param workspace workspace of the LayerGroup
* @param name name of the LayerGroup
* @return boolean indicating if the LayerGroup exists
*/
public boolean existsLayerGroup(String workspace, String name){
return existsLayerGroup(workspace, name, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
//========================================================================== //==========================================================================
//=== LAYERS //=== LAYERS
@ -876,36 +548,6 @@ public class GeoServerRESTReader {
return layer; return layer;
} }
/**
* Checks if the selected Layer is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the Layer
* @param name name of the Layer
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the Layer exists
*/
public boolean existsLayer(String workspace, String name, boolean quietOnNotFound){
String url;
if (workspace == null) {
url = baseurl + "/rest/layers/" + name + ".xml";
} else {
url = baseurl + "/rest/layers/" + workspace + ":" + name + ".xml";
}
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected Layer is present.
*
* @param workspace workspace of the Layer
* @param name name of the Layer
* @return boolean indicating if the Layer exists
*/
public boolean existsLayer(String workspace, String name){
return existsLayerGroup(workspace, name, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
//========================================================================== //==========================================================================
//=== NAMESPACES //=== NAMESPACES
//========================================================================== //==========================================================================
@ -957,32 +599,6 @@ public class GeoServerRESTReader {
return names; return names;
} }
/**
* Checks if the selected Namespace is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param prefix namespace prefix.
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the Namespace exists
*/
public boolean existsNamespace(String prefix, boolean quietOnNotFound) {
if (prefix == null || prefix.isEmpty()) {
throw new IllegalArgumentException("Namespace prefix cannot be null or empty");
}
String url = baseurl + "/rest/namespaces/" + prefix + ".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected Namespace is present.
*
* @param prefix namespace prefix.
* @return boolean indicating if the Namespace exists
*/
public boolean existsNamespace(String prefix){
return existsNamespace(prefix, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
//========================================================================== //==========================================================================
//=== WORKSPACES //=== WORKSPACES
//========================================================================== //==========================================================================
@ -1019,161 +635,4 @@ public class GeoServerRESTReader {
return names; return names;
} }
/**
* Checks if the selected Workspace is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param prefix Workspace prefix.
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the Workspace exists
*/
public boolean existsWorkspace(String prefix, boolean quietOnNotFound) {
if (prefix == null || prefix.isEmpty()) {
throw new IllegalArgumentException("Workspace prefix cannot be null or empty");
}
String url = baseurl + "/rest/workspaces/" + prefix + ".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected Workspace is present.
*
* @param prefix Workspace prefix.
* @return boolean indicating if the Workspace exists
*/
public boolean existsWorkspace(String prefix){
return existsWorkspace(prefix, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
//==========================================================================
//=== Structured Coverages
//==========================================================================
/**
* Get information about a granule for a structured coverage.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param format the format of the file to upload
* @param the absolute path to the file to upload
* @param id the ID of the granule to get information for
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*/
public RESTStructuredCoverageGranulesList getGranuleById(final String workspace,
String coverageStore, String coverage, String id) throws MalformedURLException,
UnsupportedEncodingException {
try {
GeoServerRESTStructuredGridCoverageReaderManager manager =
new GeoServerRESTStructuredGridCoverageReaderManager(new URL(baseurl), username, password);
return manager.getGranuleById(workspace, coverageStore, coverage, id);
} catch (IllegalArgumentException e) {
if(LOGGER.isInfoEnabled()){
LOGGER.info(e.getLocalizedMessage(),e);
}
} catch (MalformedURLException e) {
if(LOGGER.isInfoEnabled()){
LOGGER.info(e.getLocalizedMessage(),e);
}
}
return null;
}
/**
* Checks if the selected Granule is present. Parameter quietOnNotFound can be used for controlling the logging when 404 is returned.
*
* @param workspace workspace of the coveragestore
* @param coverageStore name of the coveragestore
* @param coverage name of the coverage
* @param id id of the granule
* @param quietOnNotFound if true, no exception is logged
* @return boolean indicating if the Granule exists
*/
public boolean existsGranule(String workspace, String coverageStore, String coverage,
String id, boolean quietOnNotFound) {
String url = baseurl + "/rest/workspaces/" + workspace + "/coveragestores/" + coverageStore
+ "/coverages/" + coverage + "/index/granules/" + id + ".xml";
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed, username, password);
}
/**
* Checks if the selected Granule is present.
*
* @param workspace workspace of the coveragestore
* @param coverageStore name of the coveragestore
* @param coverage name of the coverage
* @param id id of the granule
* @return boolean indicating if the Granule exists
*/
public boolean existsGranule(String workspace, String coverageStore, String coverage, String id) {
return existsGranule(workspace, coverageStore, coverage, id,
Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
/**
* Get information about the schema of the index for a structured coverage.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param format the format of the file to upload
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*/
public RESTStructuredCoverageIndexSchema getGranuleIndexSchema(final String workspace, String coverageStore, String coverage) throws MalformedURLException {
try {
GeoServerRESTStructuredGridCoverageReaderManager manager =
new GeoServerRESTStructuredGridCoverageReaderManager(new URL(baseurl), username, password);
return manager.getGranuleIndexSchema(workspace, coverageStore, coverage);
} catch (IllegalArgumentException e) {
if(LOGGER.isInfoEnabled()){
LOGGER.info(e.getLocalizedMessage(),e);
}
} catch (MalformedURLException e) {
if(LOGGER.isInfoEnabled()){
LOGGER.info(e.getLocalizedMessage(),e);
}
}
return null;
}
/**
* Get information about the granules for a coverage with optional filter and paging.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param coverage the name of the target coverage
* @param filter the format of the file to upload, can be <code>null</code> to include all the granules
* @param offset the start page, can be <code>null</code> or an integer
* @param limit the dimension of the page, can be <code>null</code> or a positive integer
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*/
public RESTStructuredCoverageGranulesList getGranules(final String workspace, String coverageStore, String coverage, String filter, Integer offset, Integer limit)
throws MalformedURLException, UnsupportedEncodingException {
try {
GeoServerRESTStructuredGridCoverageReaderManager manager =
new GeoServerRESTStructuredGridCoverageReaderManager(new URL(baseurl), username, password);
return manager.getGranules(workspace, coverageStore, coverage, filter, offset, limit);
} catch (IllegalArgumentException e) {
if(LOGGER.isInfoEnabled()){
LOGGER.info(e.getLocalizedMessage(),e);
}
} catch (MalformedURLException e) {
if(LOGGER.isInfoEnabled()){
LOGGER.info(e.getLocalizedMessage(),e);
}
}
return null;
}
} }

View File

@ -25,7 +25,6 @@
package it.geosolutions.geoserver.rest; package it.geosolutions.geoserver.rest;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -34,11 +33,6 @@ import java.net.ConnectException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpClient;
@ -54,9 +48,6 @@ import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -90,7 +81,7 @@ public class HTTPUtils {
* (OK). * (OK).
* @throws MalformedURLException * @throws MalformedURLException
*/ */
public static String get(String url, String username, String pw) { public static String get(String url, String username, String pw) throws MalformedURLException {
GetMethod httpMethod = null; GetMethod httpMethod = null;
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
@ -126,22 +117,6 @@ public class HTTPUtils {
return null; return null;
} }
/**
* Executes a request using the GET method and parses the result as a json object.
*
* @param path The path to request.
*
* @return The result parsed as json.
*/
public static JSON getAsJSON(String url, String username, String pw) throws Exception {
String response = get(url, username, pw);
return json(response);
}
public static JSON json(String content) {
return JSONSerializer.toJSON(content);
}
/** /**
* PUTs a File to the given URL. <BR> * PUTs a File to the given URL. <BR>
* Basic auth is used if both username and pw are not null. * Basic auth is used if both username and pw are not null.
@ -200,23 +175,6 @@ public class HTTPUtils {
return put(url, content, "text/xml", username, pw); return put(url, content, "text/xml", username, pw);
} }
/**
* PUTs a String representing an JSON Object to the given URL. <BR>
* Basic auth is used if both username and pw are not null.
*
* @param url The URL where to connect to.
* @param content The JSON Object to be sent as a String.
* @param username Basic auth credential. No basic auth if null.
* @param pw Basic auth credential. No basic auth if null.
* @return The HTTP response as a String if the HTTP response code was 200
* (OK).
* @throws MalformedURLException
* @return the HTTP response or <TT>null</TT> on errors.
*/
public static String putJson(String url, String content, String username, String pw) {
return put(url, content, "application/json", username, pw);
}
/** /**
* Performs a PUT to the given URL. <BR> * Performs a PUT to the given URL. <BR>
* Basic auth is used if both username and pw are not null. * Basic auth is used if both username and pw are not null.
@ -275,38 +233,6 @@ public class HTTPUtils {
} }
} }
/**
* POSTs a list of files as attachments to the given URL. <BR>
* Basic auth is used if both username and pw are not null.
*
* @param url The URL where to connect to.
* @param dir The folder containing the attachments.
* @param username Basic auth credential. No basic auth if null.
* @param pw Basic auth credential. No basic auth if null.
* @return The HTTP response as a String if the HTTP response code was 200
* (OK).
* @throws MalformedURLException
* @return the HTTP response or <TT>null</TT> on errors.
*/
public static String postMultipartForm(String url, File dir, String username, String pw) {
try {
List<Part> parts = new ArrayList<Part>();
for (File f : dir.listFiles()) {
parts.add(new FilePart(f.getName(), f));
}
MultipartRequestEntity multipart = new MultipartRequestEntity(
parts.toArray(new Part[parts.size()]), new PostMethod().getParams());
ByteArrayOutputStream bout = new ByteArrayOutputStream();
multipart.writeRequest(bout);
return post(url, multipart, username, pw);
} catch (Exception ex) {
LOGGER.error("Cannot POST " + url, ex);
return null;
}
}
/** /**
* POSTs a String representing an XML document to the given URL. <BR> * POSTs a String representing an XML document to the given URL. <BR>
* Basic auth is used if both username and pw are not null. * Basic auth is used if both username and pw are not null.
@ -324,23 +250,6 @@ public class HTTPUtils {
return post(url, content, "text/xml", username, pw); return post(url, content, "text/xml", username, pw);
} }
/**
* POSTs a String representing an JSON Object to the given URL. <BR>
* Basic auth is used if both username and pw are not null.
*
* @param url The URL where to connect to.
* @param content The JSON content to be sent as a String.
* @param username Basic auth credential. No basic auth if null.
* @param pw Basic auth credential. No basic auth if null.
* @return The HTTP response as a String if the HTTP response code was 200
* (OK).
* @throws MalformedURLException
* @return the HTTP response or <TT>null</TT> on errors.
*/
public static String postJson(String url, String content, String username, String pw) {
return post(url, content, "application/json", username, pw);
}
/** /**
* Performs a POST to the given URL. <BR> * Performs a POST to the given URL. <BR>
* Basic auth is used if both username and pw are not null. * Basic auth is used if both username and pw are not null.
@ -384,7 +293,6 @@ public class HTTPUtils {
httpMethod.setRequestEntity(requestEntity); httpMethod.setRequestEntity(requestEntity);
int status = client.executeMethod(httpMethod); int status = client.executeMethod(httpMethod);
InputStream responseBody;
switch (status) { switch (status) {
case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_CREATED:
@ -395,10 +303,9 @@ public class HTTPUtils {
LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response); LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response);
return response; return response;
default: default:
responseBody = httpMethod.getResponseBodyAsStream();
LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]" LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]"
+ " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName()
+ "]: " + (responseBody != null ? IOUtils.toString(responseBody) : "")); + "]: " + IOUtils.toString(httpMethod.getResponseBodyAsStream()));
return null; return null;
} }
} catch (ConnectException e) { } catch (ConnectException e) {
@ -429,9 +336,10 @@ public class HTTPUtils {
InputStream is = httpMethod.getResponseBodyAsStream(); InputStream is = httpMethod.getResponseBodyAsStream();
response = IOUtils.toString(is); response = IOUtils.toString(is);
IOUtils.closeQuietly(is); IOUtils.closeQuietly(is);
if (response.trim().equals("")) { if (response.trim().equals("")) { // sometimes gs rest fails
if (LOGGER.isTraceEnabled()) if (LOGGER.isDebugEnabled())
LOGGER.trace("ResponseBody is empty (this may be not an error since we just performed a DELETE call)"); LOGGER
.debug("ResponseBody is empty (this may be not an error since we just performed a DELETE call)");
return true; return true;
} }
if (LOGGER.isDebugEnabled()) if (LOGGER.isDebugEnabled())
@ -559,14 +467,14 @@ public class HTTPUtils {
/** /**
* @param str a string array * @param str a string array
* @return create a StringBuilder appending all the passed arguments * @return create a StringBuffer appending all the passed arguments
*/ */
public static StringBuilder append(String ... str){ public static StringBuffer append(String ... str){
if (str==null){ if (str==null){
return null; return null;
} }
StringBuilder buf=new StringBuilder(); StringBuffer buf=new StringBuffer();
for (String s: str){ for (String s: str){
if (s!=null) if (s!=null)
buf.append(s); buf.append(s);
@ -580,12 +488,12 @@ public class HTTPUtils {
* @param str strings to append * @param str strings to append
* @return the base URL with parameters attached * @return the base URL with parameters attached
*/ */
public static StringBuilder append(URL base, String ... str){ public static StringBuffer append(URL base, String ... str){
if (str==null){ if (str==null){
return append(base.toString()); return append(base.toString());
} }
StringBuilder buf=new StringBuilder(base.toString()); StringBuffer buf=new StringBuffer(base.toString());
for (String s: str){ for (String s: str){
if (s!=null) if (s!=null)
buf.append(s); buf.append(s);

View File

@ -1,121 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007 - 2016 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest;
import it.geosolutions.geoserver.rest.decoder.RESTStyle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
*
* @author ETj (etj at geo-solutions.it)
*/
public class Util {
public static final String QUIET_ON_NOT_FOUND_PARAM = "quietOnNotFound=";
public static final boolean DEFAULT_QUIET_ON_NOT_FOUND = true;
/**
* Search for a stylename in global and in all workspaces.
*/
public static List<RESTStyle> searchStyles(GeoServerRESTReader reader, String stylename) {
List<RESTStyle> styles = new ArrayList<RESTStyle>();
RESTStyle style = reader.getStyle(stylename);
// We don't want geoserver to be lenient here: take only the real global style if it exists
if(style != null) {
if(style.getWorkspace() == null || style.getWorkspace().isEmpty()) {
styles.add(style);
}
}
for (String workspace : reader.getWorkspaceNames()) {
style = reader.getStyle(workspace, stylename);
if(style != null)
styles.add(style);
}
return styles;
}
/**
* Append the quietOnNotFound parameter to the input URL
* @param quietOnNotFound parameter
* @param url input url
* @return a composed url with the parameter appended
*/
public static String appendQuietOnNotFound(boolean quietOnNotFound, String url) {
boolean contains = url.contains("?");
String composed = url + (contains ? "&":"?") + QUIET_ON_NOT_FOUND_PARAM + quietOnNotFound;
return composed;
}
public static <T> List<T> safeList(List<T> list) {
return list == null ? Collections.EMPTY_LIST : list;
}
public static <T> Collection<T> safeCollection(Collection<T> collection) {
return collection == null ? Collections.EMPTY_SET : collection;
}
public static <TK, TV> Map<TK, TV> safeMap(Map<TK, TV> map) {
return map == null ? Collections.EMPTY_MAP : map;
}
public static char getParameterSeparator(String url) {
char parameterSeparator = '?';
if (url.contains("?")) {
parameterSeparator = '&';
}
return parameterSeparator;
}
public static char getParameterSeparator(StringBuilder url) {
char parameterSeparator = '?';
if (url.indexOf("?") != -1) {
parameterSeparator = '&';
}
return parameterSeparator;
}
public static boolean appendParameter(StringBuilder url, String parameterName,
String parameterValue) {
boolean result = false;
if (parameterName != null && !parameterName.isEmpty()
&& parameterValue != null && !parameterValue.isEmpty()) {
char parameterSeparator = getParameterSeparator(url);
url.append(parameterSeparator).append(parameterName.trim())
.append('=').append(parameterValue.trim());
}
return result;
}
}

View File

@ -26,8 +26,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMListIterator; import it.geosolutions.geoserver.rest.decoder.utils.JDOMListIterator;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;

View File

@ -1,48 +0,0 @@
package it.geosolutions.geoserver.rest.decoder;
import org.jdom.Element;
/**
* Parse a Boundingbox of the following structure
*
* <minx>472800.0</minx>
* <maxx>817362.0</maxx>
* <miny>35053.40625</miny>
* <maxy>301500.0</maxy>
* <crs class="projected">EPSG:21781</crs>
*
* @author nmandery
*/
public class RESTBoundingBox {
protected Element bboxElem;
public RESTBoundingBox(Element bboxElem) {
this.bboxElem = bboxElem;
}
public String getCRS() {
return this.bboxElem.getChildText("crs");
}
protected double getEdge(String edge) {
return Double.parseDouble(this.bboxElem.getChildText(edge));
}
public double getMinX() {
return this.getEdge("minx");
}
public double getMaxX() {
return this.getEdge("maxx");
}
public double getMinY() {
return this.getEdge("miny");
}
public double getMaxY() {
return this.getEdge("maxy");
}
}

View File

@ -25,12 +25,9 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.encoder.feature.FeatureTypeAttribute;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import org.jdom.Element; import org.jdom.Element;
@ -171,9 +168,9 @@ public class RESTCoverage extends RESTResource {
// return rootElem.getChildText("name"); // return rootElem.getChildText("name");
// } // }
public String getNativeCoverageName() { // public String getNativeName() {
return rootElem.getChildText("nativeCoverageName"); // return rootElem.getChildText("nativeName");
} // }
public String getNativeFormat() { public String getNativeFormat() {
return rootElem.getChildText("nativeFormat"); return rootElem.getChildText("nativeFormat");
@ -209,141 +206,6 @@ public class RESTCoverage extends RESTResource {
return listDim; return listDim;
} }
/**
* Retrieves the list of parameters for this coverage.
*
* @return a {@link Map} where the key is the name for the parameter and the value is the value for the parameter.
*/
@SuppressWarnings("unchecked")
public Map<String, String> getParametersList() {
Map<String, String> paramsList = new HashMap<String, String>();
final Element paramsRoot = rootElem.getChild("parameters");
if (paramsRoot != null) {
final List<Element> params = paramsRoot.getChildren();
if (params != null) {
for (Element param : params) {
final List<Element> values = param.getChildren();
assert values.size()==2;
paramsList.put(values.get(0).getValue(), values.get(1).getValue()); // save key and value
}
}
}
return paramsList;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RESTCoverage [");
if (getNativeFormat() != null) {
builder.append("getNativeFormat()=");
builder.append(getNativeFormat());
builder.append(", ");
}
if (getNativeCRS() != null) {
builder.append("getNativeCRS()=");
builder.append(getNativeCRS());
builder.append(", ");
}
if (getSRS() != null) {
builder.append("getSRS()=");
builder.append(getSRS());
builder.append(", ");
}
if (getMetadataList() != null) {
builder.append("getMetadataList()=");
builder.append(getMetadataList());
builder.append(", ");
}
if (getDimensionInfo() != null) {
builder.append("getDimensionInfo()=");
builder.append(getDimensionInfo());
builder.append(", ");
}
if (getParametersList() != null) {
builder.append("getParametersList()=");
builder.append(getParametersList());
builder.append(", ");
}
if (getName() != null) {
builder.append("getName()=");
builder.append(getName());
builder.append(", ");
}
if (getTitle() != null) {
builder.append("getTitle()=");
builder.append(getTitle());
builder.append(", ");
}
if (getNativeName() != null) {
builder.append("getNativeName()=");
builder.append(getNativeName());
builder.append(", ");
}
if (getNativeCoverageName() != null) {
builder.append("getNativeCoverageName()=");
builder.append(getNativeCoverageName());
builder.append(", ");
}
if (getAbstract() != null) {
builder.append("getAbstract()=");
builder.append(getAbstract());
builder.append(", ");
}
if (getNameSpace() != null) {
builder.append("getNameSpace()=");
builder.append(getNameSpace());
builder.append(", ");
}
if (getStoreName() != null) {
builder.append("getStoreName()=");
builder.append(getStoreName());
builder.append(", ");
}
if (getStoreType() != null) {
builder.append("getStoreType()=");
builder.append(getStoreType());
builder.append(", ");
}
if (getStoreUrl() != null) {
builder.append("getStoreUrl()=");
builder.append(getStoreUrl());
builder.append(", ");
}
if (getCRS() != null) {
builder.append("getCRS()=");
builder.append(getCRS());
builder.append(", ");
}
builder.append("getMinX()=");
builder.append(getMinX());
builder.append(", getMaxX()=");
builder.append(getMaxX());
builder.append(", getMinY()=");
builder.append(getMinY());
builder.append(", getMaxY()=");
builder.append(getMaxY());
builder.append(", ");
if (getAttributeList() != null) {
builder.append("getAttributeList()=");
builder.append(getAttributeList());
builder.append(", ");
}
if (getEncodedAttributeList() != null) {
builder.append("getEncodedAttributeList()=");
builder.append(getEncodedAttributeList());
builder.append(", ");
}
if (getEncodedMetadataLinkInfoList() != null) {
builder.append("getEncodedMetadataLinkInfoList()=");
builder.append(getEncodedMetadataLinkInfoList());
}
builder.append("]");
return builder.toString();
}
// public String getStoreName() { // public String getStoreName() {
// return rootElem.getChild("store").getChildText("name"); // return rootElem.getChild("store").getChildText("name");
// } // }

View File

@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -26,7 +26,6 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**
@ -87,14 +86,6 @@ public class RESTCoverageStore {
return cs.getChild("workspace").getChildText("name"); return cs.getChild("workspace").getChildText("name");
} }
public String getURL() {
return cs.getChildText("url");
}
public String getType() {
return cs.getChildText("type");
}
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(getClass().getSimpleName()) StringBuilder sb = new StringBuilder(getClass().getSimpleName())
.append('['); .append('[');

View File

@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007,2014 GeoSolutions S.A.S. * Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -71,7 +71,6 @@ public class RESTDataStore {
public enum DBType { public enum DBType {
POSTGIS("postgis"), POSTGIS("postgis"),
ORACLE("oracle"),
SHP("shp"), SHP("shp"),
UNKNOWN(null); UNKNOWN(null);
private final String restName; private final String restName;

View File

@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -35,7 +35,6 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -33,8 +33,6 @@ import it.geosolutions.geoserver.rest.encoder.authorityurl.AuthorityURLInfo;
import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEncoder; import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder; import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.identifier.IdentifierInfo; import it.geosolutions.geoserver.rest.encoder.identifier.IdentifierInfo;
import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.ResourceMetadataLinkInfo;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
@ -53,12 +51,6 @@ import org.jdom.Namespace;
<name>capitals</name> <name>capitals</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://localhost:8080/geoserver/rest/styles/capitals.xml" type="application/xml"/> <atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://localhost:8080/geoserver/rest/styles/capitals.xml" type="application/xml"/>
</defaultStyle> </defaultStyle>
<styles class="linked-hash-set">
<style>
<name>green</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://localhost:8080/geoserver/rest/styles/green.xml" type="application/xml"/>
</style>
</styles>
<resource class="featureType"> <resource class="featureType">
<name>tasmania_cities</name> <name>tasmania_cities</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://localhost:8080/geoserver/rest/workspaces/topp/datastores/taz_shapes/featuretypes/tasmania_cities.xml" type="application/xml"/> <atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://localhost:8080/geoserver/rest/workspaces/topp/datastores/taz_shapes/featuretypes/tasmania_cities.xml" type="application/xml"/>
@ -156,15 +148,9 @@ public class RESTLayer {
return defaultStyle == null? null : defaultStyle.getChildText("name"); return defaultStyle == null? null : defaultStyle.getChildText("name");
} }
public RESTStyleList getStyles() { /**
RESTStyleList styleList = null; * @see <a href="https://github.com/geosolutions-it/geoserver-manager/issues/100">this issue</a>
final Element stylesRoot = layerElem.getChild("styles"); */
if (stylesRoot != null) {
styleList = new RESTStyleList(stylesRoot);
}
return styleList;
}
public String getDefaultStyleWorkspace() { public String getDefaultStyleWorkspace() {
Element defaultStyle = layerElem.getChild("defaultStyle"); Element defaultStyle = layerElem.getChild("defaultStyle");
return defaultStyle == null? null : defaultStyle.getChildText("workspace"); return defaultStyle == null? null : defaultStyle.getChildText("workspace");
@ -216,7 +202,6 @@ public class RESTLayer {
return atom.getAttributeValue("href"); return atom.getAttributeValue("href");
} }
/** /**
* Decodes the list of AuthorityURLInfo from the GeoServer Layer * Decodes the list of AuthorityURLInfo from the GeoServer Layer
* *
@ -271,7 +256,6 @@ public class RESTLayer {
return idList; return idList;
} }
// protected double getLatLonEdge(String edge) { // protected double getLatLonEdge(String edge) {
// Element resource = layerElem.getChild("resource"); // Element resource = layerElem.getChild("resource");
// Element elBBox = resource.getChild("latLonBoundingBox"); // Element elBBox = resource.getChild("latLonBoundingBox");

View File

@ -53,7 +53,6 @@ import org.jdom.Element;
*/ */
public class RESTLayer21 extends RESTLayer { public class RESTLayer21 extends RESTLayer {
public RESTLayer21(Element layerElem) { public RESTLayer21(Element layerElem) {
super(layerElem); super(layerElem);
} }
@ -109,11 +108,11 @@ public class RESTLayer21 extends RESTLayer{
String jsonStr = element.getValue(); String jsonStr = element.getValue();
jsonStr = jsonStr.substring(2); jsonStr = jsonStr.substring(2);
jsonStr = jsonStr.substring(0, jsonStr = jsonStr.substring(0, jsonStr.length() - 3);
jsonStr.length() - 3);
String[] items = jsonStr.split("\\}(,)\\{"); String[] items = jsonStr.split("\\}(,)\\{");
authorityURLList = new ArrayList<GSAuthorityURLInfoEncoder>(items.length); authorityURLList = new ArrayList<GSAuthorityURLInfoEncoder>(
items.length);
for (String item : items) { for (String item : items) {
String[] props = item.split(","); String[] props = item.split(",");
@ -122,8 +121,7 @@ public class RESTLayer21 extends RESTLayer{
String[] kvp2 = props[1].split("\":"); String[] kvp2 = props[1].split("\":");
String href = kvp2[1].replace("\"", ""); String href = kvp2[1].replace("\"", "");
authorityURLList authorityURLList.add(new GSAuthorityURLInfoEncoder(
.add(new GSAuthorityURLInfoEncoder(
name, href)); name, href));
} }
} }
@ -151,11 +149,11 @@ public class RESTLayer21 extends RESTLayer{
String jsonStr = element.getValue(); String jsonStr = element.getValue();
jsonStr = jsonStr.substring(2); jsonStr = jsonStr.substring(2);
jsonStr = jsonStr.substring(0, jsonStr = jsonStr.substring(0, jsonStr.length() - 3);
jsonStr.length() - 3);
String[] items = jsonStr.split("\\}(,)\\{"); String[] items = jsonStr.split("\\}(,)\\{");
identifierList = new ArrayList<GSIdentifierInfoEncoder>(items.length); identifierList = new ArrayList<GSIdentifierInfoEncoder>(
items.length);
for (String item : items) { for (String item : items) {
String[] props = item.split(","); String[] props = item.split(",");
@ -164,8 +162,7 @@ public class RESTLayer21 extends RESTLayer{
String[] kvp2 = props[1].split("\":"); String[] kvp2 = props[1].split("\":");
String identifier = kvp2[1].replace("\"", ""); String identifier = kvp2[1].replace("\"", "");
identifierList identifierList.add(new GSIdentifierInfoEncoder(
.add(new GSIdentifierInfoEncoder(
authority, identifier)); authority, identifier));
} }
} }

View File

@ -26,7 +26,6 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -26,9 +26,8 @@ package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import java.net.URI;
import org.jdom.Element; import org.jdom.Element;
import java.net.URI;
/** /**
* Parse <TT>namespace</TT>s returned as XML REST objects. * Parse <TT>namespace</TT>s returned as XML REST objects.

View File

@ -26,7 +26,6 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;

View File

@ -25,10 +25,10 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import org.jdom.Element; import org.jdom.Element;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
/** /**
* Parse a <TT>published</TT> returned as XML REST objects. * Parse a <TT>published</TT> returned as XML REST objects.

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007,2014 GeoSolutions S.A.S. * Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -26,13 +26,13 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.encoder.dimensions.GSCoverageDimensionEncoder;
import it.geosolutions.geoserver.rest.encoder.feature.FeatureTypeAttribute; import it.geosolutions.geoserver.rest.encoder.feature.FeatureTypeAttribute;
import it.geosolutions.geoserver.rest.encoder.feature.GSAttributeEncoder; import it.geosolutions.geoserver.rest.encoder.feature.GSAttributeEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.ResourceMetadataLinkInfo; import it.geosolutions.geoserver.rest.encoder.metadatalink.ResourceMetadataLinkInfo;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -42,10 +42,7 @@ import org.jdom.Namespace;
/** /**
* Parse a resource (FeatureType or Coverage) returned as XML REST objects. * Parse a resource (FeatureType or Coverage) returned as XML REST objects.
* *
* @author Emanuele Tajariol <etj at geo-solutions.it> * @author etj
* @author Emmanuel Blondel - emmanuel.blondel1@gmail.com | emmanuel.blondel@fao.org
* @author Henry Rotzoll
*
*/ */
public class RESTResource { public class RESTResource {
protected final Element rootElem; protected final Element rootElem;
@ -110,47 +107,30 @@ public class RESTResource {
return atom.getAttributeValue("href"); return atom.getAttributeValue("href");
} }
public String getNativeCRS() {
return rootElem.getChildText("nativeCRS");
}
public RESTBoundingBox getNativeBoundingBox() {
RESTBoundingBox bbox = null;
Element bboxElement = rootElem.getChild("nativeBoundingBox");
if (bboxElement != null) {
bbox = new RESTBoundingBox(bboxElement);
}
return bbox;
}
public RESTBoundingBox getLatLonBoundingBox() {
RESTBoundingBox bbox = null;
Element bboxElement = rootElem.getChild("latLonBoundingBox");
if (bboxElement != null) {
bbox = new RESTBoundingBox(bboxElement);
}
return bbox;
}
public String getCRS() { public String getCRS() {
RESTBoundingBox bbox = this.getLatLonBoundingBox(); Element elBBox = rootElem.getChild("latLonBoundingBox");
return bbox.getCRS(); return elBBox.getChildText("crs");
}
protected double getLatLonEdge(String edge) {
Element elBBox = rootElem.getChild("latLonBoundingBox");
return Double.parseDouble(elBBox.getChildText(edge));
} }
public double getMinX() { public double getMinX() {
return this.getLatLonBoundingBox().getMinX(); return getLatLonEdge("minx");
} }
public double getMaxX() { public double getMaxX() {
return this.getLatLonBoundingBox().getMaxX(); return getLatLonEdge("maxx");
} }
public double getMinY() { public double getMinY() {
return this.getLatLonBoundingBox().getMinY(); return getLatLonEdge("miny");
} }
public double getMaxY() { public double getMaxY() {
return this.getLatLonBoundingBox().getMaxY(); return getLatLonEdge("maxy");
} }
/** /**
@ -171,77 +151,30 @@ public class RESTResource {
throw new UnsupportedOperationException("This method is specific for RESTFeatureType"); throw new UnsupportedOperationException("This method is specific for RESTFeatureType");
} }
/** /**
* Decodes the list of MetadataLinkInfo from the GeoServer Resource * Decodes the list of MetadataLinkInfo from the GeoServer Resource
* *
* @since gs-2.4.x
*
* @return the list of GSMetadataLinkEncoder * @return the list of GSMetadataLinkEncoder
*/ */
public List<GSMetadataLinkInfoEncoder> getEncodedMetadataLinkInfoList() { public List<GSMetadataLinkInfoEncoder> getEncodedMetadataLinkInfoList() {
List<GSMetadataLinkInfoEncoder> metaLinksList = null; List<GSMetadataLinkInfoEncoder> metaLinksList = null;
final Element metaLinksRoot = rootElem.getChild("metadataLinks"); final Element metaLinksRoot = rootElem.getChild("metadataLinks");
if (metaLinksRoot != null) {
final List<Element> metaLinks = metaLinksRoot.getChildren(); final List<Element> metaLinks = metaLinksRoot.getChildren();
if (metaLinks != null) { if (metaLinks != null) {
metaLinksList = new ArrayList<GSMetadataLinkInfoEncoder>(metaLinks.size()); metaLinksList = new ArrayList<GSMetadataLinkInfoEncoder>(
metaLinks.size());
for (Element metaLink : metaLinks) { for (Element metaLink : metaLinks) {
final GSMetadataLinkInfoEncoder metaLinkEnc = new GSMetadataLinkInfoEncoder(); final GSMetadataLinkInfoEncoder metaLinkEnc = new GSMetadataLinkInfoEncoder();
metaLinkEnc metaLinkEnc.setType(metaLink.getChildText(ResourceMetadataLinkInfo.type.name()));
.setType(metaLink.getChildText(ResourceMetadataLinkInfo.type.name())); metaLinkEnc.setMetadataType(metaLink.getChildText(ResourceMetadataLinkInfo.metadataType.name()));
metaLinkEnc.setMetadataType(metaLink metaLinkEnc.setContent(metaLink.getChildText(ResourceMetadataLinkInfo.content.name()));
.getChildText(ResourceMetadataLinkInfo.metadataType.name()));
metaLinkEnc.setContent(metaLink.getChildText(ResourceMetadataLinkInfo.content
.name()));
metaLinksList.add(metaLinkEnc); metaLinksList.add(metaLinkEnc);
} }
} }
}
return metaLinksList; return metaLinksList;
} }
/**
* Decodes the list of GSCoverageDimensionEncoder from the GeoServer Resource
*
* @since gs-2.4.x
*
* @return the list of GSCoverageDimensionEncoder
*/
public List<GSCoverageDimensionEncoder> getEncodedDimensionsInfoList() {
List<GSCoverageDimensionEncoder> dimensionList = null;
final Element dimensionsRoot = rootElem.getChild("dimensions");
if (dimensionsRoot != null) {
final List<Element> dimensions = dimensionsRoot.getChildren();
if (dimensions != null) {
dimensionList = new ArrayList<GSCoverageDimensionEncoder>(dimensions.size());
for (Element coverageDimension : dimensions) {
final String name = coverageDimension.getChildText("name");
final String description = coverageDimension.getChildText("description");
String rangeMin = null;
String rangeMax = null;
final Element rangeElement = coverageDimension.getChild("range");
if (rangeElement != null) {
rangeMin = rangeElement.getChildText("min");
rangeMax = rangeElement.getChildText("max");
}
final String unit = coverageDimension.getChildText("unit");
String dimensionTypeName = null;
final Element dimensionTypeElement = coverageDimension
.getChild("dimensionType");
if (dimensionTypeElement != null) {
dimensionTypeName = dimensionTypeElement.getChildText("name");
}
final GSCoverageDimensionEncoder coverageDimensionEncoder = new GSCoverageDimensionEncoder(
name, description, rangeMin, rangeMax, unit, dimensionTypeName);
dimensionList.add(coverageDimensionEncoder);
}
}
}
return dimensionList;
}
} }

View File

@ -1,268 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.jdom.Element;
import org.jdom.Namespace;
/**
* This decode turns index format for a GeoServer StructuredGridCoverageReader into something
* useful, giving access to the definition of the single attributes.
*
* <P>This is the XML REST representation:
* <PRE>
{@code
<?xml version="1.0" encoding="UTF-8"?>
<wfs:FeatureCollection xmlns:gf="http://www.geoserver.org/rest/granules" xmlns:ogc="http://www.opengis.net/ogc" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml">
<gml:boundedBy>
<gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
<gml:coord>
<gml:X>5.0</gml:X>
<gml:Y>45.0</gml:Y>
</gml:coord>
<gml:coord>
<gml:X>14.875</gml:X>
<gml:Y>50.9375</gml:Y>
</gml:coord>
</gml:Box>
</gml:boundedBy>
<gml:featureMember>
<gf:V fid="V.337">
<gf:the_geom>
<gml:Polygon>
<gml:outerBoundaryIs>
<gml:LinearRing>
<gml:coordinates>5.0,45.0 5.0,50.9375 14.875,50.9375 14.875,45.0 5.0,45.0</gml:coordinates>
</gml:LinearRing>
</gml:outerBoundaryIs>
</gml:Polygon>
</gf:the_geom>
<gf:location>..\\polyphemus\\polyphemus_20130302.nc</gf:location>
<gf:imageindex>672</gf:imageindex>
<gf:time>2013-03-01T23:00:00Z</gf:time>
<gf:elevation>10.0</gf:elevation>
<gf:fileDate>2013-03-01T23:00:00Z</gf:fileDate>
<gf:updated>2013-04-08T05:40:29.061Z</gf:updated>
</gf:V>
</gml:featureMember>
</wfs:FeatureCollection>
}</PRE>
* @author Simone Giannecchini, GeoSolutions SAS
*
*/
public class RESTStructuredCoverageGranulesList implements Iterable<RESTStructuredCoverageGranulesList.RESTStructuredCoverageGranule> {
/** GML_NAMESPACE */
private static final Namespace GML_NAMESPACE = Namespace.getNamespace("gml", "http://www.opengis.net/gml");
private final List<RESTStructuredCoverageGranule> granulesList;
private final Element bbox;
/**
* @return the bbox
*/
public Element getBbox() {
return bbox;
}
/**
* @param list
*/
@SuppressWarnings("unchecked")
protected RESTStructuredCoverageGranulesList(Element featureCollection) {
// check ordering of elements
if(!featureCollection.getName().equals("FeatureCollection")){
throw new IllegalStateException("Root element should be wfs:FeatureCollection");
}
Element boundedBy = featureCollection.getChild("boundedBy",GML_NAMESPACE);
if(boundedBy==null){
throw new IllegalStateException("Unable to find boundedBy element");
}
// save bbox
bbox=boundedBy.getChild("Box",GML_NAMESPACE);
// now get the feature members
List<RESTStructuredCoverageGranule> tmpList = new ArrayList<RESTStructuredCoverageGranule>();
for(Element el : (List<Element>)featureCollection.getChildren("featureMember",GML_NAMESPACE)){
tmpList.add(new RESTStructuredCoverageGranule(el));
}
granulesList = Collections.unmodifiableList(tmpList);
}
public static RESTStructuredCoverageGranulesList build(String response) {
if(response == null)
return null;
Element pb = JDOMBuilder.buildElement(response);
if(pb != null){
return new RESTStructuredCoverageGranulesList(pb);
} else {
return null;
}
}
public int size() {
return granulesList.size();
}
public boolean isEmpty() {
return granulesList.isEmpty();
}
public RESTStructuredCoverageGranule get(int index) {
return granulesList.get(index);
}
/* (non-Javadoc)
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<RESTStructuredCoverageGranule> iterator() {
return granulesList.iterator();
}
/**
* Generic granule of the index.
*
* <P>This is the XML REST representation:
* <PRE>
{@code
<gml:featureMember>
<gf:V fid="V.1">
<gf:the_geom>
<gml:Polygon>
<gml:outerBoundaryIs>
<gml:LinearRing>
<gml:coordinates>5.0,45.0 5.0,50.9375 14.875,50.9375 14.875,45.0 5.0,45.0</gml:coordinates>
</gml:LinearRing>
</gml:outerBoundaryIs>
</gml:Polygon>
</gf:the_geom>
<gf:location>polyphemus_20130301.nc</gf:location>
<gf:imageindex>672</gf:imageindex>
<gf:time>2013-02-28T23:00:00Z</gf:time>
<gf:elevation>10.0</gf:elevation>
<gf:fileDate>2013-02-28T23:00:00Z</gf:fileDate>
<gf:updated>2013-04-08T06:18:41.597Z</gf:updated>
</gf:V>
</gml:featureMember>
* @author Simone Giannecchini, GeoSolutions SAS
*
*/
public static class RESTStructuredCoverageGranule {
protected final Element granule;
private final String fid;
private final List<Element> children;
@SuppressWarnings("unchecked")
public RESTStructuredCoverageGranule(Element elem) {
if(!elem.getName().equals("featureMember")){
throw new IllegalStateException("Root element should be gml:featureMember for a granule");
}
Element feature = (Element) elem.getChildren().get(0);
if(feature==null){
throw new IllegalStateException("Unable to find feature element for this granule");
}
this.granule = feature;
this.fid=granule.getAttribute("fid").getValue();
this.children=granule.getChildren();
}
public String getAttributeByName(String name) {
return granule.getChildTextTrim(name,null);
}
public String getAttributeByIndex(int index) {
return children.get(index).getValue();
}
@SuppressWarnings("unchecked")
public Iterator<Element> getAttributesIterator() {
return granule.getChildren().iterator();
}
/**
* @return the fid
*/
public String getFid() {
return fid;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getClass().getSimpleName()).append('[');
for (Element c : (List<Element>)granule.getChildren()) {
String text = c.getText();
if(text!= null) {
text = text.replace("\n", "");
text = text.trim();
}
sb.append('(').append(c.getName()).append("=").append(text).append(')');
}
sb.append(']');
return sb.toString();
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RESTStructuredCoverageGranulesList [");
if (bbox != null) {
builder.append("bbox=");
builder.append(bbox);
}
if (granulesList != null) {
builder.append("granulesList={");
for(RESTStructuredCoverageGranule granule:granulesList){
builder.append(granule);
}
builder.append("}, ");
}
builder.append("]");
return builder.toString();
}
}

View File

@ -1,212 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.jdom.Element;
/**
* This decode turns index format for a GeoServer StructuredGridCoverageReader into something
* useful, giving access to the definition of the single attributes.
*
* <P>This is the XML REST representation:
* <PRE>
{@code
<Schema>
<attributes>
<Attribute>
<name>the_geom</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>com.vividsolutions.jts.geom.Polygon</binding>
</Attribute>
<Attribute>
<name>location</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>java.lang.String</binding>
</Attribute>
<Attribute>
<name>imageindex</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>java.lang.Integer</binding>
</Attribute>
<Attribute>
<name>time</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>java.sql.Timestamp</binding>
</Attribute>
<Attribute>
<name>elevation</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>java.lang.Double</binding>
</Attribute>
<Attribute>
<name>fileDate</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>java.sql.Timestamp</binding>
</Attribute>
<Attribute>
<name>updated</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>java.sql.Timestamp</binding>
</Attribute>
</attributes>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://localhost:8080/geoserver/rest/workspaces/it.geosolutions/coveragestores/polyphemus/coverages/V/index/granules.xml" type="application/xml"/>
</Schema>
}</PRE>
* @author Simone Giannecchini, GeoSolutions SAS
*
*/
public class RESTStructuredCoverageIndexSchema implements Iterable<RESTStructuredCoverageIndexSchema.RESTStructuredCoverageIndexAttribute> {
private final List<RESTStructuredCoverageIndexAttribute> attributeList;
/**
* @param list
*/
@SuppressWarnings("unchecked")
protected RESTStructuredCoverageIndexSchema(Element schema) {
// check ordering of elements
if(!schema.getName().equals("Schema")){
throw new IllegalStateException("Root element should be Schema");
}
Element attributes = schema.getChild("attributes");
if(attributes==null){
throw new IllegalStateException("Root element should be Schema");
}
List<RESTStructuredCoverageIndexAttribute> tmpList = new ArrayList<RESTStructuredCoverageIndexAttribute>();
for(Element el : (List<Element>)attributes.getChildren()){
tmpList.add(new RESTStructuredCoverageIndexAttribute(el));
}
attributeList = Collections.unmodifiableList(tmpList);
}
public static RESTStructuredCoverageIndexSchema build(String response) {
if(response == null)
return null;
Element pb = JDOMBuilder.buildElement(response);
if(pb != null){
return new RESTStructuredCoverageIndexSchema(pb);
} else {
return null;
}
}
public int size() {
return attributeList.size();
}
public boolean isEmpty() {
return attributeList.isEmpty();
}
public RESTStructuredCoverageIndexAttribute get(int index) {
return attributeList.get(index);
}
/* (non-Javadoc)
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<RESTStructuredCoverageIndexAttribute> iterator() {
return attributeList.iterator();
}
/**
* Generic granule of the index.
*
* <P>This is the XML REST representation:
* <PRE>
{@code
<Attribute>
<name>the_geom</name>
<minOccurs>0</minOccurs>
<maxOccurs>1</maxOccurs>
<nillable>true</nillable>
<binding>com.vividsolutions.jts.geom.Polygon</binding>
</Attribute>
* @author Simone Giannecchini, GeoSolutions SAS
*
*/
public static class RESTStructuredCoverageIndexAttribute {
protected final Element attribute;
public RESTStructuredCoverageIndexAttribute(Element elem) {
this.attribute = elem;
}
public String getName() {
return attribute.getChildTextTrim("name");
}
public String getMinOccurs() {
return attribute.getChildTextTrim("minOccurs");
}
public String getMaxOccurs() {
return attribute.getChildTextTrim("maxOccurs");
}
public String getNillable() {
return attribute.getChildTextTrim("nillable");
}
public String getBinding() {
return attribute.getChildTextTrim("binding");
}
@Override
public String toString() {
return "RESTStructuredCoverageGranule [getName()=" + getName()
+ ", getMinOccurs()=" + getMinOccurs() + ", getMaxOccurs()=" + getMaxOccurs()
+ ", getNillable()=" + getNillable() + ", getBinding()=" + getBinding() + "]";
}
}
}

View File

@ -1,70 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2013 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element;
/**
*
* @author ETj (etj at geo-solutions.it)
*/
public class RESTStyle {
private final Element elem;
public static RESTStyle build(String xml) {
if (xml == null) {
return null;
}
Element e = JDOMBuilder.buildElement(xml);
if (e != null) {
return new RESTStyle(e);
} else {
return null;
}
}
protected RESTStyle(Element elem) {
this.elem = elem;
}
public String getName() {
return elem.getChildText("name");
}
public String getFileName() {
return elem.getChildText("filename");
}
public String getWorkspace() {
if(elem.getChild("workspace") != null)
return elem.getChild("workspace").getChildText("name");
else
return null;
}
}

View File

@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -1,306 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Element;
/**
* Parse <TT>WMS</TT>s returned as XML REST objects.
*
* <P>This is the XML REST representation:
* <PRE>
*{@code
<wmsLayer>
<name>comunilazio</name>
<nativeName>lait:comunilazio</nativeName>
<namespace>
<name>arit</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://172.27.30.25:8080/geoserver/rest/namespaces/arit.xml" type="application/xml"/>
</namespace>
<title>comunilazio</title>
<description/>
<keywords>
<string>features</string>
<string>comunilazio</string>
</keywords>
<nativeCRS>
GEOGCS["WGS 84", DATUM["World Geodetic System 1984", SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]], UNIT["degree", 0.017453292519943295], AXIS["Geodetic longitude", EAST], AXIS["Geodetic latitude", NORTH], AUTHORITY["EPSG","4326"]]
</nativeCRS>
<srs>EPSG:4326</srs>
<nativeBoundingBox>
<minx>11.4482128</minx>
<maxx>14.0288013</maxx>
<miny>40.7848334</miny>
<maxy>42.8396541</maxy>
<crs>EPSG:4326</crs>
</nativeBoundingBox>
<latLonBoundingBox>
<minx>11.4482128</minx>
<maxx>14.0288013</maxx>
<miny>40.7848334</miny>
<maxy>42.8396541</maxy>
<crs>
GEOGCS["WGS84(DD)", DATUM["WGS84", SPHEROID["WGS84", 6378137.0, 298.257223563]], PRIMEM["Greenwich", 0.0], UNIT["degree", 0.017453292519943295], AXIS["Geodetic longitude", EAST], AXIS["Geodetic latitude", NORTH]]
</crs>
</latLonBoundingBox>
<projectionPolicy>FORCE_DECLARED</projectionPolicy>
<enabled>true</enabled>
<metadata>
<entry key="cachingEnabled">false</entry>
</metadata>
<store class="wmsStore">
<name>regione</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://172.27.30.25:8080/geoserver/rest/workspaces/arit/wmsstores/regione.xml" type="application/xml"/>
</store>
</wmsLayer>
* }</PRE>
*
* @author cip
*/
public class RESTWms extends RESTResource {
public static RESTWms build(String response) {
Element elem = JDOMBuilder.buildElement(response);
return elem == null? null : new RESTWms(elem);
}
public RESTWms(Element resource) {
super(resource);
}
public RESTWms(RESTResource resource) {
super(resource.rootElem);
}
// public String getName() {
// return rootElem.getChildText("name");
// }
// public String getNativeName() {
// return rootElem.getChildText("nativeName");
// }
// public String getNameSpace() {
// return rootElem.getChild("namespace").getChildText("name");
// }
//
// public String getTitle() {
// return rootElem.getChildText("title");
// }
public String getNativeCRS() {
return rootElem.getChildText("nativeCRS");
}
public String getSRS() {
return rootElem.getChildText("srs");
}
public RESTMetadataList getMetadataList() {
return new RESTMetadataList(rootElem.getChild("metadata"));
}
public List<RESTDimensionInfo> getDimensionInfo() {
List<RESTDimensionInfo> listDim = new ArrayList<RESTDimensionInfo>();
for (RESTMetadataList.RESTMetadataElement el : getMetadataList()){
if(el.getKey().equals(RESTDimensionInfo.TIME) || el.getKey().equals(RESTDimensionInfo.ELEVATION)){
listDim.add(new RESTDimensionInfo(el.getMetadataElem()));
}
}
return listDim;
}
/**
* Retrieves the list of parameters for this wms.
*
* @return a {@link Map} where the key is the name for the parameter and the value is the value for the parameter.
*/
@SuppressWarnings("unchecked")
public Map<String, String> getParametersList() {
Map<String, String> paramsList = new HashMap<String, String>();
final Element paramsRoot = rootElem.getChild("parameters");
if (paramsRoot != null) {
final List<Element> params = paramsRoot.getChildren();
if (params != null) {
for (Element param : params) {
final List<Element> values = param.getChildren();
assert values.size()==2;
paramsList.put(values.get(0).getValue(), values.get(1).getValue()); // save key and value
}
}
}
return paramsList;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RESTWms [");
if (getNativeCRS() != null) {
builder.append("getNativeCRS()=");
builder.append(getNativeCRS());
builder.append(", ");
}
if (getSRS() != null) {
builder.append("getSRS()=");
builder.append(getSRS());
builder.append(", ");
}
if (getMetadataList() != null) {
builder.append("getMetadataList()=");
builder.append(getMetadataList());
builder.append(", ");
}
if (getDimensionInfo() != null) {
builder.append("getDimensionInfo()=");
builder.append(getDimensionInfo());
builder.append(", ");
}
if (getParametersList() != null) {
builder.append("getParametersList()=");
builder.append(getParametersList());
builder.append(", ");
}
if (getName() != null) {
builder.append("getName()=");
builder.append(getName());
builder.append(", ");
}
if (getTitle() != null) {
builder.append("getTitle()=");
builder.append(getTitle());
builder.append(", ");
}
if (getNativeName() != null) {
builder.append("getNativeName()=");
builder.append(getNativeName());
builder.append(", ");
}
if (getAbstract() != null) {
builder.append("getAbstract()=");
builder.append(getAbstract());
builder.append(", ");
}
if (getNameSpace() != null) {
builder.append("getNameSpace()=");
builder.append(getNameSpace());
builder.append(", ");
}
if (getStoreName() != null) {
builder.append("getStoreName()=");
builder.append(getStoreName());
builder.append(", ");
}
if (getStoreType() != null) {
builder.append("getStoreType()=");
builder.append(getStoreType());
builder.append(", ");
}
if (getStoreUrl() != null) {
builder.append("getStoreUrl()=");
builder.append(getStoreUrl());
builder.append(", ");
}
if (getCRS() != null) {
builder.append("getCRS()=");
builder.append(getCRS());
builder.append(", ");
}
builder.append("getMinX()=");
builder.append(getMinX());
builder.append(", getMaxX()=");
builder.append(getMaxX());
builder.append(", getMinY()=");
builder.append(getMinY());
builder.append(", getMaxY()=");
builder.append(getMaxY());
builder.append(", ");
if (getAttributeList() != null) {
builder.append("getAttributeList()=");
builder.append(getAttributeList());
builder.append(", ");
}
if (getEncodedAttributeList() != null) {
builder.append("getEncodedAttributeList()=");
builder.append(getEncodedAttributeList());
builder.append(", ");
}
if (getEncodedMetadataLinkInfoList() != null) {
builder.append("getEncodedMetadataLinkInfoList()=");
builder.append(getEncodedMetadataLinkInfoList());
}
builder.append("]");
return builder.toString();
}
// public String getStoreName() {
// return rootElem.getChild("store").getChildText("name");
// }
//
// public String getStoreType() {
// return rootElem.getChild("store").getAttributeValue("class");
// }
// public String getStoreUrl() {
// Element store = rootElem.getChild("store");
// Element atom = store.getChild("link", Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom"));
// return atom.getAttributeValue("href");
// }
// public String getBBCRS() {
// Element elBBox = rootElem.getChild("latLonBoundingBox");
// return elBBox.getChildText("crs");
// }
//
// protected double getLatLonEdge(String edge) {
// Element elBBox = rootElem.getChild("latLonBoundingBox");
// return Double.parseDouble(elBBox.getChildText(edge));
// }
//
// public double getMinX() {
// return getLatLonEdge("minx");
// }
// public double getMaxX() {
// return getLatLonEdge("maxx");
// }
// public double getMinY() {
// return getLatLonEdge("miny");
// }
// public double getMaxY() {
// return getLatLonEdge("maxy");
// }
}

View File

@ -1,59 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import org.jdom.Element;
/**
* Parses list of summary data about Wms.
*
* <P>This is the XML REST representation:
* <PRE>{@code <wmsLayers>
<wmsLayer>
<name>comunilazio</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://172.27.30.25:8080/geoserver/rest/workspaces/arit/wmsstores/regione/wmslayers/comunilazio.xml" type="application/xml"/>
</wmsLayer>
</wmsLayers>
*
}</PRE>
*
* @author cip
*/
public class RESTWmsList extends RESTAbstractList<NameLinkElem> {
public static RESTWmsList build(String response) {
Element elem = JDOMBuilder.buildElement(response);
return elem == null? null : new RESTWmsList(elem);
}
protected RESTWmsList(Element list) {
super(list);
}
}

View File

@ -1,145 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import org.jdom.Element;
/**
* Parse <TT>WmsStore</TT>s returned as XML REST objects.
* <P>
* This is the XML document returned by GeoServer when requesting a WmsStore:
* <PRE>
* {@code
<wmsStore>
<name>regione</name>
<type>WMS</type>
<enabled>true</enabled>
<workspace>
<name>arit</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://172.27.30.25:8080/geoserver/rest/workspaces/arit.xml" type="application/xml"/>
</workspace>
<metadata>
<entry key="useConnectionPooling">true</entry>
</metadata>
<__default>false</__default>
<capabilitiesURL>http://www.regione.lazio.it/geoserver/wms</capabilitiesURL>
<user>admin</user>
<password>geoserver</password>
<maxConnections>6</maxConnections>
<readTimeout>60</readTimeout>
<connectTimeout>30</connectTimeout>
<wmsLayers>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://172.27.30.25:8080/geoserver/rest/workspaces/arit/wmsstores/regione/wmslayers.xml" type="application/xml"/>
</wmsLayers>
</wmsStore>
* }
* </PRE>
*
* <I>Note: the whole XML fragment is stored in memory. At the moment, there are
* methods to retrieve only the more useful data.
*
* @author etj
*/
public class RESTWmsStore {
private final Element cs;
public RESTWmsStore(Element cs) {
this.cs = cs;
}
public static RESTWmsStore build(String response) {
if(response == null)
return null;
if(response.isEmpty())
return new RESTWmsStore(new Element("wmsStore")); // TODO check how to response
Element pb = JDOMBuilder.buildElement(response);
if(pb != null)
return new RESTWmsStore(pb);
else
return null;
}
public String getName() {
return cs.getChildText("name");
}
public String getType() {
return cs.getChildText("type");
}
public Boolean getEnabled() {
return Boolean.parseBoolean(cs.getChildText("enabled"));
}
public String getWorkspaceName() {
return cs.getChild("workspace").getChildText("name");
}
public Boolean getUseConnectionPooling(){
Element entry = cs.getChild("metadata").getChild("entry");
return entry.getAttributeValue("key").equals("useConnectionPooling") && Boolean.parseBoolean(entry.getValue());
}
public String getCapabilitiesURL() {
return cs.getChildText("capabilitiesURL");
}
public String getMaxConnections() {
return cs.getChildText("maxConnections");
}
public String getReadTimeout() {
return cs.getChildText("readTimeout");
}
public String getConnectTimeout() {
return cs.getChildText("connectTimeout");
}
public String getUser() {
return cs.getChildText("user");
}
public String getPassword() {
return cs.getChildText("password");
}
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getSimpleName())
.append('[');
if(cs == null)
sb.append("null");
else
sb.append("name:").append(getName())
.append(" wsname:").append(getWorkspaceName());
return sb.toString();
}
}

View File

@ -1,60 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import org.jdom.Element;
/**
* Parses list of summary data about WmsStores.
*
* <P>This is the XML REST representation:
* <PRE>{@code
<wmsStores>
<wmsStore>
<name>regione</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://172.27.30.25:8080/geoserver/rest/workspaces/arit/wmsstores/regione.xml" type="application/xml"/>
</wmsStore>
</wmsStores>
*
}</PRE>
*
* @author cip
*/
public class RESTWmsStoreList extends RESTAbstractList<NameLinkElem> {
public static RESTWmsStoreList build(String response) {
Element elem = JDOMBuilder.buildElement(response);
return elem == null? null : new RESTWmsStoreList(elem);
}
protected RESTWmsStoreList(Element list) {
super(list);
}
}

View File

@ -25,9 +25,8 @@
package it.geosolutions.geoserver.rest.decoder; package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007,2015 GeoSolutions S.A.S. * Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -133,36 +133,17 @@ public class GSVersionDecoder extends XmlElement {
return VERSION.getVersion(e.getTextTrim()); return VERSION.getVersion(e.getTextTrim());
} }
/**
* @see {@link Enum#compareTo(Enum)}
* @param v
* @return
*/
public int compareTo(VERSION v) {
return getVersion().compareTo(v);
}
public static GSVersionDecoder build(String response) { public static GSVersionDecoder build(String response) {
return new GSVersionDecoder(response); return new GSVersionDecoder(response);
} }
public enum VERSION { public enum VERSION {
v22(22, "2\\.2([^0-9]|$).*"), v22(22), v23(23), v24(24), v25(25), ABOVE(9999), UNRECOGNIZED(-1);
v23(23, "2\\.3([^0-9]|$).*"),
v24(24, "2\\.4([^0-9]|$).*"),
v25(25, "2\\.5([^0-9]|$).*"),
v26(26, "2\\.6([^0-9]|$).*"),
v27(27, "2\\.7([^0-9]|$).*"),
v28(28, "2\\.8([^0-9]|$).*"),
ABOVE(9999, "2\\..+"),
UNRECOGNIZED(-1, null);
final private int version; final private int version;
final private String pattern;
private VERSION(int val, String pattern) { private VERSION(int val) {
version = val; version = val;
this.pattern = pattern;
} }
public int getVersion() { public int getVersion() {
@ -176,25 +157,23 @@ public class GSVersionDecoder extends XmlElement {
public static VERSION getVersion(String v) { public static VERSION getVersion(String v) {
if (v==null) { if (v==null) {
return UNRECOGNIZED; return UNRECOGNIZED;
} } else if (v.matches("2\\.2.*")) {
return v22;
for (VERSION version : VERSION.values()) { } else if (v.matches("2\\.3.*")) {
if(version.pattern != null && v.matches(version.pattern)) { return v23;
return version; } else if (v.matches("2\\.4.*")) {
} return v24;
} } else if (v.matches("2\\.5.*")) {
return v25;
} else if (v.matches("2\\..+")) {
return ABOVE;
} else {
return UNRECOGNIZED; return UNRECOGNIZED;
} }
}
public static String print(){ public static String print(){
return "["+v22+", "+v23+", "+v24+", "+v25+", "+ABOVE+", "+UNRECOGNIZED+"]";
StringBuilder sb = new StringBuilder("[");
for (VERSION v : VERSION.values()) {
sb.append(v.toString()).append(' ');
}
sb.append("]");
return sb.toString();
} }
} }

View File

@ -27,7 +27,6 @@ package it.geosolutions.geoserver.rest.decoder.utils;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jdom.Element; import org.jdom.Element;
/** /**

View File

@ -24,13 +24,13 @@
*/ */
package it.geosolutions.geoserver.rest.encoder; package it.geosolutions.geoserver.rest.encoder;
import org.jdom.Element;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.StoreType; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.StoreType;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils; import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder; import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
import org.jdom.Element;
/** /**
* Generic Store encoder. * Generic Store encoder.
* *
@ -56,7 +56,7 @@ public abstract class GSAbstractStoreEncoder extends PropertyXMLEncoder {
} }
public String getType() { public String getType() {
return ElementUtils.contains(getRoot(), "type").getTextTrim(); return ElementUtils.contains(getRoot(), "name").getTextTrim();
} }
public void setName(String name) { public void setName(String name) {

View File

@ -25,60 +25,31 @@
package it.geosolutions.geoserver.rest.encoder; package it.geosolutions.geoserver.rest.encoder;
import org.jdom.Element;
import org.jdom.filter.Filter;
import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEncoder; import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder; import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder; import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
import org.jdom.Element;
import org.jdom.filter.Filter;
/** /**
* Layer encoder for Geoserver >= 2.2 * Layer encoder for Geoserver >= 2.2
* *
* @author ETj (etj at geo-solutions.it) * @author ETj (etj at geo-solutions.it)
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* @author Emmanuel Blondel - emmanuel.blondel1@gmail.com * @author Emmanuel Blondel - emmanuel.blondel1@gmail.com |
* emmanuel.blondel@fao.org
* *
* The layer encoder is enabled by default * The layer encoder is enabled by default
* *
* {@code
* <layer>
* <name>{LAYERNAME}</name>
* <type>RASTER</type>
* <defaultStyle>
* <name>{STYLE_NAME}</name>
* <atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://{GSURL}/rest/styles/{STYLE}xml" type="application/xml"/>
* </defaultStyle>
* <resource class="coverage">
* <name>{RESOURCE_NAME}</name>
* <atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate"
* href="http://{GSURL}/rest/workspaces/{WS}/coveragestores/{STORE}/coverages/{LAYER}.xml" type="application/xml"/>
* </resource>
* <attribution>
* <title>test</title>
* <href>http://www.fao.org/fileadmin/templates/faoweb/images/FAO-logo.png</href>
* <logoURL>http://www.fao.org/fileadmin/templates/faoweb/images/FAO-logo.png</logoURL>
* <logoWidth>412</logoWidth>
* <logoHeight>77</logoHeight>
* <logoType>image/png</logoType>
* </attribution>
* ...
*
* </layer>
* }
*
*
* @since gs-2.2.x
*/ */
public class GSLayerEncoder extends PropertyXMLEncoder { public class GSLayerEncoder extends PropertyXMLEncoder {
public final static String STYLES = "styles"; public final static String STYLES = "styles";
public final static String AUTHORITY_URLS="authorityURLs"; public final static String AUTHORITY_URLS="authorityURLs";
public final static String IDENTIFIERS="identifiers"; public final static String IDENTIFIERS="identifiers";
public final static String DEFAULT_STYLE = "defaultStyle";
final private Element stylesEncoder = new Element(STYLES); final private Element stylesEncoder = new Element(STYLES);
final private Element defaultStyleEncoder = new Element(DEFAULT_STYLE);
final private Element authorityURLListEncoder = new Element(AUTHORITY_URLS); final private Element authorityURLListEncoder = new Element(AUTHORITY_URLS);
final private Element identifierListEncoder = new Element(IDENTIFIERS); final private Element identifierListEncoder = new Element(IDENTIFIERS);
@ -167,20 +138,6 @@ public class GSLayerEncoder extends PropertyXMLEncoder {
add("defaultStyle", defaultStyle); add("defaultStyle", defaultStyle);
} }
/**
* @see {@link GSLayerEncoder#setDefaultStyle(String)}
* @param defaultStyle
*/
protected void addDefaultStyle(String workspace, String defaultStyle) {
addContent(defaultStyleEncoder);
Element el = new Element("name");
el.setText(defaultStyle);
defaultStyleEncoder.addContent(el);
el = new Element("workspace");
el.setText(workspace);
defaultStyleEncoder.addContent(el);
}
/** /**
* @param defaultStyle The style that will be applied if no style is specified. * @param defaultStyle The style that will be applied if no style is specified.
* @throws IllegalArgumentException if defaultStyle is null or empty * @throws IllegalArgumentException if defaultStyle is null or empty
@ -192,16 +149,7 @@ public class GSLayerEncoder extends PropertyXMLEncoder {
} }
/** /**
* @see {@link GSLayerEncoder#setDefaultStyle(String)} * Adds a style
* @param defaultStyle
*/
public void setDefaultStyle(String workspace, String defaultStyle) {
remove("defaultStyle");
addDefaultStyle(workspace, defaultStyle);
}
/**
* Add a style
* *
* @param style * @param style
*/ */
@ -212,7 +160,7 @@ public class GSLayerEncoder extends PropertyXMLEncoder {
} }
/** /**
* delete a style from the list of available styles * delete a style from the list
* *
* @param style * @param style
* @return true if something is removed, false otherwise * @return true if something is removed, false otherwise

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007-2016 GeoSolutions S.A.S. * Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -26,6 +26,7 @@
package it.geosolutions.geoserver.rest.encoder; package it.geosolutions.geoserver.rest.encoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -36,7 +37,6 @@ import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder
import it.geosolutions.geoserver.rest.encoder.identifier.IdentifierInfo; import it.geosolutions.geoserver.rest.encoder.identifier.IdentifierInfo;
import it.geosolutions.geoserver.rest.encoder.utils.NestedElementEncoder; import it.geosolutions.geoserver.rest.encoder.utils.NestedElementEncoder;
import it.geosolutions.geoserver.rest.encoder.utils.XmlElement; import it.geosolutions.geoserver.rest.encoder.utils.XmlElement;
import java.util.LinkedHashMap;
/** /**
* Layer encoder for Geoserver = 2.1 * Layer encoder for Geoserver = 2.1
@ -45,12 +45,9 @@ import java.util.LinkedHashMap;
* *
* The layer encoder is enabled by default * The layer encoder is enabled by default
* *
* @since gs-2.1.x
*
*/ */
public class GSLayerEncoder21 extends GSLayerEncoder { public class GSLayerEncoder21 extends GSLayerEncoder {
public final static String METADATA = "metadata"; public final static String METADATA = "metadata";
final private GSMetadataEncoder metadata = new GSMetadataEncoder(); final private GSMetadataEncoder metadata = new GSMetadataEncoder();
public Map<String, String> authorityURLList; public Map<String, String> authorityURLList;
@ -85,7 +82,8 @@ public class GSLayerEncoder21 extends GSLayerEncoder {
/** /**
* *
* @param advertised true if the layer should be advertised * @param advertised
* true if the layer should be advertised
*/ */
public void setAdvertised(boolean advertised) { public void setAdvertised(boolean advertised) {
if (advertised) { if (advertised) {
@ -102,20 +100,20 @@ public class GSLayerEncoder21 extends GSLayerEncoder {
*/ */
public void addAuthorityURL(GSAuthorityURLInfoEncoder authorityURLInfo) { public void addAuthorityURL(GSAuthorityURLInfoEncoder authorityURLInfo) {
if (authorityURLList == null) { if (authorityURLList == null) {
authorityURLList = new LinkedHashMap<String,String>(); authorityURLList = new HashMap<String, String>();
} }
authorityURLList.put(authorityURLInfo.getHref(), authorityURLInfo.getName()); authorityURLList.put(authorityURLInfo.getHref(),
authorityURLInfo.getName());
String jsonStr = ""; String jsonStr = "";
for (Entry<String, String> entry : authorityURLList.entrySet()) { for (Entry<String, String> entry : authorityURLList.entrySet()) {
jsonStr += "{"+ jsonStr += "{" + "\"" + AuthorityURLInfo.name.name() + "\":\""
"\""+AuthorityURLInfo.name.name()+"\":\""+entry.getValue()+"\","+ + entry.getValue() + "\"," + "\""
"\""+AuthorityURLInfo.href.name()+"\":\""+entry.getKey()+"\""+ + AuthorityURLInfo.href.name() + "\":\"" + entry.getKey()
"},"; + "\"" + "},";
} }
metadata.set("authorityURLs", "[" + jsonStr + "]"); metadata.set("authorityURLs", "[" + jsonStr + "]");
} }
/** /**
* Deletes a AuthorityURLInfo from the list using the authorityURL * Deletes a AuthorityURLInfo from the list using the authorityURL
* (AuthorityURLInfo href) * (AuthorityURLInfo href)
@ -133,9 +131,9 @@ public class GSLayerEncoder21 extends GSLayerEncoder {
.entrySet()) { .entrySet()) {
for (String value : entry.getValue()) { for (String value : entry.getValue()) {
jsonStr += "{" + "\"" + AuthorityURLInfo.name.name() jsonStr += "{" + "\"" + AuthorityURLInfo.name.name()
+ "\":\"" + entry.getValue() + "\"," + "\"" + "\":\"" + value + "\"," + "\""
+ AuthorityURLInfo.href.name() + "\":\"" + AuthorityURLInfo.href.name() + "\":\""
+ value + "\"" + "},"; + entry.getKey() + "\"" + "},";
} }
} }
metadata.set("identifiers", "[" + jsonStr + "]"); metadata.set("identifiers", "[" + jsonStr + "]");
@ -152,7 +150,7 @@ public class GSLayerEncoder21 extends GSLayerEncoder {
*/ */
public void addIdentifier(GSIdentifierInfoEncoder identifierInfo) { public void addIdentifier(GSIdentifierInfoEncoder identifierInfo) {
if (identifierList == null) { if (identifierList == null) {
identifierList = new LinkedHashMap<String,List<String>>(); identifierList = new HashMap<String, List<String>>();
} }
String authority = identifierInfo.getAuthority(); String authority = identifierInfo.getAuthority();
@ -180,8 +178,8 @@ public class GSLayerEncoder21 extends GSLayerEncoder {
} }
/** /**
* Deletes a IdentifierInfo from the list using the authority * Deletes a IdentifierInfo from the list using the authority name
* name (IdentifierInfo authority) * (IdentifierInfo authority)
* *
* @param authority * @param authority
* @return true if something is removed, false otherwise * @return true if something is removed, false otherwise
@ -208,5 +206,4 @@ public class GSLayerEncoder21 extends GSLayerEncoder {
return delete; return delete;
} }
} }

View File

@ -24,11 +24,11 @@
*/ */
package it.geosolutions.geoserver.rest.encoder; package it.geosolutions.geoserver.rest.encoder;
import java.net.URI;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils; import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder; import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
import java.net.URI;
/** /**
* Namespace XML encoder. Namespaces must contain a non empty prefix and a URI: * Namespace XML encoder. Namespaces must contain a non empty prefix and a URI:
* *

View File

@ -35,7 +35,7 @@ import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
* @author ETj * @author ETj
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* *
* @deprecated Will be removed in next version 1.5.x. * @deprecated Will be removed in next version 1.6.x.
* Use {@link it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder} instead. * Use {@link it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder} instead.
*/ */
public class GSPostGISDatastoreEncoder extends PropertyXMLEncoder { public class GSPostGISDatastoreEncoder extends PropertyXMLEncoder {

View File

@ -47,24 +47,17 @@ import org.jdom.filter.Filter;
* *
* @author ETj (etj at geo-solutions.it) * @author ETj (etj at geo-solutions.it)
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* @author Emmanuel Blondel - emmanuel.blondel1@gmail.com | emmanuel.blondel@fao.org
* @author Henry Rotzoll
*/ */
public abstract class GSResourceEncoder extends PropertyXMLEncoder { public abstract class GSResourceEncoder
extends PropertyXMLEncoder {
public final static String NAME = "name"; public final static String NAME = "name";
public final static String NATIVENAME = "nativeName"; public final static String NATIVENAME = "nativeName";
public final static String METADATA="metadata"; public final static String METADATA="metadata";
public final static String KEYWORDS="keywords"; public final static String KEYWORDS="keywords";
public final static String METADATALINKS="metadataLinks"; public final static String METADATALINKS="metadataLinks";
final private GSMetadataEncoder metadata = new GSMetadataEncoder(); final private GSMetadataEncoder metadata = new GSMetadataEncoder();
final private Element keywordsListEncoder = new Element(KEYWORDS); final private Element keywordsListEncoder = new Element(KEYWORDS);
final private Element metadataLinksListEncoder = new Element(METADATALINKS); final private Element metadataLinksListEncoder = new Element(METADATALINKS);
private class GSMetadataEncoder extends NestedElementEncoder{ private class GSMetadataEncoder extends NestedElementEncoder{
@ -74,7 +67,8 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
} }
/** /**
* @param rootName Actually 'feature' or 'coverage' * @param rootName
* Actually 'feature' or 'coverage'
* @see GSFeatureTypeEncoder * @see GSFeatureTypeEncoder
* @see GSCoverageEncoder * @see GSCoverageEncoder
*/ */
@ -92,6 +86,7 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
set("enabled", (enabled) ? "true" : "false"); set("enabled", (enabled) ? "true" : "false");
} }
/** /**
* @param key * @param key
* @param dimensionInfo * @param dimensionInfo
@ -114,77 +109,27 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
* @param dimensionInfo * @param dimensionInfo
*/ */
protected void addMetadataDimension(String key, GSDimensionInfoEncoder dimensionInfo) { protected void addMetadataDimension(String key, GSDimensionInfoEncoder dimensionInfo) {
addMetadataDimension(key, dimensionInfo, false);
}
/**
* Add the metadata for a custom dimension.
*
* @param key the name of the dimension
* @param dimensionInfo {@link GSDimensionInfoEncoder} with additional information about the dimension
* @param custom is the dimension custom or not?
*/
protected void addMetadataDimension(String key, GSDimensionInfoEncoder dimensionInfo,
boolean custom) {
if (custom) {
metadata.set("custom_dimension_" + key.toUpperCase(), dimensionInfo.getRoot());
} else {
metadata.add(key, dimensionInfo.getRoot()); metadata.add(key, dimensionInfo.getRoot());
} }
}
public void setMetadataDimension(String key, GSDimensionInfoEncoder dimensionInfo) { public void setMetadataDimension(String key, GSDimensionInfoEncoder dimensionInfo) {
setMetadataDimension(key, dimensionInfo, false);
}
public void setMetadataString(String key, String value) {
metadata.set(key, value);
}
/**
* Set the metadata for a custom dimension.
*
* @param key the name of the dimension
* @param dimensionInfo {@link GSDimensionInfoEncoder} with additional information about the dimension
* @param custom is the dimension custom or not?
*/
public void setMetadataDimension(String key, GSDimensionInfoEncoder dimensionInfo,
boolean custom) {
if (custom) {
metadata.set("custom_dimension_" + key.toUpperCase(), dimensionInfo.getRoot());
} else {
metadata.set(key, dimensionInfo.getRoot()); metadata.set(key, dimensionInfo.getRoot());
} }
}
/** /**
* @param key the name of the metadata to add (f.e.: elevation, time) * @param key
* the name of the metadata to add (f.e.: elevation, time)
* @return true if something is removed, false otherwise * @return true if something is removed, false otherwise
*/ */
public boolean delMetadata(String key) { public boolean delMetadata(String key) {
return metadata.remove(key); return metadata.remove(key);
} }
public void addKeyword(String keyword) {
checkKeyword(keyword);
putKeyword(keyword);
}
/** public void addKeyword(String keyword) {
* {@code final Element el = new Element("string");
* <keywords> el.setText(keyword);
* <string>WCS</string> keywordsListEncoder.addContent(el);
* <string>ImageMosaic</string>
* <string>srtm30</string> <string> KEYWORD}\@language={LANGUAGE}\;\@vocabulary={VOCABULARY}\;</string>
* <string>{KEYWORD_2}\@vocabulary={VOCABULARY_2}\;</string> <string>{KEYWORD_3}\@language={LANGUAGE_3}\;</string> </keywords> }
*
* @param keyword mandatory keyword ('\' characters are not permitted)
* @param language optional parameter
* @param vocabulary optional parameter
*/
public void addKeyword(final String keyword, final String language, final String vocabulary) {
checkKeyword(keyword);
putKeyword(buildKeyword(keyword, language, vocabulary));
} }
/** /**
@ -194,28 +139,13 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
* @return true if something is removed, false otherwise * @return true if something is removed, false otherwise
*/ */
public boolean delKeyword(final String keyword) { public boolean delKeyword(final String keyword) {
return removeKeyword(keyword, null, null); final Element el = new Element("string");
} el.setText(keyword);
/**
* delete a keyword from the list
*
* @param keyword
* @return true if something is removed, false otherwise
*/
public boolean delKeyword(final String keyword, final String language, final String vocabulary) {
return removeKeyword(keyword, language, vocabulary);
}
private boolean removeKeyword(final String keyword, final String language,
final String vocabulary) {
checkKeyword(keyword);
final String text = buildKeyword(keyword, language, vocabulary);
return (keywordsListEncoder.removeContent(new Filter() { return (keywordsListEncoder.removeContent(new Filter() {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public boolean matches(Object obj) { public boolean matches(Object obj) {
if (((Element) obj).getText().equals(text)) { if (((Element) obj).getText().equals(keyword)) {
return true; return true;
} }
return false; return false;
@ -223,36 +153,11 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
})).size() == 0 ? false : true; })).size() == 0 ? false : true;
} }
private void putKeyword(String keyword) {
final Element el = new Element("string");
el.setText(keyword);
keywordsListEncoder.addContent(el);
}
private void checkKeyword(String keyword) {
if (keyword == null || keyword.isEmpty() || keyword.contains("\\")) {
throw new IllegalArgumentException("keyword may not be null, empty or contains '\'");
}
}
private String buildKeyword(final String keyword, final String language, final String vocabulary) {
StringBuilder sb = new StringBuilder(keyword);
// \@language={LANGUAGE_3}\;
if (language != null && !language.isEmpty()) {
sb.append("\\@language=").append(language).append("\\;");
}
// \@vocabulary={VOCABULARY}\;
if (vocabulary != null && !vocabulary.isEmpty()) {
sb.append("\\@vocabulary=").append(vocabulary).append("\\;");
}
return sb.toString();
}
/** /**
* Adds a MetadataLinkInfo to the GeoServer Resource * Adds a MetadataLinkInfo to the GeoServer Resource
* *
* @param MetadataLink * @param MetadataLink
*
*/ */
public void addMetadataLinkInfo(GSMetadataLinkInfoEncoder metadataLinkInfo) { public void addMetadataLinkInfo(GSMetadataLinkInfoEncoder metadataLinkInfo) {
metadataLinksListEncoder.addContent(metadataLinkInfo.getRoot()); metadataLinksListEncoder.addContent(metadataLinkInfo.getRoot());
@ -261,28 +166,33 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
/** /**
* Adds quickly a MetadataLinkInfo to the GeoServer Resource * Adds quickly a MetadataLinkInfo to the GeoServer Resource
* *
*
* @param type * @param type
* @param metadataType * @param metadataType
* @param content * @param content
*/ */
public void addMetadataLinkInfo(String type, String metadataType, String content) { public void addMetadataLinkInfo(String type, String metadataType,
final GSMetadataLinkInfoEncoder mde = new GSMetadataLinkInfoEncoder(type, metadataType, String content) {
content); final GSMetadataLinkInfoEncoder mde = new GSMetadataLinkInfoEncoder(
type, metadataType, content);
metadataLinksListEncoder.addContent(mde.getRoot()); metadataLinksListEncoder.addContent(mde.getRoot());
} }
/** /**
* Deletes a metadataLinkInfo from the list using the metadataURL (MetadataLinkInfo content) * Deletes a metadataLinkInfo from the list using the metadataURL
* (MetadataLinkInfo content)
* *
* @param metadataURL * @param metadataURL
* @return true if something is removed, false otherwise * @return true if something is removed, false otherwise
*/ */
public boolean delMetadataLinkInfo(final String metadataURL) { public boolean delMetadataLinkInfo(final String metadataURL) {
return (metadataLinksListEncoder.removeContent(GSMetadataLinkInfoEncoder return (metadataLinksListEncoder
.getFilterByContent(metadataURL))).size() == 0 ? false : true; .removeContent(GSMetadataLinkInfoEncoder
.getFilterByContent(metadataURL))).size() == 0 ? false
: true;
} }
/** /**
* Reprojection policy for a published layer. One of: * Reprojection policy for a published layer. One of:
* <ul> * <ul>
@ -343,6 +253,7 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
return null; return null;
} }
/** /**
* Add the 'nativename' node with a text value from 'name' * Add the 'nativename' node with a text value from 'name'
* *
@ -352,16 +263,19 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
add(NATIVENAME, nativename); add(NATIVENAME, nativename);
} }
/** /**
* Set or modify the 'nativename' node with a text value from 'name' * Set or modify the 'nativename' node with a text value from 'name'
* *
* @note if not specified, the nativeName will be set with the value of the 'name' node. * @note if not specified, the nativeName will be set with the value of the
* 'name' node.
* *
*/ */
public void setNativeName(final String nativename) { public void setNativeName(final String nativename) {
set(NATIVENAME, nativename); set(NATIVENAME, nativename);
} }
/** /**
* Get the nativeName * Get the nativeName
* *
@ -393,7 +307,6 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
} }
private final static String ABSTRACT = "abstract"; private final static String ABSTRACT = "abstract";
/** /**
* Add the 'abstract' node with a text value from 'abstract' * Add the 'abstract' node with a text value from 'abstract'
* *
@ -401,7 +314,6 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
protected void addAbstract(final String _abstract) { protected void addAbstract(final String _abstract) {
add(ABSTRACT, _abstract); add(ABSTRACT, _abstract);
} }
/** /**
* Set or modify the 'abstract' node with a text value from 'abstract' * Set or modify the 'abstract' node with a text value from 'abstract'
*/ */
@ -459,13 +371,9 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
} }
private final static String LATLONBBMINX = "latLonBoundingBox/minx"; private final static String LATLONBBMINX = "latLonBoundingBox/minx";
private final static String LATLONBBMAXX = "latLonBoundingBox/maxx"; private final static String LATLONBBMAXX = "latLonBoundingBox/maxx";
private final static String LATLONBBMINY = "latLonBoundingBox/miny"; private final static String LATLONBBMINY = "latLonBoundingBox/miny";
private final static String LATLONBBMAXY = "latLonBoundingBox/maxy"; private final static String LATLONBBMAXY = "latLonBoundingBox/maxy";
private final static String LATLONBBCRS = "latLonBoundingBox/crs"; private final static String LATLONBBCRS = "latLonBoundingBox/crs";
/** /**
@ -476,8 +384,8 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
* @param miny * @param miny
* @param crs * @param crs
*/ */
protected void addLatLonBoundingBox(double minx, double miny, double maxx, double maxy, protected void addLatLonBoundingBox(double minx, double miny, double maxx,
final String crs) { double maxy, final String crs) {
add(LATLONBBMINX, String.valueOf(minx)); add(LATLONBBMINX, String.valueOf(minx));
add(LATLONBBMINY, String.valueOf(miny)); add(LATLONBBMINY, String.valueOf(miny));
add(LATLONBBMAXY, String.valueOf(maxy)); add(LATLONBBMAXY, String.valueOf(maxy));
@ -485,8 +393,8 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
add(LATLONBBCRS, crs); add(LATLONBBCRS, crs);
} }
public void setLatLonBoundingBox(double minx, double miny, double maxx, double maxy, public void setLatLonBoundingBox(double minx, double miny, double maxx,
final String crs) { double maxy, final String crs) {
set(LATLONBBMINX, String.valueOf(minx)); set(LATLONBBMINX, String.valueOf(minx));
set(LATLONBBMAXY, String.valueOf(maxy)); set(LATLONBBMAXY, String.valueOf(maxy));
set(LATLONBBMAXX, String.valueOf(maxx)); set(LATLONBBMAXX, String.valueOf(maxx));
@ -495,13 +403,9 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
} }
private final static String NATIVEBBMINX = "nativeBoundingBox/minx"; private final static String NATIVEBBMINX = "nativeBoundingBox/minx";
private final static String NATIVEBBMAXX = "nativeBoundingBox/maxx"; private final static String NATIVEBBMAXX = "nativeBoundingBox/maxx";
private final static String NATIVEBBMINY = "nativeBoundingBox/miny"; private final static String NATIVEBBMINY = "nativeBoundingBox/miny";
private final static String NATIVEBBMAXY = "nativeBoundingBox/maxy"; private final static String NATIVEBBMAXY = "nativeBoundingBox/maxy";
private final static String NATIVEBBCRS = "nativeBoundingBox/crs"; private final static String NATIVEBBCRS = "nativeBoundingBox/crs";
/** /**
@ -511,8 +415,8 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
* @param miny * @param miny
* @param crs * @param crs
*/ */
protected void addNativeBoundingBox(double minx, double miny, double maxx, double maxy, protected void addNativeBoundingBox(double minx, double miny, double maxx,
final String crs) { double maxy, final String crs) {
add(NATIVEBBMINX, String.valueOf(minx)); add(NATIVEBBMINX, String.valueOf(minx));
add(NATIVEBBMAXY, String.valueOf(maxy)); add(NATIVEBBMAXY, String.valueOf(maxy));
add(NATIVEBBMAXX, String.valueOf(maxx)); add(NATIVEBBMAXX, String.valueOf(maxx));
@ -520,8 +424,8 @@ public abstract class GSResourceEncoder extends PropertyXMLEncoder {
add(NATIVEBBCRS, crs); add(NATIVEBBCRS, crs);
} }
public void setNativeBoundingBox(double minx, double miny, double maxx, double maxy, public void setNativeBoundingBox(double minx, double miny, double maxx,
final String crs) { double maxy, final String crs) {
set(NATIVEBBMINX, String.valueOf(minx)); set(NATIVEBBMINX, String.valueOf(minx));
set(NATIVEBBMAXY, String.valueOf(maxy)); set(NATIVEBBMAXY, String.valueOf(maxy));
set(NATIVEBBMAXX, String.valueOf(maxx)); set(NATIVEBBMAXX, String.valueOf(maxx));

View File

@ -25,11 +25,11 @@
package it.geosolutions.geoserver.rest.encoder; package it.geosolutions.geoserver.rest.encoder;
import org.jdom.Element;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils; import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder; import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
import org.jdom.Element;
/** /**
* *
* @author ETj (etj at geo-solutions.it) * @author ETj (etj at geo-solutions.it)

View File

@ -33,14 +33,18 @@ import org.jdom.filter.Filter;
/** /**
* GSAuthorityURLInfoEncoder - encodes an authorityURL for a given GeoServer * GSAuthorityURLInfoEncoder - encodes an authorityURL for a given GeoServer
* layer as follows: * layer as follows:
*
* <pre> * <pre>
* {@code * {
* &#064;code
* final GSAuthorityURLInfoEncoder ae = new GSAuthorityURLInfoEncoder(); * final GSAuthorityURLInfoEncoder ae = new GSAuthorityURLInfoEncoder();
* ae.setName("an authority"); * ae.setName(&quot;an authority&quot;);
* ae.setHref("http://www.organization.org"); * ae.setHref(&quot;http://www.organization.org&quot;);
* } * }
* </pre> * </pre>
*
* For this example, the XML output is: * For this example, the XML output is:
*
* <pre> * <pre>
* {@code * {@code
* <AuthorityURL> * <AuthorityURL>

View File

@ -25,12 +25,11 @@
package it.geosolutions.geoserver.rest.encoder.coverage; package it.geosolutions.geoserver.rest.encoder.coverage;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder;
import org.jdom.Element; import org.jdom.Element;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder;
import it.geosolutions.geoserver.rest.encoder.dimensions.GSCoverageDimensionEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
/** /**
* Creates an XML * Creates an XML
@ -41,18 +40,13 @@ import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
*/ */
public class GSCoverageEncoder extends GSResourceEncoder { public class GSCoverageEncoder extends GSResourceEncoder {
public final static String NATIVECOVERAGENAME = "nativeCoverageName"; final private static String NATIVE_FORMAT="nativeFormat";
final private static String SUPPORTED_FORMATS="supportedFormats";
private final static String NATIVE_FORMAT="nativeFormat"; final private static String REQUEST_SRS="requestSRS";
private final static String SUPPORTED_FORMATS="supportedFormats"; final private static String RESPONSE_SRS="responseSRS";
private final static String REQUEST_SRS="requestSRS"; final private Element supportedFormatsListEncoder = new Element(SUPPORTED_FORMATS);
private final static String RESPONSE_SRS="responseSRS";
private final Element supportedFormatsListEncoder = new Element(SUPPORTED_FORMATS);
public final static String DIMENSIONS = "dimensions";
final private Element dimensionsEncoder = new Element(DIMENSIONS);
public GSCoverageEncoder() { public GSCoverageEncoder() {
super("coverage"); super("coverage");
@ -77,109 +71,26 @@ public class GSCoverageEncoder extends GSResourceEncoder {
super.setMetadata(key, dimensionInfo); super.setMetadata(key, dimensionInfo);
} }
/**
* Add the 'nativeFormat' node with a text value
*/
public void setNativeFormat(String format) { public void setNativeFormat(String format) {
set(NATIVE_FORMAT, format); set(NATIVE_FORMAT, format);
} }
/**
* Add the 'supportedFormat' node with a text value
*/
public void addSupportedFormats(String format) { public void addSupportedFormats(String format) {
final Element el = new Element("string"); final Element el = new Element("string");
el.setText(format); el.setText(format);
supportedFormatsListEncoder.addContent(el); supportedFormatsListEncoder.addContent(el);
} }
/**
* Add the 'requestSRS' node with a text value
*/
public void setRequestSRS(String srs) { public void setRequestSRS(String srs) {
final Element el = new Element("string"); final Element el = new Element("string");
el.setText(srs); el.setText(srs);
set(REQUEST_SRS, el); set(REQUEST_SRS, el);
} }
/**
* Add the 'responseSRS' node with a text value
*/
public void setResponseSRS(String srs) { public void setResponseSRS(String srs) {
final Element el = new Element("string"); final Element el = new Element("string");
el.setText(srs); el.setText(srs);
set(RESPONSE_SRS, el); set(RESPONSE_SRS, el);
} }
/**
* Adds a CoverageDimensionInfo to the GeoServer Resource
*
* @param coverageDimensionInfo
*
*/
public void addCoverageDimensionInfo(GSCoverageDimensionEncoder coverageDimensionInfo) {
if (ElementUtils.contains(getRoot(), DIMENSIONS) == null)
addContent(dimensionsEncoder);
dimensionsEncoder.addContent(coverageDimensionInfo.getRoot());
}
/**
* Adds quickly a CoverageDimensionInfo to the GeoServer Resource
*
* @param name
* @param description
* @param rangeMin
* @param rangeMax
* @param unit
* @param dimensionType
*/
public void addCoverageDimensionInfo(String name, String description, String rangeMin,
String rangeMax, String unit, String dimensionType) {
final GSCoverageDimensionEncoder coverageDimensionEncoder = new GSCoverageDimensionEncoder(
name, description, rangeMin, rangeMax, unit, dimensionType);
addCoverageDimensionInfo(coverageDimensionEncoder);
}
/**
* Deletes a CoverageDimensionInfo from the list using the CoverageDimension Name (CoverageDimensionInfo content)
*
* @param coverageDimensionName
* @return true if something is removed, false otherwise
*/
public boolean delCoverageDimensionInfo(final String coverageDimensionName) {
return (dimensionsEncoder.removeContent(GSCoverageDimensionEncoder
.getFilterByContent(coverageDimensionName))).size() == 0 ? false : true;
}
/**
* Add the 'nativeCoverageName' node with a text value from 'name'
*
*
*/
public void addNativeCoverageName(final String nativeCoverageName) {
add(NATIVECOVERAGENAME, nativeCoverageName);
}
/**
* Set the 'nativeCoverageName' node with a text value from 'name'
*
*
*/
public void setNativeCoverageName(final String nativeCoverageName) {
set(NATIVECOVERAGENAME, nativeCoverageName);
}
/**
* Get the nativeCoverageName
*
* @return
*/
public String getNativeCoverageName() {
final Element nativeCoverageNameNode = ElementUtils.contains(getRoot(), NATIVECOVERAGENAME, 1);
if (nativeCoverageNameNode != null)
return nativeCoverageNameNode.getText();
else
return null;
}
} }

View File

@ -38,10 +38,8 @@ import org.jdom.filter.Filter;
* Use this encoder for ImageMosaic coverages. * Use this encoder for ImageMosaic coverages.
* *
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* @author Simone Giannecchini, GeoSolutions SAS
* *
*/ */
@SuppressWarnings("unchecked")
public class GSImageMosaicEncoder extends GSCoverageEncoder { public class GSImageMosaicEncoder extends GSCoverageEncoder {
final private static String STRING = "string"; final private static String STRING = "string";
@ -100,7 +98,7 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
return null; return null;
} }
public final static String allowMultithreading = "AllowMultithreading"; private final static String allowMultithreading = "AllowMultithreading";
/** /**
* @param val * @param val
@ -135,10 +133,7 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
return null; return null;
} }
// private final static String filter = "Filter";
// Filter
//
public final static String filter = "Filter";
/** /**
* @param val * @param val
@ -156,24 +151,8 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
removeParameter(filterFilter); removeParameter(filterFilter);
addFilter(val); addFilter(val);
} }
public Boolean getFilter() {
Element el = getParameter(filterFilter);
if (el != null) {
List<Element> values = el.getChildren();
for (Element elm : values) {
String value = elm.getValue();
if (!value.equalsIgnoreCase(filter)) {
return Boolean.valueOf(value);
}
}
}
return null;
}
// private final static String maxAllowedTiles = "MaxAllowedTiles";
// MaxAllowedTiles
//
public final static String maxAllowedTiles = "MaxAllowedTiles";
/** /**
* @param val * @param val
@ -192,25 +171,7 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
addMaxAllowedTiles(val); addMaxAllowedTiles(val);
} }
public Boolean getMaxAllowedTiles() { private final static String inputTransparentColor = "InputTransparentColor";
Element el = getParameter(maxAllowedTilesFilter);
if (el != null) {
List<Element> values = el.getChildren();
for (Element elm : values) {
String value = elm.getValue();
if (!value.equalsIgnoreCase(maxAllowedTiles)) {
return Boolean.valueOf(value);
}
}
}
return null;
}
//
// InputTransparentColor
//
public final static String inputTransparentColor = "InputTransparentColor";
/** /**
* @param val * @param val
@ -230,25 +191,7 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
addInputTransparentColor(val); addInputTransparentColor(val);
} }
public Boolean getInputTransparentColor() { private final static String outputTransparentColor = "OutputTransparentColor";
Element el = getParameter(inputTransparentColorFilter);
if (el != null) {
List<Element> values = el.getChildren();
for (Element elm : values) {
String value = elm.getValue();
if (!value.equalsIgnoreCase(inputTransparentColor)) {
return Boolean.valueOf(value);
}
}
}
return null;
}
//
// OutputTransparentColor
//
public final static String outputTransparentColor = "OutputTransparentColor";
/** /**
* @param val * @param val
@ -267,24 +210,8 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
removeParameter(outputTransparentColorFilter); removeParameter(outputTransparentColorFilter);
addInputTransparentColor(val); addInputTransparentColor(val);
} }
public Boolean getOutputTransparentColor() {
Element el = getParameter(outputTransparentColorFilter);
if (el != null) {
List<Element> values = el.getChildren();
for (Element elm : values) {
String value = elm.getValue();
if (!value.equalsIgnoreCase(outputTransparentColor)) {
return Boolean.valueOf(value);
}
}
}
return null;
}
// private final static String SUGGESTED_TILE_SIZE = "SUGGESTED_TILE_SIZE";
// SUGGESTED_TILE_SIZE
//
public final static String SUGGESTED_TILE_SIZE = "SUGGESTED_TILE_SIZE";
/** /**
* @param val * @param val
@ -319,10 +246,7 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
return null; return null;
} }
// private final static String USE_JAI_IMAGEREAD = "USE_JAI_IMAGEREAD";
// USE_JAI_IMAGEREAD
//
public final static String USE_JAI_IMAGEREAD = "USE_JAI_IMAGEREAD";
/** /**
* @param val * @param val
@ -355,10 +279,7 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
return null; return null;
} }
// private final static String backgroundValues = "BackgroundValues";
// BackgroundValues
//
public final static String backgroundValues = "BackgroundValues";
/** /**
* @param val * @param val
@ -376,62 +297,5 @@ public class GSImageMosaicEncoder extends GSCoverageEncoder {
removeParameter(backgroundValuesFilter); removeParameter(backgroundValuesFilter);
addBackgroundValues(val); addBackgroundValues(val);
} }
public Boolean getBackgroundValues() {
Element el = getParameter(backgroundValuesFilter);
if (el != null) {
List<Element> values = el.getChildren();
for (Element elm : values) {
String value = elm.getValue();
if (!value.equalsIgnoreCase(backgroundValues)) {
return Boolean.valueOf(value);
}
}
}
return null;
}
//
// SORTING
//
public final static String SORTING = "SORTING";
/**
* @param val
*/
protected void addSORTING(final String val) {
final List<Element> list = new ArrayList<Element>(2);
list.add(new Element(STRING).setText(SORTING));
list.add(new Element(STRING).setText(val));
parameters.add(null, list);
}
private final static Filter SORTING_FILTER = new parametersFilter(SORTING);
public void setSORTING(final String val) {
removeParameter(SORTING_FILTER);
addBackgroundValues(val);
}
//
// SORTING
//
public final static String MERGEBEHAVIOR = "MergeBehavior";
/**
* @param val
*/
protected void addMergeBehavior(final String val) {
final List<Element> list = new ArrayList<Element>(2);
list.add(new Element(STRING).setText(MERGEBEHAVIOR));
list.add(new Element(STRING).setText(val));
parameters.add(null, list);
}
private final static Filter MERGEBEHAVIOR_FILTER = new parametersFilter(MERGEBEHAVIOR);
public void setMergeBehavior(final String val) {
removeParameter(MERGEBEHAVIOR_FILTER);
addBackgroundValues(val);
}
} }

View File

@ -125,6 +125,7 @@ public class GSOracleNGDatastoreEncoder extends GSAbstractDatastoreEncoder {
connectionParameters.set("passwd", password); connectionParameters.set("passwd", password);
} }
public void setDatabaseType(String dbtype) { public void setDatabaseType(String dbtype) {
connectionParameters.set("dbtype", dbtype); connectionParameters.set("dbtype", dbtype);
} }

View File

@ -24,13 +24,13 @@
*/ */
package it.geosolutions.geoserver.rest.encoder.datastore; package it.geosolutions.geoserver.rest.encoder.datastore;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
/** /**
* Encoder for a {@value #TYPE} datastore. * Encoder for a {@value #TYPE} datastore.
* *

View File

@ -1,393 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.encoder.dimensions;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.XmlElement;
import org.jdom.Element;
import org.jdom.filter.Filter;
/**
* GSCoverageDimension - encodes a CoverageDimension for a given GeoServer Resource (feature type /coverage), as follows:
*
* <pre>
* {@code
* final GSCoverageDimensionEncoder gsCoverageDimensionEncoder =
* new GSCoverageDimensionEncoder("GRAY_INDEX", "GridSampleDimension[-2.147483648E9,-2.147483648E9]",
* String.valueOf(Integer.MIN_VALUE), String.valueOf(Integer.MAX_VALUE), "dobson units", "REAL_32BITS");
* coverageEncoder.addCoverageDimensionInfo(gsCoverageDimensionEncoder);
* }
* </pre>
*
* For this example, the XML output is:
*
* <pre>
* {@code
* <coverageDimension>
* <name>GRAY_INDEX</name>
* <description>GridSampleDimension[-2.147483648E9,2.147483648E9]</description>
* <range>
* <min>-2.147483648E9</min>
* <max>2.147483647E9</max>
* </range>
* <unit>dobson units</unit>
* <dimensionType>
* <name>REAL_32BITS</name>
* </dimensionType>
* </coverageDimension>
* }
* </pre>
*
* @author Henry Rotzoll (henry.rotzoll@dlr.de)
*
*/
public class GSCoverageDimensionEncoder extends XmlElement {
/**
* A class to filter the GSCoverageDimension by content
*
*
*/
private static class filterByContent implements Filter {
final private String key;
public filterByContent(String content) {
this.key = content;
}
private static final long serialVersionUID = 1L;
public boolean matches(Object obj) {
Element el = ((Element) obj).getChild("name");
if (el != null && el.getTextTrim().equals(key)) {
return true;
}
return false;
}
}
/**
* Get a Filter using the GSCoverageDimensionEncoder content (GSCoverageDimensionEncoder name)
*
* @param content
* @return the filter
*/
public static Filter getFilterByContent(String content) {
return new filterByContent(content);
}
/**
* Constructs a new GSCoverageDimensionEncoder
*
*/
public GSCoverageDimensionEncoder() {
super("coverageDimension");
}
/**
* Constructs quickly a GSCoverageDimensionEncoder info
*
* @param name
* @param description
* @param rangeMin
* @param rangeMax
* @param unit
* @param dimensionTypeName
*/
public GSCoverageDimensionEncoder(String name, String description, String rangeMin,
String rangeMax, String unit, String dimensionTypeName) {
super("coverageDimension");
this.setup(name, description, rangeMin, rangeMax, unit, dimensionTypeName);
}
/**
* Set-up quickly a GSCoverageDimensionEncoder info
*
* @param name
* @param description
* @param rangeMin
* @param rangeMax
* @param unit
* @param dimensionTypeName
*/
protected void setup(String name, String description, String rangeMin, String rangeMax,
String unit, String dimensionTypeName) {
// name
setName(name);
// description
setDescription(description);
// range
setRange(rangeMin, rangeMax);
// unit
setUnit(unit);
// dimension Type
setDimensionType(dimensionTypeName);
}
/**
* Get the value of the GSCoverageDimensionEncoder member
*
* @param memberName
* @return the value of the GSCoverageDimensionEncoder member
*/
protected String getMember(String memberName) {
Element el = this.getRoot().getChild(memberName.toString());
if (el != null)
return el.getTextTrim();
else
return null;
}
/**
* Deletes a GSCoverageDimensionEncoder member
*
* @param memberName
* @return true if the GSCoverageDimensionEncoder member is removed
*/
protected boolean delMemberIfExists(String memberName) {
if (ElementUtils.contains(getRoot(), memberName) != null) {
return ElementUtils.remove(this.getRoot(),
this.getRoot().getChild(memberName.toString()));
}
return false;
}
/**
* Set a GSCoverageDimensionEncoder member
*
* @param memberName
* @param memberValue
*/
protected void setMember(String memberName, String memberValue) {
if (memberName != null && !memberName.isEmpty() && memberValue != null
&& !memberValue.isEmpty()) {
delMemberIfExists(memberName); // delete the element if it already exists
addMember(memberName.toString(), memberValue);
}
}
/**
* adds a GSCoverageDimensionEncoder member
*
* @param memberName
* @param memberValue
*/
protected void addMember(String memberName, String memberValue) {
if (memberName != null && !memberName.isEmpty() && memberValue != null
&& !memberValue.isEmpty()) {
set(memberName.toString(), memberValue);
}
}
/**
* Set the name
*
* @param name
*/
public void setName(String name) {
setMember("name", name);
}
/**
* Deletes the name
*
* @param name
* @return true if removed
*/
public boolean delName() {
return this.delMemberIfExists("name");
}
/**
* Get the description
*
* @return description
*/
public String getName() {
return this.getMember("name");
}
/**
* Set the description
*
* @param description
*/
public void setDescription(String description) {
setMember("description", description);
}
/**
* Deletes the description
*
* @param description
* @return true if removed
*/
public boolean delDescription() {
return this.delMemberIfExists("description");
}
/**
* Get the description
*
* @return description
*/
public String getDescription() {
return this.getMember("description");
}
/**
* Set the range
*
* @param range
*/
public void setRange(String rangeMin, String rangeMax) {
if (rangeMin != null && !rangeMin.isEmpty() && rangeMax != null && !rangeMax.isEmpty()) {
remove("range");
final Element rangeElement = new Element("range");
final Element rangeMinElement = new Element("min");
rangeMinElement.setText(rangeMin);
final Element rangeMaxElement = new Element("max");
rangeMaxElement.setText(rangeMax);
rangeElement.addContent(rangeMinElement);
rangeElement.addContent(rangeMaxElement);
addContent(rangeElement);
}
}
/**
* Deletes the range
*
* @param range
* @return true if removed
*/
public boolean delRange() {
return this.delMemberIfExists("range");
}
/**
* Get the range min
*
* @return range min
*/
public String getRangeMin() {
final Element range = this.getRoot().getChild("range");
if (range != null) {
return range.getChildText("min");
}
return null;
}
/**
* Get the range max
*
* @return range max
*/
public String getRangeMax() {
final Element range = this.getRoot().getChild("range");
if (range != null) {
return range.getChildText("max");
}
return null;
}
/**
* Set the unit
*
* @param unit
*/
public void setUnit(String unit) {
setMember("unit", unit);
}
/**
* Deletes the type
*
* @param type
* @return true if removed
*/
public boolean delUnit() {
return this.delMemberIfExists("unit");
}
/**
* Get the unit
*
* @return unit
*/
public String getUnit() {
return this.getMember("unit");
}
/**
* Set the dimensionType
*
* @param dimensionType
*/
public void setDimensionType(String dimensionTypeName) {
if (dimensionTypeName != null && !dimensionTypeName.isEmpty()) {
remove("dimensionType");
final Element dimensionTypeElement = new Element("dimensionType");
final Element dimensionNameElement = new Element("name");
dimensionNameElement.setText(dimensionTypeName);
dimensionTypeElement.addContent(dimensionNameElement);
addContent(dimensionTypeElement);
}
}
/**
* Deletes the dimensionType
*
* @param dimensionType
* @return true if removed
*/
public boolean delDimensionType() {
return this.delMemberIfExists("dimensionType");
}
/**
* Get the dimensionType name
*
* @return dimensionType name
*/
public String getDimensionTypeName() {
final Element dimensionType = this.getRoot().getChild("dimensionType");
if (dimensionType != null) {
return dimensionType.getChildText("name");
}
return null;
}
}

View File

@ -24,15 +24,15 @@
*/ */
package it.geosolutions.geoserver.rest.encoder.feature; package it.geosolutions.geoserver.rest.encoder.feature;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.filter.Filter; import org.jdom.filter.Filter;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
/** /**
* *
* @author carlo cancellieri - GeoSolutions * @author carlo cancellieri - GeoSolutions

View File

@ -55,13 +55,13 @@ public class GSFeatureTypeEncoder extends GSResourceEncoder {
* @deprecated Use {@link GSResourceEncoder#addMetadataDimension(String, GSDimensionInfoEncoder)} this method will be removed soon * @deprecated Use {@link GSResourceEncoder#addMetadataDimension(String, GSDimensionInfoEncoder)} this method will be removed soon
* @param key * @param key
* @param dimensionInfo * @param dimensionInfo
*
*/ */
protected void addMetadata(String key, GSFeatureDimensionInfoEncoder dimensionInfo) { protected void addMetadata(String key, GSFeatureDimensionInfoEncoder dimensionInfo) {
super.addMetadata(key, dimensionInfo); super.addMetadata(key, dimensionInfo);
} }
/** /**
* @deprecated Use {@link GSResourceEncoder#setMetadataDimension(String, GSDimensionInfoEncoder)} this method will be removed soon * @deprecated Use {@link GSResourceEncoder#setMetadataDimension(String, GSDimensionInfoEncoder)} this method will be removed soon
* @param key * @param key

View File

@ -31,16 +31,20 @@ import org.jdom.Element;
import org.jdom.filter.Filter; import org.jdom.filter.Filter;
/** /**
* GSIdentifierInfoEncoder - encodes an Identifier for a given GeoServer * GSIdentifierInfoEncoder - encodes an Identifier for a given GeoServer layer
* layer as follows: * as follows:
*
* <pre> * <pre>
* {@code * {
* &#064;code
* final GSIdentifierInfoEncoder ie = new GSIdentifierInfoEncoder(); * final GSIdentifierInfoEncoder ie = new GSIdentifierInfoEncoder();
* ie.setAuthority("an authority"); * ie.setAuthority(&quot;an authority&quot;);
* ie.setIdentifier("an identifier"); * ie.setIdentifier(&quot;an identifier&quot;);
* } * }
* </pre> * </pre>
*
* For this example, the XML output is: * For this example, the XML output is:
*
* <pre> * <pre>
* {@code * {@code
* <Identifier> * <Identifier>

View File

@ -32,20 +32,14 @@ import java.math.BigDecimal;
/** /**
* *
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* @author Simone Giannecchini, GeoSolutions
* *
*/ */
public class GSDimensionInfoEncoder extends XmlElement{ public class GSDimensionInfoEncoder extends XmlElement{
public final static String DIMENSIONINFO="dimensionInfo"; public final static String DIMENSIONINFO="dimensionInfo";
public final static String RESOLUTION="resolution"; public final static String RESOLUTION="resolution";
public final static String PRESENTATION="presentation"; public final static String PRESENTATION="presentation";
public final static String UNITS="units";
public final static String UNIT_SYMBOL="unitSymbol";
private boolean enabled; private boolean enabled;
/** /**
@ -53,7 +47,12 @@ public class GSDimensionInfoEncoder extends XmlElement{
*/ */
public enum Presentation { public enum Presentation {
LIST, LIST,
CONTINUOUS_INTERVAL, CONTINUOUS_INTERVAL
}
/**
* Enum for presentation mode which needs arguments
*/
public enum PresentationDiscrete {
DISCRETE_INTERVAL DISCRETE_INTERVAL
} }
@ -82,73 +81,39 @@ public class GSDimensionInfoEncoder extends XmlElement{
this.enabled=Boolean.TRUE; this.enabled=Boolean.TRUE;
} }
/**
* @param pres
*/
protected void addPresentation(final Presentation pres){
if (enabled){
add(PRESENTATION,pres.toString());
}
}
public void setPresentation(final Presentation pres){ public void setPresentation(final Presentation pres){
setPresentation(pres, null); if (enabled){
set(PRESENTATION,pres.toString());
remove(RESOLUTION);
}
} }
/** /**
* @param pres * @param pres
* @param interval * @param interval
*/ */
protected void addPresentation(final Presentation pres, final BigDecimal interval){ protected void addPresentation(final PresentationDiscrete pres, final BigDecimal interval){
if (enabled){ if (enabled){
add(PRESENTATION,pres.toString()); add(PRESENTATION,pres.toString());
if(pres==Presentation.DISCRETE_INTERVAL){
if(pres==Presentation.DISCRETE_INTERVAL&&interval==null){
throw new IllegalArgumentException("Null interval was provided while trying to set the presentation to discrete interval.");
}
add(RESOLUTION,String.valueOf(interval)); add(RESOLUTION,String.valueOf(interval));
} else {
remove(RESOLUTION);
}
} }
} }
public void setPresentation(final Presentation pres, final BigDecimal interval){ public void setPresentation(final PresentationDiscrete pres, final BigDecimal interval){
if (enabled){ if (enabled){
set(PRESENTATION,pres.toString()); set(PRESENTATION,pres.toString());
if(pres==Presentation.DISCRETE_INTERVAL){
if(pres==Presentation.DISCRETE_INTERVAL&&interval==null){
throw new IllegalArgumentException("Null interval was provided while trying to set the presentation to discrete interval.");
}
set(RESOLUTION,String.valueOf(interval)); set(RESOLUTION,String.valueOf(interval));
} else {
remove(RESOLUTION);
}
} }
} }
/**
* Set UoM for this dimension.
*
* <code>null</code> is acceptable and leave this UoM blank.
*
* @param unit UoM for this dimension.
*/
public void setUnit(final String unit){
if(unit==null||unit.length()<=0){
return;
}
if (enabled){
set(UNITS,unit);
}
}
/**
* Set UoM for this dimension.
*
* <code>null</code> is acceptable and leave this UoM blank.
*
* @param unit UoM for this dimension.
*/
public void setUnitSymbol(final String unitSymbol){
if(unitSymbol==null||unitSymbol.length()<=0){
return;
}
if (enabled){
set(UNIT_SYMBOL,unitSymbol);
}
}
} }

View File

@ -28,7 +28,6 @@ package it.geosolutions.geoserver.rest.encoder.metadata;
public class GSFeatureDimensionInfoEncoder extends GSDimensionInfoEncoder { public class GSFeatureDimensionInfoEncoder extends GSDimensionInfoEncoder {
public final static String ATTRIBUTE="attribute"; public final static String ATTRIBUTE="attribute";
public final static String END_ATTRIBUTE="endAttribute";
/** /**
* if this dimension is enabled this constructor should be called. * if this dimension is enabled this constructor should be called.
@ -47,12 +46,6 @@ public class GSFeatureDimensionInfoEncoder extends GSDimensionInfoEncoder {
set(ATTRIBUTE, attribute); set(ATTRIBUTE, attribute);
} }
/**
* Set the end attribute used in the dimension (optional)
* @param endAttribute the dimension end attribute
*/
public void setEndAttribute(final String endAttribute){
set(END_ATTRIBUTE, endAttribute);
}
} }

View File

@ -24,14 +24,14 @@
*/ */
package it.geosolutions.geoserver.rest.encoder.metadata.virtualtable; package it.geosolutions.geoserver.rest.encoder.metadata.virtualtable;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.XmlElement;
import java.util.List; import java.util.List;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.filter.Filter; import org.jdom.filter.Filter;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.XmlElement;
/** /**
* GSVirtualTableEncoder - Encodes a metadata VirtualTable for a GeoServer * GSVirtualTableEncoder - Encodes a metadata VirtualTable for a GeoServer
* featureType. * featureType.

View File

@ -24,12 +24,15 @@
*/ */
package it.geosolutions.geoserver.rest.encoder.metadatalink; package it.geosolutions.geoserver.rest.encoder.metadatalink;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils; import java.util.Map;
import it.geosolutions.geoserver.rest.encoder.utils.XmlElement; import java.util.Map.Entry;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.filter.Filter; import org.jdom.filter.Filter;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.XmlElement;
/** /**
* GSMetadataLinkEncoder - encodes a metadataLink for a given GeoServer Resource * GSMetadataLinkEncoder - encodes a metadataLink for a given GeoServer Resource
* (feature type /coverage), as follows: * (feature type /coverage), as follows:
@ -244,4 +247,5 @@ public class GSMetadataLinkInfoEncoder extends XmlElement {
return this.getMember(ResourceMetadataLinkInfo.content); return this.getMember(ResourceMetadataLinkInfo.content);
} }
} }

View File

@ -100,8 +100,8 @@ public abstract class ElementUtils {
final List<Element> ret = new ArrayList<Element>(); final List<Element> ret = new ArrayList<Element>();
// if match add myself // if match add myself
if (filter.matches(root)) { if (filter.matches(root)) {
if (LOGGER.isTraceEnabled()) if (LOGGER.isDebugEnabled())
LOGGER.trace("LOCATED-> name:" + root.getName() + " text:" LOGGER.debug("LOCATED-> name:" + root.getName() + " text:"
+ root.getText()); + root.getText());
ret.add(root); ret.add(root);
} }
@ -128,8 +128,8 @@ public abstract class ElementUtils {
final List<Element> ret = new ArrayList<Element>(); final List<Element> ret = new ArrayList<Element>();
// if match add myself // if match add myself
if (filter.matches(root)) { if (filter.matches(root)) {
if (LOGGER.isTraceEnabled()) if (LOGGER.isDebugEnabled())
LOGGER.trace("LOCATED-> name:" + root.getName() + " text:" LOGGER.debug("LOCATED-> name:" + root.getName() + " text:"
+ root.getText()); + root.getText());
ret.add(root); ret.add(root);
} }
@ -140,8 +140,8 @@ public abstract class ElementUtils {
if (obj instanceof Element) { if (obj instanceof Element) {
Element el = (Element) obj; Element el = (Element) obj;
if (LOGGER.isTraceEnabled()) if (LOGGER.isDebugEnabled())
LOGGER.trace("LOCATED-> name:" + el.getName() + " text:" LOGGER.debug("LOCATED-> name:" + el.getName() + " text:"
+ el.getText()); + el.getText());
ret.add(el); ret.add(el);

View File

@ -38,7 +38,7 @@ import java.net.URL;
*/ */
public abstract class GeoServerRESTAbstractManager { public abstract class GeoServerRESTAbstractManager {
protected final URL gsBaseUrl; protected final URL restURL;
protected final String gsuser; protected final String gsuser;
protected final String gspass; protected final String gspass;
@ -50,21 +50,17 @@ public abstract class GeoServerRESTAbstractManager {
* @param restURL GeoServer REST API endpoint * @param restURL GeoServer REST API endpoint
* @param username GeoServer REST API authorized username * @param username GeoServer REST API authorized username
* @param password GeoServer REST API password for the former username * @param password GeoServer REST API password for the former username
* @throws MalformedURLException if restURL is malformed
*/ */
public GeoServerRESTAbstractManager(URL restURL, String username, String password) public GeoServerRESTAbstractManager(URL restURL, String username, String password)
throws IllegalArgumentException { throws IllegalArgumentException, MalformedURLException {
try {
if (restURL == null || username == null || password == null) if (restURL == null || username == null || password == null)
throw new IllegalArgumentException("Unable to create the manager using a null argument"); throw new IllegalArgumentException("Unable to create the manager using a null argument");
this.gsBaseUrl = new URL(restURL.getProtocol(), restURL.getHost(), restURL.getPort(), this.restURL = new URL(restURL.getProtocol(), restURL.getHost(), restURL.getPort(),
HTTPUtils.decurtSlash(restURL.getPath()), null); HTTPUtils.decurtSlash(restURL.getPath()), null);
this.gsuser = username; this.gsuser = username;
this.gspass = password; this.gspass = password;
} catch (MalformedURLException ex) {
throw new IllegalArgumentException("URL can't be parsed properly", ex);
}
} }
} }

View File

@ -0,0 +1,98 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.manager;
import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSAbstractDatastoreEncoder;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Manage datastores.
*
* To pass connection parameters, use the encoders derived from {@link GSAbstractDatastoreEncoder}.
*
* @author Oscar Fonts
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
*
* @deprecated currently this is only a {@link GeoServerRESTStoreManager} wrapper for datastore
*/
public class GeoServerRESTDatastoreManager extends GeoServerRESTStoreManager {
/**
* Default constructor.
*
* @param restURL GeoServer REST API endpoint
* @param username GeoServer REST API authorized username
* @param password GeoServer REST API password for the former username
* @throws MalformedURLException
* @throws IllegalArgumentException
*/
public GeoServerRESTDatastoreManager(URL restURL, String username, String password)
throws IllegalArgumentException, MalformedURLException {
super(restURL, username, password);
}
/**
* Create a store.
*
* @param workspace Name of the workspace to contain the store. This will also be the prefix of any layer names contained in the store.
* @param datastore the set of parameters to be set to the store (including connection parameters).
* @return <TT>true</TT> if the store has been successfully created, <TT>false</TT> otherwise
*
* @deprecated use {@link GeoServerRESTStoreManager#create(String, GSAbstractStoreEncoder)}
*/
public boolean create(String workspace, GSAbstractDatastoreEncoder store) {
return super.create(workspace, store);
}
/**
* Update a store.
*
* @param workspace Name of the workspace that contains the store.
* @param datastore the set of parameters to be set to the store (including connection parameters).
* @return <TT>true</TT> if the store has been successfully updated, <TT>false</TT> otherwise
* @deprecated use {@link GeoServerRESTStoreManager#update(String, GSAbstractStoreEncoder)}
*/
public boolean update(String workspace, GSAbstractDatastoreEncoder store) {
return super.update(workspace, store);
}
/**
* Remove a given CoverageStore in a given Workspace.
*
* @param workspace The name of the workspace
* @param storename The name of the CoverageStore to remove.
* @param recurse if remove should be performed recursively
* @return <TT>true</TT> if the CoverageStore was successfully removed.
* @throws MalformedURLException
*/
public boolean remove(final String workspace, final GSAbstractStoreEncoder store,
final boolean recurse) throws IllegalArgumentException, MalformedURLException {
return super.remove(workspace, store, recurse);
}
}

View File

@ -1,321 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.manager;
import it.geosolutions.geoserver.rest.HTTPUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.restlet.data.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Alessio Fabiani, GeoSolutions S.A.S.
*
*/
public class GeoServerRESTImporterManager extends GeoServerRESTAbstractManager {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoServerRESTImporterManager.class);
/**
* Default constructor.
*
* @param restURL GeoServer REST API endpoint
* @param username GeoServer REST API authorized username
* @param password GeoServer REST API password for the former username
*/
public GeoServerRESTImporterManager(URL restURL, String username, String password)
throws IllegalArgumentException {
super(restURL, username, password);
}
/**
* Retrieves the Import JSON Object given its identifier
*
* @param imp int: Import context number ID
*/
public JSONObject getImport(int imp) throws Exception {
JSON json = HTTPUtils.getAsJSON(String.format(buildUrl()+"/%d", imp), gsuser , gspass);
return ((JSONObject)json).getJSONObject("import");
}
/**
* Retrieves the Import Task JSON Object given its identifier and task number
*
* @param imp int: Import context number ID
* @param task int: Task number
*/
public JSONObject getTask(int imp, int task) throws Exception {
JSON json = HTTPUtils.getAsJSON(String.format(buildUrl()+"/%d/tasks/%d?expand=all", imp, task), gsuser , gspass);
return ((JSONObject)json).getJSONObject("task");
}
/**
* Example usage:
* <pre>
* // Creates a new Importer Context and gets back the ID
* int i = postNewImport();
*
* // Attaches to the new Importer Context a Task pointing to a shapefile's zip archive
* int t = postNewTaskAsMultiPartForm(i, "/path_to/shape/archsites_no_crs.zip");
*
* // Check that the Task was actually created and that the CRS has not recognized in this case
* JSONObject task = getTask(i, t);
* assertEquals("NO_CRS", task.getString("state"));
*
* // Prepare the JSON String instructing the Task about the SRS to use
* String json =
* "{" +
* "\"task\": {" +
* "\"layer\": {" +
* "\"srs\": \"EPSG:4326\"" +
* "}" +
* "}" +
* "}";
*
* // Performing the Task update
* putTask(i, t, json);
*
* // Double check that the Task is in the READY state
* task = getTask(i, t);
* assertEquals("READY", task.getString("state"));
* assertEquals("gs_archsites", task.getJSONObject("layer").getJSONObject("style").getString("name"));
*
* // Prepare the JSON String instructing the Task avout the SLD to use for the new Layer
* json =
* "{" +
* "\"task\": {" +
* "\"layer\": {" +
* "\"style\": {" +
* "\"name\": \"point\"" +
* "}" +
* "}" +
* "}" +
* "}";
*
* // Performing the Task update
* putTask(i, t,json);
*
* // Double check that the Task is in the READY state and that the Style has been correctly updated
* task = getTask(i, t);
* assertEquals("READY", task.getString("state"));
* assertEquals("point", task.getJSONObject("layer").getJSONObject("style").getString("name"));
*
* // Finally starts the Import ...
* postImport(i);
* </pre>
*
* @param imp int: Import context number ID
* @param task int: Task number
* @param json String: JSON containing the Task properties to be updated
* @throws Exception
*/
public void putTask(int imp, int task, final String json) throws Exception {
//HTTPUtils.putJson(String.format(buildUrl()+"/%d/tasks/%d", imp, task), json, gsuser, gspass);
HTTPUtils.put(String.format(buildUrl()+"/%d/tasks/%d", imp, task), json, "text/plain", gsuser, gspass);
}
/**
* Just update the Layers properties associated to a Task (t) in the Importer Context (i).
*
* e.g.:
* <pre>
* putTaskLayer(i, t, "{\"title\":\"Archsites\", \"abstract\":\"Archeological Sites\"}");
* </pre>
*
* @param imp int: Import context number ID
* @param task int: Task number
* @param json String: JSON containing the Layer properties to be updated
* @throws Exception
*/
public void putTaskLayer(int imp, int task, final String json) throws Exception {
HTTPUtils.putJson(String.format(buildUrl()+"/%d/tasks/%d/layer", imp, task), json, gsuser, gspass);
}
/**
* Just update the Layers properties associated to a Task (t) in the Importer Context (i).
*
* e.g.:
* <pre>
* putTaskLayer(i, t, "{\"title\":\"Archsites\", \"abstract\":\"Archeological Sites\"}");
* </pre>
*
* @param imp int: Import context number ID
* @param task int: Task number
* @param json String: JSON containing the Layer properties to be updated
* @throws Exception
*/
public void postTaskTransform(int imp, int task, final String json) throws Exception {
HTTPUtils.postJson(String.format(buildUrl()+"/%d/tasks/%d/transforms", imp, task), json, gsuser, gspass);
}
/**
* Creates an empty Importer Context.
*
* @return The new Importer Context ID
* @throws Exception
*/
public int postNewImport() throws Exception {
return postNewImport(null);
}
/**
* e.g.:
* <pre>
* String body =
* "{" +
* "\"import\": { " +
* "\"data\": {" +
* "\"type\": \"mosaic\", " +
* "\"time\": {" +
* " \"mode\": \"auto\"" +
* "}" +
* "}" +
* "}" +
* "}";
* </pre>
*
* @param body JSON String representing the Importer Context definition
* @return The new Importer Context ID
* @throws Exception
*/
public int postNewImport(String body) throws Exception {
String resp = body == null ? HTTPUtils.post(buildUrl(), "", "text/plain", gsuser, gspass)
: HTTPUtils.postJson(buildUrl(), body, gsuser, gspass);
JSONObject json = (JSONObject) HTTPUtils.json(resp);
JSONObject imprt = json.getJSONObject("import");
return imprt.getInt("id");
}
/**
* Actually starts the READY State Import.
*
* @param imp int: Import context number ID
* @throws Exception
*/
public void postImport(int imp) throws Exception {
HTTPUtils.post(buildUrl()+"/" + imp + "?exec=true", "", "text/plain", gsuser, gspass);
}
/**
*
* @param imp int: Import context number ID
* @param data
* @return
* @throws Exception
*/
public int postNewTaskAsMultiPartForm(int imp, String data) throws Exception {
String resp = HTTPUtils.postMultipartForm(buildUrl()+"/" + imp + "/tasks", unpack(data), gsuser, gspass);
JSONObject json = (JSONObject) HTTPUtils.json(resp);
JSONObject task = json.getJSONObject("task");
return task.getInt("id");
}
/**
* Allows to attach a new zip file to an existing Importer Context.
*
* @param imp int: Import context number ID
* @param path
* @return
* @throws Exception
*/
public int putNewTask(int imp, String path) throws Exception {
File zip = new File(path);
String resp = HTTPUtils.put(buildUrl()+"/" + imp + "/tasks/" + zip.getName(), zip, MediaType.APPLICATION_ZIP.toString(), gsuser, gspass);
JSONObject json = (JSONObject) HTTPUtils.json(resp);
JSONObject task = json.getJSONObject("task");
return task.getInt("id");
}
//=========================================================================
// Util methods
//=========================================================================
/**
* Creates the base REST URL for the imports
*/
protected String buildUrl() {
StringBuilder sUrl = new StringBuilder(gsBaseUrl.toString()).append("/rest/imports");
return sUrl.toString();
}
/**
* Creates a temporary file
*
* @return Path to the temporary file
* @throws Exception
*/
public static File tmpDir() throws Exception {
File dir = File.createTempFile("importer", "data", new File("target"));
dir.delete();
dir.mkdirs();
return dir;
}
/**
* Expands a zip archive into the temporary folder.
*
* @param path The absolute path to the source zip file
* @return Path to the temporary folder containing the expanded files
* @throws Exception
*/
public static File unpack(String path) throws Exception {
return unpack(path, tmpDir());
}
/**
* Expands a zip archive into the target folder.
*
* @param path The absolute path to the source zip file
* @param dir Full path of the target folder where to expand the archive
* @return Path to the temporary folder containing the expanded files
* @throws Exception
*/
public static File unpack(String path, File dir) throws Exception {
File file = new File(path);
//new VFSWorker().extractTo(file, dir);
if (!file.delete()) {
// fail early as tests will expect it's deleted
throw new IOException("deletion failed during extraction");
}
return dir;
}
}

View File

@ -25,6 +25,7 @@
package it.geosolutions.geoserver.rest.manager; package it.geosolutions.geoserver.rest.manager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.Format; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.Format;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.StoreType;
import it.geosolutions.geoserver.rest.HTTPUtils; import it.geosolutions.geoserver.rest.HTTPUtils;
import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder; import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSAbstractDatastoreEncoder; import it.geosolutions.geoserver.rest.encoder.datastore.GSAbstractDatastoreEncoder;
@ -52,7 +53,7 @@ public class GeoServerRESTStoreManager extends GeoServerRESTAbstractManager {
* @throws IllegalArgumentException * @throws IllegalArgumentException
*/ */
public GeoServerRESTStoreManager(URL restURL, String username, String password) public GeoServerRESTStoreManager(URL restURL, String username, String password)
throws IllegalArgumentException { throws IllegalArgumentException, MalformedURLException {
super(restURL, username, password); super(restURL, username, password);
} }
@ -68,7 +69,7 @@ public class GeoServerRESTStoreManager extends GeoServerRESTAbstractManager {
* <TT>false</TT> otherwise * <TT>false</TT> otherwise
*/ */
public boolean create(String workspace, GSAbstractStoreEncoder store) { public boolean create(String workspace, GSAbstractStoreEncoder store) {
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/", store.getStoreType().toString(),".",Format.XML.toString()).toString(); String sUrl = HTTPUtils.append(restURL, "/rest/workspaces/", workspace, "/", store.getStoreType().toString(),".",Format.XML.toString()).toString();
String xml = store.toString(); String xml = store.toString();
String result = HTTPUtils.postXml(sUrl, xml, gsuser, gspass); String result = HTTPUtils.postXml(sUrl, xml, gsuser, gspass);
return result != null; return result != null;
@ -84,7 +85,7 @@ public class GeoServerRESTStoreManager extends GeoServerRESTAbstractManager {
* <TT>false</TT> otherwise * <TT>false</TT> otherwise
*/ */
public boolean update(String workspace, GSAbstractStoreEncoder store) { public boolean update(String workspace, GSAbstractStoreEncoder store) {
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace,"/", store.getStoreType().toString(),"/", String sUrl = HTTPUtils.append(restURL, "/rest/workspaces/", workspace,"/", store.getStoreType().toString(),"/",
store.getName(),".",Format.XML.toString()).toString(); store.getName(),".",Format.XML.toString()).toString();
String xml = store.toString(); String xml = store.toString();
String result = HTTPUtils.putXml(sUrl, xml, gsuser, gspass); String result = HTTPUtils.putXml(sUrl, xml, gsuser, gspass);
@ -107,7 +108,7 @@ public class GeoServerRESTStoreManager extends GeoServerRESTAbstractManager {
// if (workspace.isEmpty() || storename.isEmpty()) // if (workspace.isEmpty() || storename.isEmpty())
// throw new IllegalArgumentException("Arguments may not be empty!"); // throw new IllegalArgumentException("Arguments may not be empty!");
final StringBuilder url=HTTPUtils.append(gsBaseUrl,"/rest/workspaces/",workspace,"/", store.getStoreType().toString(), "/",store.getName()); final StringBuffer url=HTTPUtils.append(restURL,"/rest/workspaces/",workspace,"/", store.getStoreType().toString(), "/",store.getName());
if (recurse) if (recurse)
url.append("?recurse=true"); url.append("?recurse=true");
final URL deleteStore = new URL(url.toString()); final URL deleteStore = new URL(url.toString());

View File

@ -1,499 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.manager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.UploadMethod;
import it.geosolutions.geoserver.rest.HTTPUtils;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageGranulesList;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageIndexSchema;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Manage GeoTools StructuredGridCoverageReader. It allows to create a store from a file or harvest the coverages contained in a file, to delete
* granules from an existing coverage and eventually to get information about the granules inside a StructuredGridCoverageReader.
*
* @author Simone Giannecchini, GeoSolutions
*/
public class GeoServerRESTStructuredGridCoverageReaderManager extends GeoServerRESTAbstractManager {
/**
* Option that tells GeoServer whether or not to configure all the coverages for a certain ImageMosaic.
*
* @author Simone Giannecchini, GeoSolutions
*
*/
public enum ConfigureCoveragesOption{
NONE,
ALL;
public static ConfigureCoveragesOption getDefault() {
return ALL;
}
}
/**
* Default logger
*/
private final static Logger LOGGER = LoggerFactory
.getLogger(GeoServerRESTStructuredGridCoverageReaderManager.class);
/**
* Default constructor.
*
* @param restURL GeoServer REST API endpoint
* @param username GeoServer REST API authorized username
* @param password GeoServer REST API password for the former username
* @throws IllegalArgumentException
*/
public GeoServerRESTStructuredGridCoverageReaderManager(URL restURL, String username,
String password) throws IllegalArgumentException {
super(restURL, username, password);
}
/**
* Create a new ImageMosaic with the provided configuration provided as a zip file.
*
* <p>
* This call configures all the coverages contained in the ImageMosaic.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param the absolute path to the file to upload
*
* @return <code>true</code> if the call succeeds or <code>false</code> otherwise.
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public boolean create(String workspace, String coverageStore, String path) {
return create(workspace, coverageStore, path, ConfigureCoveragesOption.ALL);
}
/**
* Create a new ImageMosaic with the provided configuration provided as a zip file.
*
* <p>
* With the options configure we can decide whether or not to configure or not the coverages contained in the ImageMosaic.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param the absolute path to the file to upload
* @param configureOpt tells GeoServer whether to configure all coverages in this mosaic (ALL) or none of them (NONE).
*
* @return <code>true</code> if the call succeeds or <code>false</code> otherwise.
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public boolean create(String workspace, String coverageStore, String path, ConfigureCoveragesOption configureOpt) {
// checks
checkString(workspace);
checkString(coverageStore);
checkString(path);
final File zipFile= new File(path);
if(!zipFile.exists()||!zipFile.isFile()||!zipFile.canRead()){
throw new IllegalArgumentException("The provided pathname does not point to a valide zip file: "+path);
}
// is it a zip?
ZipFile zip=null;
try{
zip= new ZipFile(zipFile);
zip.getName();
}catch (Exception e) {
LOGGER.trace(e.getLocalizedMessage(),e.getStackTrace());
throw new IllegalArgumentException("The provided pathname does not point to a valide zip file: "+path);
}finally{
if(zip!=null){
try {
zip.close();
} catch (IOException e) {
// swallow
LOGGER.trace(e.getLocalizedMessage(),e.getStackTrace());
}
}
}
// create URL
StringBuilder ss=HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/coveragestores/",
coverageStore, "/file.imagemosaic");
switch(configureOpt){
case ALL:
break;
case NONE:
ss.append("?configure=none");
break;
default:
throw new IllegalArgumentException("Unrecognized COnfigureOption: "+configureOpt);
}
String sUrl = ss.toString();
// POST request
String result = HTTPUtils.put(sUrl, zipFile, "application/zip", gsuser, gspass);
return result != null;
}
/**
* Create a store or harvest the coverage from the provided <b>external</b> path.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param format the format of the file to upload
* @param the absolute path to the file to upload
*
* @return <code>true</code> if the call succeeds or <code>false</code> otherwise.
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public boolean harvestExternal(String workspace, String coverageStore, String format,
String path) {
// checks
checkString(workspace);
checkString(coverageStore);
checkString(format);
checkString(path);
// create URL
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/coveragestores/",
coverageStore, "/", UploadMethod.EXTERNAL.toString(), ".", format).toString();
// POST request
String result = HTTPUtils.post(sUrl, "file://" + path, "text/plain", gsuser, gspass);
return result != null;
}
/**
* Check the provided string for not being null or empty.
*
* <p>
* It throws an exception in case the string is either null or empty.
*
* @param string the {@link String} to be checked
*/
private static void checkString(String string) {
if (string == null) {
throw new NullPointerException("Provided string is is null!");
}
if (string.length() <= 0) {
throw new IllegalArgumentException("Provided string is is empty!");
}
}
/**
* Remove granules from a structured coverage, by providing a CQL filter.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param coverage the name of the target coverage from which we are going to remove
* @param filter the absolute path to the file to upload
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public boolean removeGranulesByCQL(final String workspace, String coverageStore,
String coverage, String filter) throws UnsupportedEncodingException {
// checks
checkString(workspace);
checkString(coverage);
checkString(filter);
checkString(coverageStore);
// does it exist?
RESTStructuredCoverageGranulesList granulesList = null;
try {
granulesList = getGranules(workspace, coverageStore, coverage, filter, null, 1);
} catch (MalformedURLException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
} catch (UnsupportedEncodingException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
}
if (granulesList == null || granulesList.isEmpty()) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Granules for filter: " + filter + " does not exist for coverage "
+ coverage);
}
return true; // nothing to remove
}
// method
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/coveragestores",
"/", coverageStore, "/coverages/", coverage, "/index/granules?filter=",
URLEncoder.encode(filter, "UTF-8")).toString();
if (!HTTPUtils.delete(sUrl, gsuser, gspass)) {
return false;
}
// does it exist?
granulesList = null;
try {
granulesList = getGranules(workspace, coverageStore, coverage, filter, null, 1);
} catch (MalformedURLException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
} catch (UnsupportedEncodingException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
}
if (granulesList == null || granulesList.isEmpty()) {
return true; // nothing to remove
}
return false;
}
/**
* Remove a granule from a structured coverage by id.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param coverage the name of the target coverage from which we are going to remove
* @param filter the absolute path to the file to upload
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public boolean removeGranuleById(final String workspace, String coverageStore, String coverage,
String granuleId) {
// checks
checkString(workspace);
checkString(coverage);
checkString(granuleId);
checkString(coverageStore);
// does it exist?
RESTStructuredCoverageGranulesList granule = null;
try {
granule = getGranuleById(workspace, coverageStore, coverage, granuleId);
} catch (MalformedURLException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
} catch (UnsupportedEncodingException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
}
if (granule == null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Granule for id: " + granuleId + " does not exist for coverage "
+ coverage);
}
return true; // nothing to remove
}
// delete
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/coveragestores",
"/", coverageStore, "/coverages/", coverage, "/index/granules/", granuleId)
.toString();
if (!HTTPUtils.delete(sUrl, gsuser, gspass)) {
return false;
}
// has it been canceled?
// does it exist?
granule = null;
try {
granule = getGranuleById(workspace, coverageStore, coverage, granuleId);
} catch (MalformedURLException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
} catch (UnsupportedEncodingException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}
}
if (granule == null) {
return true;
}
return false;
}
/**
* Get information about the schema of the index for a structured coverage.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param format the format of the file to upload
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public RESTStructuredCoverageIndexSchema getGranuleIndexSchema(final String workspace,
String coverageStore, String coverage) throws MalformedURLException {
// checks
checkString(workspace);
checkString(coverage);
checkString(coverageStore);
// create URL and then call it
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/coveragestores/",
coverageStore, "/coverages/", coverage, "/index.xml").toString();
String result = HTTPUtils.get(sUrl, gsuser, gspass);
if (result != null) {
return RESTStructuredCoverageIndexSchema.build(result);
}
return null;
}
/**
* Get information about all the granules for a coverage with optional filter and paging.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param coverage the name of the target coverage
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public RESTStructuredCoverageGranulesList getGranules(final String workspace,
String coverageStore, String coverage)
throws MalformedURLException, UnsupportedEncodingException {
return getGranules(workspace, coverageStore, coverage, null, null, null);
}
/**
* Get information about the granules for a coverage with optional filter and paging.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param coverage the name of the target coverage
* @param filter the format of the file to upload, can be <code>null</code> to include all the granules
* @param offset the start page, can be <code>null</code> or an integer
* @param limit the dimension of the page, can be <code>null</code> or a positive integer
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public RESTStructuredCoverageGranulesList getGranules(final String workspace,
String coverageStore, String coverage, String filter, Integer offset, Integer limit)
throws MalformedURLException, UnsupportedEncodingException {
// checks
checkString(workspace);
checkString(coverage);
checkString(coverageStore);
// method
boolean append = false;
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/coveragestores/",
coverageStore, "/coverages/", coverage, "/index/granules.xml").toString();
if (filter != null && !filter.isEmpty()) {
append = true;
sUrl = HTTPUtils.append(sUrl, "?filter=", URLEncoder.encode(filter, "UTF-8"))
.toString();
}
if (offset != null) {
if (offset < 0)
offset = 0;
sUrl = HTTPUtils.append(sUrl, append ? "&offset=" : "?offset=", offset.toString())
.toString();
append = true;
}
if (limit != null) {
if (limit < 1) {
limit = 1;
}
sUrl = HTTPUtils.append(sUrl, append ? "&limit=" : "?limit=", limit.toString())
.toString();
append = true;
}
String result = HTTPUtils.get(sUrl, gsuser, gspass);
if (result != null) {
return RESTStructuredCoverageGranulesList.build(result);
}
return null;
}
/**
* Get information about a granule for a structured coverage.
*
* @param workspace the GeoServer workspace
* @param coverageStore the GeoServer coverageStore
* @param format the format of the file to upload
* @param the absolute path to the file to upload
* @param id the ID of the granule to get information for
*
* @return <code>null</code> in case the call does not succeed, or an instance of {@link RESTStructuredCoverageGranulesList}.
*
* @throws MalformedURLException
* @throws UnsupportedEncodingException
*
* @since geoserver-2.4.0, geoserver-mng-1.6.0
*/
public RESTStructuredCoverageGranulesList getGranuleById(final String workspace,
String coverageStore, String coverage, String id) throws MalformedURLException,
UnsupportedEncodingException {
// checks
checkString(workspace);
checkString(coverage);
checkString(coverageStore);
checkString(id);
try {
Integer.parseInt(id);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(e);
}
// method
String sUrl = HTTPUtils.append(gsBaseUrl, "/rest/workspaces/", workspace, "/coveragestores/",
coverageStore, "/coverages/", coverage, "/index/granules/", id, ".xml").toString();
String result = HTTPUtils.get(sUrl, gsuser, gspass);
if (result != null) {
return RESTStructuredCoverageGranulesList.build(result);
}
return null;
}
}

View File

@ -1,791 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2015 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.manager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.HTTPUtils;
import it.geosolutions.geoserver.rest.Util;
import it.geosolutions.geoserver.rest.decoder.RESTStyle;
import it.geosolutions.geoserver.rest.decoder.RESTStyleList;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* @author ETj (etj at geo-solutions.it)
*/
public class GeoServerRESTStyleManager extends GeoServerRESTAbstractManager {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoServerRESTStyleManager.class);
/**
* Default constructor.
*
* @param restURL GeoServer REST API endpoint
* @param username GeoServer REST API authorized username
* @param password GeoServer REST API password for the former username
*/
public GeoServerRESTStyleManager(URL restURL, String username, String password)
throws IllegalArgumentException {
super(restURL, username, password);
}
/**
* Check if a Style exists in the configured GeoServer instance.
* @param name the name of the style to check for.
* @return <TT>true</TT> on HTTP 200, <TT>false</TT> on HTTP 404
* @throws RuntimeException if any other HTTP code than 200 or 404 was retrieved.
*/
public boolean existsStyle(String name) throws RuntimeException {
return existsStyle(name, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
/**
* Check if a Style exists in the configured GeoServer instance. User can choose if log a possible exception or not
* @param name the name of the style to check for.
* @param quietOnNotFound if true, mute exception if false is returned
* @return <TT>true</TT> on HTTP 200, <TT>false</TT> on HTTP 404
* @throws RuntimeException if any other HTTP code than 200 or 404 was retrieved.
*/
public boolean existsStyle(String name, boolean quietOnNotFound) {
String url = buildXmlUrl(null, name);
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed , gsuser, gspass);
}
/**
* Get summary info about all Styles.
*
* @return summary info about Styles as a {@link RESTStyleList}
*/
public RESTStyleList getStyles() {
String url = "/rest/styles.xml";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving Styles list from " + url);
}
String response = HTTPUtils.get(gsBaseUrl + url, gsuser, gspass);
return RESTStyleList.build(response);
}
public RESTStyle getStyle(String name) {
String url = buildXmlUrl(null, name);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving Style " + name + " from " + url);
}
String response = HTTPUtils.get(url, gsuser, gspass);
return RESTStyle.build(response);
}
/**
* Get the SLD body of a Style.
*/
public String getSLD(String styleName) {
String url = buildUrl(null, styleName, ".sld");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving SLD body from " + url);
}
return HTTPUtils.get( url, gsuser, gspass);
}
//=========================================================================
// Workspaces
//=========================================================================
/**
*
* @since GeoServer 2.2
*/
public boolean existsStyle(String workspace, String name) {
return existsStyle(workspace, name, Util.DEFAULT_QUIET_ON_NOT_FOUND);
}
/**
*
* @since GeoServer 2.6
*/
public boolean existsStyle(String workspace, String name, boolean quietOnNotFound) {
String url = buildXmlUrl(workspace, name);
String composed = Util.appendQuietOnNotFound(quietOnNotFound, url);
return HTTPUtils.exists(composed , gsuser, gspass);
}
/**
* Get summary info about Styles in a workspace.
*
* @return summary info about Styles as a {@link RESTStyleList}
* @since GeoServer 2.2
*/
public RESTStyleList getStyles(String workspace) {
String url = "/rest/workspaces/"+workspace+"/styles.xml";
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving Styles list from " + url);
}
String response = HTTPUtils.get(gsBaseUrl + url, gsuser, gspass);
return RESTStyleList.build(response);
}
/**
*
* @since GeoServer 2.2
*/
public RESTStyle getStyle(String workspace, String name) {
String url = buildXmlUrl(workspace, name);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving Style " + name + " from " + url);
}
String response = HTTPUtils.get(url, gsuser, gspass);
return RESTStyle.build(response);
}
/**
* Get the SLD body of a Style.
* @since GeoServer 2.2
*/
public String getSLD(String workspace, String name) {
String url = buildUrl(workspace, name, ".sld");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("### Retrieving SLD body from " + url);
}
return HTTPUtils.get(url, gsuser, gspass);
}
//=========================================================================
// Publishing
//=========================================================================
/**
* Store and publish a Style.
*
* @param sldBody the full SLD document as a String.
*
* @return <TT>true</TT> if the operation completed successfully.
*/
public boolean publishStyle(String sldBody) {
/*
* This is the equivalent call with cUrl:
*
* {@code curl -u admin:geoserver -XPOST \ -H 'Content-type: application/vnd.ogc.sld+xml' \ -d @$FULLSLD \
* http://$GSIP:$GSPORT/$SERVLET/rest/styles}
*/
try {
return publishStyle(sldBody, null);
} catch (IllegalArgumentException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(e.getLocalizedMessage(), e);
}
}
return false;
}
/**
* Store and publish a Style, assigning it a name.
*
* @param sldBody the full SLD document as a String.
* @param name the Style name.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the style body is null or empty.
*/
public boolean publishStyle(final String sldBody, final String name)
throws IllegalArgumentException {
/*
* This is the equivalent call with cUrl:
*
* {@code curl -u admin:geoserver -XPOST \ -H 'Content-type: application/vnd.ogc.sld+xml' \ -d @$FULLSLD \
* http://$GSIP:$GSPORT/$SERVLET/rest/styles?name=name}
*/
if (sldBody == null || sldBody.isEmpty()) {
throw new IllegalArgumentException("The style body may not be null or empty");
}
String sUrl = buildPostUrl(null, name);
final String result = HTTPUtils.post(sUrl, sldBody, "application/vnd.ogc.sld+xml", gsuser, gspass);
return result != null;
}
/**
* Store and publish a Style.
*
* @param sldFile the File containing the SLD document.
*
* @return <TT>true</TT> if the operation completed successfully.
*/
public boolean publishStyle(File sldFile) {
return publishStyle(sldFile, null);
}
/**
* Store and publish a Style, assigning it a name.
*
* @param sldFile the File containing the SLD document.
* @param name the Style name.
*
* @return <TT>true</TT> if the operation completed successfully.
*/
public boolean publishStyle(File sldFile, String name) {
String sUrl = buildPostUrl(null, name);
LOGGER.debug("POSTing new style " + name + " to " + sUrl);
String result = HTTPUtils.post(sUrl, sldFile, GeoServerRESTPublisher.Format.SLD.getContentType(), gsuser, gspass);
return result != null;
}
/**
* Store and publish a Style, assigning it a name and choosing the raw
* format.
*
* @param sldBody the full SLD document as a String.
* @param name the Style name.
* @param raw the raw format
*
* @return <TT>true</TT> if the operation completed successfully.
*/
public boolean publishStyle(final String sldBody, final String name, final boolean raw) {
/*
* This is the equivalent call with cUrl:
*
* {@code curl -u admin:geoserver -XPOST \ -H 'Content-type: application/vnd.ogc.sld+xml' \ -d @$FULLSLD \
* http://$GSIP:$GSPORT/$SERVLET/rest/styles?name=$name&raw=$raw}
*/
if (sldBody == null || sldBody.isEmpty()) {
throw new IllegalArgumentException("The style body may not be null or empty");
}
StringBuilder sUrl = new StringBuilder(buildPostUrl(null, name));
Util.appendParameter(sUrl, "raw", ""+raw);
String contentType = GeoServerRESTPublisher.Format.SLD.getContentType();
if(!this.checkSLD10Version(sldBody)){
contentType = GeoServerRESTPublisher.Format.SLD_1_1_0.getContentType();
}
LOGGER.debug("POSTing new style " + name + " to " + sUrl + " using version: " + contentType);
String result = HTTPUtils.post(sUrl.toString(), sldBody, contentType, gsuser, gspass);
return result != null;
}
/**
* Store and publish a Style, assigning it a name and choosing the raw
* format.
*
* @param sldFile the File containing the SLD document.
* @param name the Style name.
* @param raw the raw format
*
* @return <TT>true</TT> if the operation completed successfully.
*/
public boolean publishStyle(final File sldFile, final String name, final boolean raw) {
/*
* This is the equivalent call with cUrl:
*
* {@code curl -u admin:geoserver -XPOST \ -H 'Content-type: application/vnd.ogc.sld+xml' \ -d @$FULLSLD \
* http://$GSIP:$GSPORT/$SERVLET/rest/styles?name=$name&raw=$raw}
*/
StringBuilder sUrl = new StringBuilder(buildPostUrl(null, name));
Util.appendParameter(sUrl, "raw", ""+raw);
String contentType = GeoServerRESTPublisher.Format.SLD.getContentType();
if(!this.checkSLD10Version(sldFile)){
contentType = GeoServerRESTPublisher.Format.SLD_1_1_0.getContentType();
}
LOGGER.debug("POSTing new style " + name + " to " + sUrl + " using version: " + contentType);
String result = HTTPUtils.post(sUrl.toString(), sldFile, contentType, gsuser, gspass);
return result != null;
}
/**
* Update a Style.
*
* @param sldFile the File containing the SLD document.
* @param name the Style name.
* @param raw the raw format
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the style body or name are null or empty.
*/
public boolean updateStyle(final File sldFile, final String name, final boolean raw)
throws IllegalArgumentException {
/*
* This is the equivalent call with cUrl:
*
* {@code curl -u admin:geoserver -XPUT \ -H 'Content-type: application/vnd.ogc.sld+xml' \ -d @$FULLSLD \
* http://$GSIP:$GSPORT/$SERVLET/rest/styles?name=$name&raw=$raw}
*/
if (sldFile == null) {
throw new IllegalArgumentException("Unable to updateStyle using a null parameter file");
} else if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("The style name may not be null or empty");
}
StringBuilder sUrl = new StringBuilder(buildUrl(null, name, null));
Util.appendParameter(sUrl, "raw", ""+raw);
String contentType = GeoServerRESTPublisher.Format.SLD.getContentType();
if(!this.checkSLD10Version(sldFile)){
contentType = GeoServerRESTPublisher.Format.SLD_1_1_0.getContentType();
}
LOGGER.debug("PUTting style " + name + " to " + sUrl + " using version: " + contentType);
String result = HTTPUtils.put(sUrl.toString(), sldFile, contentType, gsuser, gspass);
return result != null;
}
/**
* Update a Style.
*
* @param sldBody the new SLD document as a String.
* @param name the Style name.
* @param raw the raw format
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the style body or name are null or empty.
*/
public boolean updateStyle(final String sldBody, final String name, final boolean raw)
throws IllegalArgumentException {
/*
* This is the equivalent call with cUrl:
*
* {@code curl -u admin:geoserver -XPUT \ -H 'Content-type: application/vnd.ogc.sld+xml' \ -d @$FULLSLD \
* http://$GSIP:$GSPORT/$SERVLET/rest/styles?name=$name&raw=$raw}
*/
if (sldBody == null || sldBody.isEmpty()) {
throw new IllegalArgumentException("The style body may not be null or empty");
} else if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("The style name may not be null or empty");
}
StringBuilder sUrl = new StringBuilder(buildUrl(null, name, null));
Util.appendParameter(sUrl, "raw", ""+raw);
String contentType = GeoServerRESTPublisher.Format.SLD.getContentType();
if(!this.checkSLD10Version(sldBody)){
contentType = GeoServerRESTPublisher.Format.SLD_1_1_0.getContentType();
}
LOGGER.debug("PUTting style " + name + " to " + sUrl + " using version: " + contentType);
String result = HTTPUtils.put(sUrl.toString(), sldBody, contentType, gsuser, gspass);
return result != null;
}
/**
* Update a Style.
*
* @param sldBody the new SLD document as a String.
* @param name the Style name to update.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the style body or name are null or empty.
*/
public boolean updateStyle(final String sldBody, final String name)
throws IllegalArgumentException {
/*
* This is the equivalent call with cUrl:
*
* {@code curl -u admin:geoserver -XPUT \ -H 'Content-type: application/vnd.ogc.sld+xml' \ -d @$FULLSLD \
* http://$GSIP:$GSPORT/$SERVLET/rest/styles/$NAME}
*/
if (sldBody == null || sldBody.isEmpty()) {
throw new IllegalArgumentException("The style body may not be null or empty");
} else if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("The style name may not be null or empty");
}
final String sUrl = buildUrl(null, name, null);
final String result = HTTPUtils.put(sUrl, sldBody, "application/vnd.ogc.sld+xml", gsuser, gspass);
return result != null;
}
/**
* Update a Style.
*
* @param sldFile the File containing the SLD document.
* @param name the Style name.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the sldFile file or name are null or name is empty.
*/
public boolean updateStyle(final File sldFile, final String name)
throws IllegalArgumentException {
if (sldFile == null) {
throw new IllegalArgumentException("Unable to updateStyle using a null parameter file");
} else if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("The style name may not be null or empty");
}
final String sUrl = buildUrl(null, name, null);
final String result = HTTPUtils.put(sUrl, sldFile,
"application/vnd.ogc.sld+xml", gsuser, gspass);
return result != null;
}
/**
* Remove a Style.
* <P>
* The Style will be unpublished, and (optionally) the SLD file will be removed.
*
* @param styleName the name of the Style to remove.
* @param purge remove the related SLD file from disk.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if styleName is null or empty.
*/
public boolean removeStyle(String styleName, final boolean purge)
throws IllegalArgumentException {
if (styleName == null || styleName.isEmpty())
throw new IllegalArgumentException(
"Check styleName parameter, it may never be null or empty");
// check style name
// TODO may we want to throw an exception instead of
// change style name?
if(styleName.contains(":"))
LOGGER.warn("Style name is going to be changed ["+styleName+"]");
styleName = styleName.replaceAll(":", "_");
// currently REST interface does't support URLencoded URL
// styleName = URLEncoder.encode(styleName);
String sUrl = buildUrl(null, styleName, null);
if (purge) {
sUrl += "?purge=true";
}
return HTTPUtils.delete(sUrl, gsuser, gspass);
}
/**
* Remove a Style.
* <P>
* The Style will be unpublished and the related SLD file will be removed.
*
* @param styleName the name of the Style to remove.
*
* @return <TT>true</TT> if the operation completed successfully.
*/
public boolean removeStyle(String styleName) {
try {
return removeStyle(styleName, true);
} catch (IllegalArgumentException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(e.getLocalizedMessage(), e);
}
}
return false;
}
//=========================================================================
// Publishing in workspace
//=========================================================================
/**
* Store and publish a Style.
*
* @param sldBody the full SLD document as a String.
*
* @return <TT>true</TT> if the operation completed successfully.
* @since GeoServer 2.2
*/
public boolean publishStyleInWorkspace(final String workspace, String sldBody) {
try {
return publishStyleInWorkspace(workspace, sldBody, null);
} catch (IllegalArgumentException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(e.getLocalizedMessage(), e);
}
}
return false;
}
/**
* Store and publish a Style, assigning it a name.
*
* @param sldBody the full SLD document as a String.
* @param name the Style name.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the style body is null or empty.
* @since GeoServer 2.2
*/
public boolean publishStyleInWorkspace(final String workspace, final String sldBody, final String name)
throws IllegalArgumentException {
if (sldBody == null || sldBody.isEmpty()) {
throw new IllegalArgumentException("The style body may not be null or empty");
}
String sUrl = buildPostUrl(workspace, name);
final String result = HTTPUtils.post(sUrl, sldBody, "application/vnd.ogc.sld+xml", gsuser, gspass);
return result != null;
}
/**
* Store and publish a Style.
*
* @param sldFile the File containing the SLD document.
*
* @return <TT>true</TT> if the operation completed successfully.
* @since GeoServer 2.2
*/
public boolean publishStyleInWorkspace(final String workspace, File sldFile) {
return publishStyleInWorkspace(workspace, sldFile, null);
}
/**
* Store and publish a Style, assigning it a name.
*
* @param sldFile the File containing the SLD document.
* @param name the Style name.
*
* @return <TT>true</TT> if the operation completed successfully.
* @since GeoServer 2.2
*/
public boolean publishStyleInWorkspace(final String workspace, File sldFile, String name) {
String sUrl = buildPostUrl(workspace, name);
LOGGER.debug("POSTing new style " + name + " to " + sUrl);
String result = HTTPUtils.post(sUrl, sldFile, GeoServerRESTPublisher.Format.SLD.getContentType(), gsuser, gspass);
return result != null;
}
/**
* Update a Style.
*
* @param sldBody the new SLD document as a String.
* @param name the Style name to update.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the style body or name are null or empty.
* @since GeoServer 2.2
*/
public boolean updateStyleInWorkspace(final String workspace, final String sldBody, final String name)
throws IllegalArgumentException {
if (sldBody == null || sldBody.isEmpty()) {
throw new IllegalArgumentException("The style body may not be null or empty");
} else if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("The style name may not be null or empty");
}
final String sUrl = buildUrl(workspace, name, null);
final String result = HTTPUtils.put(sUrl, sldBody,
"application/vnd.ogc.sld+xml", gsuser, gspass);
return result != null;
}
/**
* Update a Style.
*
* @param sldFile the File containing the SLD document.
* @param name the Style name.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if the sldFile file or name are null or name is empty.
* @since GeoServer 2.2
*/
public boolean updateStyleInWorkspace(final String workspace, final File sldFile, final String name)
throws IllegalArgumentException {
if (sldFile == null) {
throw new IllegalArgumentException("Unable to updateStyle using a null parameter file");
} else if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("The style name may not be null or empty");
}
final String sUrl = buildUrl(workspace, name, null);
final String result = HTTPUtils.put(sUrl, sldFile,
"application/vnd.ogc.sld+xml", gsuser, gspass);
return result != null;
}
/**
* Remove a Style.
* <P>
* The Style will be unpublished, and (optionally) the SLD file will be removed.
*
* @param styleName the name of the Style to remove.
* @param purge remove the related SLD file from disk.
*
* @return <TT>true</TT> if the operation completed successfully.
* @throws IllegalArgumentException if styleName is null or empty.
* @since GeoServer 2.2
*/
public boolean removeStyleInWorkspace(final String workspace, String styleName, final boolean purge)
throws IllegalArgumentException {
if (styleName == null || styleName.isEmpty())
throw new IllegalArgumentException(
"Check styleName parameter, it may never be null or empty");
// check style name
// TODO may we want to throw an exception instead of change style name?
if(styleName.contains(":"))
LOGGER.warn("Style name is going to be changed ["+styleName+"]");
styleName = styleName.replaceAll(":", "_");
styleName = URLEncoder.encode(styleName);
String sUrl = buildUrl(workspace, styleName, null);
if (purge) {
sUrl += "?purge=true";
}
return HTTPUtils.delete(sUrl, gsuser, gspass);
}
/**
* Remove a Style.
* <P>
* The Style will be unpublished and the related SLD file will be removed.
*
* @param styleName the name of the Style to remove.
*
* @return <TT>true</TT> if the operation completed successfully.
* @since GeoServer 2.2
*/
public boolean removeStyleInWorkspace(final String workspace, String styleName) {
try {
return removeStyleInWorkspace(workspace, styleName, true);
} catch (IllegalArgumentException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(e.getLocalizedMessage(), e);
}
}
return false;
}
//=========================================================================
// Util methods
//=========================================================================
/**
* Creates a URL for the given stylename with the name in querystring
* @param workspace nullable workspace name
* @param name style name
* @return
*/
protected String buildPostUrl(final String workspace, String name) {
StringBuilder sUrl = new StringBuilder(gsBaseUrl.toString()).append("/rest");
if(workspace != null)
sUrl.append("/workspaces/").append(workspace);
sUrl.append("/styles");
if ( name != null && !name.isEmpty()) {
sUrl.append("?name=").append(URLEncoder.encode(name));
}
return sUrl.toString();
}
protected String buildXmlUrl(final String workspace, final String name) {
return buildUrl(workspace, name, ".xml");
}
/**
* Creates a URL for the given stylename with the name in the REST path
* @param workspace nullable workspace name
* @param name style name
* @param ext nullable output extension (e.g. ".xml" ".sld")
*/
protected String buildUrl(final String workspace, final String name, final String ext) {
StringBuilder sUrl = new StringBuilder(gsBaseUrl.toString()).append("/rest");
if(workspace != null)
sUrl.append("/workspaces/").append(workspace);
sUrl.append("/styles/").append(URLEncoder.encode(name));
if(ext != null)
sUrl.append(ext);
return sUrl.toString();
}
private boolean checkSLD10Version(String sldBody) {
boolean result = false;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(sldBody.getBytes(Charset.forName("UTF-8")));
Document doc = builder.parse(stream);
result = this.checkSLD10Version(doc);
} catch (SAXException ex) {
LOGGER.error("Error parsing SLD file: " + ex);
} catch (IOException ex) {
LOGGER.error("Error parsing SLD file: " + ex);
} catch (ParserConfigurationException ex) {
LOGGER.error("Error parsing SLD file: " + ex);
}
return result;
}
private boolean checkSLD10Version(File fileSLD) {
boolean result = false;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(fileSLD);
result = this.checkSLD10Version(doc);
} catch (SAXException ex) {
LOGGER.error("Error parsing SLD file: " + ex);
} catch (IOException ex) {
LOGGER.error("Error parsing SLD file: " + ex);
} catch (ParserConfigurationException ex) {
LOGGER.error("Error parsing SLD file: " + ex);
}
return result;
}
private boolean checkSLD10Version(Document doc) {
boolean result = false;
try {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//@version='1.0.0'");
result = (Boolean)expr.evaluate(doc, XPathConstants.BOOLEAN);
} catch (XPathExpressionException ex) {
LOGGER.error("Error parsing SLD file: " + ex);
}
return result;
}
}

View File

@ -13,8 +13,6 @@ import junit.framework.Assert;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
/** /**
@ -26,13 +24,12 @@ import org.springframework.core.io.ClassPathResource;
*/ */
public class LayerDecoder21Test { public class LayerDecoder21Test {
private final static Logger LOGGER = LoggerFactory.getLogger(LayerDecoder21Test.class);
RESTLayer21 layer; RESTLayer21 layer;
@Before @Before
public void setUp() throws IOException { public void setUp() throws IOException {
File layerFile = new ClassPathResource("testdata/layerExample21.xml").getFile(); File layerFile = new ClassPathResource("testdata/layerExample21.xml")
.getFile();
String layerString = FileUtils.readFileToString(layerFile); String layerString = FileUtils.readFileToString(layerFile);
layer = (RESTLayer21) RESTLayer21.build(layerString); layer = (RESTLayer21) RESTLayer21.build(layerString);
} }
@ -46,7 +43,7 @@ public class LayerDecoder21Test{
public void testAuthorityURLs() { public void testAuthorityURLs() {
List<GSAuthorityURLInfoEncoder> authorityURLs = layer List<GSAuthorityURLInfoEncoder> authorityURLs = layer
.getEncodedAuthorityURLInfoList(); .getEncodedAuthorityURLInfoList();
LOGGER.debug("Number of authority URLs: " + authorityURLs.size()); System.out.println(authorityURLs.size());
Assert.assertEquals("authority1", authorityURLs.get(0).getName()); Assert.assertEquals("authority1", authorityURLs.get(0).getName());
Assert.assertEquals("http://www.authority1.org", authorityURLs.get(0) Assert.assertEquals("http://www.authority1.org", authorityURLs.get(0)
.getHref()); .getHref());
@ -65,5 +62,4 @@ public class LayerDecoder21Test{
Assert.assertEquals("identifier2", authorityURLs.get(1).getIdentifier()); Assert.assertEquals("identifier2", authorityURLs.get(1).getIdentifier());
} }
} }

View File

@ -1,7 +1,6 @@
package it.geosolutions.geoserver.decoder; package it.geosolutions.geoserver.decoder;
import it.geosolutions.geoserver.rest.decoder.RESTLayer; import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import it.geosolutions.geoserver.rest.decoder.RESTStyleList;
import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEncoder; import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder; import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder;
@ -27,7 +26,8 @@ public class LayerDecoderTest {
@Before @Before
public void setUp() throws IOException { public void setUp() throws IOException {
File layerFile = new ClassPathResource("testdata/layerExample.xml").getFile(); File layerFile = new ClassPathResource("testdata/layerExample.xml")
.getFile();
String layerString = FileUtils.readFileToString(layerFile); String layerString = FileUtils.readFileToString(layerFile);
layer = RESTLayer.build(layerString); layer = RESTLayer.build(layerString);
} }
@ -67,14 +67,6 @@ public class LayerDecoderTest {
Assert.assertEquals("capitals", layer.getDefaultStyle()); Assert.assertEquals("capitals", layer.getDefaultStyle());
} }
@Test
public void testStyles() {
RESTStyleList styles = layer.getStyles();
Assert.assertTrue(styles.size() == 2);
Assert.assertEquals("green", styles.get(0).getName());
Assert.assertEquals("blue", styles.get(1).getName());
}
@Test @Test
public void testResourceUrl() { public void testResourceUrl() {
Assert.assertEquals( Assert.assertEquals(

View File

@ -23,6 +23,8 @@ package it.geosolutions.geoserver.decoder;
import it.geosolutions.geoserver.rest.decoder.RESTCoverage; import it.geosolutions.geoserver.rest.decoder.RESTCoverage;
import it.geosolutions.geoserver.rest.decoder.RESTDimensionInfo; import it.geosolutions.geoserver.rest.decoder.RESTDimensionInfo;
import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.ResourceMetadataLinkInfo;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;

View File

@ -1,8 +1,6 @@
package it.geosolutions.geoserver.decoder; package it.geosolutions.geoserver.decoder;
import it.geosolutions.geoserver.rest.decoder.RESTBoundingBox;
import it.geosolutions.geoserver.rest.decoder.RESTCoverage; import it.geosolutions.geoserver.rest.decoder.RESTCoverage;
import it.geosolutions.geoserver.rest.encoder.dimensions.GSCoverageDimensionEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder;
import java.io.File; import java.io.File;
@ -19,16 +17,17 @@ import org.springframework.core.io.ClassPathResource;
* ResourceDecoderTest * ResourceDecoderTest
* *
* @author eblondel * @author eblondel
* @author Henry Rotzoll (henry.rotzoll@dlr.de)
* *
*/ */
public class ResourceDecoderTest { public class ResourceDecoderTest {
RESTCoverage coverage; RESTCoverage coverage;
@Before @Before
public void setup() throws IOException { public void setup() throws IOException {
File coverageFile = new ClassPathResource("testdata/coverageExample.xml").getFile(); File coverageFile = new ClassPathResource(
"testdata/coverageExample.xml").getFile();
String coverageString = FileUtils.readFileToString(coverageFile); String coverageString = FileUtils.readFileToString(coverageFile);
coverage = RESTCoverage.build(coverageString); coverage = RESTCoverage.build(coverageString);
} }
@ -78,21 +77,11 @@ public class ResourceDecoderTest {
@Test @Test
public void testStoreUrl() { public void testStoreUrl() {
Assert.assertEquals(coverage.getStoreUrl(), Assert.assertEquals(
coverage.getStoreUrl(),
"http://localhost:8080/geoserver/rest/workspaces/topp/coveragestores/granuleTestMosaic.xml"); "http://localhost:8080/geoserver/rest/workspaces/topp/coveragestores/granuleTestMosaic.xml");
} }
@Test
public void testNativeCRS() {
String expectedCrs = "GEOGCS[\"WGS 84\", \r\n DATUM[\"World Geodetic\n System 1984\", \r\n"
+" SPHEROID[\"WGS 84\", 6378137.0,\n 298.257223563,\n AUTHORITY[\"EPSG\",\"7030\"]], \r\n"
+" AUTHORITY[\"EPSG\",\"6326\"]], \r\n PRIMEM[\"Greenwich\", 0.0,\n AUTHORITY[\"EPSG\",\"8901\"]], \r\n"
+" UNIT[\"degree\", 0.017453292519943295], \r\n AXIS[\"Geodetic longitude\", EAST], \r\n"
+" AXIS[\"Geodetic\n latitude\", NORTH], \r\n AUTHORITY[\"EPSG\",\"4326\"]]";
Assert.assertEquals(expectedCrs, coverage.getNativeCRS());
}
@Test @Test
public void testCRS() { public void testCRS() {
Assert.assertEquals(coverage.getCRS(), "EPSG:4326"); Assert.assertEquals(coverage.getCRS(), "EPSG:4326");
@ -106,59 +95,26 @@ public class ResourceDecoderTest {
Assert.assertEquals(coverage.getMaxY(), 90, 0); Assert.assertEquals(coverage.getMaxY(), 90, 0);
} }
@Test
public void testLatLonBoundingBox() {
RESTBoundingBox bbox = coverage.getLatLonBoundingBox();
Assert.assertTrue(bbox != null);
Assert.assertEquals("EPSG:4326", bbox.getCRS());
Assert.assertEquals(-180.0, bbox.getMinX(), 0);
Assert.assertEquals(180.0, bbox.getMaxX(), 0);
Assert.assertEquals(-90, bbox.getMinY(), 0);
Assert.assertEquals(90, bbox.getMaxY(), 0);
}
@Test
public void testNativeBoundingBox() {
RESTBoundingBox bbox = coverage.getNativeBoundingBox();
Assert.assertTrue(bbox != null);
Assert.assertEquals("EPSG:4326", bbox.getCRS());
Assert.assertEquals(-180.0, bbox.getMinX(), 0);
Assert.assertEquals(180.0, bbox.getMaxX(), 0);
Assert.assertEquals(-90, bbox.getMinY(), 0);
Assert.assertEquals(90, bbox.getMaxY(), 0);
}
@Test @Test
public void testMetadataLinkInfo() throws IOException { public void testMetadataLinkInfo() throws IOException {
List<GSMetadataLinkInfoEncoder> list = coverage.getEncodedMetadataLinkInfoList(); List<GSMetadataLinkInfoEncoder> list = coverage
.getEncodedMetadataLinkInfoList();
GSMetadataLinkInfoEncoder metadataLinkInfo1 = list.get(0); GSMetadataLinkInfoEncoder metadataLinkInfo1 = list.get(0);
Assert.assertEquals("text/xml", metadataLinkInfo1.getType()); Assert.assertEquals("text/xml", metadataLinkInfo1.getType());
Assert.assertEquals("ISO19115:2003", metadataLinkInfo1.getMetadataType()); Assert.assertEquals("ISO19115:2003",
Assert.assertEquals("http://www.organization.org/metadata1", metadataLinkInfo1.getContent()); metadataLinkInfo1.getMetadataType());
Assert.assertEquals("http://www.organization.org/metadata1",
metadataLinkInfo1.getContent());
GSMetadataLinkInfoEncoder metadataLinkInfo2 = list.get(1); GSMetadataLinkInfoEncoder metadataLinkInfo2 = list.get(1);
Assert.assertEquals("text/html", metadataLinkInfo2.getType()); Assert.assertEquals("text/html", metadataLinkInfo2.getType());
Assert.assertEquals("ISO19115:2003", metadataLinkInfo2.getMetadataType()); Assert.assertEquals("ISO19115:2003",
Assert.assertEquals("http://www.organization.org/metadata2", metadataLinkInfo2.getContent()); metadataLinkInfo2.getMetadataType());
Assert.assertEquals("http://www.organization.org/metadata2",
metadataLinkInfo2.getContent());
} }
@Test
public void testCoverageDimension() throws IOException {
List<GSCoverageDimensionEncoder> list = coverage.getEncodedDimensionsInfoList();
GSCoverageDimensionEncoder coverageDimension1 = list.get(0);
Assert.assertEquals("GRAY_INDEX", coverageDimension1.getName());
Assert.assertEquals("GridSampleDimension[-Infinity,Infinity]",
coverageDimension1.getDescription());
Assert.assertEquals("-inf", coverageDimension1.getRangeMin());
Assert.assertEquals("inf", coverageDimension1.getRangeMax());
// Assert.assertEquals("dobson units", coverageDimension1.getUnit());
Assert.assertTrue(coverageDimension1.getUnit().startsWith("dobson units"));
Assert.assertEquals("REAL_32BITS", coverageDimension1.getDimensionTypeName());
}
} }

View File

@ -21,8 +21,11 @@
*/ */
package it.geosolutions.geoserver.decoder; package it.geosolutions.geoserver.decoder;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import it.geosolutions.geoserver.rest.GeoserverRESTTest; import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder; import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder.VERSION;
import junit.framework.Assert; import junit.framework.Assert;
import org.jdom.Element; import org.jdom.Element;
@ -75,10 +78,10 @@ public class VersionDecoderTest extends GeoserverRESTTest {
if (!enabled()) if (!enabled())
return; return;
GSVersionDecoder geoserver = reader.getGeoserverVersion(); GSVersionDecoder geoserver = reader.getGeoserverVersion();
if (GSVersionDecoder.VERSION.v22.equals(GSVersionDecoder.VERSION.getVersion(GS_VERSION))) { if (GSVersionDecoder.VERSION.v22.equals(GSVersionDecoder.VERSION.getVersion(VERSION))) {
Assert.assertEquals(geoserver.getVersion(), GSVersionDecoder.VERSION.v22); Assert.assertEquals(geoserver.getVersion(), GSVersionDecoder.VERSION.v22);
} else if (GSVersionDecoder.VERSION.UNRECOGNIZED.equals(GSVersionDecoder.VERSION } else if (GSVersionDecoder.VERSION.UNRECOGNIZED.equals(GSVersionDecoder.VERSION
.getVersion(GS_VERSION))) { .getVersion(VERSION))) {
Assert.assertEquals(geoserver.getVersion(), GSVersionDecoder.VERSION.UNRECOGNIZED); Assert.assertEquals(geoserver.getVersion(), GSVersionDecoder.VERSION.UNRECOGNIZED);
} }
// print(dec.getRoot()); // print(dec.getRoot());

View File

@ -1,85 +0,0 @@
package it.geosolutions.geoserver.decoder;
import it.geosolutions.geoserver.rest.decoder.RESTWmsStore;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
/**
* WmsStoreDecoderTest
*
* @author cip (cippinofg at gmail.com)
*
*/
public class WmsStoreDecoderTest {
RESTWmsStore wmsstore;
@Before
public void setup() throws IOException {
File wmsstoreFile = new ClassPathResource("testdata/wmsstoreExample.xml").getFile();
String wmsstoreContent = FileUtils.readFileToString(wmsstoreFile);
wmsstore = RESTWmsStore.build(wmsstoreContent);
}
@Test
public void testName() {
Assert.assertEquals(wmsstore.getName(), "wmsstore001");
}
@Test
public void testType() {
Assert.assertEquals(wmsstore.getType(), "WMS");
}
@Test
public void testEnabled() {
Assert.assertEquals(wmsstore.getEnabled(), true);
}
@Test
public void testWorkspace() {
Assert.assertEquals(wmsstore.getWorkspaceName(), "ws001");
}
@Test
public void testUseConnectionPooling() {
Assert.assertEquals(wmsstore.getUseConnectionPooling(),true);
}
@Test
public void testCapabilitiesURL() {
Assert.assertEquals(wmsstore.getCapabilitiesURL(), "http://myhost/geoserver/wms");
}
@Test
public void testUser() {
Assert.assertEquals(wmsstore.getUser(), "admin");
}
@Test
public void testPassword() {
Assert.assertEquals(wmsstore.getPassword(), "geoserver");
}
@Test
public void testMaxConnections() {
Assert.assertEquals(wmsstore.getMaxConnections(), "6");
}
@Test
public void testReadTimeout() {
Assert.assertEquals(wmsstore.getReadTimeout(), "60");
}
@Test
public void testConnectTimeout() {
Assert.assertEquals(wmsstore.getConnectTimeout(), "30");
}
}

View File

@ -36,13 +36,16 @@ import java.io.IOException;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
/** /**
* Testcase for publishing layers on geoserver. * Testcase for publishing layers on geoserver.
* We need a running GeoServer to properly run the tests.
* Login credentials are hardcoded at the moment (localhost:8080 admin/geoserver).
* If such geoserver instance cannot be contacted, tests will be skipped.
*
* *
* @author etj * @author etj
*/ */
@ -51,6 +54,25 @@ public class ConfigTest extends GeoserverRESTTest {
private static final String DEFAULT_WS = "geosolutions"; private static final String DEFAULT_WS = "geosolutions";
// @Test
// public void testEtj() throws FileNotFoundException, IOException {
// if(!enabled()){
// LOGGER.info("Skipping test "+"testEtj"+"for class:"+this.getClass().getSimpleName());
// return;
// }
// deleteAll();
//
// assertTrue(reader.getWorkspaces().isEmpty());
// assertTrue(publisher.createWorkspace(DEFAULT_WS));
//
// insertStyles();
// insertExternalGeotiff();
// insertExternalShape();
//
// boolean ok = publisher.publishDBLayer(DEFAULT_WS, "pg_kids", "easia_gaul_0_aggr", "EPSG:4326", "default_polygon");
//// assertTrue(ok);
// }
@Test @Test
public void insertStyles() throws FileNotFoundException, IOException { public void insertStyles() throws FileNotFoundException, IOException {
if(!enabled()){ if(!enabled()){
@ -64,7 +86,7 @@ public class ConfigTest extends GeoserverRESTTest {
LOGGER.info("Existing styles: " + reader.getStyles().getNames()); LOGGER.info("Existing styles: " + reader.getStyles().getNames());
String basename = FilenameUtils.getBaseName(sldFile.toString()); String basename = FilenameUtils.getBaseName(sldFile.toString());
LOGGER.info("Publishing style " + sldFile + " as " + basename); LOGGER.info("Publishing style " + sldFile + " as " + basename);
assertTrue("Could not publish " + sldFile, publisher.publishStyle(sldFile, basename)); assertTrue("Cound not publish " + sldFile, publisher.publishStyle(sldFile, basename));
} }
} }

View File

@ -1,60 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest;
import static org.junit.Assert.*;
import java.util.List;
import it.geosolutions.geoserver.rest.decoder.RESTLayerGroup;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple class for testing that the DeleteAllLayerGroups() method behaves correctly.
*
* @author Nicola Lagomarsini
*/
public class GeoServerRESTClassTest extends GeoserverRESTTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTTest.class);;
@Test
public void testGetLayerGroups() {
if(!enabled()){
return;
}
List<String> groups = reader.getLayerGroups().getNames();
LOGGER.info("Found " + groups.size() + " layerGroups");
for (String groupName : groups) {
RESTLayerGroup group = reader.getLayerGroup(groupName);
if (groups != null) {
assertNotNull(group.getPublishedList());
}
}
}
}

View File

@ -35,10 +35,6 @@ import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
/** /**
@ -47,8 +43,6 @@ import static org.junit.Assert.*;
*/ */
public class GeoserverRESTReaderTest extends GeoserverRESTTest { public class GeoserverRESTReaderTest extends GeoserverRESTTest {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTReaderTest.class);
/** /**
* Test of getLayers method, of class GeoServerRESTReader. * Test of getLayers method, of class GeoServerRESTReader.
*/ */
@ -61,16 +55,16 @@ public class GeoserverRESTReaderTest extends GeoserverRESTTest {
// assertEquals(/*CHANGEME*/19, result.getChildren("layer").size()); // value in default gs installation // assertEquals(/*CHANGEME*/19, result.getChildren("layer").size()); // value in default gs installation
// System.out.println("Layers:" + result.getChildren("layer").size()); // System.out.println("Layers:" + result.getChildren("layer").size());
LOGGER.debug("Layers: " + result.size()); System.out.println("Layers:" + result.size());
// LOGGER.debug("Layers:" ); System.out.print("Layers:" );
for (NameLinkElem shlayer : result) { for (NameLinkElem shlayer : result) {
assertNotNull(shlayer.getName()); assertNotNull(shlayer.getName());
LOGGER.debug(shlayer.getName() + " "); System.out.print(shlayer.getName() + " ");
} }
// for (Element layer : (List<Element>)result.getChildren("layer")) { // for (Element layer : (List<Element>)result.getChildren("layer")) {
// System.out.print(layer.getChildText("name") + " "); // System.out.print(layer.getChildText("name") + " ");
// } // }
LOGGER.debug(""); System.out.println();
} }
/** /**
@ -84,25 +78,25 @@ public class GeoserverRESTReaderTest extends GeoserverRESTTest {
assertNotNull(wslist); assertNotNull(wslist);
// assertEquals(7, wslist.size()); // value in default gs installation // assertEquals(7, wslist.size()); // value in default gs installation
LOGGER.debug("Workspaces: " + wslist.size()); System.out.println("Workspaces: " + wslist.size());
int dsnum = 0; int dsnum = 0;
for (RESTWorkspaceList.RESTShortWorkspace ws : wslist) { for (RESTWorkspaceList.RESTShortWorkspace ws : wslist) {
LOGGER.debug("Getting DSlist for WS " + ws.getName() + "..." ); System.out.println("Getting DSlist for WS " + ws.getName() + "..." );
RESTDataStoreList result = reader.getDatastores(ws.getName()); RESTDataStoreList result = reader.getDatastores(ws.getName());
assertNotNull(result); assertNotNull(result);
dsnum += result.size(); dsnum += result.size();
for (NameLinkElem ds : result) { for (NameLinkElem ds : result) {
assertNotNull(ds.getName()); assertNotNull(ds.getName());
LOGGER.debug(ds.getName() + " " ); System.out.print(ds.getName() + " " );
RESTDataStore datastore = reader.getDatastore(ws.getName(), ds.getName()); RESTDataStore datastore = reader.getDatastore(ws.getName(), ds.getName());
assertNotNull(datastore); assertNotNull(datastore);
assertEquals(ds.getName(), datastore.getName()); assertEquals(ds.getName(), datastore.getName());
assertEquals(ws.getName(), datastore.getWorkspaceName()); assertEquals(ws.getName(), datastore.getWorkspaceName());
} }
LOGGER.debug(""); System.out.println();
} }
LOGGER.debug(""); System.out.println();
LOGGER.debug("Datastores:" + dsnum); // value in default gs installation System.out.println("Datastores:" + dsnum); // value in default gs installation
// assertEquals(4, dsnum); // value in default gs installation // assertEquals(4, dsnum); // value in default gs installation
} }
@ -121,6 +115,7 @@ public class GeoserverRESTReaderTest extends GeoserverRESTTest {
// assertEquals(7, wsnames.size()); // value in default gs installation // assertEquals(7, wsnames.size()); // value in default gs installation
// System.out.println("Workspaces: " + wslist.size()); // System.out.println("Workspaces: " + wslist.size());
int dsnum = 0;
int wscnt = 0; int wscnt = 0;
for (RESTWorkspaceList.RESTShortWorkspace ws : wslist) { for (RESTWorkspaceList.RESTShortWorkspace ws : wslist) {
String wsname = wsnames.get(wscnt++); String wsname = wsnames.get(wscnt++);
@ -162,14 +157,14 @@ public class GeoserverRESTReaderTest extends GeoserverRESTTest {
assertNotNull(names); assertNotNull(names);
assertEquals(names.size(), result.size()); // value in default gs installation assertEquals(names.size(), result.size()); // value in default gs installation
LOGGER.debug("Namespaces:" + result.size()); System.out.println("Namespaces:" + result.size());
LOGGER.debug("Namespaces:" ); System.out.print("Namespaces:" );
int namesIdx = 0; int namesIdx = 0;
for (RESTNamespaceList.RESTShortNamespace ns : result) { for (RESTNamespaceList.RESTShortNamespace ns : result) {
assertEquals("namespace mismatch", names.get(namesIdx++), ns.getName()); assertEquals("namespace mismatch", names.get(namesIdx++), ns.getName());
LOGGER.debug(ns.getName() + " " ); System.out.print(ns.getName() + " " );
} }
LOGGER.debug(""); System.out.println();
} }
/** /**
@ -183,12 +178,12 @@ public class GeoserverRESTReaderTest extends GeoserverRESTTest {
assertNotNull(names); assertNotNull(names);
// assertEquals(7, names.size()); // value in default gs installation // assertEquals(7, names.size()); // value in default gs installation
LOGGER.debug("Namespaces:" + names.size()); System.out.println("Namespaces:" + names.size());
LOGGER.debug("Namespaces:"); System.out.print("Namespaces:");
for (String name : names) { for (String name : names) {
LOGGER.debug(name + " "); System.out.print(name + " ");
} }
LOGGER.debug(""); System.out.println();
} }
/** /**
@ -202,12 +197,12 @@ public class GeoserverRESTReaderTest extends GeoserverRESTTest {
assertNotNull(wslist); assertNotNull(wslist);
// assertEquals(7, wslist.size()); // value in default gs installation // assertEquals(7, wslist.size()); // value in default gs installation
LOGGER.debug("Workspaces:" + wslist.size()); System.out.println("Workspaces:" + wslist.size());
LOGGER.debug("Workspaces:"); System.out.print("Workspaces:");
for (RESTWorkspaceList.RESTShortWorkspace ws : wslist) { for (RESTWorkspaceList.RESTShortWorkspace ws : wslist) {
LOGGER.debug(ws.getName() + " "); System.out.print(ws.getName() + " ");
} }
LOGGER.debug(""); System.out.println();
assertEquals(wslist.size(), reader.getWorkspaceNames().size()); assertEquals(wslist.size(), reader.getWorkspaceNames().size());
} }
@ -222,12 +217,12 @@ public class GeoserverRESTReaderTest extends GeoserverRESTTest {
assertNotNull(names); assertNotNull(names);
// assertEquals(7, names.size()); // value in default gs installation // assertEquals(7, names.size()); // value in default gs installation
LOGGER.debug("Workspaces:" + names.size()); System.out.println("Workspaces:" + names.size());
LOGGER.debug("Workspaces:"); System.out.print("Workspaces:");
for (String name : names) { for (String name : names) {
LOGGER.debug(name + " "); System.out.print(name + " ");
} }
LOGGER.debug(""); System.out.println();
} }
} }

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007 - 2016 GeoSolutions S.A.S. * Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -32,20 +32,14 @@ import it.geosolutions.geoserver.rest.decoder.RESTFeatureType;
import it.geosolutions.geoserver.rest.decoder.RESTLayer; import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import it.geosolutions.geoserver.rest.decoder.RESTLayerGroup; import it.geosolutions.geoserver.rest.decoder.RESTLayerGroup;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder; import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder.VERSION;
import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem; import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -64,12 +58,9 @@ import org.slf4j.LoggerFactory;
* @author etj * @author etj
* @author carlo cancellieri - GeoSolutions * @author carlo cancellieri - GeoSolutions
*/ */
public abstract class GeoserverRESTTest { public abstract class GeoserverRESTTest extends Assert {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTTest.class); private final static Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTTest.class);
@Rule
public TestName _testName = new TestName();
public static final String DEFAULT_WS = "geosolutions"; public static final String DEFAULT_WS = "geosolutions";
public static final String RESTURL; public static final String RESTURL;
@ -79,7 +70,7 @@ public abstract class GeoserverRESTTest {
public static final String RESTPW; public static final String RESTPW;
// geoserver target version // geoserver target version
public static final String GS_VERSION; public static final String VERSION;
public static URL URL; public static URL URL;
@ -97,7 +88,7 @@ public abstract class GeoserverRESTTest {
RESTURL = getenv("gsmgr_resturl", "http://localhost:8080/geoserver"); RESTURL = getenv("gsmgr_resturl", "http://localhost:8080/geoserver");
RESTUSER = getenv("gsmgr_restuser", "admin"); RESTUSER = getenv("gsmgr_restuser", "admin");
RESTPW = getenv("gsmgr_restpw", "geoserver"); RESTPW = getenv("gsmgr_restpw", "geoserver");
GS_VERSION = getenv("gsmgr_version", "2.8"); VERSION = getenv("gsmgr_version", "2.4");
// These tests will destroy data, so let's make sure we do want to run them // These tests will destroy data, so let's make sure we do want to run them
enabled = getenv("gsmgr_resttest", "false").equalsIgnoreCase("true"); enabled = getenv("gsmgr_resttest", "false").equalsIgnoreCase("true");
@ -116,9 +107,9 @@ public abstract class GeoserverRESTTest {
private static String getenv(String envName, String envDefault) { private static String getenv(String envName, String envDefault) {
String env = System.getenv(envName); String env = System.getenv(envName);
String prop = System.getProperty(envName, env); String ret = System.getProperty(envName, env);
LOGGER.debug("varname " + envName + " --> env:" + env + " prop:"+prop); LOGGER.debug("env var " + envName + " is " + ret);
return prop != null ? prop : envDefault; return ret != null ? ret : envDefault;
} }
@BeforeClass @BeforeClass
@ -134,31 +125,21 @@ public abstract class GeoserverRESTTest {
LOGGER.info("Using geoserver instance " + RESTUSER + ":" + RESTPW + " @ " LOGGER.info("Using geoserver instance " + RESTUSER + ":" + RESTPW + " @ "
+ RESTURL); + RESTURL);
} }
} else if (existgs == false){ } else {
LOGGER.debug("Failing tests : geoserver not found"); System.out.println("Failing tests : geoserver not found");
fail("GeoServer not found"); fail("GeoServer not found");
} }
GSVersionDecoder v=reader.getGeoserverVersion(); GSVersionDecoder v=reader.getGeoserverVersion();
if (v.compareTo(VERSION.getVersion(GS_VERSION))!=0){ if (!v.getVersion().equals(GSVersionDecoder.VERSION.getVersion(VERSION))){
LOGGER.debug("Failing tests : geoserver version does not match.\nAccepted versions: "+VERSION.print()); System.out.println("Failing tests : geoserver version does not match.\nAccepted versions: "+GSVersionDecoder.VERSION.print());
fail("GeoServer version ("+v.getVersion()+") does not match the desired one ("+GS_VERSION+")"); fail("GeoServer version ("+v.getVersion()+") does not match the desired one (+VERSION+)");
} }
} else { } else {
LOGGER.debug("Skipping tests "); System.out.println("Skipping tests ");
LOGGER.warn("Tests are disabled. Please read the documentation to enable them.");
} }
} }
@Before
public void before(){
String testName = _testName.getMethodName();
LOGGER.warn("");
LOGGER.warn("============================================================");
LOGGER.warn("=== RUNNING TEST " + testName);
LOGGER.warn("");
}
protected boolean enabled() { protected boolean enabled() {
return enabled; return enabled;
} }
@ -188,9 +169,8 @@ public abstract class GeoserverRESTTest {
LOGGER.info("Found " + groups.size() + " layerGroups"); LOGGER.info("Found " + groups.size() + " layerGroups");
for (String groupName : groups) { for (String groupName : groups) {
RESTLayerGroup group = reader.getLayerGroup(groupName); RESTLayerGroup group = reader.getLayerGroup(groupName);
if (groups != null) {
StringBuilder sb = new StringBuilder("Group: ").append(groupName).append(":"); StringBuilder sb = new StringBuilder("Group: ").append(groupName).append(":");
for (NameLinkElem layer : group.getPublishedList()) { for (NameLinkElem layer : group.getLayerList()) {
sb.append(" ").append(layer); sb.append(" ").append(layer);
} }
@ -198,12 +178,11 @@ public abstract class GeoserverRESTTest {
LOGGER.info(sb.toString() + ": removed: " + removed); LOGGER.info(sb.toString() + ": removed: " + removed);
assertTrue("LayerGroup not removed: " + groupName, removed); assertTrue("LayerGroup not removed: " + groupName, removed);
} }
}
} }
private void deleteAllLayers() { private void deleteAllLayers() {
List<String> layers = reader.getLayers().getNames(); List<String> layers = reader.getLayers().getNames();
if (layers != null) {
for (String layerName : layers) { for (String layerName : layers) {
RESTLayer layer = reader.getLayer(layerName); RESTLayer layer = reader.getLayer(layerName);
if (layer.getType() == RESTLayer.Type.VECTOR) if (layer.getType() == RESTLayer.Type.VECTOR)
@ -213,7 +192,7 @@ public abstract class GeoserverRESTTest {
else else
LOGGER.error("Unknown layer type " + layer.getType()); LOGGER.error("Unknown layer type " + layer.getType());
} }
}
} }
private void deleteAllCoverageStores() { private void deleteAllCoverageStores() {
@ -225,7 +204,7 @@ public abstract class GeoserverRESTTest {
// RESTCoverageStore store = reader.getCoverageStore(workspace, storename); // RESTCoverageStore store = reader.getCoverageStore(workspace, storename);
LOGGER.warn("Deleting CoverageStore " + workspace + " : " + storename); LOGGER.warn("Deleting CoverageStore " + workspace + " : " + storename);
boolean removed = publisher.removeCoverageStore(workspace, storename, false, GeoServerRESTPublisher.Purge.METADATA); boolean removed = publisher.removeCoverageStore(workspace, storename, false);
assertTrue("CoverageStore not removed " + workspace + " : " + storename, removed); assertTrue("CoverageStore not removed " + workspace + " : " + storename, removed);
} }
} }
@ -245,7 +224,7 @@ public abstract class GeoserverRESTTest {
// } // }
LOGGER.warn("Deleting DataStore " + workspace + " : " + storename); LOGGER.warn("Deleting DataStore " + workspace + " : " + storename);
boolean removed = publisher.removeDatastore(workspace, storename, false, GeoServerRESTPublisher.Purge.METADATA); boolean removed = publisher.removeDatastore(workspace, storename, false);
assertTrue("DataStore not removed " + workspace + " : " + storename, removed); assertTrue("DataStore not removed " + workspace + " : " + storename, removed);
} }
} }
@ -273,12 +252,11 @@ public abstract class GeoserverRESTTest {
protected void deleteAllStyles() { protected void deleteAllStyles() {
List<String> styles = reader.getStyles().getNames(); List<String> styles = reader.getStyles().getNames();
if (styles != null) {
for (String style : styles) { for (String style : styles) {
LOGGER.warn("Deleting Style " + style); LOGGER.warn("Deleting Style " + style);
boolean removed = publisher.removeStyle(style,true); boolean removed = publisher.removeStyle(style,true);
assertTrue("Style not removed " + style, removed); assertTrue("Style not removed " + style, removed);
}
} }
} }

View File

@ -1,106 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007 - 2016 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest;
import it.geosolutions.geoserver.rest.decoder.RESTStyle;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
import org.springframework.core.io.ClassPathResource;
/**
*
* @author etj
*/
public class UtilTest extends GeoserverRESTTest {
private final static Logger LOGGER = LoggerFactory.getLogger(UtilTest.class);
@Test
public void testSearchStyle() throws IOException {
if (!enabled()) {
return;
}
deleteAll();
final String WORKSPACE = "testWorkspace";
final String STYLENAME = "restteststyle";
File sldFile = new ClassPathResource("testdata/restteststyle.sld").getFile();
publisher.createWorkspace(WORKSPACE);
assertEquals(0, reader.getStyles().size());
assertEquals(0, reader.getStyles(WORKSPACE).size());
assertEquals(0, Util.searchStyles(reader, STYLENAME).size());
// insert style in workspace
assertTrue(publisher.publishStyleInWorkspace(WORKSPACE, sldFile, STYLENAME));
assertTrue(reader.existsStyle(WORKSPACE, STYLENAME));
// GeoServer returns workspace specific names if hte name is not found as global
assertTrue(reader.existsStyle(STYLENAME));
assertEquals(0, reader.getStyles().size());
assertEquals(1, reader.getStyles(WORKSPACE).size());
assertEquals(1, Util.searchStyles(reader, STYLENAME).size());
// insert global style
assertTrue(publisher.publishStyle(sldFile, STYLENAME));
assertTrue(reader.existsStyle(STYLENAME));
assertTrue(reader.existsStyle(WORKSPACE, STYLENAME));
for(RESTStyle style : Util.searchStyles(reader, STYLENAME))
{
LOGGER.debug(style.getWorkspace() + " :: " + style.getName());
}
// there's a bug in geoserver here: the global style will include workspace info
// https://osgeo-org.atlassian.net/browse/GEOS-7498
// Commenting out all the concerned test code
// assertEquals(2, Util.searchStyles(reader, STYLENAME).size());
//
// assertEquals(1, reader.getStyles().size());
// assertEquals(1, reader.getStyles(WORKSPACE).size());
//
// List<RESTStyle> styles = Util.searchStyles(reader, STYLENAME);
//
// assertEquals(STYLENAME, styles.get(0).getName());
//
//
// // assertEquals(null, styles.get(0).getWorkspace()); // first one is the global one, if any
//
// assertEquals(STYLENAME, styles.get(1).getName());
// assertEquals(WORKSPACE, styles.get(1).getWorkspace());
}
}

View File

@ -24,11 +24,12 @@
*/ */
package it.geosolutions.geoserver.rest.datastore; package it.geosolutions.geoserver.rest.datastore;
import java.net.MalformedURLException;
import it.geosolutions.geoserver.rest.GeoserverRESTTest; import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder; import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSArcSDEDatastoreEncoder; import it.geosolutions.geoserver.rest.encoder.datastore.GSArcSDEDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSOracleNGDatastoreEncoder;
import java.net.MalformedURLException;
/** /**
* Testcase for creating arcsde-based resources on geoserver. * Testcase for creating arcsde-based resources on geoserver.
@ -60,7 +61,7 @@ public class GSArcSDEDatastoreEncoderTest extends StoreIntegrationTest {
public GSArcSDEDatastoreEncoderTest() throws IllegalArgumentException, MalformedURLException { public GSArcSDEDatastoreEncoderTest() throws IllegalArgumentException, MalformedURLException {
super(System.getProperty("Ignore", "true").equalsIgnoreCase("true")); super(System.getProperty("Ignore", "false").equalsIgnoreCase("true"));
} }
@Override @Override

View File

@ -24,11 +24,16 @@
*/ */
package it.geosolutions.geoserver.rest.datastore; package it.geosolutions.geoserver.rest.datastore;
import java.net.MalformedURLException;
import it.geosolutions.geoserver.rest.GeoserverRESTTest; import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder; import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSOracleNGDatastoreEncoder; import it.geosolutions.geoserver.rest.encoder.datastore.GSOracleNGDatastoreEncoder;
import java.net.MalformedURLException; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Testcase for creating OracleNG-based resources on geoserver. * Testcase for creating OracleNG-based resources on geoserver.
@ -61,7 +66,7 @@ public class GSOracleNGDatastoreEncoderTest extends StoreIntegrationTest {
// private final static Logger LOGGER = LoggerFactory.getLogger(GSOracleNGDatastoreEncoderTest.class); // private final static Logger LOGGER = LoggerFactory.getLogger(GSOracleNGDatastoreEncoderTest.class);
public GSOracleNGDatastoreEncoderTest() throws IllegalArgumentException, MalformedURLException { public GSOracleNGDatastoreEncoderTest() throws IllegalArgumentException, MalformedURLException {
super(System.getProperty("pgIgnore", "true").equalsIgnoreCase("true")); super(System.getProperty("pgIgnore", "false").equalsIgnoreCase("true"));
} }

View File

@ -24,19 +24,19 @@
*/ */
package it.geosolutions.geoserver.rest.datastore; package it.geosolutions.geoserver.rest.datastore;
import java.net.MalformedURLException;
import it.geosolutions.geoserver.rest.GeoserverRESTTest; import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore; import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder; import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder; import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSAbstractDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSOracleNGDatastoreEncoder; import it.geosolutions.geoserver.rest.encoder.datastore.GSOracleNGDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.feature.GSFeatureTypeEncoder; import it.geosolutions.geoserver.rest.encoder.feature.GSFeatureTypeEncoder;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStoreManager; import it.geosolutions.geoserver.rest.manager.GeoServerRESTStoreManager;
import java.net.MalformedURLException; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -44,8 +44,10 @@ import org.slf4j.LoggerFactory;
* <P> * <P>
* Since these tests require a running Store instance, this is more like integration tests.<br/> * Since these tests require a running Store instance, this is more like integration tests.<br/>
* *
* For testing that a datastore is properly configured, a layer publication has to be attempted. For this, the 'states' data (states shapefile - * For testing that a datastore is properly configured, a layer publication has
* available in testdata/states.zip) has to be imported in the corresponding store. Note: For Oracle NG this name has to be uppercase (STATES). * to be attempted. For this, the 'states' data (states shapefile - available in
* testdata/states.zip) has to be imported in the corresponding store.
* Note: For Oracle NG this name has to be uppercase (STATES).
* *
* @author carlo cancellieri - GeoSolutions * @author carlo cancellieri - GeoSolutions
* @author emmanuel blondel * @author emmanuel blondel
@ -54,14 +56,14 @@ import org.slf4j.LoggerFactory;
*/ */
public abstract class StoreIntegrationTest extends GeoserverRESTTest { public abstract class StoreIntegrationTest extends GeoserverRESTTest {
protected final GeoServerRESTStoreManager storeManager; private final static Logger LOGGER = LoggerFactory.getLogger(StoreIntegrationTest.class);
private final GeoServerRESTStoreManager storeManager;
/** /**
* ignore integration tests * ignore integration tests
*/ */
protected final boolean ignore; private final boolean ignore;
private final static Logger LOGGER = LoggerFactory.getLogger(StoreIntegrationTest.class);
public boolean isIgnore() { public boolean isIgnore() {
return ignore; return ignore;
@ -69,12 +71,11 @@ public abstract class StoreIntegrationTest extends GeoserverRESTTest {
/** /**
* *
* @param ignore true if this test should be disabled * @param ignore false if this test shoudl be disabled
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws MalformedURLException * @throws MalformedURLException
*/ */
public StoreIntegrationTest(boolean ignore) throws IllegalArgumentException, public StoreIntegrationTest(boolean ignore) throws IllegalArgumentException, MalformedURLException {
MalformedURLException {
super(); super();
this.storeManager = new GeoServerRESTStoreManager(URL, RESTUSER, RESTPW); this.storeManager = new GeoServerRESTStoreManager(URL, RESTUSER, RESTPW);
this.ignore=ignore; this.ignore=ignore;
@ -84,7 +85,7 @@ public abstract class StoreIntegrationTest extends GeoserverRESTTest {
@Test @Test
public void testCreateDeleteDatastore() throws IllegalArgumentException, MalformedURLException { public void testCreateDeleteDatastore() throws IllegalArgumentException, MalformedURLException {
if (!enabled() || ignore) { if (!enabled()) {
return; return;
} }
deleteAll(); deleteAll();
@ -99,7 +100,11 @@ public abstract class StoreIntegrationTest extends GeoserverRESTTest {
boolean created = storeManager.create(DEFAULT_WS, storeEncoder); boolean created = storeManager.create(DEFAULT_WS, storeEncoder);
assertTrue("*** store " + storeName + " has not been created.", created); if( ! ignore )
assertTrue("Datastore not created", created);
else if( ! created)
LOGGER.error("*** store " + storeName + " has not been created.");
RESTDataStore datastore = reader.getDatastore(DEFAULT_WS, storeName); RESTDataStore datastore = reader.getDatastore(DEFAULT_WS, storeName);
assertNotNull(datastore); assertNotNull(datastore);
@ -107,14 +112,12 @@ public abstract class StoreIntegrationTest extends GeoserverRESTTest {
// check if the datastore is properly configured in GS for publishing layers // check if the datastore is properly configured in GS for publishing layers
String layername = "states"; String layername = "states";
if (storeEncoder instanceof GSOracleNGDatastoreEncoder) if (storeEncoder instanceof GSOracleNGDatastoreEncoder)
layername = layername.toUpperCase(); layername = layername.toUpperCase();
GSFeatureTypeEncoder fte = new GSFeatureTypeEncoder(); GSFeatureTypeEncoder fte = new GSFeatureTypeEncoder();
fte.setName(layername); fte.setName(layername);
fte.setNativeName(layername); fte.setTitle(layername);
fte.setTitle(layername+"_TITLE");
fte.setNativeCRS("EPSG:4326"); fte.setNativeCRS("EPSG:4326");
fte.setDescription("desc"); fte.setDescription("desc");
fte.setEnabled(true); fte.setEnabled(true);
@ -123,14 +126,23 @@ public abstract class StoreIntegrationTest extends GeoserverRESTTest {
layerEncoder.setQueryable(true); layerEncoder.setQueryable(true);
layerEncoder.setDefaultStyle("polygon"); layerEncoder.setDefaultStyle("polygon");
boolean published = publisher.publishDBLayer(DEFAULT_WS, storeName, fte, layerEncoder); boolean published = publisher.publishDBLayer(DEFAULT_WS, storeName,
fte, layerEncoder);
assertTrue("*** Test layer " + layername if (!ignore) {
+ " has not been published. Problem in datastore configuration", published); assertTrue("Test layer not published", published);
} else if (!published) {
LOGGER.error("*** Test layer "
+ layername
+ " has not been published. Problem in datastore configuration");
}
// removing test // removing test
boolean removed = storeManager.remove(DEFAULT_WS, storeEncoder, true); boolean removed = storeManager.remove(DEFAULT_WS, storeEncoder, true);
assertTrue("*** Datastore " + storeName + " has not been removed.", removed); if( ! ignore )
assertTrue("Datastore not removed", removed);
else if( ! removed )
LOGGER.error("*** Datastore " + storeName + " has not been removed.");
assertTrue(publisher.removeWorkspace(DEFAULT_WS, false)); assertTrue(publisher.removeWorkspace(DEFAULT_WS, false));
} }
} }

View File

@ -1,58 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2015 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder.about;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author etj <etj at geo-solutions dot it>
*/
public class GSVersionDecoderTest {
@Test
public void testGetGeoServer() {
assertEquals(GSVersionDecoder.VERSION.v22, GSVersionDecoder.VERSION.getVersion("2.2"));
assertEquals(GSVersionDecoder.VERSION.v22, GSVersionDecoder.VERSION.getVersion("2.2-SNAPSHOT"));
assertEquals(GSVersionDecoder.VERSION.v26, GSVersionDecoder.VERSION.getVersion("2.6"));
assertEquals(GSVersionDecoder.VERSION.v26, GSVersionDecoder.VERSION.getVersion("2.6-SNAPSHOT"));
assertEquals(GSVersionDecoder.VERSION.v26, GSVersionDecoder.VERSION.getVersion("2.6-ENTERPRISE"));
assertEquals(GSVersionDecoder.VERSION.v26, GSVersionDecoder.VERSION.getVersion("2.6-ENTERPRISE-SNAPSHOT"));
assertEquals(GSVersionDecoder.VERSION.ABOVE, GSVersionDecoder.VERSION.getVersion("2.21"));
assertEquals(GSVersionDecoder.VERSION.ABOVE, GSVersionDecoder.VERSION.getVersion("2.21-SNAPSHOT"));
assertEquals(GSVersionDecoder.VERSION.ABOVE, GSVersionDecoder.VERSION.getVersion("2.42"));
assertEquals(GSVersionDecoder.VERSION.ABOVE, GSVersionDecoder.VERSION.getVersion("2.42-SNAPSHOT"));
assertEquals(GSVersionDecoder.VERSION.UNRECOGNIZED, GSVersionDecoder.VERSION.getVersion("3.0"));
assertEquals(GSVersionDecoder.VERSION.UNRECOGNIZED, GSVersionDecoder.VERSION.getVersion("anystring"));
assertEquals(GSVersionDecoder.VERSION.UNRECOGNIZED, GSVersionDecoder.VERSION.getVersion(null));
}
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2007-2016 GeoSolutions S.A.S. * Copyright (C) 2007 - 2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* GPLv3 + Classpath exception * GPLv3 + Classpath exception
@ -45,58 +45,56 @@ public class GSLayerEncoder21Test {
public void setup() { public void setup() {
layerEncoder = new GSLayerEncoder21(); layerEncoder = new GSLayerEncoder21();
layerEncoder.setAdvertised(true); layerEncoder.setAdvertised(true);
layerEncoder.addAuthorityURL( layerEncoder.addAuthorityURL(new GSAuthorityURLInfoEncoder(
new GSAuthorityURLInfoEncoder(
"authority1", "http://www.authority1.org")); "authority1", "http://www.authority1.org"));
layerEncoder.addIdentifier( layerEncoder.addIdentifier(new GSIdentifierInfoEncoder("authority1",
new GSIdentifierInfoEncoder( "identifier1"));
"authority1", "identifier1")); layerEncoder.addAuthorityURL(new GSAuthorityURLInfoEncoder(
layerEncoder.addAuthorityURL(
new GSAuthorityURLInfoEncoder(
"authority2", "http://www.authority2.org")); "authority2", "http://www.authority2.org"));
layerEncoder.addIdentifier( layerEncoder.addIdentifier(new GSIdentifierInfoEncoder("authority2",
new GSIdentifierInfoEncoder( "identifier2"));
"authority2", "identifier2")); layerEncoder.addIdentifier(new GSIdentifierInfoEncoder("authority2",
layerEncoder.addIdentifier( "additionalId"));
new GSIdentifierInfoEncoder(
"authority2", "additionalId"));
} }
@Test @Test
public void testMetadata() { public void testMetadata() {
List<Element> metaElements = layerEncoder.getRoot().getChild("metadata").getChildren(); List<Element> metaElements = layerEncoder.getRoot()
.getChild("metadata").getChildren();
for (Element el : metaElements) { for (Element el : metaElements) {
String key = el.getAttributeValue("key"); String key = el.getAttributeValue("key");
if (key.matches("advertised")) { if (key.matches("advertised")) {
Assert.assertEquals(true, Assert.assertEquals(true, Boolean.parseBoolean(el.getValue()));
Boolean.parseBoolean(el.getValue()));
} else if (key.matches("authorityURLs")) { } else if (key.matches("authorityURLs")) {
String jsonStr = el.getValue(); String jsonStr = el.getValue();
jsonStr = jsonStr.substring(2); jsonStr = jsonStr.substring(2);
jsonStr = jsonStr.substring(0, jsonStr = jsonStr.substring(0, jsonStr.length() - 3);
jsonStr.length() - 3);
String[] items = jsonStr.split("\\}(,)\\{"); String[] items = jsonStr.split("\\}(,)\\{");
String[] props1 = items[0].split(","); String[] props1 = items[0].split(",");
String[] kvp1_1 = props1[0].split("\":"); String[] kvp1_1 = props1[0].split("\":");
String[] kvp1_2 = props1[1].split("\":"); String[] kvp1_2 = props1[1].split("\":");
Assert.assertEquals(AuthorityURLInfo.name.name(), kvp1_1[0].replace("\"", "")); Assert.assertEquals(AuthorityURLInfo.name.name(),
kvp1_1[0].replace("\"", ""));
Assert.assertEquals("authority1", kvp1_1[1].replace("\"", "")); Assert.assertEquals("authority1", kvp1_1[1].replace("\"", ""));
Assert.assertEquals(AuthorityURLInfo.href.name(), kvp1_2[0].replace("\"", "")); Assert.assertEquals(AuthorityURLInfo.href.name(),
Assert.assertEquals("http://www.authority1.org", kvp1_2[1].replace("\"", "")); kvp1_2[0].replace("\"", ""));
Assert.assertEquals("http://www.authority1.org",
kvp1_2[1].replace("\"", ""));
String[] props2 = items[1].split(","); String[] props2 = items[1].split(",");
String[] kvp2_1 = props2[0].split("\":"); String[] kvp2_1 = props2[0].split("\":");
String[] kvp2_2 = props2[1].split("\":"); String[] kvp2_2 = props2[1].split("\":");
Assert.assertEquals(AuthorityURLInfo.name.name(), kvp2_1[0].replace("\"", "")); Assert.assertEquals(AuthorityURLInfo.name.name(),
kvp2_1[0].replace("\"", ""));
Assert.assertEquals("authority2", kvp2_1[1].replace("\"", "")); Assert.assertEquals("authority2", kvp2_1[1].replace("\"", ""));
Assert.assertEquals(AuthorityURLInfo.href.name(), kvp2_2[0].replace("\"", "")); Assert.assertEquals(AuthorityURLInfo.href.name(),
Assert.assertEquals("http://www.authority2.org", kvp2_2[1].replace("\"", "")); kvp2_2[0].replace("\"", ""));
Assert.assertEquals("http://www.authority2.org",
kvp2_2[1].replace("\"", ""));
} else if (key.matches("identifiers")) { } else if (key.matches("identifiers")) {
String jsonStr = el.getValue(); String jsonStr = el.getValue();
@ -108,26 +106,30 @@ public class GSLayerEncoder21Test {
String[] props1 = items[0].split(","); String[] props1 = items[0].split(",");
String[] kvp1_1 = props1[0].split("\":"); String[] kvp1_1 = props1[0].split("\":");
String[] kvp1_2 = props1[1].split("\":"); String[] kvp1_2 = props1[1].split("\":");
Assert.assertEquals("idx0", IdentifierInfo.authority.name(), kvp1_1[0].replace("\"", "")); Assert.assertEquals(IdentifierInfo.authority.name(),
Assert.assertEquals("idx0", "authority1", kvp1_1[1].replace("\"", "")); kvp1_1[0].replace("\"", ""));
Assert.assertEquals("idx0", IdentifierInfo.identifier.name(), kvp1_2[0].replace("\"", "")); Assert.assertEquals("authority2", kvp1_1[1].replace("\"", ""));
Assert.assertEquals("idx0", "identifier1", kvp1_2[1].replace("\"", "")); Assert.assertEquals(IdentifierInfo.identifier.name(),
kvp1_2[0].replace("\"", ""));
Assert.assertEquals("identifier2", kvp1_2[1].replace("\"", ""));
String[] props2 = items[1].split(","); String[] props2 = items[1].split(",");
String[] kvp2_1 = props2[0].split("\":"); String[] kvp2_1 = props2[0].split("\":");
String[] kvp2_2 = props2[1].split("\":"); String[] kvp2_2 = props2[1].split("\":");
Assert.assertEquals("idx1", IdentifierInfo.authority.name(), kvp2_1[0].replace("\"", "")); Assert.assertEquals(IdentifierInfo.authority.name(),
Assert.assertEquals("idx1", "authority2", kvp2_1[1].replace("\"", "")); kvp2_1[0].replace("\"", ""));
Assert.assertEquals("idx1", IdentifierInfo.identifier.name(), kvp2_2[0].replace("\"", "")); Assert.assertEquals("authority2", kvp2_1[1].replace("\"", ""));
Assert.assertEquals("idx1", "identifier2", kvp2_2[1].replace("\"", "")); Assert.assertEquals(IdentifierInfo.identifier.name(),
kvp2_2[0].replace("\"", ""));
Assert.assertEquals("additionalId", kvp2_2[1].replace("\"", ""));
String[] props3 = items[2].split(","); String[] props3 = items[2].split(",");
String[] kvp3_1 = props3[0].split("\":"); String[] kvp3_1 = props3[0].split("\":");
String[] kvp3_2 = props3[1].split("\":"); String[] kvp3_2 = props3[1].split("\":");
Assert.assertEquals("idx2", IdentifierInfo.authority.name(), kvp3_1[0].replace("\"", "")); Assert.assertEquals(IdentifierInfo.authority.name(), kvp3_1[0].replace("\"", ""));
Assert.assertEquals("idx2", "authority2", kvp3_1[1].replace("\"", "")); Assert.assertEquals("authority1", kvp3_1[1].replace("\"", ""));
Assert.assertEquals("idx2", IdentifierInfo.identifier.name(), kvp3_2[0].replace("\"", "")); Assert.assertEquals(IdentifierInfo.identifier.name(), kvp3_2[0].replace("\"", ""));
Assert.assertEquals("idx2", "additionalId", kvp3_2[1].replace("\"", "")); Assert.assertEquals("identifier1", kvp3_2[1].replace("\"", ""));
} }
} }

View File

@ -52,6 +52,7 @@ public class GSLayerEncoderTest {
"authority1", "http://www.authority1.org")); "authority1", "http://www.authority1.org"));
layerEncoder.addIdentifier(new GSIdentifierInfoEncoder("authority1", layerEncoder.addIdentifier(new GSIdentifierInfoEncoder("authority1",
"identifier1")); "identifier1"));
} }
@Test @Test
@ -112,11 +113,4 @@ public class GSLayerEncoderTest {
Assert.assertEquals("identifier1", el.getChild("identifier").getValue()); Assert.assertEquals("identifier1", el.getChild("identifier").getValue());
} }
@Test
public void testDefaultStyleWithWorkspace(){
layerEncoder.setDefaultStyle("ws", "style");
Element el = (Element) layerEncoder.getRoot().getChild("defaultStyle");
Assert.assertEquals("style", el.getChild("name").getValue());
Assert.assertEquals("ws", el.getChild("workspace").getValue());
}
} }

View File

@ -37,7 +37,6 @@ import java.util.List;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
/** /**
@ -92,8 +91,6 @@ public class GSLayerGroupEncoderTest extends GeoserverRESTTest {
groupWriter.addLayer("topp:boundaries"); groupWriter.addLayer("topp:boundaries");
groupWriter.addLayer("topp:cities"); groupWriter.addLayer("topp:cities");
assertTrue(publisher.createLayerGroup(groupName, groupWriter)); assertTrue(publisher.createLayerGroup(groupName, groupWriter));
// Test exists
assertTrue(reader.existsLayerGroup(null, groupName));
try { try {
RESTLayerGroup groupReader = reader.getLayerGroup(groupName); RESTLayerGroup groupReader = reader.getLayerGroup(groupName);
assertNull(groupReader.getWorkspace()); assertNull(groupReader.getWorkspace());
@ -116,8 +113,6 @@ public class GSLayerGroupEncoderTest extends GeoserverRESTTest {
} }
} finally { } finally {
assertTrue(publisher.removeLayerGroup(groupName)); assertTrue(publisher.removeLayerGroup(groupName));
// Test not exists
assertFalse(reader.existsLayerGroup(null, groupName));
} }
} }
@ -133,8 +128,6 @@ public class GSLayerGroupEncoderTest extends GeoserverRESTTest {
groupWriter.addLayer("topp:boundaries"); groupWriter.addLayer("topp:boundaries");
groupWriter.addLayer("topp:cities"); groupWriter.addLayer("topp:cities");
assertTrue(publisher.createLayerGroup("topp", groupName, groupWriter)); assertTrue(publisher.createLayerGroup("topp", groupName, groupWriter));
// Test exists
assertTrue(reader.existsLayerGroup("topp", groupName));
try { try {
RESTLayerGroup groupReader = reader.getLayerGroup("topp", groupName); RESTLayerGroup groupReader = reader.getLayerGroup("topp", groupName);
assertEquals("topp", groupReader.getWorkspace()); assertEquals("topp", groupReader.getWorkspace());
@ -157,8 +150,6 @@ public class GSLayerGroupEncoderTest extends GeoserverRESTTest {
} }
} finally { } finally {
assertTrue(publisher.removeLayerGroup("topp", groupName)); assertTrue(publisher.removeLayerGroup("topp", groupName));
// Test not exists
assertFalse(reader.existsLayerGroup("topp", groupName));
} }
} }

View File

@ -24,11 +24,8 @@
*/ */
package it.geosolutions.geoserver.rest.encoder; package it.geosolutions.geoserver.rest.encoder;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.fail;
import java.net.URI; import java.net.URI;
import org.junit.Test; import org.junit.Test;
/** /**

View File

@ -21,7 +21,6 @@ package it.geosolutions.geoserver.rest.encoder.coverage;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder; import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy; import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy;
import it.geosolutions.geoserver.rest.encoder.dimensions.GSCoverageDimensionEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation; import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils; import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
@ -106,8 +105,6 @@ public class GSCoverageEncoderTest extends TestCase {
encoder.addKeyword("..."); encoder.addKeyword("...");
encoder.addKeyword("KEYWORD_N"); encoder.addKeyword("KEYWORD_N");
// setting dimensions (into metadata)
final GSDimensionInfoEncoder timeDimension=new GSDimensionInfoEncoder(true); final GSDimensionInfoEncoder timeDimension=new GSDimensionInfoEncoder(true);
timeDimension.setPresentation(Presentation.CONTINUOUS_INTERVAL); timeDimension.setPresentation(Presentation.CONTINUOUS_INTERVAL);
encoder.setMetadata("time", timeDimension); encoder.setMetadata("time", timeDimension);
@ -123,20 +120,9 @@ public class GSCoverageEncoderTest extends TestCase {
elevationDimension.setPresentation(Presentation.LIST); elevationDimension.setPresentation(Presentation.LIST);
encoder.setMetadata("elevation", elevationDimension); encoder.setMetadata("elevation", elevationDimension);
// setting dimensions (since gs-2.4.x)
GSCoverageDimensionEncoder gsCoverageDimensionEncoder = new GSCoverageDimensionEncoder(
"GRAY_INDEX", "GridSampleDimension[-Infinity,Infinity]", "-inf", "inf",
"dobson units", "REAL_32BITS");
encoder.addCoverageDimensionInfo(gsCoverageDimensionEncoder);
encoder.setNativeCoverageName("Sample native name");
if (LOGGER.isInfoEnabled()) if (LOGGER.isInfoEnabled())
LOGGER.info(encoder.toString()); LOGGER.info(encoder.toString());
Element nativeCoverageName = ElementUtils.contains(encoder.getRoot(), GSCoverageEncoder.NATIVECOVERAGENAME);
assertNotNull(nativeCoverageName);
assertEquals("Sample native name", nativeCoverageName.getText());
final Element el2=ElementUtils.contains(encoder.getRoot(),GSDimensionInfoEncoder.PRESENTATION); final Element el2=ElementUtils.contains(encoder.getRoot(),GSDimensionInfoEncoder.PRESENTATION);
Assert.assertNotNull(el2); Assert.assertNotNull(el2);
LOGGER.info("contains_key:"+el2.toString()); LOGGER.info("contains_key:"+el2.toString());

View File

@ -1,73 +0,0 @@
/*
* Copyright (C) 2007 - 2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.geosolutions.geoserver.rest.encoder.dimensions;
import junit.framework.Assert;
import org.junit.Test;
/**
*
* @author Henry Rotzoll (henry.rotzoll@dlr.de)
*
*/
public class GSCoverageDimensionEncoderTest {
@Test
public void coverageDimensionTest() {
GSCoverageDimensionEncoder encoder = new GSCoverageDimensionEncoder("GRAY_INDEX",
"GridSampleDimension[-Infinity,Infinity]", "-inf", "inf", "dobson units",
"REAL_32BITS");
Assert.assertEquals("GRAY_INDEX", encoder.getName());
Assert.assertEquals("GridSampleDimension[-Infinity,Infinity]", encoder.getDescription());
Assert.assertEquals("-inf", encoder.getRangeMin());
Assert.assertEquals("inf", encoder.getRangeMax());
Assert.assertEquals("dobson units", encoder.getUnit());
Assert.assertEquals("REAL_32BITS", encoder.getDimensionTypeName());
Assert.assertTrue(encoder.delName());
Assert.assertTrue(encoder.delDescription());
Assert.assertTrue(encoder.delRange());
Assert.assertTrue(encoder.delUnit());
Assert.assertTrue(encoder.delDimensionType());
Assert.assertNull(encoder.getName());
Assert.assertNull(encoder.getDescription());
Assert.assertNull(encoder.getRangeMin());
Assert.assertNull(encoder.getRangeMax());
Assert.assertNull(encoder.getUnit());
Assert.assertNull(encoder.getDimensionTypeName());
encoder.setName("GRAY_INDEX");
encoder.setDescription("GridSampleDimension[-Infinity,Infinity]");
encoder.setRange("-inf", "inf");
encoder.setUnit("dobson units");
encoder.setDimensionType("REAL_32BITS");
Assert.assertEquals("GRAY_INDEX", encoder.getName());
Assert.assertEquals("GridSampleDimension[-Infinity,Infinity]", encoder.getDescription());
Assert.assertEquals("-inf", encoder.getRangeMin());
Assert.assertEquals("inf", encoder.getRangeMax());
Assert.assertEquals("dobson units", encoder.getUnit());
Assert.assertEquals("REAL_32BITS", encoder.getDimensionTypeName());
}
}

View File

@ -1,8 +1,9 @@
package it.geosolutions.geoserver.rest.encoder.feature; package it.geosolutions.geoserver.rest.encoder.feature;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation;
import it.geosolutions.geoserver.rest.encoder.metadata.GSFeatureDimensionInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.GSFeatureDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.PresentationDiscrete;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils; import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -24,10 +25,10 @@ public class GSFeatureDimensionInfoEncoderTest {
// LOGGER.info(encoder.toString()); // LOGGER.info(encoder.toString());
elevationDimension.setPresentation( elevationDimension.setPresentation(
Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(10)); PresentationDiscrete.DISCRETE_INTERVAL, BigDecimal.valueOf(10));
elevationDimension.setPresentation( elevationDimension.setPresentation(
Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(12)); PresentationDiscrete.DISCRETE_INTERVAL, BigDecimal.valueOf(12));
List<Element> elList = ElementUtils.search( List<Element> elList = ElementUtils.search(
elevationDimension.getRoot(), new Filter() { elevationDimension.getRoot(), new Filter() {
@ -43,8 +44,8 @@ public class GSFeatureDimensionInfoEncoderTest {
} }
}); });
// using set we get only one element called // using set we get only one element called
// Presentation.DISCRETE_INTERVAL // PresentationDiscrete.DISCRETE_INTERVAL
Assert.assertEquals(elList.size(), 1); Assert.assertEquals(Integer.valueOf(elList.size()), Integer.valueOf(1));
elevationDimension.setPresentation(Presentation.LIST); elevationDimension.setPresentation(Presentation.LIST);
@ -64,7 +65,7 @@ public class GSFeatureDimensionInfoEncoderTest {
} }
}); });
Assert.assertEquals(elList.size(), 0); Assert.assertEquals(Integer.valueOf(elList.size()), Integer.valueOf(0));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2007 - 2015 GeoSolutions S.A.S. * Copyright (C) 2007 - 2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* GPLv3 + Classpath exception * GPLv3 + Classpath exception
@ -20,10 +20,9 @@
package it.geosolutions.geoserver.rest.encoder.feature; package it.geosolutions.geoserver.rest.encoder.feature;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTFeatureType;
import it.geosolutions.geoserver.rest.decoder.RESTLayer; import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder.VERSION; import it.geosolutions.geoserver.rest.decoder.RESTResource;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder; import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder21; import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder21;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder; import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder;
@ -31,12 +30,14 @@ import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEnc
import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder; import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation; import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.PresentationDiscrete;
import it.geosolutions.geoserver.rest.encoder.metadata.GSFeatureDimensionInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.GSFeatureDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.GSVirtualTableEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.GSVirtualTableEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTGeometryEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTGeometryEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTParameterEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTParameterEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils; import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.publisher.GeoserverRESTPublisherTest;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -44,22 +45,23 @@ import java.math.BigDecimal;
import java.util.List; import java.util.List;
import org.jdom.Element; import org.jdom.Element;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
/** /**
* * Note on adding multiple available styles to the GSLayerEncoder: - to run the
* Note on adding multiple available styles to the GSLayerEncoder: - to run the testIntegration(), 2 clones of the "point" style, named "point2" and * testIntegration(), 2 clones of the "point" style, named "point2" and "point3"
* "point3" have to be created. * have to be created.
* *
* @author ETj (etj at geo-solutions.it) * @author ETj (etj at geo-solutions.it)
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* @author Emmanuel Blondel - emmanuel.blondel1@gmail.com | emmanuel.blondel@fao.org * @author Emmanuel Blondel - emmanuel.blondel1@gmail.com |
* emmanuel.blondel@fao.org
*/ */
public class GSFeatureEncoderTest extends GeoserverRESTTest { public class GSFeatureEncoderTest extends GeoserverRESTPublisherTest {
protected final static Logger LOGGER = LoggerFactory.getLogger(GSFeatureEncoderTest.class); protected final static Logger LOGGER = LoggerFactory.getLogger(GSFeatureEncoderTest.class);
@Test @Test
@ -74,6 +76,50 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
String storeName = "resttestshp"; String storeName = "resttestshp";
String layerName = "cities"; String layerName = "cities";
GSFeatureTypeEncoder fte = new GSFeatureTypeEncoder();
fte.setNativeName(layerName);
fte.setName(layerName + "_NEW");
fte.setTitle("title");
// fte.addKeyword("TODO");
fte.setNativeCRS("EPSG:4326");
fte.setDescription("desc");
fte.setEnabled(true);
//metadataLink
GSMetadataLinkInfoEncoder metadatalink = new GSMetadataLinkInfoEncoder(
"text/xml", "ISO19115:2003",
"http://www.organization.org/metadata1");
fte.addMetadataLinkInfo(metadatalink);
GSLayerEncoder layerEncoder = null;
if (!GSVersionDecoder.VERSION.getVersion(VERSION).equals(
GSVersionDecoder.VERSION.UNRECOGNIZED)) {
layerEncoder = new GSLayerEncoder();
} else if (GSVersionDecoder.VERSION.getVersion(VERSION).equals(
GSVersionDecoder.VERSION.UNRECOGNIZED)) {
layerEncoder = new GSLayerEncoder21();
}
layerEncoder.setEnabled(true);
layerEncoder.setQueryable(true);
layerEncoder.setAdvertised(true);
layerEncoder.setDefaultStyle("point");
layerEncoder.addStyle("point2");
layerEncoder.addStyle("point3");
// authorityURL
GSAuthorityURLInfoEncoder authorityURL = new GSAuthorityURLInfoEncoder(
"authority1", "http://www.authority1.org");
layerEncoder.addAuthorityURL(authorityURL);
// identifier
GSIdentifierInfoEncoder identifier1 = new GSIdentifierInfoEncoder(
"authority1", "identifier1");
GSIdentifierInfoEncoder identifier2 = new GSIdentifierInfoEncoder(
"authority1", "another_identifier");
layerEncoder.addIdentifier(identifier1);
layerEncoder.addIdentifier(identifier2);
publisher.createWorkspace(DEFAULT_WS); publisher.createWorkspace(DEFAULT_WS);
File zipFile = new ClassPathResource("testdata/resttestshp.zip").getFile(); File zipFile = new ClassPathResource("testdata/resttestshp.zip").getFile();
@ -86,52 +132,9 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
publisher.publishStyle(new File(new ClassPathResource("testdata").getFile(), publisher.publishStyle(new File(new ClassPathResource("testdata").getFile(),
"default_point.sld")); "default_point.sld"));
GSFeatureTypeEncoder fte = new GSFeatureTypeEncoder();
fte.setNativeName(layerName);
fte.setName(layerName + "_NEW");
fte.setTitle("title");
// fte.addKeyword("TODO");
fte.setNativeCRS("EPSG:4326");
fte.setDescription("desc");
fte.setEnabled(true);
// metadataLink
GSMetadataLinkInfoEncoder metadatalink = new GSMetadataLinkInfoEncoder("text/xml",
"ISO19115:2003", "http://www.organization.org/metadata1");
fte.addMetadataLinkInfo(metadatalink);
GSLayerEncoder layerEncoder = null;
if (VERSION.getVersion(GS_VERSION) == VERSION.UNRECOGNIZED ) {
layerEncoder = new GSLayerEncoder21();
} else {
layerEncoder = new GSLayerEncoder();
}
layerEncoder.setEnabled(true);
layerEncoder.setQueryable(true);
layerEncoder.setAdvertised(true);
layerEncoder.setDefaultStyle("point");
layerEncoder.addStyle("point2");
layerEncoder.addStyle("point3");
// authorityURL
GSAuthorityURLInfoEncoder authorityURL = new GSAuthorityURLInfoEncoder("authority1",
"http://www.authority1.org");
layerEncoder.addAuthorityURL(authorityURL);
// identifier
GSIdentifierInfoEncoder identifier1 = new GSIdentifierInfoEncoder("authority1",
"identifier1");
GSIdentifierInfoEncoder identifier2 = new GSIdentifierInfoEncoder("authority1",
"another_identifier");
layerEncoder.addIdentifier(identifier1);
layerEncoder.addIdentifier(identifier2);
// optionally select the attributes to publish // optionally select the attributes to publish
RESTLayer layer = reader.getLayer(DEFAULT_WS, layerName); RESTLayer layer = reader.getLayer(layerName);
RESTFeatureType resource = reader.getFeatureType(layer); RESTResource resource = reader.getResource(layer);
List<GSAttributeEncoder> attrs = resource.getEncodedAttributeList(); List<GSAttributeEncoder> attrs = resource.getEncodedAttributeList();
assertNotNull(attrs); assertNotNull(attrs);
for (GSAttributeEncoder enc : attrs) { for (GSAttributeEncoder enc : attrs) {
@ -139,7 +142,6 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
} }
assertTrue(publisher.publishDBLayer(DEFAULT_WS, storeName, fte, layerEncoder)); assertTrue(publisher.publishDBLayer(DEFAULT_WS, storeName, fte, layerEncoder));
} }
@Test @Test
@ -178,36 +180,36 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
GSFeatureDimensionInfoEncoder dim2 = new GSFeatureDimensionInfoEncoder("ELE"); GSFeatureDimensionInfoEncoder dim2 = new GSFeatureDimensionInfoEncoder("ELE");
encoder.setMetadataDimension("elevation", dim2); encoder.addMetadata("elevation", dim2);
dim2.setPresentation(Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(10)); dim2.setPresentation(PresentationDiscrete.DISCRETE_INTERVAL, BigDecimal.valueOf(10));
Element el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.PRESENTATION); Element el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.PRESENTATION);
assertNotNull(el); Assert.assertNotNull(el);
LOGGER.info("contains_key:" + el.toString()); LOGGER.info("contains_key:" + el.toString());
dim2.setPresentation(Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(12)); dim2.setPresentation(PresentationDiscrete.DISCRETE_INTERVAL, BigDecimal.valueOf(12));
el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.RESOLUTION); el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.RESOLUTION);
assertNotNull(el); Assert.assertNotNull(el);
assertEquals("12", el.getText()); Assert.assertEquals("12", el.getText());
dim2.setPresentation(Presentation.CONTINUOUS_INTERVAL); dim2.setPresentation(Presentation.CONTINUOUS_INTERVAL);
encoder.setMetadataDimension("time", new GSFeatureDimensionInfoEncoder("time")); encoder.setMetadata("time", new GSFeatureDimensionInfoEncoder("time"));
el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.PRESENTATION); el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.PRESENTATION);
assertNotNull(el); Assert.assertNotNull(el);
el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.RESOLUTION); el = ElementUtils.contains(encoder.getRoot(), GSDimensionInfoEncoder.RESOLUTION);
assertNull(el); Assert.assertNull(el);
el = ElementUtils.contains(encoder.getRoot(), GSResourceEncoder.METADATA); el = ElementUtils.contains(encoder.getRoot(), GSResourceEncoder.METADATA);
assertNotNull(el); Assert.assertNotNull(el);
LOGGER.info("contains_key:" + el.toString()); LOGGER.info("contains_key:" + el.toString());
final boolean removed = ElementUtils.remove(encoder.getRoot(), el); final boolean removed = ElementUtils.remove(encoder.getRoot(), el);
LOGGER.info("remove:" + removed); LOGGER.info("remove:" + removed);
assertTrue(removed); Assert.assertTrue(removed);
el = ElementUtils.contains(encoder.getRoot(), "metadata"); el = ElementUtils.contains(encoder.getRoot(), "metadata");
assertNull(el); Assert.assertNull(el);
if (el == null) if (el == null)
LOGGER.info("REMOVED"); LOGGER.info("REMOVED");
@ -221,25 +223,19 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
public void testModifyFeature() { public void testModifyFeature() {
GSFeatureTypeEncoder encoder = new GSFeatureTypeEncoder(); GSFeatureTypeEncoder encoder = new GSFeatureTypeEncoder();
encoder.addKeyword("KEYWORD_1"); encoder.addKeyword("KEYWORD_1");
encoder.addKeyword("KEYWORD_1", "LAN_1", "VOCAB_1"); encoder.addKeyword("KEYWORD_2");
assertTrue(encoder.delKeyword("KEYWORD_1", "LAN_1", "VOCAB_1"));
encoder.addKeyword("..."); encoder.addKeyword("...");
encoder.addKeyword("KEYWORD_N"); encoder.addKeyword("KEYWORD_N");
assertFalse(encoder.delKeyword("KEYWORD_M"));
encoder.addKeyword("KEYWORD_2"); Assert.assertTrue(encoder.delKeyword("KEYWORD_2"));
assertFalse(encoder.delKeyword("KEYWORD_2", "LAN_1", "VOCAB_1")); Assert.assertFalse(encoder.delKeyword("KEYWORD_M"));
assertTrue(encoder.delKeyword("KEYWORD_2"));
//metadataLinkInfo //metadataLinkInfo
encoder.addMetadataLinkInfo("text/xml", "ISO19115:2003", encoder.addMetadataLinkInfo("text/xml", "ISO19115:2003","http://www.organization.org/metadata1");
"http://www.organization.org/metadata1"); encoder.addMetadataLinkInfo("text/html", "ISO19115:2003","http://www.organization.org/metadata2");
encoder.addMetadataLinkInfo("text/html", "ISO19115:2003",
"http://www.organization.org/metadata2");
assertTrue(encoder.delMetadataLinkInfo("http://www.organization.org/metadata2")); Assert.assertTrue(encoder.delMetadataLinkInfo("http://www.organization.org/metadata2"));
assertFalse(encoder.delMetadataLinkInfo("http://www.organization.org/metadata3")); Assert.assertFalse(encoder.delMetadataLinkInfo("http://www.organization.org/metadata3"));
//dimensions //dimensions
final GSFeatureDimensionInfoEncoder elevationDimension = new GSFeatureDimensionInfoEncoder( final GSFeatureDimensionInfoEncoder elevationDimension = new GSFeatureDimensionInfoEncoder(
@ -249,21 +245,22 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
// LOGGER.info(encoder.toString()); // LOGGER.info(encoder.toString());
final String metadata = "elevation"; final String metadata = "elevation";
encoder.setMetadataDimension(metadata, elevationDimension); encoder.setMetadata(metadata, elevationDimension);
elevationDimension.setPresentation(Presentation.DISCRETE_INTERVAL, BigDecimal.valueOf(10)); elevationDimension.setPresentation(PresentationDiscrete.DISCRETE_INTERVAL,
BigDecimal.valueOf(10));
if (LOGGER.isInfoEnabled()) if (LOGGER.isInfoEnabled())
LOGGER.info(encoder.toString()); LOGGER.info(encoder.toString());
assertTrue(encoder.delMetadata(metadata)); Assert.assertTrue(encoder.delMetadata(metadata));
if (LOGGER.isInfoEnabled()) if (LOGGER.isInfoEnabled())
LOGGER.info(encoder.toString()); LOGGER.info(encoder.toString());
final Element el = ElementUtils.contains(encoder.getRoot(), final Element el = ElementUtils.contains(encoder.getRoot(),
GSDimensionInfoEncoder.DIMENSIONINFO); GSDimensionInfoEncoder.DIMENSIONINFO);
assertNull(el); Assert.assertNull(el);
if (el == null) if (el == null)
LOGGER.info("REMOVED"); LOGGER.info("REMOVED");
@ -272,39 +269,26 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
/** /**
* Test method for virtual table encoding / SQL view layer integration * Test method for virtual table encoding / SQL view layer integration
* *
* Settings information for integration tests - test is based on the data used in * Settings information for integration tests
* http://docs.geoserver.org/latest/en/user/data/database/sqlview.html#parameterizing-sql-views (states shapefile - available in * - test is based on the data used in http://docs.geoserver.org/latest/en/user/data/database/sqlview.html#parameterizing-sql-views
* testdata/states.zip) - create a postgis db - import the states shapefile (using shp2pgsql or Postgis shapefile uploader) - In Geoserver, create * (states shapefile - available in testdata/states.zip)
* a postgis datastore for this DB, with the name "statesdb" * - create a postgis db
* * - import the states shapefile (using shp2pgsql or Postgis shapefile uploader)
* @throws IOException * - In Geoserver, create a postgis datastore for this DB, with the name "statesdb"
* *
*/ */
@Test @Test
public void testSQLViewIntegration() throws IOException { public void testSQLViewIntegration() {
if (!enabled()) if (!enabled())
return; return;
deleteAll(); deleteAll();
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(RESTURL,
RESTUSER, RESTPW);
GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(RESTURL, RESTUSER, RESTPW); String storeName = "statesdb"; // name of the datastore setup for tests
String layerName = "my_sqlviewlayer";
String storeName = "resttestshp"; String nativeName = "popstates";
String layerName = "cities";
// build the store
publisher.createWorkspace(DEFAULT_WS);
// test insert
File zipFile = new ClassPathResource("testdata/resttestshp.zip").getFile();
boolean published = publisher.publishShp(DEFAULT_WS, storeName, layerName, zipFile);
assertTrue("publish() failed", published);
publisher.publishStyle(new File(new ClassPathResource("testdata").getFile(),
"default_point.sld"));
String nativeName = layerName;
layerName=layerName+"_NEW";
GSFeatureTypeEncoder fte = new GSFeatureTypeEncoder(); GSFeatureTypeEncoder fte = new GSFeatureTypeEncoder();
fte.setName(layerName); fte.setName(layerName);
@ -320,11 +304,14 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
// virtual table // virtual table
// ------------- // -------------
// Set-up the vtGeom // Set-up the vtGeom
final VTGeometryEncoder vtGeom = new VTGeometryEncoder("the_geom", "Point", "4326"); final VTGeometryEncoder vtGeom = new VTGeometryEncoder("the_geom",
"Point", "4326");
// Set-up 2 virtual table parameters // Set-up 2 virtual table parameters
final VTParameterEncoder vtParam1 = new VTParameterEncoder("high", "100000000", "^[\\d]+$"); final VTParameterEncoder vtParam1 = new VTParameterEncoder("high",
final VTParameterEncoder vtParam2 = new VTParameterEncoder("low", "0", "^[\\d]+$"); "100000000", "^[\\d]+$");
final VTParameterEncoder vtParam2 = new VTParameterEncoder("low", "0",
"^[\\d]+$");
// sql // sql
String sql = "select gid, state_name, the_geom from pgstates where persons between %low% and %high% and state_abbr = '%state%'"; String sql = "select gid, state_name, the_geom from pgstates where persons between %low% and %high% and state_abbr = '%state%'";
@ -336,17 +323,17 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
vte.addVirtualTableGeometry(vtGeom); vte.addVirtualTableGeometry(vtGeom);
vte.addVirtualTableParameter(vtParam1); vte.addVirtualTableParameter(vtParam1);
vte.addVirtualTableParameter(vtParam2); vte.addVirtualTableParameter(vtParam2);
fte.setMetadataVirtualTable(vte); // Set the virtual table
// modif the vte // modif the vte
vte.delVirtualTableGeometry("the_geom"); vte.delVirtualTableGeometry("the_geom");
vte.addVirtualTableGeometry("the_geom", "MultiPolygon", "4326"); vte.addVirtualTableGeometry("the_geom", "MultiPolygon", "4326");
final VTParameterEncoder vtParam3 = new VTParameterEncoder("state", "FL", "^[\\w\\d\\s]+$"); final VTParameterEncoder vtParam3 = new VTParameterEncoder("state",
"FL", "^[\\w\\d\\s]+$");
vte.addVirtualTableParameter(vtParam3); vte.addVirtualTableParameter(vtParam3);
vte.addKeyColumn("gid"); vte.addKeyColumn("gid");
fte.setMetadataVirtualTable(vte); // Set the virtual table
// Layer encoder // Layer encoder
// ------------- // -------------
GSLayerEncoder layerEncoder = new GSLayerEncoder(); GSLayerEncoder layerEncoder = new GSLayerEncoder();
@ -357,9 +344,10 @@ public class GSFeatureEncoderTest extends GeoserverRESTTest {
// test insert // test insert
// ------------ // ------------
publisher.createWorkspace(DEFAULT_WS); publisher.createWorkspace(DEFAULT_WS);
published = publisher.publishDBLayer(DEFAULT_WS, storeName, fte, layerEncoder); boolean published = publisher.publishDBLayer(DEFAULT_WS, storeName,
assertTrue("Publication unsuccessful", published); fte, layerEncoder);
assertTrue("Layer does not exist", existsLayer(layerName)); assertTrue("Successfull publication", published);
assertTrue(existsLayer(layerName));
} }
} }

View File

@ -1,10 +1,14 @@
package it.geosolutions.geoserver.rest.encoder.feature; package it.geosolutions.geoserver.rest.encoder.feature;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.GSVirtualTableEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.GSVirtualTableEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTGeometry;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTGeometryEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTGeometryEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTParameter;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTParameterEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTParameterEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTGeometry;
import it.geosolutions.geoserver.rest.encoder.metadata.virtualtable.VTParameter;
import it.geosolutions.geoserver.rest.encoder.utils.XmlElement;
import java.util.Arrays;
import junit.framework.Assert; import junit.framework.Assert;
import org.jdom.Element; import org.jdom.Element;

View File

@ -1,337 +0,0 @@
package it.geosolutions.geoserver.rest.manager;
import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTCoverage;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageGranulesList;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageGranulesList.RESTStructuredCoverageGranule;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageIndexSchema;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageIndexSchema.RESTStructuredCoverageIndexAttribute;
import it.geosolutions.geoserver.rest.encoder.coverage.GSImageMosaicEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
/**
* Self contained test for working with Structured readers
*
*
* @author Simone Giannecchini, simone.giannecchini@geo-solutions.it
* @author Daniele Romagnoli, GeoSolutions SAS
*
*/
public class GeoServerRESTImageMosaicManagerTest extends GeoserverRESTTest {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoServerRESTImageMosaicManagerTest.class);
/**
* This test is ignored because it cannot be repeated.
* Once the test is run, the index is created for the granules, but it won't be removed,
* so next run will still find all the granules in the db.
*
* Tried with purge=metadata when removing datastores, but removing indices
* in shapefiles is not supported by geoserver (which throws an UnsupportedOperation)
* Adding a datastore.properties for using an h2 DB won't work as well, because
* only postgis is supported at lower levels.
*
* @throws Exception
*/
@Ignore
@Test
public void createAndDelete() throws Exception{
if (!enabled()) {
return;
}
deleteAll();
assertFalse("Workspace was not properly removed", reader.existsNamespace(DEFAULT_WS) );
publisher.createWorkspace(DEFAULT_WS);
// crea the manager
GeoServerRESTStructuredGridCoverageReaderManager manager =
new GeoServerRESTStructuredGridCoverageReaderManager(new URL(RESTURL), RESTUSER, RESTPW);
// create mosaic
final String coverageStoreName = "mosaic";
final String coverageName = "mosaic";
final String format = "imagemosaic";
assertFalse("CoverageStore was not properly removed", reader.existsCoveragestore(DEFAULT_WS, coverageStoreName));
// upload the mosaic
boolean create=manager.create(DEFAULT_WS, coverageStoreName,new ClassPathResource("testdata/granules/mosaic.zip").getFile().getAbsolutePath());
assertTrue(create);
// enable dimension
fixDimensions(DEFAULT_WS, coverageStoreName, coverageName);
// check index format
RESTStructuredCoverageIndexSchema indexFormat = manager.getGranuleIndexSchema(DEFAULT_WS, coverageName,coverageName);
assertNotNull(indexFormat);
assertFalse(indexFormat.isEmpty());
assertEquals(5, indexFormat.size());
Set<String> allowedDateFormats = new HashSet<String>(Arrays.asList(
"java.util.Date", // shapefile
"java.sql.Timestamp")); // h2
for (RESTStructuredCoverageIndexAttribute element : indexFormat) {
final String elementName = element.getName();
if (elementName.equals("location")) {
assertEquals("0", element.getMinOccurs());
assertEquals("1", element.getMaxOccurs());
assertEquals("true", element.getNillable());
assertEquals("java.lang.String", element.getBinding());
} else if (elementName.equals("time")) {
assertEquals("0", element.getMinOccurs());
assertEquals("1", element.getMaxOccurs());
assertEquals("true", element.getNillable());
assertTrue(allowedDateFormats.contains(element.getBinding()));
} else if (elementName.equals("date")) {
assertEquals("0", element.getMinOccurs());
assertEquals("1", element.getMaxOccurs());
assertEquals("true", element.getNillable());
assertEquals("java.lang.String", element.getBinding());
} else if (elementName.equals("depth")) {
assertEquals("0", element.getMinOccurs());
assertEquals("1", element.getMaxOccurs());
assertEquals("true", element.getNillable());
assertEquals("java.lang.Integer", element.getBinding());
}
}
RESTStructuredCoverageGranulesList granulesList = null;
RESTStructuredCoverageGranule granule = null;
// get with paging
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName , null, 0, 1);
assertNotNull(granulesList);
assertEquals(1, granulesList.size());
assertFalse(granulesList.isEmpty());
granule = granulesList.get(0);
assertNotNull(granule);
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName, null, null, 2);
assertNotNull(granulesList);
assertEquals(2, granulesList.size());
assertFalse(granulesList.isEmpty());
granule = granulesList.get(0);
assertNotNull(granule);
// get with no paging
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName);
assertNotNull(granulesList);
for (RESTStructuredCoverageGranule g : granulesList) {
LOGGER.info(" GRANULE before delete: " + g);
}
assertEquals("At first insertion 4 granules are expected", 4, granulesList.size());
assertFalse(granulesList.isEmpty());
granule = granulesList.get(0);
assertNotNull(granule);
// examples of filtering with CQL
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName, "depth = 100", null, null);
assertNotNull(granulesList);
assertEquals(2, granulesList.size());
assertFalse(granulesList.isEmpty());
granule = granulesList.get(0);
assertNotNull(granule);
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName, "depth = 100 AND date='20081101T0000000'", null, null);
assertNotNull(granulesList);
assertEquals(1, granulesList.size());
assertFalse(granulesList.isEmpty());
granule = granulesList.get(0);
assertNotNull(granule);
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName, "location LIKE 'NCOM_wattemp%'", 0, 1);
assertNotNull(granulesList);
assertEquals(1, granulesList.size());
assertFalse(granulesList.isEmpty());
granule = granulesList.get(0);
assertNotNull(granule);
// remove by filter
final String fileLocation = "NCOM_wattemp_100_20081101T0000000_12.tiff";
boolean result = manager.removeGranulesByCQL(DEFAULT_WS, coverageStoreName, coverageName, "location = '" + fileLocation + "'");
Assert.assertTrue(result);
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName);
assertNotNull(granulesList);
assertFalse(granulesList.isEmpty());
for (RESTStructuredCoverageGranule g : granulesList) {
LOGGER.info(" GRANULE: " + g);
}
assertEquals("After deletion only 3 granules are expected", 3, granulesList.size());
granule = granulesList.get(0);
assertNotNull(granule);
// Readding that granule with harvest
result = manager.harvestExternal(DEFAULT_WS, coverageStoreName, format, new ClassPathResource("testdata/granules/NCOM_wattemp_100_20081101T0000000_12.tiff").getFile().getAbsolutePath() );
Assert.assertTrue(result);
granulesList = manager.getGranules(DEFAULT_WS, coverageStoreName, coverageName, null, null, null);
assertNotNull(granulesList);
assertEquals("After harvest 4 granules are expected", 4, granulesList.size());
assertFalse(granulesList.isEmpty());
granule = granulesList.get(0);
assertNotNull(granule);
// delete
delete(DEFAULT_WS, coverageStoreName);
}
/**
* This method enables the various dimensions for the coverage autocreated for this test.
*
* <p> Notice that
* @param wsName the workspace
* @param coverageStoreName the coverage store name
* @param csname the coverage name
*/
private void fixDimensions(String wsName, String coverageStoreName, String csname) {
final GSImageMosaicEncoder coverageEncoder = copyParameters(wsName, coverageStoreName,
csname);
// activate time dimension
final GSDimensionInfoEncoder time=new GSDimensionInfoEncoder(true);
time.setUnit("Seconds");
time.setUnitSymbol("s");
time.setPresentation(Presentation.CONTINUOUS_INTERVAL);
coverageEncoder.setMetadataDimension("time", time);
// activate run which is a custom dimension
final GSDimensionInfoEncoder date=new GSDimensionInfoEncoder(true);
date.setPresentation(Presentation.LIST);
coverageEncoder.setMetadataDimension("date", date,true);
final GSDimensionInfoEncoder depth=new GSDimensionInfoEncoder(true);
depth.setPresentation(Presentation.LIST);
depth.setUnit("Meters");
depth.setUnitSymbol("m");
coverageEncoder.setMetadataDimension("depth", depth,true);
// persiste the changes
boolean config=publisher.configureCoverage(coverageEncoder, wsName, csname);
assertTrue(config);
}
/**
* @param wsName
* @param coverageStoreName
* @param csname
* @return
* @throws NumberFormatException
*/
private GSImageMosaicEncoder copyParameters(String wsName, String coverageStoreName,
String csname) throws NumberFormatException {
// get current config for the coverage to extract the params we want to set again
final RESTCoverage coverage = reader.getCoverage(wsName, coverageStoreName, csname);
if (coverage==null)
return null;
final Map<String, String> params = coverage.getParametersList();
// prepare and fill the encoder
final GSImageMosaicEncoder coverageEncoder = new GSImageMosaicEncoder();
coverageEncoder.setName("mosaic");
// set the current params, change here if you want to change the values
for(Map.Entry<String, String> entry:params.entrySet()){
if(entry.getKey().equals(GSImageMosaicEncoder.allowMultithreading)){
coverageEncoder.setAllowMultithreading(Boolean.parseBoolean(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.backgroundValues)){
coverageEncoder.setBackgroundValues(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.filter)){
coverageEncoder.setFilter(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.inputTransparentColor)){
coverageEncoder.setInputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.maxAllowedTiles)){
coverageEncoder.setMaxAllowedTiles(Integer.parseInt(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.MERGEBEHAVIOR)){
coverageEncoder.setMergeBehavior(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.outputTransparentColor)){
coverageEncoder.setOutputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SORTING)){
coverageEncoder.setSORTING(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SUGGESTED_TILE_SIZE)){
coverageEncoder.setSUGGESTED_TILE_SIZE(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.USE_JAI_IMAGEREAD)){
coverageEncoder.setUSE_JAI_IMAGEREAD(Boolean.parseBoolean(entry.getValue()));
continue;
}
}
return coverageEncoder;
}
/**
* Deletes the provided coverage recursively with purging.
* @param workspaceName
* @param coverageStoreName
* @throws Exception
*/
private void delete(String workspaceName, String coverageStoreName) throws Exception {
if (!enabled()) {
return;
}
// delete mosaic
boolean result = publisher.removeCoverageStore(workspaceName, coverageStoreName, true);
assertTrue(result);
}
}

View File

@ -1,7 +1,7 @@
/* /*
* GeoServer-Manager - Simple Manager Library for GeoServer * GeoServer-Manager - Simple Manager Library for GeoServer
* *
* Copyright (C) 2007 - 2016 GeoSolutions S.A.S. * Copyright (C) 2007,2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it * http://www.geo-solutions.it
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
@ -36,8 +36,6 @@ import java.nio.charset.Charset;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Ignore;
/** /**
* Test datastore handling (create, read and update): * Test datastore handling (create, read and update):
@ -65,11 +63,9 @@ import org.junit.Ignore;
* <li>Test all new values. * <li>Test all new values.
* </ol> * </ol>
* *
* @deprecated ignored since dir of shapes cannot be uploaded
* @author Oscar Fonts * @author Oscar Fonts
*/ */
@Ignore public class GeoserverRESTDatastoreManagerTest extends StoreIntegrationTest {
public class DirShapeStoreManagerTest extends StoreIntegrationTest {
private static final String WS_NAME = DEFAULT_WS; private static final String WS_NAME = DEFAULT_WS;
@ -81,9 +77,9 @@ public class DirShapeStoreManagerTest extends StoreIntegrationTest {
private static URL LOCATION_2; private static URL LOCATION_2;
public DirShapeStoreManagerTest() throws Exception { public GeoserverRESTDatastoreManagerTest() throws Exception {
super(false); super(true);
LOCATION_1 = new URL("file:data/shapefiles/"); LOCATION_1 = new URL("file:data/1");
LOCATION_2 = new URL("file:data/2"); LOCATION_2 = new URL("file:data/2");
} }
@ -107,7 +103,7 @@ public class DirShapeStoreManagerTest extends StoreIntegrationTest {
// Create a directory of spatial files with default parameters // Create a directory of spatial files with default parameters
GSDirectoryOfShapefilesDatastoreEncoder create = new GSDirectoryOfShapefilesDatastoreEncoder( GSDirectoryOfShapefilesDatastoreEncoder create = new GSDirectoryOfShapefilesDatastoreEncoder(
DS_NAME, LOCATION_1); DS_NAME, LOCATION_1);
assertTrue("Could not create create store", manager.getStoreManager().create(WS_NAME, create)); assertTrue(manager.getStoreManager().create(WS_NAME, create));
// Read the store from server; check all parameter values // Read the store from server; check all parameter values
RESTDataStore read = reader.getDatastore(WS_NAME, DS_NAME); RESTDataStore read = reader.getDatastore(WS_NAME, DS_NAME);
@ -134,14 +130,14 @@ public class DirShapeStoreManagerTest extends StoreIntegrationTest {
update.setCacheAndReuseMemoryMaps(false); update.setCacheAndReuseMemoryMaps(false);
// update the store // update the store
assertTrue("Could not update store " + WS_NAME, manager.getStoreManager().update(WS_NAME, update)); assertTrue(manager.getStoreManager().update(WS_NAME, update));
// Read again, check that all parameters have changed // Read again, check that all parameters have changed
read = reader.getDatastore(WS_NAME, DS_NAME); read = reader.getDatastore(WS_NAME, DS_NAME);
assertEquals("Bad workspace name", read.getWorkspaceName(), WS_NAME); assertEquals(read.getWorkspaceName(), WS_NAME);
assertEquals("Datastore should not be enabled", read.isEnabled(), false); assertEquals(read.isEnabled(), false);
connParams = read.getConnectionParameters(); connParams = read.getConnectionParameters();
assertEquals("Bad URL", connParams.get("url"), LOCATION_2.toString()); assertEquals(connParams.get("url"), LOCATION_2.toString());
assertEquals(connParams.get("charset"), "UTF-8"); assertEquals(connParams.get("charset"), "UTF-8");
assertEquals(connParams.get("create spatial index"), "false"); assertEquals(connParams.get("create spatial index"), "false");
assertEquals(connParams.get("memory mapped buffer"), "true"); assertEquals(connParams.get("memory mapped buffer"), "true");

View File

@ -1,180 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2016 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.publisher;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.StoreType;
import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTCoverageStore;
import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* Testcase for publishing layers on geoserver.
* We need a running GeoServer to properly run the tests.
* If such geoserver instance cannot be contacted, tests will be skipped.
*
* @author Lennart Karsten - lennart.k@thinking-aloud.eu
* inspired by: Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
*/
public class GeoserverRESTArcGridTest extends GeoserverRESTTest {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTArcGridTest.class);
private String storeName = "testRESTStoreArcGrid";
private String layerName = "resttestdem";
@Test
public void testExternalArcGrid() throws FileNotFoundException, IOException {
if (!enabled()) return;
deleteAll();
File arcgrid = new ClassPathResource("testdata/resttestdem.asc").getFile();
assertTrue(reader.getWorkspaces().isEmpty());
assertTrue(publisher.createWorkspace(DEFAULT_WS));
// known state?
assertFalse("Cleanup failed", existsLayer(layerName));
// Test exists
assertFalse(reader.existsLayer(DEFAULT_WS, layerName));
// test insert
boolean pc = publisher.publishExternalArcGrid(DEFAULT_WS, storeName, arcgrid, layerName,"EPSG:4326",ProjectionPolicy.FORCE_DECLARED,"raster");
assertTrue("publish() failed", pc);
assertTrue(existsLayer(layerName));
assertFalse(reader.existsLayer(DEFAULT_WS, layerName));
LOGGER.info("Published "+pc);
RESTCoverageStore reloadedCS = reader.getCoverageStore(DEFAULT_WS, storeName);
assertEquals(storeName, reloadedCS.getName());
assertEquals(DEFAULT_WS, reloadedCS.getWorkspaceName());
//test delete
assertTrue("Unpublish() failed", publisher.unpublishCoverage(DEFAULT_WS, storeName, layerName));
assertTrue("Unpublish() failed", publisher.removeCoverageStore(DEFAULT_WS, storeName));
assertFalse("Bad unpublish()", publisher.unpublishCoverage(DEFAULT_WS, storeName, layerName));
assertFalse(existsLayer(layerName));
}
@Test
public void testArcGrid() throws FileNotFoundException, IOException {
if (!enabled()) return;
deleteAll();
File arcgrid = new ClassPathResource("testdata/resttestdem.asc").getFile();
assertTrue(reader.getWorkspaces().isEmpty());
assertTrue(publisher.createWorkspace(DEFAULT_WS));
// known state?
assertFalse("Cleanup failed", existsLayer(layerName));
// test insert
boolean pub = publisher.publishArcGrid(DEFAULT_WS, storeName, arcgrid);
assertNotNull("publish() failed", pub);
// Test exists
assertTrue(reader.existsCoveragestore(DEFAULT_WS, storeName));
assertTrue(reader.existsCoverage(DEFAULT_WS, storeName, storeName));
pub = publisher.publishArcGrid(DEFAULT_WS, storeName+"another", "layername", arcgrid);
assertTrue("publish() failed", pub);
double[] bbox = {-103.85, 44.38, -103.62, 44.50};
pub = publisher.publishArcGrid(DEFAULT_WS, storeName+"another_complex", storeName+"another_complex", arcgrid, "EPSG:4326", ProjectionPolicy.REPROJECT_TO_DECLARED, "raster", bbox);
assertTrue("publish() failed", pub);
//delete
assertTrue("Unpublish() failed", publisher.removeCoverageStore(DEFAULT_WS, storeName,true));
// Test not exists
assertFalse(reader.existsCoveragestore(DEFAULT_WS, storeName));
}
@Test
public void testArcGridWithStyleInWorkspace() throws IOException {
if (!enabled()) return;
deleteAll();
File arcgrid = new ClassPathResource("testdata/resttestdem.asc").getFile();
assertTrue(reader.getWorkspaces().isEmpty());
assertTrue(publisher.createWorkspace(DEFAULT_WS));
File sldFile = new ClassPathResource("testdata/raster.sld").getFile();
// insert style
assertTrue(publisher.publishStyleInWorkspace(DEFAULT_WS, sldFile, "mystyle"));
assertTrue(reader.existsStyle(DEFAULT_WS, "mystyle"));
// known state?
assertFalse("Cleanup failed", existsLayer(layerName));
// test insert
boolean pub = publisher.publishArcGrid(DEFAULT_WS, storeName, storeName,
arcgrid, "EPSG:4326", ProjectionPolicy.FORCE_DECLARED, DEFAULT_WS + ":" + "mystyle", null);
assertNotNull("publish() failed", pub);
// Test exists
assertTrue(reader.existsCoveragestore(DEFAULT_WS, storeName));
assertTrue(reader.existsCoverage(DEFAULT_WS, storeName, storeName));
RESTLayer layer = reader.getLayer(DEFAULT_WS, storeName);
assertEquals(DEFAULT_WS + ":mystyle", layer.getDefaultStyle());
assertEquals(DEFAULT_WS, layer.getDefaultStyleWorkspace());
}
@Test
public void testReloadCoverageStore() throws FileNotFoundException, IOException {
if (!enabled()) return;
deleteAll();
File arcgrid = new ClassPathResource("testdata/resttestdem.asc").getFile();
assertTrue(publisher.createWorkspace(DEFAULT_WS));
// test insert
boolean pub = publisher.publishArcGrid(DEFAULT_WS, storeName, arcgrid);
assertNotNull("publish() failed", pub);
// test reload
assertTrue(publisher.reloadStore(DEFAULT_WS, storeName, StoreType.COVERAGESTORES));
}
}

View File

@ -25,20 +25,17 @@
package it.geosolutions.geoserver.rest.publisher; package it.geosolutions.geoserver.rest.publisher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.StoreType;
import it.geosolutions.geoserver.rest.GeoserverRESTTest; import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.StoreType;
import it.geosolutions.geoserver.rest.decoder.RESTCoverageStore; import it.geosolutions.geoserver.rest.decoder.RESTCoverageStore;
import it.geosolutions.geoserver.rest.decoder.RESTLayer;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy; import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -72,14 +69,10 @@ public class GeoserverRESTGeoTiffTest extends GeoserverRESTTest {
// known state? // known state?
assertFalse("Cleanup failed", existsLayer(layerName)); assertFalse("Cleanup failed", existsLayer(layerName));
// Test exists
assertFalse(reader.existsLayer(DEFAULT_WS, layerName));
// test insert // test insert
boolean pc = publisher.publishExternalGeoTIFF(DEFAULT_WS, storeName, geotiff, layerName,"EPSG:4326",ProjectionPolicy.FORCE_DECLARED,"raster"); boolean pc = publisher.publishExternalGeoTIFF(DEFAULT_WS, storeName, geotiff, layerName,"EPSG:4326",ProjectionPolicy.FORCE_DECLARED,"raster");
assertTrue("publish() failed", pc); assertTrue("publish() failed", pc);
assertTrue(existsLayer(layerName)); assertTrue(existsLayer(layerName));
assertFalse(reader.existsLayer(DEFAULT_WS, layerName));
LOGGER.info("Published "+pc); LOGGER.info("Published "+pc);
RESTCoverageStore reloadedCS = reader.getCoverageStore(DEFAULT_WS, storeName); RESTCoverageStore reloadedCS = reader.getCoverageStore(DEFAULT_WS, storeName);
@ -110,58 +103,20 @@ public class GeoserverRESTGeoTiffTest extends GeoserverRESTTest {
boolean pub = publisher.publishGeoTIFF(DEFAULT_WS, storeName, geotiff); boolean pub = publisher.publishGeoTIFF(DEFAULT_WS, storeName, geotiff);
assertNotNull("publish() failed", pub); assertNotNull("publish() failed", pub);
// Test exists
assertTrue(reader.existsCoveragestore(DEFAULT_WS, storeName));
assertTrue(reader.existsCoverage(DEFAULT_WS, storeName, storeName));
pub = publisher.publishGeoTIFF(DEFAULT_WS, storeName+"another", "layername", geotiff); pub = publisher.publishGeoTIFF(DEFAULT_WS, storeName+"another", "layername", geotiff);
assertTrue("publish() failed", pub); assertTrue("publish() failed", pub);
double[] bbox = {-103.85, 44.38, -103.62, 44.50}; double[] bbox = {-103.85, 44.38, -103.62, 44.50};
pub = publisher.publishGeoTIFF(DEFAULT_WS, storeName+"another_complex", storeName+"another_complex", geotiff, "EPSG:4326", ProjectionPolicy.REPROJECT_TO_DECLARED, "raster", bbox); pub = publisher.publishGeoTIFF(DEFAULT_WS, storeName+"another_complex", "layername_complex", geotiff, "EPSG:4326", ProjectionPolicy.REPROJECT_TO_DECLARED, "raster", bbox);
assertTrue("publish() failed", pub); assertTrue("publish() failed", pub);
//delete //delete
assertTrue("Unpublish() failed", publisher.removeCoverageStore(DEFAULT_WS, storeName,true)); assertTrue("Unpublish() failed", publisher.removeCoverageStore(DEFAULT_WS, storeName,true));
// Test not exists
assertFalse(reader.existsCoveragestore(DEFAULT_WS, storeName));
} }
@Test
public void testGeoTiffWithStyleInWorkspace() throws IOException
{
if (!enabled()) return;
deleteAll();
File geotiff = new ClassPathResource("testdata/resttestdem.tif").getFile();
assertTrue(reader.getWorkspaces().isEmpty());
assertTrue(publisher.createWorkspace(DEFAULT_WS));
File sldFile = new ClassPathResource("testdata/raster.sld").getFile();
// insert style
assertTrue(publisher.publishStyleInWorkspace(DEFAULT_WS, sldFile, "mystyle"));
assertTrue(reader.existsStyle(DEFAULT_WS, "mystyle"));
// known state?
assertFalse("Cleanup failed", existsLayer(layerName));
// test insert
boolean pub = publisher.publishGeoTIFF(DEFAULT_WS, storeName, storeName,
geotiff, "EPSG:4326", ProjectionPolicy.FORCE_DECLARED, DEFAULT_WS + ":" + "mystyle", null);
assertNotNull("publish() failed", pub);
// Test exists
assertTrue("New coverage not found", reader.existsCoveragestore(DEFAULT_WS, storeName));
assertTrue("New Store not found", reader.existsCoverage(DEFAULT_WS, storeName, storeName));
RESTLayer layer = reader.getLayer(DEFAULT_WS, storeName);
assertEquals("Bad default style", DEFAULT_WS + ":mystyle", layer.getDefaultStyle());
assertEquals("Bad workspace for style", DEFAULT_WS, layer.getDefaultStyleWorkspace());
}
@Test @Test
public void testReloadCoverageStore() throws FileNotFoundException, IOException { public void testReloadCoverageStore() throws FileNotFoundException, IOException {

View File

@ -29,25 +29,18 @@ package it.geosolutions.geoserver.rest.publisher;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.ParameterConfigure; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.ParameterConfigure;
import it.geosolutions.geoserver.rest.GeoserverRESTTest; import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTCoverageStore; import it.geosolutions.geoserver.rest.decoder.RESTCoverageStore;
import it.geosolutions.geoserver.rest.decoder.RESTStructuredCoverageGranulesList;
import it.geosolutions.geoserver.rest.decoder.about.GSVersionDecoder;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder; import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy; import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy;
import it.geosolutions.geoserver.rest.encoder.coverage.GSImageMosaicEncoder; import it.geosolutions.geoserver.rest.encoder.coverage.GSImageMosaicEncoder;
import it.geosolutions.geoserver.rest.encoder.dimensions.GSCoverageDimensionEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder; import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation; import it.geosolutions.geoserver.rest.encoder.metadata.GSDimensionInfoEncoder.Presentation;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.NameValuePair;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
@ -80,7 +73,7 @@ public class GeoserverRESTImageMosaicTest extends GeoserverRESTTest {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTImageMosaicTest.class); private final static Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTImageMosaicTest.class);
@Test @Test
public void testCreateDeleteImageMosaicDatastore() throws MalformedURLException, UnsupportedEncodingException { public void testCreateDeleteImageMosaicDatastore() {
if (!enabled()) { if (!enabled()) {
return; return;
} }
@ -97,7 +90,7 @@ public class GeoserverRESTImageMosaicTest extends GeoserverRESTTest {
* or create a new one from an existing store: * or create a new one from an existing store:
* publisher.createCoverage(ce, wsname, csname); * publisher.createCoverage(ce, wsname, csname);
*/ */
// coverageEncoder.setName("time_geotiff"); coverageEncoder.setName("CoverageName");
coverageEncoder.setAllowMultithreading(true); coverageEncoder.setAllowMultithreading(true);
coverageEncoder.setBackgroundValues(""); coverageEncoder.setBackgroundValues("");
@ -111,15 +104,6 @@ public class GeoserverRESTImageMosaicTest extends GeoserverRESTTest {
coverageEncoder.setSRS("EPSG:4326"); coverageEncoder.setSRS("EPSG:4326");
coverageEncoder.setSUGGESTED_TILE_SIZE("256,256"); coverageEncoder.setSUGGESTED_TILE_SIZE("256,256");
coverageEncoder.setUSE_JAI_IMAGEREAD(true); coverageEncoder.setUSE_JAI_IMAGEREAD(true);
GSVersionDecoder v=reader.getGeoserverVersion();
if (v.compareTo(GSVersionDecoder.VERSION.v24)>=0){
GSCoverageDimensionEncoder gsCoverageDimensionEncoder = new GSCoverageDimensionEncoder(
"GRAY_INDEX", "GridSampleDimension[-Infinity,Infinity]", "-inf", "inf",
"dobson units", "REAL_32BITS");
coverageEncoder.addCoverageDimensionInfo(gsCoverageDimensionEncoder);
}
// activate time // activate time
final GSDimensionInfoEncoder time=new GSDimensionInfoEncoder(true); final GSDimensionInfoEncoder time=new GSDimensionInfoEncoder(true);
time.setPresentation(Presentation.LIST); time.setPresentation(Presentation.LIST);
@ -128,8 +112,6 @@ public class GeoserverRESTImageMosaicTest extends GeoserverRESTTest {
// not active elevation // not active elevation
coverageEncoder.setMetadata("elevation", new GSDimensionInfoEncoder()); coverageEncoder.setMetadata("elevation", new GSDimensionInfoEncoder());
assertTrue(publisher.createWorkspace(wsName)); assertTrue(publisher.createWorkspace(wsName));
LOGGER.info(coverageEncoder.toString()); LOGGER.info(coverageEncoder.toString());
@ -172,14 +154,7 @@ public class GeoserverRESTImageMosaicTest extends GeoserverRESTTest {
e.printStackTrace(); e.printStackTrace();
fail(e.getLocalizedMessage()); fail(e.getLocalizedMessage());
} }
// Get a Granule
String coverageName = "time_geotiff";
RESTStructuredCoverageGranulesList granules = reader.getGranules(wsName, coverageStoreName, coverageName, null, null, null);
String granuleId = granules.get(0).getFid();
// Test Granule Exists
assertTrue(reader.existsGranule(wsName, coverageStoreName, coverageName, granuleId));
// test a Granule does not exists
assertFalse(reader.existsGranule(wsName, coverageStoreName, coverageName, granuleId.substring(0, granuleId.indexOf(".")) + "." + granules.size() + 1));
// removing recursively coveragestore // removing recursively coveragestore
boolean removed = publisher.removeCoverageStore(coverageStore.getWorkspaceName(), coverageStore.getName(), true); boolean removed = publisher.removeCoverageStore(coverageStore.getWorkspaceName(), coverageStore.getName(), true);

View File

@ -1,97 +0,0 @@
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.publisher;
import static org.junit.Assert.assertEquals;
import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import net.sf.json.JSONObject;
import org.junit.After;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
/**
* Testcase for publishing layers on geoserver.
* We need a running GeoServer to properly run the tests.
* If such geoserver instance cannot be contacted, tests will be skipped.
*
* @author Alessio Fabiani, GeoSolutions S.A.S.
*
*/
public class GeoserverRESTImporterTest extends GeoserverRESTTest {
private final static Logger LOGGER = LoggerFactory.getLogger(GeoserverRESTImporterTest.class);
@After
public void cleanUp() {
}
@Test
public void testShapeFileImport() throws Exception {
if (!enabled())
return;
// Creates a new Importer Context and gets back the ID
int i = publisher.postNewImport();
// Attaches to the new Importer Context a Task pointing to a shapefile's zip archive
String data = new ClassPathResource("testdata/test_noepsg.zip").getFile().getAbsolutePath();
int t = publisher.postNewTaskAsMultiPartForm(i, data);
// Check that the Task was actually created and that the CRS has not recognized in this case
JSONObject task = publisher.getTask(i, t);
//assertEquals("NO_CRS", task.getString("state"));
assertEquals("READY", task.getString("state"));
// Prepare the JSON String instructing the Task about the SRS to use
String json = "{\"layer\":{\"srs\":\"EPSG:26713\"}}";
// Performing the Task update
publisher.putTaskLayer(i, t, json);
// Double check that the Task is in the READY state
task = publisher.getTask(i, t);
assertEquals("READY", task.getString("state"));
assertEquals("nurc_10m_populated_places", task.getJSONObject("layer").getJSONObject("style").getString("name"));
// Prepare the JSON String instructing the Task avout the SLD to use for the new Layer
json = "{\"layer\":{\"style\":{\"name\": \"point\"}}}";
// Performing the Task update
publisher.putTaskLayer(i, t,json);
// Double check that the Task is in the READY state and that the Style has been correctly updated
task = publisher.getTask(i, t);
assertEquals("READY", task.getString("state"));
assertEquals("point", task.getJSONObject("layer").getJSONObject("style").getString("name"));
// Finally starts the Import ...
publisher.postImport(i);
}
}

View File

@ -24,14 +24,13 @@
*/ */
package it.geosolutions.geoserver.rest.publisher; package it.geosolutions.geoserver.rest.publisher;
import org.junit.Test;
import it.geosolutions.geoserver.rest.GeoserverRESTTest; import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTNamespace; import it.geosolutions.geoserver.rest.decoder.RESTNamespace;
import java.net.URI; import java.net.URI;
import org.junit.Test;
import static org.junit.Assert.*;
/** /**
* Testcase for namespace management. * Testcase for namespace management.
* *
@ -58,10 +57,6 @@ public class GeoserverRESTNamespaceTest extends GeoserverRESTTest {
assertTrue(publisher.createNamespace("NS2", URI.create("http://b.example.com"))); assertTrue(publisher.createNamespace("NS2", URI.create("http://b.example.com")));
assertEquals(2, reader.getNamespaces().size()); assertEquals(2, reader.getNamespaces().size());
// Test Namespace exists
assertTrue(reader.existsNamespace("NS1"));
assertTrue(reader.existsNamespace("NS2"));
// When creating a namespace, its associated workspace will be automatically created: // When creating a namespace, its associated workspace will be automatically created:
assertEquals(2, reader.getWorkspaces().size()); assertEquals(2, reader.getWorkspaces().size());
@ -100,7 +95,5 @@ public class GeoserverRESTNamespaceTest extends GeoserverRESTTest {
assertEquals(0, reader.getNamespaces().size()); assertEquals(0, reader.getNamespaces().size());
assertEquals(0, reader.getWorkspaces().size()); assertEquals(0, reader.getWorkspaces().size());
// Test non existens
assertFalse(reader.existsNamespace("NS1"));
} }
} }

View File

@ -30,9 +30,13 @@ import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.datastore.StoreIntegrationTest; import it.geosolutions.geoserver.rest.datastore.StoreIntegrationTest;
import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder; import it.geosolutions.geoserver.rest.encoder.GSAbstractStoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder; import it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTStoreManager;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Testcase for creating postgis-based resources on geoserver. * Testcase for creating postgis-based resources on geoserver.
* <P> * <P>
@ -62,7 +66,7 @@ public class GeoserverRESTPostgisDatastoreTest extends StoreIntegrationTest {
public GeoserverRESTPostgisDatastoreTest() public GeoserverRESTPostgisDatastoreTest()
throws IllegalArgumentException, MalformedURLException { throws IllegalArgumentException, MalformedURLException {
super(System.getProperty("pgIgnore", "true").equalsIgnoreCase("true")); super(System.getProperty("pgIgnore", "false").equalsIgnoreCase("true"));
} }

View File

@ -30,7 +30,6 @@ import java.net.URI;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
/** /**

Some files were not shown because too many files have changed in this diff Show More