This commit is contained in:
GitHub Merge Button 2012-05-24 06:39:20 -07:00
commit b8dbb7a52a
23 changed files with 1083 additions and 17 deletions

View File

@ -0,0 +1,82 @@
/*
* 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;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTAbstractManager;
import it.geosolutions.geoserver.rest.manager.GeoServerRESTDatastoreManager;
import java.net.URL;
/**
* <i>The</i> single entry point to all of geoserver-manager functionality.
*
* Instance this one, and use getters to use different components. These are:
* <ul>
* <li>getReader() simple, high-level access methods.
* <li>getPublisher() simple, high-level pubhish methods.
* <li>get<i>Foo</i>Manager, full-fledged management of catalog objects.
* </ul>
* @author Oscar Fonts
*/
public class GeoServerRESTManager extends GeoServerRESTAbstractManager {
private final GeoServerRESTPublisher publisher;
private final GeoServerRESTReader reader;
private final GeoServerRESTDatastoreManager datastoreManager;
/**
* Default constructor.
*
* Indicates connection parameters to remote GeoServer instance.
*
* @param restURL GeoServer REST API endpoint
* @param username GeoServer REST API authorized username
* @param password GeoServer REST API password for the former username
*/
public GeoServerRESTManager(URL restURL, String username, String password) {
super(restURL, username, password);
// Internal publisher and reader, provide simple access methods.
publisher = new GeoServerRESTPublisher(restURL.toString(), username, password);
reader = new GeoServerRESTReader(restURL, username, password);
// Classes for fine-grained management of catalog components.
datastoreManager = new GeoServerRESTDatastoreManager(restURL, username, password);
}
public GeoServerRESTPublisher getPublisher() {
return publisher;
}
public GeoServerRESTReader getReader() {
return reader;
}
public GeoServerRESTDatastoreManager getDatastoreManager() {
return datastoreManager;
}
}

View File

