Work in progress on GeoWebCache Manager

This commit is contained in:
andypower 2015-10-06 08:47:27 +02:00
parent a4268dda60
commit 63733ccabd
4 changed files with 546 additions and 1 deletions

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,2015 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

View File

@ -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.: <TT>http://localhost:8080/geowebcache</TT>.
*/
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 <TT>GeoWebCacheRESTManager</TT> to connect against a GeoWebCache instance with the given URL and user credentials.
*
* @param restURL the base GeoWebCache URL (e.g.: <TT>http://localhost:8080/geowebcache</TT>)
* @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.
* <BR>
* Return <TT>true</TT> if the configured GeoWebCache is up and replies to REST requests.
* <BR>
* Send a HTTP GET request to the configured URL.<BR>
* Return <TT>true</TT> if a HTTP 200 code (OK) is read from the HTTP response;
* any other response code, or connection error, will return a
* <TT>false</TT> boolean.
*
* @return true if a GeoWebCache instance was found at the configured URL.
*/
public boolean existGeoWebCache() {
return HTTPUtils.httpPing(restURL + "/rest/", gwcUser, gwcPass);
}
// <editor-fold desc="/layers" defaultstate="collapsed">
/**
* 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;
}
// </editor-fold>
private String load(String url) {
LOGGER.info("Loading from REST path " + url);
String response = HTTPUtils.get(restURL + url, gwcUser, gwcPass);
return response;
}
}

View File

@ -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 <TT>wmsLayer</TT>s returned as XML REST objects.
*
* <P>This is the XML REST representation:
* <PRE>
* {@code
<wmsLayer>
<metaInformation>
<name>img states</name>
<title>Nicer title for Image States</title>
<description>This is a description. Fascinating.</description>
</metaInformation>
<mimeFormats>
<string>image/gif</string>
<string>image/jpeg</string>
<string>image/png</string>
<string>image/png8</string>
</mimeFormats>
<gridSubsets>
<gridSubset>
<gridSetName>EPSG:4326</gridSetName>
<extent>
<coords>
<double>-129.6</double>
<double>3.45</double>
<double>-62.1</double>
<double>70.9</double>
</coords>
</extent>
</gridSubset>
</gridSubsets>
<expireCacheList>
<expirationRule minZoom="0" expiration="60" />
</expireCacheList>
<expireClientsList>
<expirationRule minZoom="0" expiration="500" />
</expireClientsList>
<wmsUrl>
<string>http://demo.opengeo.org/geoserver/wms</string>
</wmsUrl>
<wmsLayers>nurc:Img_Sample,topp:states</wmsLayers>
<transparent>false</transparent>
<bgColor>0x0066FF</bgColor>
</wmsLayer>
* }</PRE>
* @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<String> getMimeFormats() {
List<String> mimeFormatsList = new ArrayList<String>();
final Element mimeFormatsRoot = wmsLayerElem.getChild("mimeFormats");
if (mimeFormatsRoot != null) {
for (Element listItem : (List<Element>) 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.
// * <PRE>{@code
// <resource class="featureType">
// <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"/>
// </resource>
// * }</CODE>
// */
// 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<GSAuthorityURLInfoEncoder> getEncodedAuthorityURLInfoList() {
// List<GSAuthorityURLInfoEncoder> authorityURLList = null;
//
// final Element authorityURLsRoot = wmsLayerElem.getChild("authorityURLs");
// if (authorityURLsRoot != null) {
// final List<Element> authorityURLs = authorityURLsRoot.getChildren();
// if (authorityURLs != null) {
// authorityURLList = new ArrayList<GSAuthorityURLInfoEncoder>(
// 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<GSIdentifierInfoEncoder> getEncodedIdentifierInfoList() {
// List<GSIdentifierInfoEncoder> idList = null;
//
// final Element idRoot = wmsLayerElem.getChild("identifiers");
// if (idRoot != null) {
// final List<Element> identifiers = idRoot.getChildren();
// if (identifiers != null) {
// idList = new ArrayList<GSIdentifierInfoEncoder>(
// 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;
// }
}

View File

@ -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.
* <P>
* <B>These tests are destructive, so you have to explicitly enable them</B> by setting the env var <TT>resttest</TT> to <TT>true</TT>.
* <P>
* The target geoserver instance can be customized by defining the following env vars:
* <ul>
* <LI><TT>resturl</TT> (default <TT>http://localhost:8080/geowebcache</TT>)</LI>
* <LI><TT>restuser</TT> (default: <TT>geowebcache</TT>)</LI>
* <LI><TT>restpw</TT> (default: <TT>secured</TT>)</LI>
* </ul>
*
* @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"));
}
}