Mercurial > dive4elements > http-client
changeset 71:a857866d162f
Moved directories to org.dive4elements
author | Sascha L. Teichmann <teichmann@intevation.de> |
---|---|
date | Thu, 25 Apr 2013 11:14:14 +0200 |
parents | da691e917f98 |
children | 133281653904 |
files | src/main/java/de/intevation/artifacts/httpclient/ConsoleClient.java src/main/java/de/intevation/artifacts/httpclient/exceptions/ConnectionException.java src/main/java/de/intevation/artifacts/httpclient/exceptions/NoSuchOptionException.java src/main/java/de/intevation/artifacts/httpclient/http/HttpClient.java src/main/java/de/intevation/artifacts/httpclient/http/HttpClientImpl.java src/main/java/de/intevation/artifacts/httpclient/http/response/DocumentResponseHandler.java src/main/java/de/intevation/artifacts/httpclient/http/response/ResponseHandler.java src/main/java/de/intevation/artifacts/httpclient/http/response/StreamResponseHandler.java src/main/java/de/intevation/artifacts/httpclient/http/response/StringResponseHandler.java src/main/java/de/intevation/artifacts/httpclient/objects/Artifact.java src/main/java/de/intevation/artifacts/httpclient/objects/ArtifactFactory.java src/main/java/de/intevation/artifacts/httpclient/utils/ArtifactCreator.java src/main/java/de/intevation/artifacts/httpclient/utils/ArtifactNamespaceContext.java src/main/java/de/intevation/artifacts/httpclient/utils/ArtifactProtocolUtils.java src/main/java/de/intevation/artifacts/httpclient/utils/Configuration.java src/main/java/de/intevation/artifacts/httpclient/utils/XFormNamespaceContext.java src/main/java/de/intevation/artifacts/httpclient/utils/XMLUtils.java src/main/java/org/dive4elements/artifacts/httpclient/ConsoleClient.java src/main/java/org/dive4elements/artifacts/httpclient/exceptions/ConnectionException.java src/main/java/org/dive4elements/artifacts/httpclient/exceptions/NoSuchOptionException.java src/main/java/org/dive4elements/artifacts/httpclient/http/HttpClient.java src/main/java/org/dive4elements/artifacts/httpclient/http/HttpClientImpl.java src/main/java/org/dive4elements/artifacts/httpclient/http/response/DocumentResponseHandler.java src/main/java/org/dive4elements/artifacts/httpclient/http/response/ResponseHandler.java src/main/java/org/dive4elements/artifacts/httpclient/http/response/StreamResponseHandler.java src/main/java/org/dive4elements/artifacts/httpclient/http/response/StringResponseHandler.java src/main/java/org/dive4elements/artifacts/httpclient/objects/Artifact.java src/main/java/org/dive4elements/artifacts/httpclient/objects/ArtifactFactory.java src/main/java/org/dive4elements/artifacts/httpclient/utils/ArtifactCreator.java src/main/java/org/dive4elements/artifacts/httpclient/utils/ArtifactNamespaceContext.java src/main/java/org/dive4elements/artifacts/httpclient/utils/ArtifactProtocolUtils.java src/main/java/org/dive4elements/artifacts/httpclient/utils/Configuration.java src/main/java/org/dive4elements/artifacts/httpclient/utils/XFormNamespaceContext.java src/main/java/org/dive4elements/artifacts/httpclient/utils/XMLUtils.java src/test/java/de/intevation/artifacts/httpclient/ConsoleClientTest.java src/test/java/org/dive4elements/artifacts/httpclient/ConsoleClientTest.java |
diffstat | 36 files changed, 2234 insertions(+), 2234 deletions(-) [+] |
line wrap: on
line diff
--- a/src/main/java/de/intevation/artifacts/httpclient/ConsoleClient.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,354 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ - -package de.intevation.artifacts.httpclient; - -import java.io.IOException; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; - -import java.net.MalformedURLException; - -import java.util.Arrays; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.xpath.XPathConstants; - -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; - -import de.intevation.artifacts.httpclient.http.HttpClient; -import de.intevation.artifacts.httpclient.http.HttpClientImpl; -import de.intevation.artifacts.httpclient.http.response.DocumentResponseHandler; - -import de.intevation.artifacts.httpclient.exceptions.ConnectionException; -import de.intevation.artifacts.httpclient.exceptions.NoSuchOptionException; -import de.intevation.artifacts.httpclient.objects.Artifact; -import de.intevation.artifacts.httpclient.utils.ArtifactProtocolUtils; -import de.intevation.artifacts.httpclient.utils.Configuration; -import de.intevation.artifacts.httpclient.utils.XFormNamespaceContext; -import de.intevation.artifacts.httpclient.utils.XMLUtils; - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class ConsoleClient -{ - /** - * The logging is done via Log4j. To configure the logging - * a file 'log4j.properties' is search in the configuration directory. - */ - public static final String LOG4J_PROPERTIES = "log4j.properties"; - - - /** - * The path of the configuration directory. - */ - public static final String CONFIG_PATH = System.getProperty("config.dir", - "conf"); - - public static final String CONFIG = System.getProperty("config.file", - "use_case1.conf"); - - - public static final String XPATH_DYNAMIC = "/art:result/art:ui/art:dynamic"; - - /** - * The logger used in this class. - */ - private static Logger logger; - - - static { - configureLogging(); - - logger = Logger.getLogger(ConsoleClient.class); - } - - - /** - * Trys to load the Log4j configuration from ${config.dir}/log4j.properties. - */ - public static final void configureLogging() { - File configDir = new File(CONFIG_PATH); - File propFile = new File(configDir, LOG4J_PROPERTIES); - - if (propFile.isFile() && propFile.canRead()) { - try { - PropertyConfigurator.configure(propFile.toURI().toURL()); - } - catch (MalformedURLException mue) { - mue.printStackTrace(System.err); - } - } - } - - - public static final Configuration readConfiguration() { - File configDir = new File(CONFIG_PATH); - File configFile = new File(configDir, CONFIG); - - logger.debug("Configuration file: " + configFile.getAbsolutePath()); - - if (configFile.isFile() && configFile.canRead()) { - try { - Configuration conf = new Configuration(configFile); - conf.initialize(); - - return conf; - } - catch (IOException ioe) { - logger.error("Error while reading configuration."); - } - } - - return null; - } - - - public static void main( String[] args ) - { - logger.info("Starting console client."); - - Configuration conf = readConfiguration(); - - String serverHost = (String) conf.getServerSettings("host"); - String serverPort = (String) conf.getServerSettings("port"); - HttpClient client = new HttpClientImpl(serverHost + ":" + serverPort); - - try { - Document create = ArtifactProtocolUtils.createCreateDocument( - (String) conf.getArtifactSettings("fis")); - Artifact artifact = (Artifact) client.create(create, null); - - Map attr = new HashMap(); - String product = (String) conf.getArtifactSettings("product"); - String[] products = extractOptions(client, artifact, product); - attr.put("product", products[0]); - - feedAndGo(client, artifact, attr, "timeSeries"); - - attr.clear(); - String area = (String) conf.getArtifactSettings("areaid"); - String[] areas = extractOptions(client, artifact, area); - attr.put("areaid", areas[0]); - feedAndGo(client, artifact, attr, "timeseries_without_geom"); - - attr.clear(); - String feature = (String) conf.getArtifactSettings("featureid"); - String[] features = extractOptions(client, artifact, feature); - attr.put("featureid", features[0]); - feedAndGo(client, artifact, attr, "timeseries_vector_scalar"); - - attr.clear(); - String vector = (String) conf.getArtifactSettings("vectorscalar"); - String[] vectors = extractOptions(client, artifact, vector); - attr.put("vectorscalar", vectors[0]); - feedAndGo(client, artifact, attr, "timeseries_parameter"); - - attr.clear(); - String parameter = (String) conf.getArtifactSettings("parameterid"); - String[] parameters = extractOptions(client, artifact, parameter); - attr.put("parameterid", parameters); - feedAndGo(client, artifact, attr, "timeseries_depth_height"); - - attr.clear(); - String measure = (String) conf.getArtifactSettings("measurementid"); - String[] measures = extractMeasurements(client, artifact, measure); - attr.put("measurementid", measures); - feedAndGo(client, artifact, attr, "timeseries_interval"); - - attr.clear(); - String min = (String) conf.getArtifactSettings("minvalue"); - String max = (String) conf.getArtifactSettings("maxvalue"); - attr.put("minvalue", min); - attr.put("maxvalue", max); - feedAndGo(client, artifact, attr, "timeseries_calculate_results"); - - try { - Map opts = new HashMap(); - opts.put("mime-type", conf.getOutputSettings("mime-type")); - opts.put("width", conf.getOutputSettings("width")); - opts.put("height", conf.getOutputSettings("height")); - opts.put("points", conf.getOutputSettings("points")); - - Document chart = - ArtifactProtocolUtils.createChartDocument(artifact, opts); - - String dir = (String) conf.getOutputSettings("directory"); - - File outDir = new File(dir); - File output = new File(outDir, "output.png"); - OutputStream os = new FileOutputStream(output); - - client.out(artifact, chart, "chart", os); - } - catch (IOException ioe) { - logger.error( - "IO error while writing the output: " + ioe.getMessage()); - } - - logger.debug("Finished console client."); - } - catch (ConnectionException ce) { - logger.error(ce.getMessage()); - } - catch (NoSuchOptionException nsoe) { - logger.error( - "No such option found: " + nsoe.getMessage()); - } - } - - - public static void feedAndGo( - HttpClient client, - Artifact artifact, - Map attr, - String target) - throws ConnectionException - { - Document feed = ArtifactProtocolUtils.createFeedDocument(artifact, attr); - client.feed(artifact, feed, new DocumentResponseHandler()); - - Document advance = ArtifactProtocolUtils.createAdvanceDocument( - artifact, - target); - - client.advance(artifact, advance, new DocumentResponseHandler()); - } - - - /** - * XXX I think, this method should be implemented somewhere else to be able - * to re-use this implementation. But this method needs more work to be more - * abstract, so it needs to be reimplemented later, I think. - */ - public static String[] extractOptions( - HttpClient client, - Artifact artifact, - String text) - throws NoSuchOptionException, ConnectionException - { - Document describe = ArtifactProtocolUtils.createDescribeDocument( - artifact, true); - - Document description = (Document) client.describe( - artifact, describe, new DocumentResponseHandler()); - - List pieces = Arrays.asList(text.split(",")); - List options = new ArrayList(pieces.size()); - - Node dynamic = XMLUtils.getNodeXPath(description, XPATH_DYNAMIC); - - // TODO We should handle these cases better!! - NodeList items = (NodeList) XMLUtils.getXPath( - dynamic, "xform:select1/xform:choices/xform:item", - XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); - - if (items == null || items.getLength() == 0) { - items = (NodeList) XMLUtils.getXPath( - dynamic, "xform:select/xform:choices/xform:item", - XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); - } - - if (items == null || items.getLength() == 0) { - items = (NodeList) XMLUtils.getXPath( - dynamic, "xform:group/xform:select/xform:item", - XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); - } - - - for (int i = 0; i < items.getLength(); i++) { - Node item = items.item(i); - Node label = (Node) XMLUtils.getXPath( - item, "xform:label", XPathConstants.NODE, - XFormNamespaceContext.INSTANCE); - - Node value = (Node) XMLUtils.getXPath( - item, "xform:value", XPathConstants.NODE, - XFormNamespaceContext.INSTANCE); - - if (pieces.indexOf(label.getTextContent()) >= 0) - options.add(value.getTextContent()); - } - - if (options.isEmpty()) - throw new NoSuchOptionException(text); - - return (String[]) options.toArray(new String[options.size()]); - } - - - /** - * XXX This method extracts the measurement ids depending on the user - * configuration from describe document. Currently, this is a special case - * that should be handled the same way as all the other options in the - * describe document. - */ - public static String[] extractMeasurements( - HttpClient client, - Artifact artifact, - String text) - throws NoSuchOptionException, ConnectionException - { - Document describe = ArtifactProtocolUtils.createDescribeDocument( - artifact, true); - - Document description = (Document) client.describe( - artifact, describe, new DocumentResponseHandler()); - - List pieces = Arrays.asList(text.split(",")); - List options = new ArrayList(pieces.size()); - - Node dynamic = XMLUtils.getNodeXPath(description, XPATH_DYNAMIC); - - NodeList params = (NodeList) XMLUtils.getXPath( - dynamic, "xform:group/xform:select", - XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); - - for (int i = 0; i < params.getLength(); i++) { - Node param = params.item(i); - - NodeList items = (NodeList) XMLUtils.getXPath( - param, "xform:item[@disabled='false']", XPathConstants.NODESET, - XFormNamespaceContext.INSTANCE); - - for (int j = 0; j < items.getLength(); j++) { - Node item = items.item(j); - - Node label = (Node) XMLUtils.getXPath( - item, "xform:label", XPathConstants.NODE, - XFormNamespaceContext.INSTANCE); - - if (pieces.indexOf(label.getTextContent()) < 0) { - continue; - } - - Node value = (Node) XMLUtils.getXPath( - item, "xform:value", XPathConstants.NODE, - XFormNamespaceContext.INSTANCE); - - options.add(value.getTextContent()); - } - } - - if (options.isEmpty()) - throw new NoSuchOptionException(text); - - return (String[]) options.toArray(new String[options.size()]); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/exceptions/ConnectionException.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.exceptions; - -import java.io.IOException; - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class ConnectionException extends IOException { - - public ConnectionException(String msg) { - super(msg); - } - - public ConnectionException(String msg, Throwable throwable) { - super(msg, throwable); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/exceptions/NoSuchOptionException.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.exceptions; - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class NoSuchOptionException extends Exception { - - public NoSuchOptionException(String msg) { - super(msg); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/http/HttpClient.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.http; - -import java.io.InputStream; -import java.io.OutputStream; - -import org.w3c.dom.Document; - -import de.intevation.artifacts.httpclient.exceptions.ConnectionException; -import de.intevation.artifacts.httpclient.http.response.ResponseHandler; -import de.intevation.artifacts.httpclient.objects.Artifact; -import de.intevation.artifacts.httpclient.objects.ArtifactFactory; -import de.intevation.artifacts.httpclient.utils.ArtifactCreator; - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public interface HttpClient { - - ArtifactFactory[] getArtifactFactories() - throws ConnectionException; - - Object create(Document createDocument, ArtifactCreator creator) - throws ConnectionException; - - Object describe( - Artifact artifact, - Document describeDocument, - ResponseHandler handler) - throws ConnectionException; - - Object feed(Artifact artifact, Document feedDocument, ResponseHandler handler) - throws ConnectionException; - - Object advance( - Artifact artifact, - Document advanceDocument, - ResponseHandler handler) - throws ConnectionException; - - void out( - Artifact artifact, - Document outDocument, - String target, - OutputStream out) - throws ConnectionException; - - - /******************************* - * Service API - *******************************/ - - Document callService(String url, String service, Document input) - throws ConnectionException; - - Object callService( - String url, - String service, - Document input, - ResponseHandler handler) - throws ConnectionException; - - - /******************************* - * Collections API - *******************************/ - - Object createCollection( - Document createDocument, - String ownerId, - ResponseHandler handler) - throws ConnectionException; - - Object doCollectionAction( - Document actionDocument, - String uuid, - ResponseHandler handler) - throws ConnectionException; - - void collectionOut( - Document outDocument, - String uuid, - String type, - OutputStream out) - throws ConnectionException; - - InputStream collectionOut( - Document doc, - String uuid, - String type) - throws ConnectionException; - - - /******************************* - * Users API - *******************************/ - - Document listUsers() - throws ConnectionException; - - Document listUserCollections(String userid) - throws ConnectionException; - - Document createUser(Document doc) - throws ConnectionException; - - Document findUser(Document doc) - throws ConnectionException; -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/http/HttpClientImpl.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,577 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.http; - -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import org.restlet.Client; -import org.restlet.Request; -import org.restlet.Response; -import org.restlet.data.ClientInfo; -import org.restlet.data.Language; -import org.restlet.data.MediaType; -import org.restlet.data.Method; -import org.restlet.data.Preference; -import org.restlet.data.Protocol; -import org.restlet.data.Status; -import org.restlet.ext.xml.DomRepresentation; -import org.restlet.representation.Representation; - -import org.w3c.dom.Document; - -import de.intevation.artifacts.httpclient.exceptions.ConnectionException; -import de.intevation.artifacts.httpclient.http.response.DocumentResponseHandler; -import de.intevation.artifacts.httpclient.http.response.ResponseHandler; -import de.intevation.artifacts.httpclient.http.response.StreamResponseHandler; -import de.intevation.artifacts.httpclient.objects.Artifact; -import de.intevation.artifacts.httpclient.objects.ArtifactFactory; -import de.intevation.artifacts.httpclient.utils.ArtifactProtocolUtils; -import de.intevation.artifacts.httpclient.utils.ArtifactCreator; - - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class HttpClientImpl implements HttpClient { - - private static final Logger logger = Logger.getLogger(HttpClient.class); - - /** The URL part of the resource to list the existing users of the server.*/ - public static final String PATH_LIST_USERS = "/list-users"; - - /** The URL part of the resource to list the Collections owned by a specific - * user.*/ - public static final String PATH_USER_COLLECTIONS = "/list-collections"; - - /** The URL part og the resource to create a new user on the server.*/ - public static final String PATH_CREATE_USER = "/create-user"; - - /** The URL part og the resource to find an existing user on the server.*/ - public static final String PATH_FIND_USER = "/find-user"; - - /** The URL part of the resource to call a specific service.*/ - public static final String PATH_SERVICE = "/service"; - - /** The URL path of the resource to create new artifact collections.*/ - public static final String PATH_CREATE_COLLECTION = "/create-collection"; - - /** The URL path of the resource to work with an artifact collections.*/ - public static final String PATH_ACTION_COLLECTION = "/collection"; - - /** The URL path of the resource to work with an artifact collections.*/ - public static final String PATH_OUT_COLLECTION = "/collection"; - - private String serverUrl; - - private String localeString; - - private static final ThreadLocal<Client> CLIENT = - new ThreadLocal<Client>() { - @Override - protected Client initialValue() { - logger.debug("create new HTTP client"); - return new Client(Protocol.HTTP); - } - }; - - public HttpClientImpl(String serverUrl) { - this.serverUrl = serverUrl; - } - - - /** - * This constructor might be used to modify the request's locale manually. - * E.g. the localization should not be based on the configured browser - * locale, but site specific configuration - than you are able to set the - * locale in this constructor. - * - * @param serverUrl The url that is used for the request. - * @param localeString The string representation of the desired locale. - */ - public HttpClientImpl(String serverUrl, String localeString) { - this(serverUrl); - - this.localeString = localeString; - } - - - @Override - public ArtifactFactory[] getArtifactFactories() - throws ConnectionException - { - ResponseHandler handler = new DocumentResponseHandler(); - - try { - String url = serverUrl + "/factories"; - Document result = (Document) handler.handle(doGet(url)); - - return ArtifactProtocolUtils.extractArtifactFactories(result); - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed. No Factories recieved."); - } - } - - - /** - * This method creates a new artifact in the artifact server and returns - * this artifact. The new artifact is created using <i>creator</i>. If no - * {@link ArtifactCreator} is given (null), an {@link Artifact} is returned. - * - * @param doc The CREATE document. - * @param creator The {@link ArtifactCreator} that is used to extract the - * new artifact from response document of the server. - * - * @return the new artifact. - */ - @Override - public Object create(Document doc, ArtifactCreator creator) - throws ConnectionException - { - ResponseHandler handler = new DocumentResponseHandler(); - - try { - String url = serverUrl + "/create"; - Document result = (Document) handler.handle(doPost(url, doc)); - - return creator == null - ? ArtifactProtocolUtils.extractArtifact(result) - : creator.create(result); - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed. No Artifact created."); - } - } - - - @Override - public Object describe( - Artifact artifact, - Document doc, - ResponseHandler handler) - throws ConnectionException - { - try { - String url = serverUrl + "/artifact/" + artifact.getUuid(); - return handler.handle(doPost(url, doc)); - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed: " + ioe.getMessage()); - } - } - - - @Override - public Object feed(Artifact artifact, Document doc, ResponseHandler handler) - throws ConnectionException - { - try { - String url = serverUrl + "/artifact/" + artifact.getUuid(); - Document result = (Document) handler.handle(doPost(url, doc)); - - return result; - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed: " + ioe.getMessage()); - } - } - - - @Override - public Object advance(Artifact artifact, Document doc, ResponseHandler handler) - throws ConnectionException - { - try { - String url = serverUrl + "/artifact/" + artifact.getUuid(); - Document result = (Document) handler.handle(doPost(url, doc)); - - return result; - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed: " + ioe.getMessage()); - } - } - - - @Override - public void out( - Artifact artifact, - Document doc, - String target, - OutputStream out) - throws ConnectionException - { - try { - String url = - serverUrl - + "/artifact/" - + artifact.getUuid() - + "/" + target; - - ResponseHandler handler = new StreamResponseHandler(); - - InputStream stream = (InputStream) handler.handle(doPost(url, doc)); - try { - byte[] b = new byte[4096]; - int i; - while ((i = stream.read(b)) >= 0) { - out.write(b, 0, i); - } - } - finally { - stream.close(); - } - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed: " + ioe.getMessage()); - } - } - - - //============================== - // HTTP specific methods - //============================== - - private Response doPost(String url, Document body) throws IOException { - if (logger.isDebugEnabled()) { - logger.debug("Start HTTP-POST request to: " + url); - } - - Client client = getClient(); - Request request = prepareRequest(Method.POST, url); - - Representation representation = new DomRepresentation( - MediaType.APPLICATION_XML, - body); - - request.setEntity(representation); - Response response = client.handle(request); - - Status status = response.getStatus(); - if (status.getCode() != 200) { - logger.error("Response status: " + status.getCode()); - throw new IOException(status.getDescription()); - } - - return response; - } - - - private static Client getClient() { - return CLIENT.get(); - } - - - private Response doGet(String url) throws IOException { - if (logger.isDebugEnabled()) { - logger.debug("Start HTTP-POST request to: "+ url); - } - - Client client = getClient(); - Request request = prepareRequest(Method.GET, url); - - Response response = client.handle(request); - - Status status = response.getStatus(); - if (status.getCode() != 200) { - logger.error("Response status: " + status.getCode()); - throw new IOException(status.getDescription()); - } - - return response; - } - - - /** - * This method prepares the request object. - * - * @param method The HTTP method (GET,POST). - * @param url The URL used for the request. - * - * @return the request object. - */ - private Request prepareRequest(Method method, String url) { - Request request = new Request(method, url); - - ClientInfo info = request.getClientInfo(); - - setLocale(info); - - request.setClientInfo(info); - - return request; - } - - - /** - * This method is called to set the request's locale. - * - * @param info The ClientInfo that is used to provide request information. - */ - private void setLocale(ClientInfo info) { - if (localeString == null) { - return; - } - - List<Preference<Language>> accepted = - new ArrayList<Preference<Language>>(); - - Language lang = Language.valueOf(localeString); - - if (lang != null) { - if (logger.isDebugEnabled()) { - logger.debug( - "Set locale of the request object: " + lang.toString()); - } - - Preference<Language> pref = new Preference<Language>(); - pref.setMetadata(lang); - accepted.add(pref); - - info.setAcceptedLanguages(accepted); - } - } - - - //============================== - // Collection API - //============================== - - /** - * This method triggers the artifact servers resource to create a new - * artifact collection. - * - * @param create The CREATE document for the collection. - * @param ownerId The uuid of the creator. - * @param handler The handler that is used to create the result object. - * - * @return a result object created by <i>handler</i>. - */ - public Object createCollection( - Document create, - String ownerId, - ResponseHandler handler) - throws ConnectionException - { - String url = serverUrl + PATH_CREATE_COLLECTION + "/" + ownerId; - - try { - return handler.handle(doPost(url, create)); - } - catch (IOException ioe) { - throw new ConnectionException(ioe.getMessage(), ioe); - } - } - - - /** - * This method might be used to trigger a collection specific action. The - * action that is executed depends on the document <i>actionDoc</i>. - * - * @param actionDoc The document that describes the action to be executed. - * @param uuid The uuid of the collection. - * @param handler The handler that is used to create the result object. - * - * @return a result object created by <i>handler</i>. - */ - public Object doCollectionAction( - Document actionDoc, - String uuid, - ResponseHandler handler) - throws ConnectionException - { - String url = serverUrl + PATH_ACTION_COLLECTION + "/" + uuid; - - try { - return handler.handle(doPost(url, actionDoc)); - } - catch (IOException ioe) { - throw new ConnectionException(ioe.getMessage(), ioe); - } - } - - - /** - * This method triggers the out() operation of a Collection. The result of - * this operation is written to <i>out</i> directly - there is no return - * value. - * - * @param doc The request document for the out() operation. - * @param uuid The identifier of the Collection. - * @param type The name of the output type. - * @param out The OutputStream. - */ - public void collectionOut( - Document doc, - String uuid, - String type, - OutputStream out) - throws ConnectionException - { - try { - InputStream stream = collectionOut(doc, uuid, type); - - byte[] b = new byte[4096]; - try { - int i; - while ((i = stream.read(b)) >= 0) { - out.write(b, 0, i); - } - } - finally { - stream.close(); - } - } - catch (IOException ioe) { - throw new ConnectionException(ioe.getMessage(), ioe); - } - } - - - /** - * This method triggers the out() operation of a Collection. The result of - * this operation is returned as an InputStream. - * - * @param doc The request document for the out() operation. - * @param uuid The identifier of the Collection. - * @param type The name of the output type. - * - * @return an InputStream. - */ - public InputStream collectionOut( - Document doc, - String uuid, - String type) - throws ConnectionException - { - String url = serverUrl + PATH_OUT_COLLECTION + "/" + uuid + "/" + type; - - ResponseHandler handler = new StreamResponseHandler(); - - try { - return (InputStream) handler.handle(doPost(url, doc)); - } - catch (IOException ioe) { - throw new ConnectionException(ioe.getMessage(), ioe); - } - } - - - /******************************* - * Service API - *******************************/ - - public Document callService(String url, String service, Document input) - throws ConnectionException - { - DocumentResponseHandler handler = new DocumentResponseHandler(); - - return (Document) callService(url, service, input, handler); - } - - - public Object callService( - String url, - String service, - Document input, - ResponseHandler handler) - throws ConnectionException { - if (logger.isDebugEnabled()) { - logger.debug("Start service call to '" + service + "'"); - } - - try { - String serverUrl = url + PATH_SERVICE + "/" + service; - return handler.handle(doPost(serverUrl, input)); - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed: " + ioe.getMessage()); - } - } - - - /******************************* - * Users API - *******************************/ - - public Document listUsers() - throws ConnectionException - { - ResponseHandler handler = new DocumentResponseHandler(); - String url = serverUrl + PATH_LIST_USERS; - - try { - return (Document) handler.handle(doGet(url)); - } - catch (IOException ioe) { - throw new ConnectionException(ioe.getMessage(), ioe); - } - } - - - public Document listUserCollections(String userid) - throws ConnectionException - { - ResponseHandler handler = new DocumentResponseHandler(); - - String url = serverUrl + PATH_USER_COLLECTIONS + "/" + userid; - - try { - return (Document) handler.handle(doGet(url)); - } - catch (IOException ioe) { - throw new ConnectionException(ioe.getMessage(), ioe); - } - } - - @Override - public Document createUser(Document doc) - throws ConnectionException { - ResponseHandler handler = new DocumentResponseHandler(); - - String url = this.serverUrl + PATH_CREATE_USER; - - try { - return (Document) handler.handle(doPost(url, doc)); - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed: " + ioe.getMessage()); - } - } - - @Override - public Document findUser(Document doc) - throws ConnectionException { - ResponseHandler handler = new DocumentResponseHandler(); - - String url = this.serverUrl + PATH_FIND_USER; - - try { - return (Document) handler.handle(doPost(url, doc)); - } - catch (IOException ioe) { - throw new ConnectionException( - "Connection to server failed: " + ioe.getMessage()); - } - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/http/response/DocumentResponseHandler.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.http.response; - -import java.io.IOException; - -import org.restlet.Response; -import org.restlet.representation.Representation; - -import de.intevation.artifacts.httpclient.utils.XMLUtils; - - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class DocumentResponseHandler implements ResponseHandler { - - public DocumentResponseHandler() { - } - - @Override - public Object handle(Response response) throws IOException { - Representation output = response.getEntity(); - return XMLUtils.readDocument(output.getStream()); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/http/response/ResponseHandler.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.http.response; - -import java.io.IOException; - -import org.restlet.Response; - - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public interface ResponseHandler { - - Object handle(Response response) throws IOException; -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/http/response/StreamResponseHandler.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.http.response; - -import java.io.IOException; - -import org.restlet.Response; -import org.restlet.representation.Representation; - - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class StreamResponseHandler implements ResponseHandler { - - public StreamResponseHandler() { - } - - @Override - public Object handle(Response response) throws IOException { - Representation output = response.getEntity(); - return output.getStream(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/http/response/StringResponseHandler.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.http.response; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.restlet.Response; - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class StringResponseHandler extends StreamResponseHandler { - - public StringResponseHandler() { - } - - @Override - public Object handle(Response response) throws IOException { - InputStream in = (InputStream) super.handle(response); - OutputStream out = new ByteArrayOutputStream(); - - byte[] b = new byte[4096]; - int i = -1; - while ((i = in.read(b)) > 0) { - out.write(b, 0, i); - } - out.close(); - - return out.toString(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/objects/Artifact.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ - -package de.intevation.artifacts.httpclient.objects; - -/** - * An <code>ArtifactObject</code> representing an artifact. - * - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - * - */ -public class Artifact { - - /** - * The uuid of this Artifact which must be used to identify - * the artifact at the <code>ArtifactDatabase</code>. - */ - private String uuid = null; - - /** - * The hash of the artifact which was send be the <code>ArtifactDatabase</code>. - */ - private String hash = null; - - /** - * Constructor - * @param uuid the uuid of this Artifact which must be used to identify - * the artifact at the <code>ArtifactDatabase</code> - * @param hash the hash of the artifact which was send be the - * <code>ArtifactDatabase</code> - */ - public Artifact(String uuid, String hash) { - this.uuid = uuid; - this.hash = hash; - } - - public String getHash() { - return this.hash; - } - - public String getUuid() { - return this.uuid; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :
--- a/src/main/java/de/intevation/artifacts/httpclient/objects/ArtifactFactory.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ - -package de.intevation.artifacts.httpclient.objects; - - -public class ArtifactFactory { - - private String name; - private String description; - - public ArtifactFactory(String name, String description) { - this.name = name; - this.description = description; - } - - - public String getName() { - return name; - } - - - public String getDescription() { - return description; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/utils/ArtifactCreator.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2011 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.utils; - -import org.w3c.dom.Document; - - -/** - * This interface is used to create new implementation dependend instances of an - * <i>Artifact</i>. - * - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public interface ArtifactCreator { - - /** - * This method should return a new Artifact object. - * - * @param doc A document that describes the artifact. - * - * @return an implementation dependend instance of an <i>Artifact</i>. - */ - public Object create(Document doc); -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/utils/ArtifactNamespaceContext.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ - -package de.intevation.artifacts.httpclient.utils; - -import java.util.Iterator; - -import javax.xml.XMLConstants; -import javax.xml.namespace.NamespaceContext; - -/** - * The namespacecontext object used in xml documents retrieved by the artifact - * server. - * - * @author <a href="mailto:sascha.teichmann@intevation">Sascha L. Teichmann</a> - */ -public class ArtifactNamespaceContext -implements NamespaceContext -{ - /** - * The URI of the namespace of the artifacts. - */ - public final static String NAMESPACE_URI = "http://www.intevation.de/2009/artifacts"; - - /** - * The XML prefix for the artifacts namespace. - */ - public final static String NAMESPACE_PREFIX = "art"; - - /** - * The singleton instance of this <code>NamespaceContext</code> - */ - public static final ArtifactNamespaceContext INSTANCE = - new ArtifactNamespaceContext(); - - /** - * Constructor - */ - public ArtifactNamespaceContext() { - } - - public String getNamespaceURI(String prefix) { - - if (prefix == null) { - throw new NullPointerException("Null prefix"); - } - - if (NAMESPACE_PREFIX.equals(prefix)) { - return NAMESPACE_URI; - } - - if ("xml".equals(prefix)) { - return XMLConstants.XML_NS_URI; - } - - return XMLConstants.NULL_NS_URI; - } - - public String getPrefix(String uri) { - throw new UnsupportedOperationException(); - } - - public Iterator getPrefixes(String uri) { - throw new UnsupportedOperationException(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/src/main/java/de/intevation/artifacts/httpclient/utils/ArtifactProtocolUtils.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,277 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.utils; - -import java.util.Map; - -import javax.xml.xpath.XPathConstants; - -import org.apache.log4j.Logger; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -import de.intevation.artifacts.httpclient.objects.Artifact; -import de.intevation.artifacts.httpclient.objects.ArtifactFactory; - -public class ArtifactProtocolUtils { - - private static final Logger logger = - Logger.getLogger(ArtifactProtocolUtils.class); - - - public static ArtifactFactory[] extractArtifactFactories(Document doc) { - NodeList elements = (NodeList) XMLUtils.getXPath( - doc, - "/art:result/art:factories/art:factory", - XPathConstants.NODESET, - ArtifactNamespaceContext.INSTANCE); - - if (elements == null || elements.getLength() == 0) { - return null; - } - - ArtifactFactory[] facs = new ArtifactFactory[elements.getLength()]; - - String uri = ArtifactNamespaceContext.NAMESPACE_URI; - - for (int idx = 0; idx < facs.length; idx++) { - Element factory = (Element)elements.item(idx); - String desc = factory.getAttributeNS(uri, "description"); - String name = factory.getAttributeNS(uri, "name"); - - if (name.length() != 0) { - facs[idx] = new ArtifactFactory(name, desc); - } - } - - return facs; - } - - - public static Document createCreateDocument(String fis) { - Document document = XMLUtils.newDocument(); - - XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( - document, - ArtifactNamespaceContext.NAMESPACE_URI, - ArtifactNamespaceContext.NAMESPACE_PREFIX - ); - - Element action = creator.create("action"); - - Element type = creator.create("type"); - type.setAttribute("name", "create"); - - Element factory = creator.create("factory"); - factory.setAttribute("name", fis); - - action.appendChild(type); - action.appendChild(factory); - document.appendChild(action); - - return document; - } - - - /** - * Returns a new artifact defined by uuid and hash values of the document - * returned by the artifact server after creating a new artifact. - * - * @param document Contains information about the server-side created - * artifact. - * @return a new artifact object. - */ - public static Artifact extractArtifact(Document document) { - String uuid = XMLUtils.getStringXPath( - document, - "/art:result/art:uuid/@value"); - - String hash = XMLUtils.getStringXPath( - document, - "/art:result/art:hash/@value"); - - logger.info("NEW Artifact: " + uuid + " / " + hash); - return new Artifact(uuid, hash); - } - - - private static Element createArtifactAction( - XMLUtils.ElementCreator creator, - Artifact artifact, - String artifactAction) - { - Element action = creator.create("action"); - - Element type = creator.create("type"); - type.setAttribute("name", artifactAction); - - Element uuid = creator.create("uuid"); - uuid.setAttribute("value", artifact.getUuid()); - - Element hash = creator.create("hash"); - hash.setAttribute("value", artifact.getHash()); - - action.appendChild(type); - action.appendChild(uuid); - action.appendChild(hash); - - return action; - } - - - public static Document createFeedDocument(Artifact artifact, Map attr) { - Document document = XMLUtils.newDocument(); - - XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( - document, - ArtifactNamespaceContext.NAMESPACE_URI, - ArtifactNamespaceContext.NAMESPACE_PREFIX - ); - - Element action = createArtifactAction(creator, artifact, "feed"); - Element data = creator.create("data"); - - for (Map.Entry<String, Object> entry: - ((Map<String, Object>)attr).entrySet()) { - - String key = entry.getKey(); - Object values = entry.getValue(); - - if (values instanceof Object[]) { - appendInputNodes(creator, data, key, (Object[]) values); - } - else { - appendInputNodes(creator, data, key, values); - } - } - - action.appendChild(data); - document.appendChild(action); - - return document; - } - - - private static void appendInputNodes( - XMLUtils.ElementCreator creator, - Element root, - String key, - Object value) - { - Element input = creator.create("input"); - input.setAttribute("name", key); - input.setAttribute("value", (String) value); - root.appendChild(input); - } - - - private static void appendInputNodes( - XMLUtils.ElementCreator creator, - Element root, - String key, - Object[] values) - { - for (Object value: values) { - Element input = creator.create("input"); - input.setAttribute("name", key); - input.setAttribute("value", (String) value); - root.appendChild(input); - } - } - - - public static Document createDescribeDocument(Artifact art, boolean ui) { - Document document = XMLUtils.newDocument(); - - XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( - document, - ArtifactNamespaceContext.NAMESPACE_URI, - ArtifactNamespaceContext.NAMESPACE_PREFIX - ); - - Element action = createArtifactAction(creator, art, "describe"); - Element includeUi = creator.create("include-ui"); - includeUi.setTextContent(String.valueOf(ui)); - - action.appendChild(includeUi); - document.appendChild(action); - - return document; - } - - - public static Document createAdvanceDocument(Artifact art, String target) { - Document document = XMLUtils.newDocument(); - - XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( - document, - ArtifactNamespaceContext.NAMESPACE_URI, - ArtifactNamespaceContext.NAMESPACE_PREFIX - ); - - Element action = createArtifactAction(creator, art, "advance"); - Element targetEle = creator.create("target"); - targetEle.setAttribute("name", target); - - action.appendChild(targetEle); - document.appendChild(action); - - return document; - } - - - public static Document createChartDocument(Artifact artifact, Map opts) { - Document document = XMLUtils.newDocument(); - - XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( - document, - ArtifactNamespaceContext.NAMESPACE_URI, - ArtifactNamespaceContext.NAMESPACE_PREFIX - ); - - Element action = createArtifactAction(creator, artifact, "out"); - Element out = creator.create("out"); - out.setAttribute("name", "chart"); - - Element export = creator.create("export"); - export.setAttribute("name", "img"); - - Element mimetype = creator.create("mime-type"); - export.setAttribute("value", (String) opts.get("mime-type")); - - Element params = creator.create("params"); - - Element width = creator.create("input"); - width.setAttribute("name", "width"); - width.setAttribute("value", (String) opts.get("width")); - - Element height = creator.create("input"); - height.setAttribute("name", "height"); - height.setAttribute("value", (String) opts.get("height")); - - Element points = creator.create("input"); - points.setAttribute("name", "points"); - points.setAttribute("value", (String) opts.get("points")); - - params.appendChild(width); - params.appendChild(height); - params.appendChild(points); - - out.appendChild(export); - out.appendChild(mimetype); - out.appendChild(params); - - action.appendChild(out); - document.appendChild(action); - - return document; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/utils/Configuration.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient.utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import org.apache.log4j.Logger; - -/** - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - */ -public class Configuration { - - private static final Logger logger = Logger.getLogger(Configuration.class); - - private File config; - - private Map serverSettings; - private Map artifactSettings; - private Map outputSettings; - - public static final String XPATH_SERVER = "/configuration/artifact-server"; - public static final String XPATH_ARTIFACT = "/configuration/artifact"; - public static final String XPATH_OUTPUT = "/configuration/output"; - - - public Configuration(File config) { - this.config = config; - serverSettings = new HashMap(); - artifactSettings = new HashMap(); - outputSettings = new HashMap(); - } - - - public void initialize() - throws IOException - { - Document conf = XMLUtils.readDocument(new FileInputStream(config)); - - if (conf == null) { - throw new IOException("Can't read config: " + config.getName()); - } - - readServerSettings(conf); - readArtifactSettings(conf); - readOutputSettings(conf); - } - - - private void readServerSettings(Document document) - throws IOException - { - Node serverNode = XMLUtils.getNodeXPath(document, XPATH_SERVER); - - if (serverNode == null) { - throw new IOException("No server configuration found."); - } - - serverSettings = extractSettings(serverSettings, serverNode); - } - - - private void readArtifactSettings(Document document) - throws IOException - { - Node artifactNode = XMLUtils.getNodeXPath(document, XPATH_ARTIFACT); - - if (artifactNode == null) { - throw new IOException("No artifact configuration found."); - } - - artifactSettings = extractSettings(artifactSettings, artifactNode); - } - - - private void readOutputSettings(Document document) - throws IOException - { - Node outputNode = XMLUtils.getNodeXPath(document, XPATH_OUTPUT); - - if (outputNode == null) { - throw new IOException("No output configuration found."); - } - - outputSettings = extractSettings(outputSettings, outputNode); - } - - - private Map extractSettings(Map settings, Node node) { - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) - logger.debug(child.getNodeName() + "|" + child.getTextContent()); - settings.put(child.getNodeName(), child.getTextContent()); - } - - return settings; - } - - - public Object getServerSettings(String key) { - return serverSettings.get(key); - } - - - public Object getArtifactSettings(String key) { - return artifactSettings.get(key); - } - - - public Object getOutputSettings(String key) { - return outputSettings.get(key); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/main/java/de/intevation/artifacts/httpclient/utils/XFormNamespaceContext.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ - -package de.intevation.artifacts.httpclient.utils; - -import java.util.Iterator; - -import javax.xml.XMLConstants; -import javax.xml.namespace.NamespaceContext; - -/** - * The namespacecontext object used in xml documents retrieved by the artifact - * server. - * - * @author <a href="mailto:ingo.weinzierl@intevation">Ingo Weinzierl</a> - */ -public class XFormNamespaceContext -implements NamespaceContext -{ - public final static String NAMESPACE_URI = "http://www.w3.org/2002/xforms"; - - public final static String NAMESPACE_PREFIX = "xform"; - - public static final XFormNamespaceContext INSTANCE = - new XFormNamespaceContext(); - - /** - * Constructor - */ - public XFormNamespaceContext() { - } - - public String getNamespaceURI(String prefix) { - - if (prefix == null) { - throw new NullPointerException("Null prefix"); - } - - if (NAMESPACE_PREFIX.equals(prefix)) { - return NAMESPACE_URI; - } - - if ("xml".equals(prefix)) { - return XMLConstants.XML_NS_URI; - } - - return XMLConstants.NULL_NS_URI; - } - - public String getPrefix(String uri) { - throw new UnsupportedOperationException(); - } - - public Iterator getPrefixes(String uri) { - throw new UnsupportedOperationException(); - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/src/main/java/de/intevation/artifacts/httpclient/utils/XMLUtils.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ - -package de.intevation.artifacts.httpclient.utils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.namespace.NamespaceContext; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.apache.log4j.Logger; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** - * This class provides many helper-Methods for handling different kinds of - * XML-stuff. - * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> - * @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a> - */ -public class XMLUtils { - - /** - * the logger, used to log exceptions and additonaly information - */ - private static Logger logger = Logger.getLogger(XMLUtils.class); - - /** - * Constructor - */ - public XMLUtils() { - } - - /** - * Class which could be used to create XML-Elements - * @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a> - * - */ - public static class ElementCreator { - - /** - * The document the elements should be placed in. - */ - protected Document document; - - /** - * The namespace that should be used. - */ - protected String ns; - - /** - * The prefix of the namespace that should be used. - */ - protected String prefix; - - /** - * Constructor - * @param document the document the elements should be placed in - * @param ns the namespace that should be used - * @param prefix the prefix of the namespace that should be used - */ - public ElementCreator(Document document, String ns, String prefix) { - this.document = document; - this.ns = ns; - this.prefix = prefix; - } - - /** - * Creates a new element using the given name. - * @param name the name of the new element. - * @return the new element - */ - public Element create(String name) { - Element element = document.createElementNS(ns, name); - element.setPrefix(prefix); - return element; - } - - /** - * Adds a new attribute to the given element. - * @param element the element where the attribute should be placed in. - * @param name the name of the attribute - * @param value the value of the attribute - */ - public void addAttr(Element element, String name, String value) { - Attr attr = document.createAttributeNS(ns, name); - attr.setValue(value); - attr.setPrefix(prefix); - element.setAttributeNode(attr); - } - } // class ElementCreator - - /** - * Creates a new document. - * @return the new document - */ - public static Document newDocument() { - try { - return DocumentBuilderFactory.newInstance().newDocumentBuilder() - .newDocument(); - } catch (ParserConfigurationException pce) { - logger.error(pce.getLocalizedMessage(), pce); - } - return null; - } - - /** - * Creates a new <code>XPath</code>-expression - * @return the new <code>XPath</code>-expression - */ - public static XPath newXPath() { - return newXPath(null); - } - - /** - * Creates a new <code>XPath</code>-expression - * @param namespaceContext the namespacecontext that should be used. - * @return the new <code>XPath</code>-expression - */ - public static XPath newXPath(NamespaceContext namespaceContext) { - XPathFactory factory = XPathFactory.newInstance(); - XPath xpath = factory.newXPath(); - if (namespaceContext != null) { - xpath.setNamespaceContext(namespaceContext); - } - return xpath; - } - - /** - * Fetch the value of an element or attribute from the given resource - * using the query. - * @param root the source where the value should be fetch from - * @param query the query that should be used to fetch the value - * @param namespaceContext the namespacecontext that must match to - * fetch the value. - * @return the value - */ - public static final String xpathString(Object root, String query, - NamespaceContext namespaceContext) { - return (String) xpath(root, query, XPathConstants.STRING, - namespaceContext); - } - - /** - * Fetch the object rom the given resource using the query. - * @param root the source where the value should be fetch from - * @param query the query that should be used to fetch the object - * @param returnType the Type that must be used to return the object, - * @param namespaceContext the namespacecontext that must match to - * fetch the object. - * @return the value - */ - public static final Object xpath(Object root, String query, - QName returnType, - NamespaceContext namespaceContext) { - if (root == null) { - return null; - } - try { - XPath xpath = XMLUtils.newXPath(namespaceContext); - if (xpath != null) { - return xpath.evaluate(query, root, returnType); - } - } catch (XPathExpressionException xpee) { - logger.error(xpee.getLocalizedMessage(), xpee); - } - return null; - } - - /** - * Fetch the object rom the given resource using the query - * and the default <code>ArtifactNamespaceContext</code> - * @param root the source where the value should be fetch from - * @param query the query that should be used to fetch the object - * @param returnType the Type that must be used to return the object - * @return the value - */ - public static Object getXPath(Object root, String query, QName returnType) { - return getXPath(root,query,returnType,ArtifactNamespaceContext.INSTANCE); - } - - /** - * Fetch the object rom the given resource using the query - * and the default <code>ArtifactNamespaceContext</code> - * @param root the source where the value should be fetch from - * @param query the query that should be used to fetch the object - * @param returnType the Type that must be used to return the object. - * @param context the namespacecontext that must match to - * fetch the object. - * @return the value - */ - public static Object getXPath( - Object root, String query, QName returnType, NamespaceContext context - ) { - return xpath(root, query, returnType, context); - } - - /** - * Fetch a Nodeset value from a XML-Fragment or XML-Document using the - * given query. - * @param root the source where the String should be fetched from - * @param query the query that should be used, - * @return the Nodeset fetched from the source - */ - public static NodeList getNodeSetXPath(Object root, String query) { - return (NodeList) getXPath(root, query, XPathConstants.NODESET); - } - - /** - * Fetch a Node from a XML-Fragment or XML-Document using the - * given query. - * @param root the source where the Node should be fetched from - * @param query the query that should be used, - * @return the Node fetched from the source - */ - public static Node getNodeXPath(Object root, String query) { - return (Node) getXPath(root, query, XPathConstants.NODE); - } - - /** - * Fetch a String value from a XML-Fragment or XML-Document using the - * given query. - * @param root the source where the String should be fetched from - * @param xpath the query that should be used, - * @return the String fetched from the source - */ - public static String getStringXPath(Object root, String xpath) { - return getStringXPath(root, xpath, null); - } - - /** - * Fetch a String value from a XML-Fragment or XML-Document using the - * given query. - * @param root the source where the String should be fetched from - * @param query the query that should be used, - * @param def the default-value that will be returned id no value was found - * @return the String fetched from the source - */ - public static String getStringXPath(Object root, String query, String def) { - String s = (String) getXPath(root, query, XPathConstants.STRING); - return s == null || s.length() == 0 ? def : s; - } - - /** - * Reads an XML-document from a given <code>InputStream</code> - * @param inputStream the <code>InputStream</code> where the document - * should be read from - * @return the document that could be read. - */ - public static Document readDocument(InputStream inputStream) { - Document returnValue = null; - try { - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory - .newInstance(); - docBuilderFactory.setNamespaceAware(true); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - returnValue = docBuilder.parse(inputStream); - } catch (ParserConfigurationException e) { - logger.error(e, e); - } catch (SAXException e) { - logger.error(e, e); - } catch (IOException e) { - logger.error(e, e); - } - return returnValue; - } - - /** - * Writes a given Document to an <code>OutputStream</code> - * @param document the document that should be written - * @param out the stream where the document should be written to, - * @return true if it was successful, false if not. - */ - public static boolean toStream(Document document, OutputStream out) { - try { - Transformer transformer = - TransformerFactory.newInstance().newTransformer(); - DOMSource source = new DOMSource(document); - StreamResult result = new StreamResult(out); - transformer.transform(source, result); - return true; - } - catch (TransformerConfigurationException tce) { - logger.error(tce.getLocalizedMessage(), tce); - } - catch (TransformerFactoryConfigurationError tfce) { - logger.error(tfce.getLocalizedMessage(), tfce); - } - catch (TransformerException te) { - logger.error(te.getLocalizedMessage(), te); - } - return false; - } -} -// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/ConsoleClient.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ + +package de.intevation.artifacts.httpclient; + +import java.io.IOException; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; + +import java.net.MalformedURLException; + +import java.util.Arrays; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.xpath.XPathConstants; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +import de.intevation.artifacts.httpclient.http.HttpClient; +import de.intevation.artifacts.httpclient.http.HttpClientImpl; +import de.intevation.artifacts.httpclient.http.response.DocumentResponseHandler; + +import de.intevation.artifacts.httpclient.exceptions.ConnectionException; +import de.intevation.artifacts.httpclient.exceptions.NoSuchOptionException; +import de.intevation.artifacts.httpclient.objects.Artifact; +import de.intevation.artifacts.httpclient.utils.ArtifactProtocolUtils; +import de.intevation.artifacts.httpclient.utils.Configuration; +import de.intevation.artifacts.httpclient.utils.XFormNamespaceContext; +import de.intevation.artifacts.httpclient.utils.XMLUtils; + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class ConsoleClient +{ + /** + * The logging is done via Log4j. To configure the logging + * a file 'log4j.properties' is search in the configuration directory. + */ + public static final String LOG4J_PROPERTIES = "log4j.properties"; + + + /** + * The path of the configuration directory. + */ + public static final String CONFIG_PATH = System.getProperty("config.dir", + "conf"); + + public static final String CONFIG = System.getProperty("config.file", + "use_case1.conf"); + + + public static final String XPATH_DYNAMIC = "/art:result/art:ui/art:dynamic"; + + /** + * The logger used in this class. + */ + private static Logger logger; + + + static { + configureLogging(); + + logger = Logger.getLogger(ConsoleClient.class); + } + + + /** + * Trys to load the Log4j configuration from ${config.dir}/log4j.properties. + */ + public static final void configureLogging() { + File configDir = new File(CONFIG_PATH); + File propFile = new File(configDir, LOG4J_PROPERTIES); + + if (propFile.isFile() && propFile.canRead()) { + try { + PropertyConfigurator.configure(propFile.toURI().toURL()); + } + catch (MalformedURLException mue) { + mue.printStackTrace(System.err); + } + } + } + + + public static final Configuration readConfiguration() { + File configDir = new File(CONFIG_PATH); + File configFile = new File(configDir, CONFIG); + + logger.debug("Configuration file: " + configFile.getAbsolutePath()); + + if (configFile.isFile() && configFile.canRead()) { + try { + Configuration conf = new Configuration(configFile); + conf.initialize(); + + return conf; + } + catch (IOException ioe) { + logger.error("Error while reading configuration."); + } + } + + return null; + } + + + public static void main( String[] args ) + { + logger.info("Starting console client."); + + Configuration conf = readConfiguration(); + + String serverHost = (String) conf.getServerSettings("host"); + String serverPort = (String) conf.getServerSettings("port"); + HttpClient client = new HttpClientImpl(serverHost + ":" + serverPort); + + try { + Document create = ArtifactProtocolUtils.createCreateDocument( + (String) conf.getArtifactSettings("fis")); + Artifact artifact = (Artifact) client.create(create, null); + + Map attr = new HashMap(); + String product = (String) conf.getArtifactSettings("product"); + String[] products = extractOptions(client, artifact, product); + attr.put("product", products[0]); + + feedAndGo(client, artifact, attr, "timeSeries"); + + attr.clear(); + String area = (String) conf.getArtifactSettings("areaid"); + String[] areas = extractOptions(client, artifact, area); + attr.put("areaid", areas[0]); + feedAndGo(client, artifact, attr, "timeseries_without_geom"); + + attr.clear(); + String feature = (String) conf.getArtifactSettings("featureid"); + String[] features = extractOptions(client, artifact, feature); + attr.put("featureid", features[0]); + feedAndGo(client, artifact, attr, "timeseries_vector_scalar"); + + attr.clear(); + String vector = (String) conf.getArtifactSettings("vectorscalar"); + String[] vectors = extractOptions(client, artifact, vector); + attr.put("vectorscalar", vectors[0]); + feedAndGo(client, artifact, attr, "timeseries_parameter"); + + attr.clear(); + String parameter = (String) conf.getArtifactSettings("parameterid"); + String[] parameters = extractOptions(client, artifact, parameter); + attr.put("parameterid", parameters); + feedAndGo(client, artifact, attr, "timeseries_depth_height"); + + attr.clear(); + String measure = (String) conf.getArtifactSettings("measurementid"); + String[] measures = extractMeasurements(client, artifact, measure); + attr.put("measurementid", measures); + feedAndGo(client, artifact, attr, "timeseries_interval"); + + attr.clear(); + String min = (String) conf.getArtifactSettings("minvalue"); + String max = (String) conf.getArtifactSettings("maxvalue"); + attr.put("minvalue", min); + attr.put("maxvalue", max); + feedAndGo(client, artifact, attr, "timeseries_calculate_results"); + + try { + Map opts = new HashMap(); + opts.put("mime-type", conf.getOutputSettings("mime-type")); + opts.put("width", conf.getOutputSettings("width")); + opts.put("height", conf.getOutputSettings("height")); + opts.put("points", conf.getOutputSettings("points")); + + Document chart = + ArtifactProtocolUtils.createChartDocument(artifact, opts); + + String dir = (String) conf.getOutputSettings("directory"); + + File outDir = new File(dir); + File output = new File(outDir, "output.png"); + OutputStream os = new FileOutputStream(output); + + client.out(artifact, chart, "chart", os); + } + catch (IOException ioe) { + logger.error( + "IO error while writing the output: " + ioe.getMessage()); + } + + logger.debug("Finished console client."); + } + catch (ConnectionException ce) { + logger.error(ce.getMessage()); + } + catch (NoSuchOptionException nsoe) { + logger.error( + "No such option found: " + nsoe.getMessage()); + } + } + + + public static void feedAndGo( + HttpClient client, + Artifact artifact, + Map attr, + String target) + throws ConnectionException + { + Document feed = ArtifactProtocolUtils.createFeedDocument(artifact, attr); + client.feed(artifact, feed, new DocumentResponseHandler()); + + Document advance = ArtifactProtocolUtils.createAdvanceDocument( + artifact, + target); + + client.advance(artifact, advance, new DocumentResponseHandler()); + } + + + /** + * XXX I think, this method should be implemented somewhere else to be able + * to re-use this implementation. But this method needs more work to be more + * abstract, so it needs to be reimplemented later, I think. + */ + public static String[] extractOptions( + HttpClient client, + Artifact artifact, + String text) + throws NoSuchOptionException, ConnectionException + { + Document describe = ArtifactProtocolUtils.createDescribeDocument( + artifact, true); + + Document description = (Document) client.describe( + artifact, describe, new DocumentResponseHandler()); + + List pieces = Arrays.asList(text.split(",")); + List options = new ArrayList(pieces.size()); + + Node dynamic = XMLUtils.getNodeXPath(description, XPATH_DYNAMIC); + + // TODO We should handle these cases better!! + NodeList items = (NodeList) XMLUtils.getXPath( + dynamic, "xform:select1/xform:choices/xform:item", + XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); + + if (items == null || items.getLength() == 0) { + items = (NodeList) XMLUtils.getXPath( + dynamic, "xform:select/xform:choices/xform:item", + XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); + } + + if (items == null || items.getLength() == 0) { + items = (NodeList) XMLUtils.getXPath( + dynamic, "xform:group/xform:select/xform:item", + XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); + } + + + for (int i = 0; i < items.getLength(); i++) { + Node item = items.item(i); + Node label = (Node) XMLUtils.getXPath( + item, "xform:label", XPathConstants.NODE, + XFormNamespaceContext.INSTANCE); + + Node value = (Node) XMLUtils.getXPath( + item, "xform:value", XPathConstants.NODE, + XFormNamespaceContext.INSTANCE); + + if (pieces.indexOf(label.getTextContent()) >= 0) + options.add(value.getTextContent()); + } + + if (options.isEmpty()) + throw new NoSuchOptionException(text); + + return (String[]) options.toArray(new String[options.size()]); + } + + + /** + * XXX This method extracts the measurement ids depending on the user + * configuration from describe document. Currently, this is a special case + * that should be handled the same way as all the other options in the + * describe document. + */ + public static String[] extractMeasurements( + HttpClient client, + Artifact artifact, + String text) + throws NoSuchOptionException, ConnectionException + { + Document describe = ArtifactProtocolUtils.createDescribeDocument( + artifact, true); + + Document description = (Document) client.describe( + artifact, describe, new DocumentResponseHandler()); + + List pieces = Arrays.asList(text.split(",")); + List options = new ArrayList(pieces.size()); + + Node dynamic = XMLUtils.getNodeXPath(description, XPATH_DYNAMIC); + + NodeList params = (NodeList) XMLUtils.getXPath( + dynamic, "xform:group/xform:select", + XPathConstants.NODESET, XFormNamespaceContext.INSTANCE); + + for (int i = 0; i < params.getLength(); i++) { + Node param = params.item(i); + + NodeList items = (NodeList) XMLUtils.getXPath( + param, "xform:item[@disabled='false']", XPathConstants.NODESET, + XFormNamespaceContext.INSTANCE); + + for (int j = 0; j < items.getLength(); j++) { + Node item = items.item(j); + + Node label = (Node) XMLUtils.getXPath( + item, "xform:label", XPathConstants.NODE, + XFormNamespaceContext.INSTANCE); + + if (pieces.indexOf(label.getTextContent()) < 0) { + continue; + } + + Node value = (Node) XMLUtils.getXPath( + item, "xform:value", XPathConstants.NODE, + XFormNamespaceContext.INSTANCE); + + options.add(value.getTextContent()); + } + } + + if (options.isEmpty()) + throw new NoSuchOptionException(text); + + return (String[]) options.toArray(new String[options.size()]); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/exceptions/ConnectionException.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.exceptions; + +import java.io.IOException; + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class ConnectionException extends IOException { + + public ConnectionException(String msg) { + super(msg); + } + + public ConnectionException(String msg, Throwable throwable) { + super(msg, throwable); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/exceptions/NoSuchOptionException.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.exceptions; + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class NoSuchOptionException extends Exception { + + public NoSuchOptionException(String msg) { + super(msg); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/http/HttpClient.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.http; + +import java.io.InputStream; +import java.io.OutputStream; + +import org.w3c.dom.Document; + +import de.intevation.artifacts.httpclient.exceptions.ConnectionException; +import de.intevation.artifacts.httpclient.http.response.ResponseHandler; +import de.intevation.artifacts.httpclient.objects.Artifact; +import de.intevation.artifacts.httpclient.objects.ArtifactFactory; +import de.intevation.artifacts.httpclient.utils.ArtifactCreator; + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public interface HttpClient { + + ArtifactFactory[] getArtifactFactories() + throws ConnectionException; + + Object create(Document createDocument, ArtifactCreator creator) + throws ConnectionException; + + Object describe( + Artifact artifact, + Document describeDocument, + ResponseHandler handler) + throws ConnectionException; + + Object feed(Artifact artifact, Document feedDocument, ResponseHandler handler) + throws ConnectionException; + + Object advance( + Artifact artifact, + Document advanceDocument, + ResponseHandler handler) + throws ConnectionException; + + void out( + Artifact artifact, + Document outDocument, + String target, + OutputStream out) + throws ConnectionException; + + + /******************************* + * Service API + *******************************/ + + Document callService(String url, String service, Document input) + throws ConnectionException; + + Object callService( + String url, + String service, + Document input, + ResponseHandler handler) + throws ConnectionException; + + + /******************************* + * Collections API + *******************************/ + + Object createCollection( + Document createDocument, + String ownerId, + ResponseHandler handler) + throws ConnectionException; + + Object doCollectionAction( + Document actionDocument, + String uuid, + ResponseHandler handler) + throws ConnectionException; + + void collectionOut( + Document outDocument, + String uuid, + String type, + OutputStream out) + throws ConnectionException; + + InputStream collectionOut( + Document doc, + String uuid, + String type) + throws ConnectionException; + + + /******************************* + * Users API + *******************************/ + + Document listUsers() + throws ConnectionException; + + Document listUserCollections(String userid) + throws ConnectionException; + + Document createUser(Document doc) + throws ConnectionException; + + Document findUser(Document doc) + throws ConnectionException; +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/http/HttpClientImpl.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,577 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.http; + +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; + +import org.restlet.Client; +import org.restlet.Request; +import org.restlet.Response; +import org.restlet.data.ClientInfo; +import org.restlet.data.Language; +import org.restlet.data.MediaType; +import org.restlet.data.Method; +import org.restlet.data.Preference; +import org.restlet.data.Protocol; +import org.restlet.data.Status; +import org.restlet.ext.xml.DomRepresentation; +import org.restlet.representation.Representation; + +import org.w3c.dom.Document; + +import de.intevation.artifacts.httpclient.exceptions.ConnectionException; +import de.intevation.artifacts.httpclient.http.response.DocumentResponseHandler; +import de.intevation.artifacts.httpclient.http.response.ResponseHandler; +import de.intevation.artifacts.httpclient.http.response.StreamResponseHandler; +import de.intevation.artifacts.httpclient.objects.Artifact; +import de.intevation.artifacts.httpclient.objects.ArtifactFactory; +import de.intevation.artifacts.httpclient.utils.ArtifactProtocolUtils; +import de.intevation.artifacts.httpclient.utils.ArtifactCreator; + + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class HttpClientImpl implements HttpClient { + + private static final Logger logger = Logger.getLogger(HttpClient.class); + + /** The URL part of the resource to list the existing users of the server.*/ + public static final String PATH_LIST_USERS = "/list-users"; + + /** The URL part of the resource to list the Collections owned by a specific + * user.*/ + public static final String PATH_USER_COLLECTIONS = "/list-collections"; + + /** The URL part og the resource to create a new user on the server.*/ + public static final String PATH_CREATE_USER = "/create-user"; + + /** The URL part og the resource to find an existing user on the server.*/ + public static final String PATH_FIND_USER = "/find-user"; + + /** The URL part of the resource to call a specific service.*/ + public static final String PATH_SERVICE = "/service"; + + /** The URL path of the resource to create new artifact collections.*/ + public static final String PATH_CREATE_COLLECTION = "/create-collection"; + + /** The URL path of the resource to work with an artifact collections.*/ + public static final String PATH_ACTION_COLLECTION = "/collection"; + + /** The URL path of the resource to work with an artifact collections.*/ + public static final String PATH_OUT_COLLECTION = "/collection"; + + private String serverUrl; + + private String localeString; + + private static final ThreadLocal<Client> CLIENT = + new ThreadLocal<Client>() { + @Override + protected Client initialValue() { + logger.debug("create new HTTP client"); + return new Client(Protocol.HTTP); + } + }; + + public HttpClientImpl(String serverUrl) { + this.serverUrl = serverUrl; + } + + + /** + * This constructor might be used to modify the request's locale manually. + * E.g. the localization should not be based on the configured browser + * locale, but site specific configuration - than you are able to set the + * locale in this constructor. + * + * @param serverUrl The url that is used for the request. + * @param localeString The string representation of the desired locale. + */ + public HttpClientImpl(String serverUrl, String localeString) { + this(serverUrl); + + this.localeString = localeString; + } + + + @Override + public ArtifactFactory[] getArtifactFactories() + throws ConnectionException + { + ResponseHandler handler = new DocumentResponseHandler(); + + try { + String url = serverUrl + "/factories"; + Document result = (Document) handler.handle(doGet(url)); + + return ArtifactProtocolUtils.extractArtifactFactories(result); + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed. No Factories recieved."); + } + } + + + /** + * This method creates a new artifact in the artifact server and returns + * this artifact. The new artifact is created using <i>creator</i>. If no + * {@link ArtifactCreator} is given (null), an {@link Artifact} is returned. + * + * @param doc The CREATE document. + * @param creator The {@link ArtifactCreator} that is used to extract the + * new artifact from response document of the server. + * + * @return the new artifact. + */ + @Override + public Object create(Document doc, ArtifactCreator creator) + throws ConnectionException + { + ResponseHandler handler = new DocumentResponseHandler(); + + try { + String url = serverUrl + "/create"; + Document result = (Document) handler.handle(doPost(url, doc)); + + return creator == null + ? ArtifactProtocolUtils.extractArtifact(result) + : creator.create(result); + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed. No Artifact created."); + } + } + + + @Override + public Object describe( + Artifact artifact, + Document doc, + ResponseHandler handler) + throws ConnectionException + { + try { + String url = serverUrl + "/artifact/" + artifact.getUuid(); + return handler.handle(doPost(url, doc)); + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed: " + ioe.getMessage()); + } + } + + + @Override + public Object feed(Artifact artifact, Document doc, ResponseHandler handler) + throws ConnectionException + { + try { + String url = serverUrl + "/artifact/" + artifact.getUuid(); + Document result = (Document) handler.handle(doPost(url, doc)); + + return result; + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed: " + ioe.getMessage()); + } + } + + + @Override + public Object advance(Artifact artifact, Document doc, ResponseHandler handler) + throws ConnectionException + { + try { + String url = serverUrl + "/artifact/" + artifact.getUuid(); + Document result = (Document) handler.handle(doPost(url, doc)); + + return result; + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed: " + ioe.getMessage()); + } + } + + + @Override + public void out( + Artifact artifact, + Document doc, + String target, + OutputStream out) + throws ConnectionException + { + try { + String url = + serverUrl + + "/artifact/" + + artifact.getUuid() + + "/" + target; + + ResponseHandler handler = new StreamResponseHandler(); + + InputStream stream = (InputStream) handler.handle(doPost(url, doc)); + try { + byte[] b = new byte[4096]; + int i; + while ((i = stream.read(b)) >= 0) { + out.write(b, 0, i); + } + } + finally { + stream.close(); + } + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed: " + ioe.getMessage()); + } + } + + + //============================== + // HTTP specific methods + //============================== + + private Response doPost(String url, Document body) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("Start HTTP-POST request to: " + url); + } + + Client client = getClient(); + Request request = prepareRequest(Method.POST, url); + + Representation representation = new DomRepresentation( + MediaType.APPLICATION_XML, + body); + + request.setEntity(representation); + Response response = client.handle(request); + + Status status = response.getStatus(); + if (status.getCode() != 200) { + logger.error("Response status: " + status.getCode()); + throw new IOException(status.getDescription()); + } + + return response; + } + + + private static Client getClient() { + return CLIENT.get(); + } + + + private Response doGet(String url) throws IOException { + if (logger.isDebugEnabled()) { + logger.debug("Start HTTP-POST request to: "+ url); + } + + Client client = getClient(); + Request request = prepareRequest(Method.GET, url); + + Response response = client.handle(request); + + Status status = response.getStatus(); + if (status.getCode() != 200) { + logger.error("Response status: " + status.getCode()); + throw new IOException(status.getDescription()); + } + + return response; + } + + + /** + * This method prepares the request object. + * + * @param method The HTTP method (GET,POST). + * @param url The URL used for the request. + * + * @return the request object. + */ + private Request prepareRequest(Method method, String url) { + Request request = new Request(method, url); + + ClientInfo info = request.getClientInfo(); + + setLocale(info); + + request.setClientInfo(info); + + return request; + } + + + /** + * This method is called to set the request's locale. + * + * @param info The ClientInfo that is used to provide request information. + */ + private void setLocale(ClientInfo info) { + if (localeString == null) { + return; + } + + List<Preference<Language>> accepted = + new ArrayList<Preference<Language>>(); + + Language lang = Language.valueOf(localeString); + + if (lang != null) { + if (logger.isDebugEnabled()) { + logger.debug( + "Set locale of the request object: " + lang.toString()); + } + + Preference<Language> pref = new Preference<Language>(); + pref.setMetadata(lang); + accepted.add(pref); + + info.setAcceptedLanguages(accepted); + } + } + + + //============================== + // Collection API + //============================== + + /** + * This method triggers the artifact servers resource to create a new + * artifact collection. + * + * @param create The CREATE document for the collection. + * @param ownerId The uuid of the creator. + * @param handler The handler that is used to create the result object. + * + * @return a result object created by <i>handler</i>. + */ + public Object createCollection( + Document create, + String ownerId, + ResponseHandler handler) + throws ConnectionException + { + String url = serverUrl + PATH_CREATE_COLLECTION + "/" + ownerId; + + try { + return handler.handle(doPost(url, create)); + } + catch (IOException ioe) { + throw new ConnectionException(ioe.getMessage(), ioe); + } + } + + + /** + * This method might be used to trigger a collection specific action. The + * action that is executed depends on the document <i>actionDoc</i>. + * + * @param actionDoc The document that describes the action to be executed. + * @param uuid The uuid of the collection. + * @param handler The handler that is used to create the result object. + * + * @return a result object created by <i>handler</i>. + */ + public Object doCollectionAction( + Document actionDoc, + String uuid, + ResponseHandler handler) + throws ConnectionException + { + String url = serverUrl + PATH_ACTION_COLLECTION + "/" + uuid; + + try { + return handler.handle(doPost(url, actionDoc)); + } + catch (IOException ioe) { + throw new ConnectionException(ioe.getMessage(), ioe); + } + } + + + /** + * This method triggers the out() operation of a Collection. The result of + * this operation is written to <i>out</i> directly - there is no return + * value. + * + * @param doc The request document for the out() operation. + * @param uuid The identifier of the Collection. + * @param type The name of the output type. + * @param out The OutputStream. + */ + public void collectionOut( + Document doc, + String uuid, + String type, + OutputStream out) + throws ConnectionException + { + try { + InputStream stream = collectionOut(doc, uuid, type); + + byte[] b = new byte[4096]; + try { + int i; + while ((i = stream.read(b)) >= 0) { + out.write(b, 0, i); + } + } + finally { + stream.close(); + } + } + catch (IOException ioe) { + throw new ConnectionException(ioe.getMessage(), ioe); + } + } + + + /** + * This method triggers the out() operation of a Collection. The result of + * this operation is returned as an InputStream. + * + * @param doc The request document for the out() operation. + * @param uuid The identifier of the Collection. + * @param type The name of the output type. + * + * @return an InputStream. + */ + public InputStream collectionOut( + Document doc, + String uuid, + String type) + throws ConnectionException + { + String url = serverUrl + PATH_OUT_COLLECTION + "/" + uuid + "/" + type; + + ResponseHandler handler = new StreamResponseHandler(); + + try { + return (InputStream) handler.handle(doPost(url, doc)); + } + catch (IOException ioe) { + throw new ConnectionException(ioe.getMessage(), ioe); + } + } + + + /******************************* + * Service API + *******************************/ + + public Document callService(String url, String service, Document input) + throws ConnectionException + { + DocumentResponseHandler handler = new DocumentResponseHandler(); + + return (Document) callService(url, service, input, handler); + } + + + public Object callService( + String url, + String service, + Document input, + ResponseHandler handler) + throws ConnectionException { + if (logger.isDebugEnabled()) { + logger.debug("Start service call to '" + service + "'"); + } + + try { + String serverUrl = url + PATH_SERVICE + "/" + service; + return handler.handle(doPost(serverUrl, input)); + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed: " + ioe.getMessage()); + } + } + + + /******************************* + * Users API + *******************************/ + + public Document listUsers() + throws ConnectionException + { + ResponseHandler handler = new DocumentResponseHandler(); + String url = serverUrl + PATH_LIST_USERS; + + try { + return (Document) handler.handle(doGet(url)); + } + catch (IOException ioe) { + throw new ConnectionException(ioe.getMessage(), ioe); + } + } + + + public Document listUserCollections(String userid) + throws ConnectionException + { + ResponseHandler handler = new DocumentResponseHandler(); + + String url = serverUrl + PATH_USER_COLLECTIONS + "/" + userid; + + try { + return (Document) handler.handle(doGet(url)); + } + catch (IOException ioe) { + throw new ConnectionException(ioe.getMessage(), ioe); + } + } + + @Override + public Document createUser(Document doc) + throws ConnectionException { + ResponseHandler handler = new DocumentResponseHandler(); + + String url = this.serverUrl + PATH_CREATE_USER; + + try { + return (Document) handler.handle(doPost(url, doc)); + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed: " + ioe.getMessage()); + } + } + + @Override + public Document findUser(Document doc) + throws ConnectionException { + ResponseHandler handler = new DocumentResponseHandler(); + + String url = this.serverUrl + PATH_FIND_USER; + + try { + return (Document) handler.handle(doPost(url, doc)); + } + catch (IOException ioe) { + throw new ConnectionException( + "Connection to server failed: " + ioe.getMessage()); + } + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/http/response/DocumentResponseHandler.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.http.response; + +import java.io.IOException; + +import org.restlet.Response; +import org.restlet.representation.Representation; + +import de.intevation.artifacts.httpclient.utils.XMLUtils; + + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class DocumentResponseHandler implements ResponseHandler { + + public DocumentResponseHandler() { + } + + @Override + public Object handle(Response response) throws IOException { + Representation output = response.getEntity(); + return XMLUtils.readDocument(output.getStream()); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/http/response/ResponseHandler.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.http.response; + +import java.io.IOException; + +import org.restlet.Response; + + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public interface ResponseHandler { + + Object handle(Response response) throws IOException; +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/http/response/StreamResponseHandler.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.http.response; + +import java.io.IOException; + +import org.restlet.Response; +import org.restlet.representation.Representation; + + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class StreamResponseHandler implements ResponseHandler { + + public StreamResponseHandler() { + } + + @Override + public Object handle(Response response) throws IOException { + Representation output = response.getEntity(); + return output.getStream(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/http/response/StringResponseHandler.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.http.response; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.restlet.Response; + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class StringResponseHandler extends StreamResponseHandler { + + public StringResponseHandler() { + } + + @Override + public Object handle(Response response) throws IOException { + InputStream in = (InputStream) super.handle(response); + OutputStream out = new ByteArrayOutputStream(); + + byte[] b = new byte[4096]; + int i = -1; + while ((i = in.read(b)) > 0) { + out.write(b, 0, i); + } + out.close(); + + return out.toString(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/objects/Artifact.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ + +package de.intevation.artifacts.httpclient.objects; + +/** + * An <code>ArtifactObject</code> representing an artifact. + * + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + * + */ +public class Artifact { + + /** + * The uuid of this Artifact which must be used to identify + * the artifact at the <code>ArtifactDatabase</code>. + */ + private String uuid = null; + + /** + * The hash of the artifact which was send be the <code>ArtifactDatabase</code>. + */ + private String hash = null; + + /** + * Constructor + * @param uuid the uuid of this Artifact which must be used to identify + * the artifact at the <code>ArtifactDatabase</code> + * @param hash the hash of the artifact which was send be the + * <code>ArtifactDatabase</code> + */ + public Artifact(String uuid, String hash) { + this.uuid = uuid; + this.hash = hash; + } + + public String getHash() { + return this.hash; + } + + public String getUuid() { + return this.uuid; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/objects/ArtifactFactory.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ + +package de.intevation.artifacts.httpclient.objects; + + +public class ArtifactFactory { + + private String name; + private String description; + + public ArtifactFactory(String name, String description) { + this.name = name; + this.description = description; + } + + + public String getName() { + return name; + } + + + public String getDescription() { + return description; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/utils/ArtifactCreator.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2011 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.utils; + +import org.w3c.dom.Document; + + +/** + * This interface is used to create new implementation dependend instances of an + * <i>Artifact</i>. + * + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public interface ArtifactCreator { + + /** + * This method should return a new Artifact object. + * + * @param doc A document that describes the artifact. + * + * @return an implementation dependend instance of an <i>Artifact</i>. + */ + public Object create(Document doc); +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/utils/ArtifactNamespaceContext.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ + +package de.intevation.artifacts.httpclient.utils; + +import java.util.Iterator; + +import javax.xml.XMLConstants; +import javax.xml.namespace.NamespaceContext; + +/** + * The namespacecontext object used in xml documents retrieved by the artifact + * server. + * + * @author <a href="mailto:sascha.teichmann@intevation">Sascha L. Teichmann</a> + */ +public class ArtifactNamespaceContext +implements NamespaceContext +{ + /** + * The URI of the namespace of the artifacts. + */ + public final static String NAMESPACE_URI = "http://www.intevation.de/2009/artifacts"; + + /** + * The XML prefix for the artifacts namespace. + */ + public final static String NAMESPACE_PREFIX = "art"; + + /** + * The singleton instance of this <code>NamespaceContext</code> + */ + public static final ArtifactNamespaceContext INSTANCE = + new ArtifactNamespaceContext(); + + /** + * Constructor + */ + public ArtifactNamespaceContext() { + } + + public String getNamespaceURI(String prefix) { + + if (prefix == null) { + throw new NullPointerException("Null prefix"); + } + + if (NAMESPACE_PREFIX.equals(prefix)) { + return NAMESPACE_URI; + } + + if ("xml".equals(prefix)) { + return XMLConstants.XML_NS_URI; + } + + return XMLConstants.NULL_NS_URI; + } + + public String getPrefix(String uri) { + throw new UnsupportedOperationException(); + } + + public Iterator getPrefixes(String uri) { + throw new UnsupportedOperationException(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/utils/ArtifactProtocolUtils.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.utils; + +import java.util.Map; + +import javax.xml.xpath.XPathConstants; + +import org.apache.log4j.Logger; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import de.intevation.artifacts.httpclient.objects.Artifact; +import de.intevation.artifacts.httpclient.objects.ArtifactFactory; + +public class ArtifactProtocolUtils { + + private static final Logger logger = + Logger.getLogger(ArtifactProtocolUtils.class); + + + public static ArtifactFactory[] extractArtifactFactories(Document doc) { + NodeList elements = (NodeList) XMLUtils.getXPath( + doc, + "/art:result/art:factories/art:factory", + XPathConstants.NODESET, + ArtifactNamespaceContext.INSTANCE); + + if (elements == null || elements.getLength() == 0) { + return null; + } + + ArtifactFactory[] facs = new ArtifactFactory[elements.getLength()]; + + String uri = ArtifactNamespaceContext.NAMESPACE_URI; + + for (int idx = 0; idx < facs.length; idx++) { + Element factory = (Element)elements.item(idx); + String desc = factory.getAttributeNS(uri, "description"); + String name = factory.getAttributeNS(uri, "name"); + + if (name.length() != 0) { + facs[idx] = new ArtifactFactory(name, desc); + } + } + + return facs; + } + + + public static Document createCreateDocument(String fis) { + Document document = XMLUtils.newDocument(); + + XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( + document, + ArtifactNamespaceContext.NAMESPACE_URI, + ArtifactNamespaceContext.NAMESPACE_PREFIX + ); + + Element action = creator.create("action"); + + Element type = creator.create("type"); + type.setAttribute("name", "create"); + + Element factory = creator.create("factory"); + factory.setAttribute("name", fis); + + action.appendChild(type); + action.appendChild(factory); + document.appendChild(action); + + return document; + } + + + /** + * Returns a new artifact defined by uuid and hash values of the document + * returned by the artifact server after creating a new artifact. + * + * @param document Contains information about the server-side created + * artifact. + * @return a new artifact object. + */ + public static Artifact extractArtifact(Document document) { + String uuid = XMLUtils.getStringXPath( + document, + "/art:result/art:uuid/@value"); + + String hash = XMLUtils.getStringXPath( + document, + "/art:result/art:hash/@value"); + + logger.info("NEW Artifact: " + uuid + " / " + hash); + return new Artifact(uuid, hash); + } + + + private static Element createArtifactAction( + XMLUtils.ElementCreator creator, + Artifact artifact, + String artifactAction) + { + Element action = creator.create("action"); + + Element type = creator.create("type"); + type.setAttribute("name", artifactAction); + + Element uuid = creator.create("uuid"); + uuid.setAttribute("value", artifact.getUuid()); + + Element hash = creator.create("hash"); + hash.setAttribute("value", artifact.getHash()); + + action.appendChild(type); + action.appendChild(uuid); + action.appendChild(hash); + + return action; + } + + + public static Document createFeedDocument(Artifact artifact, Map attr) { + Document document = XMLUtils.newDocument(); + + XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( + document, + ArtifactNamespaceContext.NAMESPACE_URI, + ArtifactNamespaceContext.NAMESPACE_PREFIX + ); + + Element action = createArtifactAction(creator, artifact, "feed"); + Element data = creator.create("data"); + + for (Map.Entry<String, Object> entry: + ((Map<String, Object>)attr).entrySet()) { + + String key = entry.getKey(); + Object values = entry.getValue(); + + if (values instanceof Object[]) { + appendInputNodes(creator, data, key, (Object[]) values); + } + else { + appendInputNodes(creator, data, key, values); + } + } + + action.appendChild(data); + document.appendChild(action); + + return document; + } + + + private static void appendInputNodes( + XMLUtils.ElementCreator creator, + Element root, + String key, + Object value) + { + Element input = creator.create("input"); + input.setAttribute("name", key); + input.setAttribute("value", (String) value); + root.appendChild(input); + } + + + private static void appendInputNodes( + XMLUtils.ElementCreator creator, + Element root, + String key, + Object[] values) + { + for (Object value: values) { + Element input = creator.create("input"); + input.setAttribute("name", key); + input.setAttribute("value", (String) value); + root.appendChild(input); + } + } + + + public static Document createDescribeDocument(Artifact art, boolean ui) { + Document document = XMLUtils.newDocument(); + + XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( + document, + ArtifactNamespaceContext.NAMESPACE_URI, + ArtifactNamespaceContext.NAMESPACE_PREFIX + ); + + Element action = createArtifactAction(creator, art, "describe"); + Element includeUi = creator.create("include-ui"); + includeUi.setTextContent(String.valueOf(ui)); + + action.appendChild(includeUi); + document.appendChild(action); + + return document; + } + + + public static Document createAdvanceDocument(Artifact art, String target) { + Document document = XMLUtils.newDocument(); + + XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( + document, + ArtifactNamespaceContext.NAMESPACE_URI, + ArtifactNamespaceContext.NAMESPACE_PREFIX + ); + + Element action = createArtifactAction(creator, art, "advance"); + Element targetEle = creator.create("target"); + targetEle.setAttribute("name", target); + + action.appendChild(targetEle); + document.appendChild(action); + + return document; + } + + + public static Document createChartDocument(Artifact artifact, Map opts) { + Document document = XMLUtils.newDocument(); + + XMLUtils.ElementCreator creator = new XMLUtils.ElementCreator( + document, + ArtifactNamespaceContext.NAMESPACE_URI, + ArtifactNamespaceContext.NAMESPACE_PREFIX + ); + + Element action = createArtifactAction(creator, artifact, "out"); + Element out = creator.create("out"); + out.setAttribute("name", "chart"); + + Element export = creator.create("export"); + export.setAttribute("name", "img"); + + Element mimetype = creator.create("mime-type"); + export.setAttribute("value", (String) opts.get("mime-type")); + + Element params = creator.create("params"); + + Element width = creator.create("input"); + width.setAttribute("name", "width"); + width.setAttribute("value", (String) opts.get("width")); + + Element height = creator.create("input"); + height.setAttribute("name", "height"); + height.setAttribute("value", (String) opts.get("height")); + + Element points = creator.create("input"); + points.setAttribute("name", "points"); + points.setAttribute("value", (String) opts.get("points")); + + params.appendChild(width); + params.appendChild(height); + params.appendChild(points); + + out.appendChild(export); + out.appendChild(mimetype); + out.appendChild(params); + + action.appendChild(out); + document.appendChild(action); + + return document; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/utils/Configuration.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.apache.log4j.Logger; + +/** + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + */ +public class Configuration { + + private static final Logger logger = Logger.getLogger(Configuration.class); + + private File config; + + private Map serverSettings; + private Map artifactSettings; + private Map outputSettings; + + public static final String XPATH_SERVER = "/configuration/artifact-server"; + public static final String XPATH_ARTIFACT = "/configuration/artifact"; + public static final String XPATH_OUTPUT = "/configuration/output"; + + + public Configuration(File config) { + this.config = config; + serverSettings = new HashMap(); + artifactSettings = new HashMap(); + outputSettings = new HashMap(); + } + + + public void initialize() + throws IOException + { + Document conf = XMLUtils.readDocument(new FileInputStream(config)); + + if (conf == null) { + throw new IOException("Can't read config: " + config.getName()); + } + + readServerSettings(conf); + readArtifactSettings(conf); + readOutputSettings(conf); + } + + + private void readServerSettings(Document document) + throws IOException + { + Node serverNode = XMLUtils.getNodeXPath(document, XPATH_SERVER); + + if (serverNode == null) { + throw new IOException("No server configuration found."); + } + + serverSettings = extractSettings(serverSettings, serverNode); + } + + + private void readArtifactSettings(Document document) + throws IOException + { + Node artifactNode = XMLUtils.getNodeXPath(document, XPATH_ARTIFACT); + + if (artifactNode == null) { + throw new IOException("No artifact configuration found."); + } + + artifactSettings = extractSettings(artifactSettings, artifactNode); + } + + + private void readOutputSettings(Document document) + throws IOException + { + Node outputNode = XMLUtils.getNodeXPath(document, XPATH_OUTPUT); + + if (outputNode == null) { + throw new IOException("No output configuration found."); + } + + outputSettings = extractSettings(outputSettings, outputNode); + } + + + private Map extractSettings(Map settings, Node node) { + NodeList children = node.getChildNodes(); + + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) + logger.debug(child.getNodeName() + "|" + child.getTextContent()); + settings.put(child.getNodeName(), child.getTextContent()); + } + + return settings; + } + + + public Object getServerSettings(String key) { + return serverSettings.get(key); + } + + + public Object getArtifactSettings(String key) { + return artifactSettings.get(key); + } + + + public Object getOutputSettings(String key) { + return outputSettings.get(key); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/utils/XFormNamespaceContext.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ + +package de.intevation.artifacts.httpclient.utils; + +import java.util.Iterator; + +import javax.xml.XMLConstants; +import javax.xml.namespace.NamespaceContext; + +/** + * The namespacecontext object used in xml documents retrieved by the artifact + * server. + * + * @author <a href="mailto:ingo.weinzierl@intevation">Ingo Weinzierl</a> + */ +public class XFormNamespaceContext +implements NamespaceContext +{ + public final static String NAMESPACE_URI = "http://www.w3.org/2002/xforms"; + + public final static String NAMESPACE_PREFIX = "xform"; + + public static final XFormNamespaceContext INSTANCE = + new XFormNamespaceContext(); + + /** + * Constructor + */ + public XFormNamespaceContext() { + } + + public String getNamespaceURI(String prefix) { + + if (prefix == null) { + throw new NullPointerException("Null prefix"); + } + + if (NAMESPACE_PREFIX.equals(prefix)) { + return NAMESPACE_URI; + } + + if ("xml".equals(prefix)) { + return XMLConstants.XML_NS_URI; + } + + return XMLConstants.NULL_NS_URI; + } + + public String getPrefix(String uri) { + throw new UnsupportedOperationException(); + } + + public Iterator getPrefixes(String uri) { + throw new UnsupportedOperationException(); + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/dive4elements/artifacts/httpclient/utils/XMLUtils.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ + +package de.intevation.artifacts.httpclient.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.apache.log4j.Logger; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +/** + * This class provides many helper-Methods for handling different kinds of + * XML-stuff. + * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a> + * @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a> + */ +public class XMLUtils { + + /** + * the logger, used to log exceptions and additonaly information + */ + private static Logger logger = Logger.getLogger(XMLUtils.class); + + /** + * Constructor + */ + public XMLUtils() { + } + + /** + * Class which could be used to create XML-Elements + * @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a> + * + */ + public static class ElementCreator { + + /** + * The document the elements should be placed in. + */ + protected Document document; + + /** + * The namespace that should be used. + */ + protected String ns; + + /** + * The prefix of the namespace that should be used. + */ + protected String prefix; + + /** + * Constructor + * @param document the document the elements should be placed in + * @param ns the namespace that should be used + * @param prefix the prefix of the namespace that should be used + */ + public ElementCreator(Document document, String ns, String prefix) { + this.document = document; + this.ns = ns; + this.prefix = prefix; + } + + /** + * Creates a new element using the given name. + * @param name the name of the new element. + * @return the new element + */ + public Element create(String name) { + Element element = document.createElementNS(ns, name); + element.setPrefix(prefix); + return element; + } + + /** + * Adds a new attribute to the given element. + * @param element the element where the attribute should be placed in. + * @param name the name of the attribute + * @param value the value of the attribute + */ + public void addAttr(Element element, String name, String value) { + Attr attr = document.createAttributeNS(ns, name); + attr.setValue(value); + attr.setPrefix(prefix); + element.setAttributeNode(attr); + } + } // class ElementCreator + + /** + * Creates a new document. + * @return the new document + */ + public static Document newDocument() { + try { + return DocumentBuilderFactory.newInstance().newDocumentBuilder() + .newDocument(); + } catch (ParserConfigurationException pce) { + logger.error(pce.getLocalizedMessage(), pce); + } + return null; + } + + /** + * Creates a new <code>XPath</code>-expression + * @return the new <code>XPath</code>-expression + */ + public static XPath newXPath() { + return newXPath(null); + } + + /** + * Creates a new <code>XPath</code>-expression + * @param namespaceContext the namespacecontext that should be used. + * @return the new <code>XPath</code>-expression + */ + public static XPath newXPath(NamespaceContext namespaceContext) { + XPathFactory factory = XPathFactory.newInstance(); + XPath xpath = factory.newXPath(); + if (namespaceContext != null) { + xpath.setNamespaceContext(namespaceContext); + } + return xpath; + } + + /** + * Fetch the value of an element or attribute from the given resource + * using the query. + * @param root the source where the value should be fetch from + * @param query the query that should be used to fetch the value + * @param namespaceContext the namespacecontext that must match to + * fetch the value. + * @return the value + */ + public static final String xpathString(Object root, String query, + NamespaceContext namespaceContext) { + return (String) xpath(root, query, XPathConstants.STRING, + namespaceContext); + } + + /** + * Fetch the object rom the given resource using the query. + * @param root the source where the value should be fetch from + * @param query the query that should be used to fetch the object + * @param returnType the Type that must be used to return the object, + * @param namespaceContext the namespacecontext that must match to + * fetch the object. + * @return the value + */ + public static final Object xpath(Object root, String query, + QName returnType, + NamespaceContext namespaceContext) { + if (root == null) { + return null; + } + try { + XPath xpath = XMLUtils.newXPath(namespaceContext); + if (xpath != null) { + return xpath.evaluate(query, root, returnType); + } + } catch (XPathExpressionException xpee) { + logger.error(xpee.getLocalizedMessage(), xpee); + } + return null; + } + + /** + * Fetch the object rom the given resource using the query + * and the default <code>ArtifactNamespaceContext</code> + * @param root the source where the value should be fetch from + * @param query the query that should be used to fetch the object + * @param returnType the Type that must be used to return the object + * @return the value + */ + public static Object getXPath(Object root, String query, QName returnType) { + return getXPath(root,query,returnType,ArtifactNamespaceContext.INSTANCE); + } + + /** + * Fetch the object rom the given resource using the query + * and the default <code>ArtifactNamespaceContext</code> + * @param root the source where the value should be fetch from + * @param query the query that should be used to fetch the object + * @param returnType the Type that must be used to return the object. + * @param context the namespacecontext that must match to + * fetch the object. + * @return the value + */ + public static Object getXPath( + Object root, String query, QName returnType, NamespaceContext context + ) { + return xpath(root, query, returnType, context); + } + + /** + * Fetch a Nodeset value from a XML-Fragment or XML-Document using the + * given query. + * @param root the source where the String should be fetched from + * @param query the query that should be used, + * @return the Nodeset fetched from the source + */ + public static NodeList getNodeSetXPath(Object root, String query) { + return (NodeList) getXPath(root, query, XPathConstants.NODESET); + } + + /** + * Fetch a Node from a XML-Fragment or XML-Document using the + * given query. + * @param root the source where the Node should be fetched from + * @param query the query that should be used, + * @return the Node fetched from the source + */ + public static Node getNodeXPath(Object root, String query) { + return (Node) getXPath(root, query, XPathConstants.NODE); + } + + /** + * Fetch a String value from a XML-Fragment or XML-Document using the + * given query. + * @param root the source where the String should be fetched from + * @param xpath the query that should be used, + * @return the String fetched from the source + */ + public static String getStringXPath(Object root, String xpath) { + return getStringXPath(root, xpath, null); + } + + /** + * Fetch a String value from a XML-Fragment or XML-Document using the + * given query. + * @param root the source where the String should be fetched from + * @param query the query that should be used, + * @param def the default-value that will be returned id no value was found + * @return the String fetched from the source + */ + public static String getStringXPath(Object root, String query, String def) { + String s = (String) getXPath(root, query, XPathConstants.STRING); + return s == null || s.length() == 0 ? def : s; + } + + /** + * Reads an XML-document from a given <code>InputStream</code> + * @param inputStream the <code>InputStream</code> where the document + * should be read from + * @return the document that could be read. + */ + public static Document readDocument(InputStream inputStream) { + Document returnValue = null; + try { + DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory + .newInstance(); + docBuilderFactory.setNamespaceAware(true); + DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); + returnValue = docBuilder.parse(inputStream); + } catch (ParserConfigurationException e) { + logger.error(e, e); + } catch (SAXException e) { + logger.error(e, e); + } catch (IOException e) { + logger.error(e, e); + } + return returnValue; + } + + /** + * Writes a given Document to an <code>OutputStream</code> + * @param document the document that should be written + * @param out the stream where the document should be written to, + * @return true if it was successful, false if not. + */ + public static boolean toStream(Document document, OutputStream out) { + try { + Transformer transformer = + TransformerFactory.newInstance().newTransformer(); + DOMSource source = new DOMSource(document); + StreamResult result = new StreamResult(out); + transformer.transform(source, result); + return true; + } + catch (TransformerConfigurationException tce) { + logger.error(tce.getLocalizedMessage(), tce); + } + catch (TransformerFactoryConfigurationError tfce) { + logger.error(tfce.getLocalizedMessage(), tfce); + } + catch (TransformerException te) { + logger.error(te.getLocalizedMessage(), te); + } + return false; + } +} +// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/src/test/java/de/intevation/artifacts/httpclient/ConsoleClientTest.java Wed Apr 24 17:35:50 2013 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2010 by Intevation GmbH - * - * This program is free software under the LGPL (>=v2.1) - * Read the file LGPL.txt coming with the software for details - * or visit http://www.gnu.org/licenses/ if it does not exist. - */ -package de.intevation.artifacts.httpclient; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple ConsoleClient. - */ -public class ConsoleClientTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public ConsoleClientTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( ConsoleClientTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testConsoleClient() - { - assertTrue( true ); - } -}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/test/java/org/dive4elements/artifacts/httpclient/ConsoleClientTest.java Thu Apr 25 11:14:14 2013 +0200 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2010 by Intevation GmbH + * + * This program is free software under the LGPL (>=v2.1) + * Read the file LGPL.txt coming with the software for details + * or visit http://www.gnu.org/licenses/ if it does not exist. + */ +package de.intevation.artifacts.httpclient; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple ConsoleClient. + */ +public class ConsoleClientTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public ConsoleClientTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( ConsoleClientTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testConsoleClient() + { + assertTrue( true ); + } +}