@ -30,11 +30,11 @@ import it.geosolutions.geoserver.rest.decoder.utils.NameLinkElem;
import it.geosolutions.geoserver.rest.encoder.GSBackupEncoder; import it.geosolutions.geoserver.rest.encoder.GSBackupEncoder;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder; import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder;
import it.geosolutions.geoserver.rest.encoder.GSNamespaceEncoder; import it.geosolutions.geoserver.rest.encoder.GSNamespaceEncoder;
import it.geosolutions.geoserver.rest.encoder.GSPostGISDatastoreEncoder;
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.GSWorkspaceEncoder; import it.geosolutions.geoserver.rest.encoder.GSWorkspaceEncoder;
import it.geosolutions.geoserver.rest.encoder.coverage.GSCoverageEncoder; import it.geosolutions.geoserver.rest.encoder.coverage.GSCoverageEncoder;
import it.geosolutions.geoserver.rest.encoder.GSPostGISDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.feature.GSFeatureTypeEncoder; import it.geosolutions.geoserver.rest.encoder.feature.GSFeatureTypeEncoder;
import java.io.File; import java.io.File;
@ -655,20 +655,20 @@ public class GeoServerRESTPublisher {
} }
/** /**
* The file, url, and external endpoints are used to specify the method that * The {@code file}, {@code url}, and {@code external} endpoints are used to specify
* is used to upload the file. * the method that is used to upload the file.
* * <ul>
* The file method is used to directly upload a file from a local source. * <li>The {@code file} method is used to directly upload a file from a local source.
* The body of the request is the file itself. * The body of the request is the file itself.
* *
* The url method is used to indirectly upload a file from an remote source. * <li>The {@code url} method is used to indirectly upload a file from an remote source.
* The body of the request is a url pointing to the file to upload. This url * The body of the request is a url pointing to the file to upload. This url
* must be visible from the server. * must be visible from the server.
* *
* The external method is used to forgo upload and use an existing file on * <li>The {@code external} method is used to forgo upload and use an existing file on
* the server. The body of the request is the absolute path to the existing * the server. The body of the request is the absolute path to the existing
* file. * file.
* * </ul>
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* *
*/ */
@ -677,7 +677,7 @@ public class GeoServerRESTPublisher {
} }
// ========================================================================== // ==========================================================================
// === DATASTORE // === DATASTORES
// ========================================================================== // ==========================================================================
/** /**
@ -693,6 +693,8 @@ public class GeoServerRESTPublisher {
* *
* @return <TT>true</TT> if the PostGIS datastore has been successfully * @return <TT>true</TT> if the PostGIS datastore has been successfully
* created, <TT>false</TT> otherwise * created, <TT>false</TT> otherwise
* @deprecated Will be deleted in next version 1.5.x.
* Use {@link GeoServerRESTDatastoreManager} instead.
*/ */
public boolean createPostGISDatastore(String workspace, public boolean createPostGISDatastore(String workspace,
GSPostGISDatastoreEncoder datastoreEncoder) { GSPostGISDatastoreEncoder datastoreEncoder) {
@ -897,6 +899,57 @@ public class GeoServerRESTPublisher {
return publishShp(workspace, storename, params, layername, UploadMethod.file, zipFile.toURI(), srs, ProjectionPolicy.NONE,null); return publishShp(workspace, storename, params, layername, UploadMethod.file, zipFile.toURI(), srs, ProjectionPolicy.NONE,null);
} }
/**
* Publish a collection of shapefiles.
*
* It will automatically create the store and publish each shapefile as a layer.
*
* @param workspace the name of the workspace to use
* @param storeName the name of the store to create
* @param resource the shapefile collection. It can be: <ul>
* <li>A path to a directory containing shapefiles in the server.
* <li>A local zip file containing shapefiles that will be uploaded.
* <li>A URL pointing to a shapefile collection in the wild web (not tested).</ul>
* @return {@code true} if publication successful.
* @throws FileNotFoundException if the specified zip file does not exist.
*/
public boolean publishShpCollection(String workspace, String storeName, URI resource)
throws FileNotFoundException {
// Deduce upload method & mime type from resource syntax.
UploadMethod method = null;
String mime = null;
if (resource.getScheme().equals("file") || resource.isAbsolute() == false) {
File f = new File(resource);
if (f.exists() && f.isFile() && f.toString().endsWith(".zip")) {
method = UploadMethod.file;
mime = "application/zip";
} else if (f.isDirectory()) {
method = UploadMethod.external;
mime = "text/plain";
}
} else {
try {
if(resource.toURL() != null) {
method = UploadMethod.url;
mime = "text/plain";
}
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Resource is not recognized as a zip file, or a directory, or a valid URL", e);
}
}
// Create store, upload data, and publish layers
return createStore(
workspace, DataStoreType.datastores,
storeName, method,
DataStoreExtension.shp,
mime, resource,
ParameterConfigure.ALL,
new NameValuePair[0]);
}
/** /**
* @param workspace * @param workspace
* @param storename * @param storename

View File

@ -54,7 +54,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Low level HTTP utilities. * Low level HTTP utilities.
*/ */
class HTTPUtils { public class HTTPUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(HTTPUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(HTTPUtils.class);
/** /**

View File

@ -26,7 +26,11 @@
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.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import org.jdom.Element; import org.jdom.Element;
/** /**
@ -109,10 +113,39 @@ public class RESTDataStore {
return dsElem.getChildText("name"); return dsElem.getChildText("name");
} }
public String getStoreType() {
return dsElem.getChildText("type");
}
public String getDescription() {
return dsElem.getChildText("description");
}
public boolean isEnabled() {
return Boolean.parseBoolean(dsElem.getChildText("enabled"));
}
public String getWorkspaceName() { public String getWorkspaceName() {
return dsElem.getChild("workspace").getChildText("name"); return dsElem.getChild("workspace").getChildText("name");
} }
public Map<String, String> getConnectionParameters() {
Element elConnparm = dsElem.getChild("connectionParameters");
if (elConnparm != null) {
@SuppressWarnings("unchecked")
List<Element> elements = (List<Element>)elConnparm.getChildren("entry");
Map<String, String> params = new HashMap<String, String>(elements.size());
for (Element element : elements) {
String key = element.getAttributeValue("key");
String value = element.getTextTrim();
params.put(key, value);
}
return params;
}
return null;
}
@SuppressWarnings("unchecked")
protected String getConnectionParameter(String paramName) { protected String getConnectionParameter(String paramName) {
Element elConnparm = dsElem.getChild("connectionParameters"); Element elConnparm = dsElem.getChild("connectionParameters");
if (elConnparm != null) { if (elConnparm != null) {

View File

@ -34,6 +34,9 @@ import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
* @author Eric Grosso * @author Eric Grosso
* @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.
* Use {@link it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder} instead.
*/ */
public class GSPostGISDatastoreEncoder extends PropertyXMLEncoder { public class GSPostGISDatastoreEncoder extends PropertyXMLEncoder {

View File

@ -0,0 +1,146 @@
/*
* 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.encoder.datastore;
import java.util.Map;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import it.geosolutions.geoserver.rest.encoder.utils.ElementUtils;
import it.geosolutions.geoserver.rest.encoder.utils.NestedElementEncoder;
import it.geosolutions.geoserver.rest.encoder.utils.PropertyXMLEncoder;
/**
* Generic Datastore encoder.
*
* Provides getters and setters for parameters common to all Datastores,
* an internal placeholder for specific connection parameters, and
* a constructor to read parameters from a {@link RESTDataStore}.
*
* @author Oscar Fonts
*/
public abstract class GSAbstractDatastoreEncoder extends PropertyXMLEncoder {
final static String ROOT = "dataStore";
NestedElementEncoder connectionParameters = new NestedElementEncoder("connectionParameters");
GSAbstractDatastoreEncoder(String storeName) {
super(ROOT);
// Add mandatory parameter
ensureValidName(storeName);
setName(storeName);
// Add connection parameters
addContent(connectionParameters.getRoot());
}
/**
* Create a {@value #TYPE} datastore encoder from a store read from server.
*
* @param store The existing store.
* @throws IllegalArgumentException if store type or mandatory parameters are not valid
*/
GSAbstractDatastoreEncoder(RESTDataStore store) {
this(store.getName());
// Match datastore type
ensureValidType(store.getStoreType());
setType(store.getStoreType());
// Copy store parameters
setDescription(store.getDescription());
setEnabled(store.isEnabled());
// Copy connection parameters - bulk
Map<String, String> params = store.getConnectionParameters();
for(String key : params.keySet()) {
connectionParameters.set(key, params.get(key));
}
}
void setType(String type) {
set("type", type);
}
public String getType() {
return ElementUtils.contains(getRoot(), "type").getTextTrim();
}
public void setName(String name) {
ensureValidName(name);
set("name", name);
}
public String getName() {
return ElementUtils.contains(getRoot(), "name").getTextTrim();
}
public void setDescription(String description) {
set("description", description);
}
public String getDescription() {
return ElementUtils.contains(getRoot(), "description").getTextTrim();
}
public void setEnabled(boolean enabled) {
set("enabled", Boolean.toString(enabled));
}
public boolean getEnabled() {
return Boolean.parseBoolean(ElementUtils.contains(getRoot(), "enabled").getTextTrim());
}
/**
* Check name validity.
*
* @param name the name
* @throws IllegalArgumentException if name is null or empty
*/
void ensureValidName(String name) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException(
"Store name cannot be null or empty");
}
}
/**
* Check type validity.
*
* @param type the type.
* @throws IllegalArgumentException if type is not {@value #TYPE}
*/
void ensureValidType(String type) {
if (!type.equals(getValidType())) {
throw new IllegalArgumentException(
"The store type '"+ type +"' is not valid");
}
}
/**
* The type of the implementing datastore.
*/
abstract String getValidType();
}

View File

@ -0,0 +1,68 @@
/*
* 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.encoder.datastore;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import java.net.URL;
/**
* Encoder for a {@value #TYPE} datastore.
*
* @author Oscar Fonts
*/
public class GSDirectoryOfShapefilesDatastoreEncoder extends GSShapefileDatastoreEncoder {
static final String TYPE = "Directory of spatial files (shapefiles)";
/**
* Create a {@value #TYPE} datastore with default connection parameters,
* given a store name and a url (the store location).
*
* @param name New datastore name
* @param url The shapefile location in the server, relative to $GEOSERVER_DATA_DIR.
*/
public GSDirectoryOfShapefilesDatastoreEncoder(String name, URL url) {
super(name, url);
setType(TYPE);
}
/**
* Create a {@value #TYPE} datastore encoder from an existing store read from server.
*
* @param store The existing store.
* @throws IllegalArgumentException if store type or mandatory parameters are not valid
*/
public GSDirectoryOfShapefilesDatastoreEncoder(RESTDataStore store) {
super(store);
}
/**
* @return {@value #TYPE}
*/
String getValidType() {
return TYPE;
}
}

View File

@ -0,0 +1,147 @@
/*
* 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.encoder.datastore;
/**
* Encoder for a {@value #TYPE} datastore.
*
* @author Eric Grosso
* @author ETj
* @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
* @author Oscar Fonts
*/
public class GSPostGISDatastoreEncoder extends GSAbstractDatastoreEncoder {
static final String TYPE = "PostGIS";
static final int DEFAULT_MIN_CONNECTIONS = 1;
static final int DEFAULT_MAX_CONNECTIONS = 10;
static final int DEFAULT_FETCH_SIZE = 1000;
static final int DEFAULT_CONNECTION_TIMEOUT = 20;
static final boolean DEFAULT_LOOSE_BBOX = true;
static final boolean DEFAULT_PREPARED_STATEMENTS = false;
static final int DEFAULT_MAX_OPEN_PREPARED_STATEMENTS = 50;
public GSPostGISDatastoreEncoder(String name) {
super(name);
// Set mandatory parameter
setType(TYPE);
setDatabaseType("postgis");
// Set default values
setMinConnections(DEFAULT_MIN_CONNECTIONS);
setMaxConnections(DEFAULT_MAX_CONNECTIONS);
setFetchSize(DEFAULT_FETCH_SIZE);
setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
setLooseBBox(DEFAULT_LOOSE_BBOX);
setPreparedStatements(DEFAULT_PREPARED_STATEMENTS);
setMaxOpenPreparedStatements(DEFAULT_MAX_OPEN_PREPARED_STATEMENTS);
}
public void setNamespace(String namespace) {
connectionParameters.set("namespace", namespace);
}
public void setHost(String host) {
connectionParameters.set("host", host);
}
public void setPort(int port) {
connectionParameters.set("port", Integer.toString(port));
}
public void setDatabase(String database) {
connectionParameters.set("database", database);
}
public void setSchema(String schema) {
connectionParameters.set("schema", schema);
}
public void setUser(String user) {
connectionParameters.set("user", user);
}
public void setPassword(String password) {
connectionParameters.set("passwd", password);
}
public void setDatabaseType(String dbtype) {
connectionParameters.set("dbtype", dbtype);
}
public void setJndiReferenceName(String jndiReferenceName) {
connectionParameters.set("jndiReferenceName", jndiReferenceName);
}
public void setExposePrimaryKeys(boolean exposePrimaryKeys) {
connectionParameters.set("Expose primary keys", Boolean.toString(exposePrimaryKeys));
}
public void setMaxConnections(int maxConnections) {
connectionParameters.set("max connections", Integer.toString(maxConnections));
}
public void setMinConnections(int minConnections) {
connectionParameters.set("min connections", Integer.toString(minConnections));
}
public void setFetchSize(int fetchSize) {
connectionParameters.set("fetch size", Integer.toString(fetchSize));
}
public void setConnectionTimeout(int seconds) {
connectionParameters.set("Connection timeout", Integer.toString(seconds));
}
public void setValidateConnections(boolean validateConnections) {
connectionParameters.set("validate connections", Boolean.toString(validateConnections));
}
public void setPrimaryKeyMetadataTable(String primaryKeyMetadataTable) {
connectionParameters.set("Primary key metadata table", primaryKeyMetadataTable);
}
public void setLooseBBox(boolean looseBBox) {
connectionParameters.set("Loose bbox", Boolean.toString(looseBBox));
}
public void setPreparedStatements(boolean preparedStatements) {
connectionParameters.set("preparedStatements", Boolean.toString(preparedStatements));
}
public void setMaxOpenPreparedStatements(int maxOpenPreparedStatements) {
connectionParameters.set("Max open prepared statements", Integer.toString(maxOpenPreparedStatements));
}
/**
* @return {@value #TYPE}
*/
String getValidType() {
return TYPE;
}
}

View File

@ -0,0 +1,163 @@
/*
* 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.encoder.datastore;
import java.net.MalformedURLException;
import java.net.URL;
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.
*
* @author Oscar Fonts
*/
public class GSShapefileDatastoreEncoder extends GSAbstractDatastoreEncoder {
static final String TYPE = "Shapefile";
final static boolean DEFAULT_ENABLED = true;
final static String DEFAULT_CHARSET = "ISO-8859-1";
final static boolean DEFAULT_CREATE_SPATIAL_INDEX = true;
final static boolean DEFAULT_MEMORY_MAPPED_BUFFER = false;
final static boolean DEFAULT_CACHE_AND_REUSE_MEMORY_MAPS = true;
/**
* Create a {@value #TYPE} datastore with default connection parameters,
* given a store name and a url (the store location).
*
* The following default connection parameters are set:
* <ul>
* <li>enabled: {@value #DEFAULT_ENABLED}
* <li>charset: {@value #DEFAULT_CHARSET}
* <li>create spatial index: {@value #DEFAULT_CREATE_SPATIAL_INDEX}
* <li>memory mapped buffer: {@value #DEFAULT_MEMORY_MAPPED_BUFFER}
* <li>cache and reuse memory maps: {@value #DEFAULT_CACHE_AND_REUSE_MEMORY_MAPS}
* </ul>
*
* @param name New datastore name
* @param url The shapefile location in the server, relative to $GEOSERVER_DATA_DIR.
*/
public GSShapefileDatastoreEncoder(String name, URL url) {
// Set fixed values
super(name);
setType(TYPE);
// Set mandatory parameter
ensureValidURL(url);
setUrl(url);
// Set default values
setEnabled(DEFAULT_ENABLED);
setCharset(Charset.forName(DEFAULT_CHARSET));
setCreateSpatialIndex(DEFAULT_CREATE_SPATIAL_INDEX);
setMemoryMappedBuffer(DEFAULT_MEMORY_MAPPED_BUFFER);
setCacheAndReuseMemoryMaps(DEFAULT_CACHE_AND_REUSE_MEMORY_MAPS);
}
/**
* Create a {@value #TYPE} datastore encoder from an existing store read from server.
*
* @param store The existing store.
* @throws IllegalArgumentException if store type or mandatory parameters are not valid
*/
public GSShapefileDatastoreEncoder(RESTDataStore store) {
super(store);
// Check mandatory parameter validity
try {
ensureValidURL(new URL(store.getConnectionParameters().get("url")));
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Shapefile store URL is malformed", e);
}
}
public void setUrl(URL url) {
ensureValidURL(url);
connectionParameters.set("url", url.toString());
}
public URL getUrl() {
try {
return new URL(ElementUtils.contains(connectionParameters.getRoot(), "description").getTextTrim());
} catch (MalformedURLException e) {
return null;
}
}
public void setCharset(Charset charset) {
connectionParameters.set("charset", charset.name());
}
public Charset getCharset() {
return Charset.forName(ElementUtils.contains(connectionParameters.getRoot(), "charset").getTextTrim());
}
public void setCreateSpatialIndex(boolean createSpatialIndex) {
connectionParameters.set("create spatial index", Boolean.toString(createSpatialIndex));
}
public boolean getCreateSpatialIndex() {
return Boolean.parseBoolean(ElementUtils.contains(connectionParameters.getRoot(), "create spatial index").getTextTrim());
}
public void setMemoryMappedBuffer(boolean memoryMappedBuffer) {
connectionParameters.set("memory mapped buffer", Boolean.toString(memoryMappedBuffer));
}
public boolean getMemoryMappedBuffer() {
return Boolean.parseBoolean(ElementUtils.contains(connectionParameters.getRoot(), "memory mapped buffer").getTextTrim());
}
public void setCacheAndReuseMemoryMaps(boolean cacheAndReuseMemoryMaps) {
connectionParameters.set("cache and reuse memory maps", Boolean.toString(cacheAndReuseMemoryMaps));
}
public boolean getCacheAndReuseMemoryMaps() {
return Boolean.parseBoolean(ElementUtils.contains(connectionParameters.getRoot(), "cache and reuse memory maps").getTextTrim());
}
/**
* Check url validity.
*
* @param url the url
* @throws IllegalArgumentException if url is null or empty
*/
private static void ensureValidURL(URL url) {
if (url == null || url.toString().isEmpty()) {
throw new IllegalArgumentException(
"Shapefile store URL cannot be null or empty");
}
}
/**
* @return {@value #TYPE}
*/
String getValidType() {
return TYPE;
}
}

View File

@ -155,7 +155,7 @@ public class NestedElementEncoder extends XmlElement {
// if some previous similar object is found // if some previous similar object is found
final Element search; final Element search;
if ((search = ElementUtils.contains(getRoot(), new NestedElementFilter( if ((search = ElementUtils.contains(getRoot(), new NestedElementFilter(
getRoot(), key, value))) != null) { getRoot(), key, null))) != null) {
// remove it // remove it
ElementUtils.remove(getRoot(), search); ElementUtils.remove(getRoot(), search);
} }

View File

@ -0,0 +1,55 @@
/*
* 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 java.net.URL;
/**
* Abstract manager, common functionality and interface
* for all GeoServerREST<i>Foo</i>Manager classes.
*
* @author Oscar Fonts
*/
public abstract class GeoServerRESTAbstractManager {
protected final URL restURL;
protected final String gsuser;
protected final String gspass;
/**
* Default constructor.
*
* Indicates connection parameters to remote GeoServer instance.
*
* @param restURL GeoServer REST API endpoint
* @param username GeoServer REST API authorized username
* @param password GeoServer REST API password for the former username
*/
public GeoServerRESTAbstractManager(URL restURL, String username, String password) {
this.restURL = restURL;
this.gsuser = username;
this.gspass = password;
}
}

View File

@ -0,0 +1,92 @@
/*
* 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.HTTPUtils;
import it.geosolutions.geoserver.rest.encoder.datastore.GSAbstractDatastoreEncoder;
import java.net.URL;
/**
* Manage datastores.
*
* To pass connection parameters, use the encoders derived from
* {@link GSAbstractDatastoreEncoder}.
*
* @author Oscar Fonts
*/
public class GeoServerRESTDatastoreManager extends GeoServerRESTAbstractManager {
/**
* 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 GeoServerRESTDatastoreManager(URL restURL, String username, String password) {
super(restURL, username, password);
}
/**
* Create a datastore.
*
* @param workspace
* Name of the workspace to contain the datastore. This will also
* be the prefix of any layer names contained in the datastore.
* @param datastore
* the set of parameters to be set to the datastore (including
* connection parameters).
* @return <TT>true</TT> if the datastore has been successfully
* created, <TT>false</TT> otherwise
*/
public boolean create(String workspace, GSAbstractDatastoreEncoder datastore) {
String sUrl = restURL + "/rest/workspaces/" + workspace
+ "/datastores/";
String xml = datastore.toString();
String result = HTTPUtils.postXml(sUrl, xml, gsuser, gspass);
return result != null;
}
/**
* Update a datastore.
*
* @param workspace
* Name of the workspace that contains the datastore.
* @param datastore
* the set of parameters to be set to the datastore (including
* connection parameters).
* @return <TT>true</TT> if the datastore has been successfully
* updated, <TT>false</TT> otherwise
*/
public boolean update(String workspace, GSAbstractDatastoreEncoder datastore) {
String sUrl = restURL + "/rest/workspaces/" + workspace
+ "/datastores/" + datastore.getName();
String xml = datastore.toString();
String result = HTTPUtils.putXml(sUrl, xml, gsuser, gspass);
return result != null;
}
}

View File

@ -0,0 +1,137 @@
/*
* 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 org.junit.Test;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import it.geosolutions.geoserver.rest.GeoServerRESTManager;
import it.geosolutions.geoserver.rest.GeoserverRESTTest;
import it.geosolutions.geoserver.rest.decoder.RESTDataStore;
import it.geosolutions.geoserver.rest.encoder.datastore.GSAbstractDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSShapefileDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSDirectoryOfShapefilesDatastoreEncoder;
/**
* Test datastore handling (create, read and update):
*
* <ul><li>Tests all the constructors and setters from
* {@link GSDirectoryOfShapefilesDatastoreEncoder} and parent classes
* ({@link GSShapefileDatastoreEncoder}, {@link GSAbstractDatastoreEncoder}).
*
* <li>Tests constructors and getters from {@link RESTDataStore} (reader).
*
* <li>Tests {@link GeoServerRESTDatastoreManager} create and update methods.</ul>
*
* <p>The sequence is:
* <ol>
* <li>Create a DirectoryOfShapefilesDatastoreEncoder, with default parameters.
* <li>Publish via GeoServerRESTDatastoreManager.create.
* <li>Read the datastore from server.
* <li>Test all parameter values.
* <li>Create a new Encoder from it.
* <li>Change all datastore parameter to non-default ones.
* <li>Update via GeoServerRESTDatastoreManager.update.
* <li>Read again.
* <li>Test all new values.
* </ol>
*
* @author Oscar Fonts
*/
public class GeoserverRESTDatastoreManagerTest extends GeoserverRESTTest {
public final GeoServerRESTManager manager;
private static final String WS_NAME = DEFAULT_WS;
private static final String DS_NAME = "testCreateDatastore";
private static final String DS_DESCRIPTION = "A description";
private static URL LOCATION_1;
private static URL LOCATION_2;
public GeoserverRESTDatastoreManagerTest(String testName) throws Exception {
super(testName);
manager = new GeoServerRESTManager(new URL(RESTURL), RESTUSER, RESTPW);
LOCATION_1 = new URL("file:data/1");
LOCATION_2 = new URL("file:data/2");
}
@Test
public void test() throws Exception {
if (!enabled()) {
return;
}
// Delete all resources except styles
deleteAllWorkspacesRecursively();
// Create workspace
assertTrue(publisher.createWorkspace(WS_NAME));
// Create a directory of spatial files with default parameters
GSDirectoryOfShapefilesDatastoreEncoder create = new GSDirectoryOfShapefilesDatastoreEncoder(DS_NAME, LOCATION_1);
assertTrue(manager.getDatastoreManager().create(WS_NAME, create));
// Read the store from server; check all parameter values
RESTDataStore read = reader.getDatastore(WS_NAME, DS_NAME);
assertEquals(read.getName(), DS_NAME);
assertEquals(read.getWorkspaceName(), WS_NAME);
assertEquals(read.isEnabled(), true);
Map<String,String> connParams = read.getConnectionParameters();
assertEquals(connParams.get("url"), LOCATION_1.toString());
assertEquals(connParams.get("charset"), "ISO-8859-1");
assertEquals(connParams.get("create spatial index"), "true");
assertEquals(connParams.get("memory mapped buffer"), "false");
assertEquals(connParams.get("cache and reuse memory maps"), "true");
// Change all parameter to non-default values
GSDirectoryOfShapefilesDatastoreEncoder update = new GSDirectoryOfShapefilesDatastoreEncoder(read);
update.setDescription(DS_DESCRIPTION);
update.setEnabled(false);
update.setUrl(LOCATION_2);
update.setCharset(Charset.forName("UTF-8"));
update.setCreateSpatialIndex(false);
update.setMemoryMappedBuffer(true);
update.setCacheAndReuseMemoryMaps(false);
//update the store
assertTrue(manager.getDatastoreManager().update(WS_NAME, update));
// Read again, check that all parameters have changed
read = reader.getDatastore(WS_NAME, DS_NAME);
assertEquals(read.getWorkspaceName(), WS_NAME);
assertEquals(read.isEnabled(), false);
connParams = read.getConnectionParameters();
assertEquals(connParams.get("url"), LOCATION_2.toString());
assertEquals(connParams.get("charset"), "UTF-8");
assertEquals(connParams.get("create spatial index"), "false");
assertEquals(connParams.get("memory mapped buffer"), "true");
assertEquals(connParams.get("cache and reuse memory maps"), "false");
}
}

View File

@ -0,0 +1,85 @@
/*
* 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.publisher;
import org.junit.Test;
import java.net.URI;
import java.util.List;
import org.springframework.core.io.ClassPathResource;
import it.geosolutions.geoserver.rest.GeoserverRESTTest;
/**
* @author Oscar Fonts
*/
public class GeoserverRESTPublishShpCollectionTest extends GeoserverRESTTest {
final String workspace = DEFAULT_WS;
final String storeName = "testshpcollection";
public GeoserverRESTPublishShpCollectionTest(String testName) {
super(testName);
}
@Test
public void testLocalZip() throws Exception {
if (!enabled()) {
return;
}
URI location = new ClassPathResource("testdata/multipleshp.zip").getFile().toURI();
test(location);
}
@Test
public void testExternalDir() throws Exception {
if (!enabled()) {
return;
}
URI location = new ClassPathResource("testdata/multipleshapefiles").getFile().toURI();
test(location);
}
void test(URI location) throws Exception {
// Delete all resources except styles
deleteAllWorkspacesRecursively();
// Create workspace
assertTrue(publisher.createWorkspace(workspace));
// Publish shp collection
assertTrue(publisher.publishShpCollection(workspace, storeName, location));
String storeType = reader.getDatastore(workspace, storeName).getStoreType();
assertEquals(storeType, "Shapefile");
// Test published layer names
List<String> layers = reader.getLayers().getNames();
assertTrue(layers.contains("cities"));
assertTrue(layers.contains("boundaries"));
}
}

View File

@ -166,11 +166,12 @@ public class GeoserverRESTShapeTest extends GeoserverRESTTest {
String ns = "geosolutions"; String ns = "geosolutions";
String storeName = "resttestshp"; String storeName = "resttestshp";
String layerName = "cities"; String layerName = "cities";
final String styleName = "restteststyle";
File zipFile = new ClassPathResource("testdata/resttestshp.zip").getFile(); File zipFile = new ClassPathResource("testdata/resttestshp.zip").getFile();
publisher.removeDatastore(DEFAULT_WS, storeName,true); publisher.removeDatastore(DEFAULT_WS, storeName,true);
publisher.removeStyle(styleName);
final String styleName = "restteststyle";
File sldFile = new ClassPathResource("testdata/restteststyle.sld").getFile(); File sldFile = new ClassPathResource("testdata/restteststyle.sld").getFile();
// insert style // insert style

Binary file not shown.

View File

@ -0,0 +1 @@
GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.