diff --git a/src/main/java/it/geosolutions/geoserver/rest/GeoServerRESTReader.java b/src/main/java/it/geosolutions/geoserver/rest/GeoServerRESTReader.java index 5aa06ef..37ae575 100644 --- a/src/main/java/it/geosolutions/geoserver/rest/GeoServerRESTReader.java +++ b/src/main/java/it/geosolutions/geoserver/rest/GeoServerRESTReader.java @@ -1,7 +1,7 @@ /* * GeoServer-Manager - Simple Manager Library for GeoServer * - * Copyright (C) 2007,2013 GeoSolutions S.A.S. + * 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 diff --git a/src/main/java/it/geosolutions/geoserver/rest/GeoWebCacheRESTManager.java b/src/main/java/it/geosolutions/geoserver/rest/GeoWebCacheRESTManager.java new file mode 100644 index 0000000..631db6c --- /dev/null +++ b/src/main/java/it/geosolutions/geoserver/rest/GeoWebCacheRESTManager.java @@ -0,0 +1,127 @@ +/* + * 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; + +import it.geosolutions.geoserver.rest.decoder.gwc.GWCRESTWMSLayer; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.util.logging.Level; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Nazzareno Sileno - CNR IMAA geoSDI Group + * @email nazzareno.sileno@geosdi.org + */ +public class GeoWebCacheRESTManager { + + private final static Logger LOGGER = LoggerFactory.getLogger(GeoWebCacheRESTManager.class); + + /** + * GeoWebCache instance base URL. E.g.: http://localhost:8080/geowebcache. + */ + private final String restURL; + + /** + * GeoWebCache instance privileged username, with read & write permission on REST API + */ + private final String gwcUser; + + /** + * GeoWebCache instance password for privileged username with r&w permission on REST API + */ + private final String gwcPass; + + /** + * Creates a GeoWebCacheRESTManager to connect against a GeoWebCache instance with the given URL and user credentials. + * + * @param restURL the base GeoWebCache URL (e.g.: http://localhost:8080/geowebcache) + * @param username auth credential + * @param password auth credential + */ + public GeoWebCacheRESTManager(String restURL, String username, String password) { + this.restURL = HTTPUtils.decurtSlash(restURL); + this.gwcUser = username; + this.gwcPass = password; + + URL url = null; + try { + url = new URL(restURL); + } catch (MalformedURLException ex) { + LOGGER.error("Bad URL: Calls to GeoWebCache are going to fail" , ex); + } + } + + /** + * Check if a GeoWebCache instance is running at the given URL. + *
+ * Return true if the configured GeoWebCache is up and replies to REST requests. + *
+ * Send a HTTP GET request to the configured URL.
+ * Return true if a HTTP 200 code (OK) is read from the HTTP response; + * any other response code, or connection error, will return a + * false boolean. + * + * @return true if a GeoWebCache instance was found at the configured URL. + */ + public boolean existGeoWebCache() { + return HTTPUtils.httpPing(restURL + "/rest/", gwcUser, gwcPass); + } + + // + /** + * Get detailed info about a given Layer. + * + * @param name the layer name + * @return a GWCRESTWMSLayer with layer information or null + */ + public GWCRESTWMSLayer getLayer(String name) { + if (name == null || name.isEmpty()) + throw new IllegalArgumentException("Layername may not be null"); + String nameEncoded = null; + try { + nameEncoded = URLEncoder.encode(name, "UTF-8"); + } catch (UnsupportedEncodingException ex) { + LOGGER.error("Error encoding layer name: " + ex); + } + String url = HTTPUtils.append("/rest/layers/", nameEncoded, ".xml").toString(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("### Retrieving layer from " + url); + } + GWCRESTWMSLayer layer = GWCRESTWMSLayer.build(load(url)); + return layer; + } + // + + private String load(String url) { + LOGGER.info("Loading from REST path " + url); + String response = HTTPUtils.get(restURL + url, gwcUser, gwcPass); + return response; + } + +} diff --git a/src/main/java/it/geosolutions/geoserver/rest/decoder/gwc/GWCRESTWMSLayer.java b/src/main/java/it/geosolutions/geoserver/rest/decoder/gwc/GWCRESTWMSLayer.java new file mode 100644 index 0000000..77ab9a7 --- /dev/null +++ b/src/main/java/it/geosolutions/geoserver/rest/decoder/gwc/GWCRESTWMSLayer.java @@ -0,0 +1,257 @@ +/* + * 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.gwc; + +import it.geosolutions.geoserver.rest.decoder.*; +import java.util.ArrayList; +import java.util.List; + +import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; +import it.geosolutions.geoserver.rest.encoder.authorityurl.AuthorityURLInfo; +import it.geosolutions.geoserver.rest.encoder.authorityurl.GSAuthorityURLInfoEncoder; +import it.geosolutions.geoserver.rest.encoder.identifier.GSIdentifierInfoEncoder; +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.Namespace; + +/** + * Parse wmsLayers returned as XML REST objects. + * + *

This is the XML REST representation: + *

+ * {@code
+    
+      
+      img states
+        Nicer title for Image States
+        This is a description. Fascinating.
+      
+      
+        image/gif
+        image/jpeg
+        image/png
+        image/png8
+      
+      
+        
+          EPSG:4326
+          
+            
+              -129.6
+              3.45
+              -62.1
+              70.9
+            
+          
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        http://demo.opengeo.org/geoserver/wms
+      
+      nurc:Img_Sample,topp:states
+      false
+      0x0066FF
+    
+ * }
+ * @author Nazzareno Sileno + */ +public class GWCRESTWMSLayer { + protected final Element wmsLayerElem; + + public static GWCRESTWMSLayer build(String response) { + if(response == null) + return null; + + Element pb = JDOMBuilder.buildElement(response); + if(pb != null) + return new GWCRESTWMSLayer(pb); + else + return null; + } + + public GWCRESTWMSLayer(Element layerElem) { + this.wmsLayerElem = layerElem; + } + + public String getName() { + return wmsLayerElem.getChildText("name"); + } + + public String getTitle() { + Element metaInformation = wmsLayerElem.getChild("metaInformation"); + return metaInformation.getChildText("title"); + } + + public String getDescription() { + Element metaInformation = wmsLayerElem.getChild("metaInformation"); + return metaInformation.getChildText("description"); + } + + public List getMimeFormats() { + List mimeFormatsList = new ArrayList(); + final Element mimeFormatsRoot = wmsLayerElem.getChild("mimeFormats"); + if (mimeFormatsRoot != null) { + for (Element listItem : (List) mimeFormatsRoot.getChildren()) { + mimeFormatsList.add(listItem.getChildText("string")); + } + } + return mimeFormatsList; + } + +// public boolean getEnabled(){ +// return Boolean.parseBoolean(wmsLayerElem.getChildText("enabled")); +// } +// +// public boolean getQueryable(){ +// return Boolean.parseBoolean(wmsLayerElem.getChildText("queryable")); +// } +// +// public boolean getAdvertised(){ +// return Boolean.parseBoolean(wmsLayerElem.getChildText("advertised")); +// } +// +// public String getTypeString() { +// return wmsLayerElem.getChildText("type"); +// } +// +// public Type getType() { +// return Type.get(getTypeString()); +// } +// +// public String getDefaultStyle() { +// Element defaultStyle = wmsLayerElem.getChild("defaultStyle"); +// return defaultStyle == null? null : defaultStyle.getChildText("name"); +// } +// +// public RESTStyleList getStyles() { +// RESTStyleList styleList = null; +// final Element stylesRoot = wmsLayerElem.getChild("styles"); +// if (stylesRoot != null) { +// styleList = new RESTStyleList(stylesRoot); +// } +// return styleList; +// } +// +// public String getDefaultStyleWorkspace() { +// Element defaultStyle = wmsLayerElem.getChild("defaultStyle"); +// return defaultStyle == null? null : defaultStyle.getChildText("workspace"); +// } +// +// public String getTitle() { +// Element resource = wmsLayerElem.getChild("resource"); +// return resource.getChildText("title"); +// } +// +// public String getAbstract() { +// Element resource = wmsLayerElem.getChild("resource"); +// return resource.getChildText("abstract"); +// } +// +// public String getNameSpace() { +// Element resource = wmsLayerElem.getChild("resource"); +// return resource.getChild("namespace").getChildText("name"); +// } +// +// /** +// * Get the URL to retrieve the featuretype. +// *
{@code
+//        
+//        tasmania_cities
+//        
+//    
+//     * }
+//     */
+//    public String getResourceUrl() {
+//	Element resource = wmsLayerElem.getChild("resource");
+//        Element atom = resource.getChild("link", Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom"));
+//        return atom.getAttributeValue("href");
+//    }
+//    
+//    
+//	/**
+//	 * Decodes the list of AuthorityURLInfo from the GeoServer Layer
+//	 * 
+//	 * @return the list of GSAuthorityURLInfoEncoder
+//	 */
+//	public List getEncodedAuthorityURLInfoList() {
+//		List authorityURLList = null;
+//
+//		final Element authorityURLsRoot = wmsLayerElem.getChild("authorityURLs");
+//		if (authorityURLsRoot != null) {
+//			final List authorityURLs = authorityURLsRoot.getChildren();
+//			if (authorityURLs != null) {
+//				authorityURLList = new ArrayList(
+//						authorityURLs.size());
+//				for (Element authorityURL : authorityURLs) {
+//					final GSAuthorityURLInfoEncoder authEnc = new GSAuthorityURLInfoEncoder();
+//					authEnc.setName(authorityURL
+//							.getChildText(AuthorityURLInfo.name.name()));
+//					authEnc.setHref(authorityURL
+//							.getChildText(AuthorityURLInfo.href.name()));
+//					authorityURLList.add(authEnc);
+//				}
+//			}
+//		}
+//		return authorityURLList;
+//	}
+//
+//	/**
+//	 * Decodes the list of IdentifierInfo from the GeoServer Layer
+//	 * 
+//	 * @return the list of IdentifierInfoEncoder
+//	 */
+//	public List getEncodedIdentifierInfoList() {
+//		List idList = null;
+//
+//		final Element idRoot = wmsLayerElem.getChild("identifiers");
+//		if (idRoot != null) {
+//			final List identifiers = idRoot.getChildren();
+//			if (identifiers != null) {
+//				idList = new ArrayList(
+//						identifiers.size());
+//				for (Element identifier : identifiers) {
+//					final GSIdentifierInfoEncoder idEnc = new GSIdentifierInfoEncoder();
+//					idEnc.setAuthority(identifier
+//							.getChildText(IdentifierInfo.authority.name()));
+//					idEnc.setIdentifier(identifier
+//							.getChildText(IdentifierInfo.identifier.name()));
+//					idList.add(idEnc);
+//				}
+//			}
+//		}
+//		return idList;
+//	}
+    
+}
diff --git a/src/test/java/it/geosolutions/geoserver/rest/GeoWebCacheRESTTest.java b/src/test/java/it/geosolutions/geoserver/rest/GeoWebCacheRESTTest.java
new file mode 100644
index 0000000..54cff4b
--- /dev/null
+++ b/src/test/java/it/geosolutions/geoserver/rest/GeoWebCacheRESTTest.java
@@ -0,0 +1,161 @@
+/*
+ *  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 it.geosolutions.geoserver.rest.decoder.gwc.GWCRESTWMSLayer;
+import java.net.MalformedURLException;
+import java.net.URL;
+import junit.framework.Assert;
+import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Initializes REST params.
+ * 

+ * These tests are destructive, so you have to explicitly enable them by setting the env var resttest to true. + *

+ * The target geoserver instance can be customized by defining the following env vars: + *

    + *
  • resturl (default http://localhost:8080/geowebcache)
  • + *
  • restuser (default: geowebcache)
  • + *
  • restpw (default: secured)
  • + *
+ * + * @author Nazzareno Sileno - CNR IMAA geoSDI Group + * @email nazzareno.sileno@geosdi.org + */ +public class GeoWebCacheRESTTest { + private final static Logger LOGGER = LoggerFactory.getLogger(GeoWebCacheRESTTest.class); + + @Rule + public TestName _testName = new TestName(); + + public static final String RESTURL; + + public static final String RESTUSER; + + public static final String RESTPW; + + // geowebcache target version +// public static final String GWC_VERSION; + + public static URL URL; + + public static GeoWebCacheRESTManager geoWebCache; + + private static boolean enabled = false; + + private static Boolean existgwc = null; + + static { + RESTURL = getenv("gwcmgr_resturl", "http://localhost:8989/geowebcache"); + RESTUSER = getenv("gwcmgr_restuser", "geowebcache"); + RESTPW = getenv("gwcmgr_restpw", "secured"); +// GWC_VERSION = getenv("gwcmgr_version", "1.8.0"); + + // These tests will destroy data, so let's make sure we do want to run them + enabled = getenv("gwcmgr_resttest", "false").equalsIgnoreCase("true"); + if (!enabled) + LOGGER.warn("Tests are disabled. Please read the documentation to enable them."); + + try { + URL = new URL(RESTURL); + geoWebCache = new GeoWebCacheRESTManager(RESTURL, RESTUSER, RESTPW); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } + + private static String getenv(String envName, String envDefault) { + String env = System.getenv(envName); + String prop = System.getProperty(envName, env); + LOGGER.debug("varname " + envName + " --> env:" + env + " prop:"+prop); + return prop != null ? prop : envDefault; + } + + @BeforeClass + public static void setUp() throws Exception { + + if (enabled) { + if (existgwc == null) { + existgwc = geoWebCache.existGeoWebCache(); + if (!existgwc) { + LOGGER.error("TESTS WILL FAIL BECAUSE NO GEOWEBCACHE WAS FOUND AT " + RESTURL + + " (" + RESTUSER + ":" + RESTPW + ")"); + } else { + LOGGER.info("Using geowebcache instance " + RESTUSER + ":" + RESTPW + " @ " + + RESTURL); + } + } else if (existgwc == false){ + System.out.println("Failing tests : geowebcache not found"); + fail("GeoWebCache not found"); + } + + } else { + 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() { + return enabled; + } + + + @Test + public void testGWCExistence(){ + LOGGER.debug("Testing GWC Existence"); + Assert.assertTrue("The GeoWebCache is unreachable", geoWebCache.existGeoWebCache()); + } + + @Test + public void testGWCGetLayer(){ + LOGGER.debug("Testing GWC GetLayer"); + GWCRESTWMSLayer layer = geoWebCache.getLayer("img states"); + Assert.assertNotNull("Please, ensure that the 'img states' default layer is available", layer); + Assert.assertEquals("img states", layer.getName()); + Assert.assertEquals("Nicer title for Image States", layer.getTitle()); + Assert.assertEquals(4, layer.getMimeFormats().size()); + LOGGER.info("Testing GWC GetLayer result: " + geoWebCache.getLayer("img states")); + } + + +} \ No newline at end of file