You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@deltacloud.apache.org by ma...@apache.org on 2011/06/01 12:03:43 UTC

svn commit: r1130080 [5/5] - in /incubator/deltacloud/trunk/clients/java: ./ org.apache.deltacloud.client.test/ org.apache.deltacloud.client.test/META-INF/ org.apache.deltacloud.client.test/src/ org.apache.deltacloud.client.test/src/org/ org.apache.del...

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/Base64Coder.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/Base64Coder.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/Base64Coder.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/Base64Coder.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,226 @@
+// Copyright 2003-2010 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
+// www.source-code.biz, www.inventec.ch/chdh
+//
+// This module is multi-licensed and may be used under the terms
+// of any of the following licenses:
+//
+//  EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal
+//  LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html
+//  GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html
+//  AL, Apache License, V2.0 or later, http://www.apache.org/licenses
+//  BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php
+//
+// Please contact the author if you need another license.
+// This module is provided "as is", without warranties of any kind.
+
+package org.apache.deltacloud.client.transport;
+
+/**
+* A Base64 encoder/decoder.
+*
+* <p>
+* This class is used to encode and decode data in Base64 format as described in RFC 1521.
+*
+* <p>
+* Project home page: <a href="http://www.source-code.biz/base64coder/java/">www.source-code.biz/base64coder/java</a><br>
+* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
+* Multi-licensed: EPL / LGPL / GPL / AL / BSD.
+*/
+public class Base64Coder {
+
+// The line separator string of the operating system.
+private static final String systemLineSeparator = System.getProperty("line.separator");
+
+// Mapping table from 6-bit nibbles to Base64 characters.
+private static char[]    map1 = new char[64];
+   static {
+      int i=0;
+      for (char c='A'; c<='Z'; c++) map1[i++] = c;
+      for (char c='a'; c<='z'; c++) map1[i++] = c;
+      for (char c='0'; c<='9'; c++) map1[i++] = c;
+      map1[i++] = '+'; map1[i++] = '/'; }
+
+// Mapping table from Base64 characters to 6-bit nibbles.
+private static byte[]    map2 = new byte[128];
+   static {
+      for (int i=0; i<map2.length; i++) map2[i] = -1;
+      for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; }
+
+/**
+* Encodes a string into Base64 format.
+* No blanks or line breaks are inserted.
+* @param s  A String to be encoded.
+* @return   A String containing the Base64 encoded data.
+*/
+public static String encodeString (String s) {
+   return new String(encode(s.getBytes())); }
+
+/**
+* Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters.
+* This method is compatible with <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>.
+* @param in  An array containing the data bytes to be encoded.
+* @return    A String containing the Base64 encoded data, broken into lines.
+*/
+public static String encodeLines (byte[] in) {
+   return encodeLines(in, 0, in.length, 76, systemLineSeparator); }
+
+/**
+* Encodes a byte array into Base 64 format and breaks the output into lines.
+* @param in            An array containing the data bytes to be encoded.
+* @param iOff          Offset of the first byte in <code>in</code> to be processed.
+* @param iLen          Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>.
+* @param lineLen       Line length for the output data. Should be a multiple of 4.
+* @param lineSeparator The line separator to be used to separate the output lines.
+* @return              A String containing the Base64 encoded data, broken into lines.
+*/
+public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) {
+   int blockLen = (lineLen*3) / 4;
+   if (blockLen <= 0) throw new IllegalArgumentException();
+   int lines = (iLen+blockLen-1) / blockLen;
+   int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length();
+   StringBuilder buf = new StringBuilder(bufLen);
+   int ip = 0;
+   while (ip < iLen) {
+      int l = Math.min(iLen-ip, blockLen);
+      buf.append (encode(in, iOff+ip, l));
+      buf.append (lineSeparator);
+      ip += l; }
+   return buf.toString(); }
+
+/**
+* Encodes a byte array into Base64 format.
+* No blanks or line breaks are inserted in the output.
+* @param in  An array containing the data bytes to be encoded.
+* @return    A character array containing the Base64 encoded data.
+*/
+public static char[] encode (byte[] in) {
+   return encode(in, 0, in.length); }
+
+/**
+* Encodes a byte array into Base64 format.
+* No blanks or line breaks are inserted in the output.
+* @param in    An array containing the data bytes to be encoded.
+* @param iLen  Number of bytes to process in <code>in</code>.
+* @return      A character array containing the Base64 encoded data.
+*/
+public static char[] encode (byte[] in, int iLen) {
+   return encode(in, 0, iLen); }
+
+/**
+* Encodes a byte array into Base64 format.
+* No blanks or line breaks are inserted in the output.
+* @param in    An array containing the data bytes to be encoded.
+* @param iOff  Offset of the first byte in <code>in</code> to be processed.
+* @param iLen  Number of bytes to process in <code>in</code>, starting at <code>iOff</code>.
+* @return      A character array containing the Base64 encoded data.
+*/
+public static char[] encode (byte[] in, int iOff, int iLen) {
+   int oDataLen = (iLen*4+2)/3;       // output length without padding
+   int oLen = ((iLen+2)/3)*4;         // output length including padding
+   char[] out = new char[oLen];
+   int ip = iOff;
+   int iEnd = iOff + iLen;
+   int op = 0;
+   while (ip < iEnd) {
+      int i0 = in[ip++] & 0xff;
+      int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
+      int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
+      int o0 = i0 >>> 2;
+      int o1 = ((i0 &   3) << 4) | (i1 >>> 4);
+      int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
+      int o3 = i2 & 0x3F;
+      out[op++] = map1[o0];
+      out[op++] = map1[o1];
+      out[op] = op < oDataLen ? map1[o2] : '='; op++;
+      out[op] = op < oDataLen ? map1[o3] : '='; op++; }
+   return out; }
+
+/**
+* Decodes a string from Base64 format.
+* No blanks or line breaks are allowed within the Base64 encoded input data.
+* @param s  A Base64 String to be decoded.
+* @return   A String containing the decoded data.
+* @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
+*/
+public static String decodeString (String s) {
+   return new String(decode(s)); }
+
+/**
+* Decodes a byte array from Base64 format and ignores line separators, tabs and blanks.
+* CR, LF, Tab and Space characters are ignored in the input data.
+* This method is compatible with <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>.
+* @param s  A Base64 String to be decoded.
+* @return   An array containing the decoded data bytes.
+* @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
+*/
+public static byte[] decodeLines (String s) {
+   char[] buf = new char[s.length()];
+   int p = 0;
+   for (int ip = 0; ip < s.length(); ip++) {
+      char c = s.charAt(ip);
+      if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
+         buf[p++] = c; }
+   return decode(buf, 0, p); }
+
+/**
+* Decodes a byte array from Base64 format.
+* No blanks or line breaks are allowed within the Base64 encoded input data.
+* @param s  A Base64 String to be decoded.
+* @return   An array containing the decoded data bytes.
+* @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
+*/
+public static byte[] decode (String s) {
+   return decode(s.toCharArray()); }
+
+/**
+* Decodes a byte array from Base64 format.
+* No blanks or line breaks are allowed within the Base64 encoded input data.
+* @param in  A character array containing the Base64 encoded data.
+* @return    An array containing the decoded data bytes.
+* @throws    IllegalArgumentException If the input is not valid Base64 encoded data.
+*/
+public static byte[] decode (char[] in) {
+   return decode(in, 0, in.length); }
+
+/**
+* Decodes a byte array from Base64 format.
+* No blanks or line breaks are allowed within the Base64 encoded input data.
+* @param in    A character array containing the Base64 encoded data.
+* @param iOff  Offset of the first character in <code>in</code> to be processed.
+* @param iLen  Number of characters to process in <code>in</code>, starting at <code>iOff</code>.
+* @return      An array containing the decoded data bytes.
+* @throws      IllegalArgumentException If the input is not valid Base64 encoded data.
+*/
+public static byte[] decode (char[] in, int iOff, int iLen) {
+   if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
+   while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--;
+   int oLen = (iLen*3) / 4;
+   byte[] out = new byte[oLen];
+   int ip = iOff;
+   int iEnd = iOff + iLen;
+   int op = 0;
+   while (ip < iEnd) {
+      int i0 = in[ip++];
+      int i1 = in[ip++];
+      int i2 = ip < iEnd ? in[ip++] : 'A';
+      int i3 = ip < iEnd ? in[ip++] : 'A';
+      if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
+         throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
+      int b0 = map2[i0];
+      int b1 = map2[i1];
+      int b2 = map2[i2];
+      int b3 = map2[i3];
+      if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
+         throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
+      int o0 = ( b0       <<2) | (b1>>>4);
+      int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
+      int o2 = ((b2 &   3)<<6) |  b3;
+      out[op++] = (byte)o0;
+      if (op<oLen) out[op++] = (byte)o1;
+      if (op<oLen) out[op++] = (byte)o2; }
+   return out; }
+
+// Dummy constructor.
+private Base64Coder() {}
+
+} // end class Base64Coder
\ No newline at end of file

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/IHttpTransport.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/IHttpTransport.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/IHttpTransport.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/IHttpTransport.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,38 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.transport;
+
+import java.io.InputStream;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.request.DeltaCloudRequest;
+
+/**
+ * An interface for http transport implementation to be used by the
+ * DeltaCloudClient.
+ *
+ * @author André Dietisheim
+ * @see URLConnectionTransport
+ */
+public interface IHttpTransport {
+
+	public InputStream request(DeltaCloudRequest request) throws DeltaCloudClientException;
+
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/URLConnectionTransport.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/URLConnectionTransport.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/URLConnectionTransport.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/transport/URLConnectionTransport.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,186 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+package org.apache.deltacloud.client.transport;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.Authenticator;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.MessageFormat;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.deltacloud.client.DeltaCloudNotFoundClientException;
+import org.apache.deltacloud.client.HttpMethod;
+import org.apache.deltacloud.client.request.DeltaCloudRequest;
+
+public class URLConnectionTransport extends AbstractHttpTransport {
+
+	private static final char USERNAME_PASSWORD_DELIMITER = ':';
+	private static final String PROPERTY_AUTHORIZATION = "Authorization";
+	private static final String PROPERTY_ACCEPT = "Accept";
+	private static final String PREFIX_BASIC_AUTHENTICATION = "Basic ";
+	private static final int TIMEOUT = 10 * 1024;
+
+	public URLConnectionTransport(String username, String password) {
+		super(username, password);
+	}
+
+	@Override
+	protected InputStream doRequest(DeltaCloudRequest request) throws Exception {
+		HttpURLConnection connection = null;
+		try {
+			URL url = request.getUrl();
+			connection = (HttpURLConnection) url.openConnection();
+			connection.setUseCaches(false);
+			connection.setDoInput(true);
+			connection.setAllowUserInteraction(false);
+			connection.setConnectTimeout(TIMEOUT);
+			connection.setRequestProperty(PROPERTY_ACCEPT, "application/xml;q=1");
+			connection.setInstanceFollowRedirects(true);
+			addCredentials(connection);
+			setRequestMethod(request, connection);
+			BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
+//			return StreamUtils.writeTo(in, System.err);
+			return in;		} catch (FileNotFoundException e) {
+			/*
+			 * thrown by #connect when server resonds with 404
+			 */
+			throw new DeltaCloudNotFoundClientException(
+					MessageFormat.format("Could not find resource {0}", request.getUrlString()));
+		} catch (IOException e) {
+			/*
+			 * thrown by #connect when server resonds with 401.
+			 */
+			HttpError httpError = HttpError.getInstance(e, connection);
+			if (httpError != null) {
+				throwOnHttpErrors(httpError.getStatusCode(), httpError.getStatusMessage(), request.getUrl());
+			}
+			throw e;
+		}
+
+	}
+
+	private void setRequestMethod(DeltaCloudRequest request, HttpURLConnection connection) throws IOException {
+		HttpMethod httpMethod = request.getHttpMethod();
+		connection.setRequestMethod(httpMethod.name());
+		switch (httpMethod) {
+		case PUT:
+		case POST:
+			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+			connection.setRequestProperty("Content-Length", "0");// String.valueOf(request.getParametersLength()));
+			connection.setDoOutput(true);
+			connection.getOutputStream().flush();
+			break;
+		case GET:
+			connection.setDoOutput(false);
+			break;
+		}
+
+	}
+
+	/**
+	 * Adds the credentials to the given http url connection.
+	 *
+	 * The current implementation uses low level API. Alternatively
+	 * {@link Authenticator#setDefault(Authenticator)} could be used which would
+	 * then rule all url connections in the same jvm.
+	 *
+	 * @param httpClient
+	 *            the http client
+	 * @return the default http client
+	 * @throws IOException
+	 */
+	private void addCredentials(URLConnection urlConnection) throws IOException {
+		String username = getUsername();
+		String password = getPassword();
+		if (username != null && password != null) {
+			String credentials = new StringBuilder()
+					.append(PREFIX_BASIC_AUTHENTICATION)
+					.append(getAuthenticationValue(username, password))
+					.toString();
+			urlConnection.setRequestProperty(PROPERTY_AUTHORIZATION, credentials);
+		}
+
+	}
+
+	private String getAuthenticationValue(String username, String password) throws IOException {
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		out.write(username.getBytes());
+		out.write(USERNAME_PASSWORD_DELIMITER);
+		out.write(password.getBytes());
+		char[] encoded = Base64Coder.encode(out.toByteArray());
+		return new String(encoded);
+	}
+
+	private static final class HttpError {
+
+		private static final Pattern STATUS_REGEX = Pattern.compile(".+ HTTP response code: ([0-9]{3}) .+");
+		private int statusCode;
+		private String statusMessage;
+
+		private HttpError(int statusCode, String statusMessage) {
+			this.statusCode = statusCode;
+			this.statusMessage = statusMessage;
+		}
+
+		public static HttpError getInstance(IOException ioe, HttpURLConnection connection) throws IOException {
+			HttpError httpError = null;
+			try {
+				int statusCode = getStatusCode(ioe);
+				if (statusCode > -1) {
+					String statusMessage = connection.getResponseMessage();
+					httpError = new HttpError(statusCode, statusMessage);
+				}
+			} catch (Exception e) {
+				// ignore
+			}
+			return httpError;
+		}
+
+		public String getStatusMessage() {
+			return statusMessage;
+		}
+
+		private static int getStatusCode(IOException e) {
+			Matcher matcher = STATUS_REGEX.matcher(e.getMessage());
+			if (matcher.matches()) {
+				return getStatusCode(matcher.group(1));
+			}
+			return -1;
+		}
+
+		private static int getStatusCode(String statusCode) {
+			try {
+				return Integer.parseInt(statusCode);
+			} catch (NumberFormatException e) {
+				return -1;
+			}
+		}
+
+		public int getStatusCode() {
+			return statusCode;
+		}
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/APIUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/APIUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/APIUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/APIUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,40 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.API;
+import org.w3c.dom.Element;
+
+/**
+ * @author André Dietisheim
+ */
+public class APIUnmarshaller extends AbstractDOMUnmarshaller<API> {
+
+	public APIUnmarshaller() {
+		super("api", API.class);
+	}
+
+	protected API doUnmarshall(Element element, API server) throws Exception {
+		if (element != null) {
+			server.setDriver(getAttributeText("driver", element));
+		}
+		return server;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractActionAwareUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractActionAwareUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractActionAwareUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractActionAwareUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,69 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.deltacloud.client.Action;
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * @author André Dietisheim
+ *
+ * @param <DELTACLOUDOBJECT>
+ */
+public abstract class AbstractActionAwareUnmarshaller<DELTACLOUDOBJECT> extends AbstractDOMUnmarshaller<DELTACLOUDOBJECT>{
+
+	private String actionElementName;
+	public AbstractActionAwareUnmarshaller(String tagName, Class<DELTACLOUDOBJECT> type, String actionElementName) {
+		super(tagName, type);
+		this.actionElementName = actionElementName;
+	}
+
+	protected List<Action<DELTACLOUDOBJECT>> getActions(Element element, DELTACLOUDOBJECT owner) throws DeltaCloudClientException {
+		if (element == null) {
+			return null;
+		}
+		List<Action<DELTACLOUDOBJECT>> actions = new ArrayList<Action<DELTACLOUDOBJECT>>();
+		NodeList nodeList = element.getElementsByTagName(actionElementName);
+		for (int i = 0; i < nodeList.getLength(); i++) {
+			Node linkNode = nodeList.item(i);
+			Action<DELTACLOUDOBJECT> action = createAction(linkNode);
+			if (action != null) {
+				action.setOwner(owner);
+				actions.add(action);
+			}
+		}
+		return actions;
+	}
+
+	protected Action<DELTACLOUDOBJECT> createAction(Node node) throws DeltaCloudClientException {
+		if (!(node instanceof Element)) {
+			return null;
+		}
+		return unmarshallAction((Element) node);
+	}
+
+	protected abstract Action<DELTACLOUDOBJECT> unmarshallAction(Element element) throws DeltaCloudClientException;
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDOMUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDOMUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDOMUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDOMUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,135 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.MessageFormat;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+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;
+
+/**
+ * @author André Dietisheim
+ *
+ * @param <DELTACLOUDOBJECT>
+ */
+public abstract class AbstractDOMUnmarshaller<DELTACLOUDOBJECT> {
+
+	private Class<DELTACLOUDOBJECT> type;
+	private String tagName;
+
+	public AbstractDOMUnmarshaller(String tagName, Class<DELTACLOUDOBJECT> type) {
+		this.type = type;
+		this.tagName = tagName;
+	}
+
+	public DELTACLOUDOBJECT unmarshall(InputStream inputStream, DELTACLOUDOBJECT deltacloudObject) throws DeltaCloudClientException {
+		try {
+			Element element = getFirstElement(tagName, getDocument(inputStream));
+			if (element == null) {
+				return null;
+			}
+			return unmarshall(element, deltacloudObject);
+		} catch (Exception e) {
+			// TODO: internationalize strings
+			throw new DeltaCloudClientException(
+					MessageFormat.format("Could not unmarshall type \"{0}\"", type), e);
+		}
+
+	}
+
+	protected Document getDocument(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException {
+		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+		DocumentBuilder documentBuilder = factory.newDocumentBuilder();
+		return documentBuilder.parse(inputStream);
+	}
+
+	public DELTACLOUDOBJECT unmarshall(Element element, DELTACLOUDOBJECT resource) throws DeltaCloudClientException {
+		try {
+			return doUnmarshall(element, resource);
+		} catch (Exception e) {
+			// TODO: internationalize strings
+			throw new DeltaCloudClientException(
+					MessageFormat.format("Could not unmarshall type \"{0}\"", type), e);
+		}
+	}
+
+	protected abstract DELTACLOUDOBJECT doUnmarshall(Element element, DELTACLOUDOBJECT resource) throws Exception;
+
+	protected String getFirstElementAttributeText(String elementName, String attributeId, Element element) {
+		Element firstElement = getFirstElement(elementName, element);
+		if (firstElement == null) {
+			return null;
+		}
+		return firstElement.getAttribute(attributeId);
+	}
+
+	protected String getFirstElementText(String elementName, Element element) {
+		Element firstElement = getFirstElement(elementName, element);
+		if (firstElement == null) {
+			return null;
+		}
+		return firstElement.getTextContent();
+	}
+
+	protected Element getFirstElement(String elementName, Element element) {
+		NodeList elements = element.getElementsByTagName(elementName);
+		if (elements != null
+				&& elements.getLength() > 0) {
+			return (Element) elements.item(0);
+		}
+		return null;
+	}
+
+	protected Element getFirstElement(String elementName, Document document) {
+		NodeList elements = document.getElementsByTagName(elementName);
+		if (elements != null
+				&& elements.getLength() > 0) {
+			return (Element) elements.item(0);
+		}
+		return null;
+	}
+
+	protected String getAttributeText(String attributeName, Element element) {
+		Node attribute = element.getAttributeNode(attributeName);
+		if (attribute != null) {
+			return attribute.getTextContent();
+		}
+		return null;
+	}
+
+	protected String stripText(String textContent) {
+		if (textContent == null || textContent.length() == 0) {
+			return textContent;
+		}
+		return textContent.trim();
+	}
+
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,53 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.io.InputStream;
+import java.text.MessageFormat;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+
+/**
+ * @author André Dietisheim
+ *
+ * @param <RESOURCE>
+ */
+public abstract class AbstractDeltaCloudObjectUnmarshaller<RESOURCE> implements IDeltaCloudObjectUnmarshaller<RESOURCE> {
+
+	private Class<RESOURCE> type;
+
+	public AbstractDeltaCloudObjectUnmarshaller(Class<RESOURCE> type) {
+		this.type = type;
+	}
+
+	public RESOURCE create(InputStream inputStream) throws DeltaCloudClientException {
+
+		try {
+			return doCreate(inputStream);
+		} catch (Exception e) {
+			// TODO: internationalize strings
+			throw new DeltaCloudClientException(
+					MessageFormat.format("Could not unmarshall resource of type \"{0}\"", type), e);
+		}
+	}
+
+	protected abstract RESOURCE doCreate(InputStream inputStream) throws Exception;
+
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectsUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectsUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectsUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/AbstractDeltaCloudObjectsUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,61 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.util.List;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * @author André Dietisheim
+ */
+@SuppressWarnings("rawtypes")
+public abstract class AbstractDeltaCloudObjectsUnmarshaller<CHILD> extends AbstractDOMUnmarshaller<List> {
+
+	private String childTag;
+
+	public AbstractDeltaCloudObjectsUnmarshaller(String parentTag, String childTag) {
+		super(parentTag, List.class);
+		this.childTag = childTag;
+	}
+
+	@SuppressWarnings("unchecked")
+	protected List doUnmarshall(Element element, List children) throws Exception {
+		if (element != null) {
+			NodeList nodeList = element.getElementsByTagName(childTag);
+			if (nodeList != null
+					&& nodeList.getLength() > 0) {
+				for (int i = 0; i < nodeList.getLength(); i++) {
+					Node node = nodeList.item(i);
+					if (node instanceof Element) {
+						CHILD child = unmarshallChild(node);
+						children.add(child);
+					}
+				}
+			}
+		}
+		return children;
+	}
+
+	protected abstract CHILD unmarshallChild(Node node) throws DeltaCloudClientException;
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ActionUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ActionUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ActionUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ActionUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,44 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.Action;
+import org.w3c.dom.Element;
+
+/**
+ * @author André Dietisheim
+ */
+public class ActionUnmarshaller<OWNER> extends AbstractDOMUnmarshaller<Action<OWNER>> {
+
+	@SuppressWarnings({ "unchecked", "rawtypes" })
+	public ActionUnmarshaller() {
+		super("link", (Class) Action.class);
+	}
+
+	@Override
+	protected Action<OWNER> doUnmarshall(Element element, Action<OWNER> action) throws Exception {
+		if (element != null) {
+			action.setMethod(getAttributeText("method", element));
+			action.setName(getAttributeText("rel", element));
+			action.setUrl(getAttributeText("href", element));
+		}
+		return action;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfileUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfileUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfileUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfileUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,106 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.deltacloud.client.HardwareProfile;
+import org.apache.deltacloud.client.Property;
+import org.apache.deltacloud.client.Property.Kind;
+import org.apache.deltacloud.client.utils.Assert;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * @author André Dietisheim
+ */
+public class HardwareProfileUnmarshaller extends
+		AbstractDOMUnmarshaller<HardwareProfile> {
+
+	public HardwareProfileUnmarshaller() {
+		super("hardware_profile", HardwareProfile.class);
+	}
+
+	@Override
+	protected HardwareProfile doUnmarshall(Element element,
+			HardwareProfile profile) throws Exception {
+		profile.setId(getAttributeText("id", element));
+		profile.setProperties(createProperties(element
+				.getElementsByTagName("property")));
+		return profile;
+	}
+
+	private List<Property> createProperties(NodeList propertiesList) {
+		List<Property> properties = new ArrayList<Property>();
+		for (int i = 0; i < propertiesList.getLength(); i++) {
+			Property property = createProperty(propertiesList.item(i));
+			properties.add(property);
+		}
+		return properties;
+	}
+
+	private Property createProperty(Node node) {
+		Assert.isTrue(node instanceof Element);
+		Element element = (Element) node;
+		Property property = new Property();
+		property.setName(element.getAttribute("name"));
+		property.setId(element.getAttribute("id"));
+		property.setUnit(element.getAttribute("unit"));
+		property.setValue(element.getAttribute("value"));
+		String kind = element.getAttribute("kind");
+		Assert.isTrue(kind != null);
+		kind = kind.toUpperCase();
+		property.setKind(kind);
+		if (Kind.RANGE.toString().equals(property.getKind())) {
+			setRange(element, property);
+		} else if (Kind.ENUM.toString().equals(property.getKind())) {
+			setEnum(element, property);
+		} else if (Kind.FIXED.toString().equals(property.getKind())) {
+			// no special treatement
+		}
+		return property;
+	}
+
+	private void setRange(Element propertyElement, Property property) {
+		Node node = propertyElement.getElementsByTagName("range").item(0);
+		Assert.isTrue(node instanceof Element);
+		Element rangeElement = (Element) node;
+		property.setRange(rangeElement.getAttribute("first"),
+				rangeElement.getAttribute("last"));
+	}
+
+	private void setEnum(Element propertyElement, Property property) {
+		Node node = propertyElement.getElementsByTagName("enum").item(0);
+		Assert.isTrue(node instanceof Element);
+		Element enumElement = (Element) node;
+		NodeList nodeList = enumElement.getElementsByTagName("entry");
+		ArrayList<String> enumValues = new ArrayList<String>();
+		for (int i = 0; i < nodeList.getLength(); i++) {
+			Node entryNode = nodeList.item(i);
+			Assert.isTrue(entryNode instanceof Element);
+			Element entryElement = (Element) entryNode;
+			enumValues.add(entryElement.getAttribute("value"));
+		}
+		property.setEnums(enumValues);
+	}
+
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfilesUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfilesUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfilesUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/HardwareProfilesUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,40 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.HardwareProfile;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * @author André Dietisheim
+ */
+public class HardwareProfilesUnmarshaller extends AbstractDeltaCloudObjectsUnmarshaller<HardwareProfile> {
+
+	public HardwareProfilesUnmarshaller() {
+		super("hardware_profiles", "hardware_profile");
+	}
+
+	@Override
+	protected HardwareProfile unmarshallChild(Node node) throws DeltaCloudClientException {
+		return new HardwareProfileUnmarshaller().unmarshall((Element) node, new HardwareProfile());
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/IDeltaCloudObjectUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/IDeltaCloudObjectUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/IDeltaCloudObjectUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/IDeltaCloudObjectUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,31 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.io.InputStream;
+
+/**
+ * @author André Dietisheim
+ */
+public interface IDeltaCloudObjectUnmarshaller<DELTACLOUDOBJECT> {
+
+	public DELTACLOUDOBJECT unmarshall(InputStream inputStream);
+
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImageUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImageUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImageUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImageUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,42 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.Image;
+import org.w3c.dom.Element;
+
+/**
+ * @author André Dietisheim
+ */
+public class ImageUnmarshaller extends AbstractDOMUnmarshaller<Image> {
+
+	public ImageUnmarshaller() {
+		super("image", Image.class);
+	}
+
+	protected Image doUnmarshall(Element element, Image image) throws Exception {
+		image.setId(getAttributeText("id", element));
+		image.setName(getFirstElementText("name", element));
+		image.setOwnerId(getFirstElementText("owner_id", element));
+		image.setDescription(getFirstElementText("description", element));
+		image.setArchitecture(getFirstElementText("architecture", element));
+		return image;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImagesUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImagesUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImagesUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/ImagesUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,41 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.Image;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * @author André Dietisheim
+ */
+public class ImagesUnmarshaller extends AbstractDeltaCloudObjectsUnmarshaller<Image> {
+
+	public ImagesUnmarshaller() {
+		super("images", "image");
+	}
+
+	@Override
+	protected Image unmarshallChild(Node node) throws DeltaCloudClientException {
+		Image image = new ImageUnmarshaller().unmarshall((Element) node, new Image());
+		return image;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstanceUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstanceUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstanceUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstanceUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,96 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.deltacloud.client.Action;
+import org.apache.deltacloud.client.AddressList;
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.Instance;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * @author André Dietisheim
+ */
+public class InstanceUnmarshaller extends AbstractActionAwareUnmarshaller<Instance> {
+
+	public InstanceUnmarshaller() {
+		super("instance", Instance.class, "link");
+	}
+
+	protected Instance doUnmarshall(Element element, Instance instance) throws Exception {
+		instance.setId(getAttributeText("id", element));
+		instance.setName(getFirstElementText("name", element));
+		instance.setOwnerId(getFirstElementText("owner_id", element));
+		instance.setOwnerId(getFirstElementText("owner_id", element));
+		instance.setImageId(getFirstElementAttributeText("image", "id", element));
+		instance.setProfileId(getFirstElementAttributeText("hardware_profile", "id", element));
+		instance.setRealmId(getFirstElementAttributeText("realm", "id", element));
+		instance.setState(getFirstElementText("state", element));
+		setKeyname(instance, element);
+		instance.setActions(getActions(element, instance));
+		instance.setPublicAddresses(getAddressList("public_addresses", element));
+		instance.setPrivateAddresses(getAddressList("private_addresses", element));
+		return instance;
+	}
+
+	private AddressList getAddressList(String elementName, Element element) {
+		Element addressElement = getFirstElement(elementName, element);
+		if (addressElement != null) {
+			NodeList addressList = addressElement.getChildNodes();
+			if (addressList != null) {
+				List<String> addresses = new ArrayList<String>();
+				for (int i = 0; i < addressList.getLength(); i++) {
+					Node addressNode = addressList.item(i);
+					if (addressNode != null) {
+						String address = stripText(addressNode.getTextContent());
+						if (address != null && address.length() > 0) {
+							addresses.add(address);
+						}
+					}
+				}
+				return new AddressList(addresses);
+			}
+		}
+		return new AddressList();
+	}
+
+	private void setKeyname(Instance instance, Element element) {
+		Element authenticationElement = getFirstElement("authentication", element);
+		if (authenticationElement != null) {
+			Element loginElement = getFirstElement("login", authenticationElement);
+			if (loginElement != null) {
+				String keyname = getFirstElementText("keyname", loginElement);
+				instance.setKeyId(keyname);
+			}
+		}
+	}
+
+	@Override
+	protected Action<Instance> unmarshallAction(Element element) throws DeltaCloudClientException {
+		Action<Instance> action = new Action<Instance>();
+		new ActionUnmarshaller<Instance>().unmarshall(element, action);
+		return action;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstancesUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstancesUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstancesUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/InstancesUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,41 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.Instance;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * @author André Dietisheim
+ */
+public class InstancesUnmarshaller extends AbstractDeltaCloudObjectsUnmarshaller<Instance> {
+
+	public InstancesUnmarshaller() {
+		super("instances", "instance");
+	}
+
+	@Override
+	protected Instance unmarshallChild(Node node) throws DeltaCloudClientException {
+		Instance instance = new InstanceUnmarshaller().unmarshall((Element) node, new Instance());
+		return instance;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeyUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeyUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeyUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeyUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,85 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.StringReader;
+
+import org.apache.deltacloud.client.Action;
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.Key;
+import org.w3c.dom.Element;
+
+/**
+ * @author André Dietisheim
+ */
+public class KeyUnmarshaller extends AbstractActionAwareUnmarshaller<Key> {
+
+	public KeyUnmarshaller() {
+		super("key", Key.class, "link");
+	}
+
+	protected Key doUnmarshall(Element element, Key key) throws Exception {
+		if (element != null) {
+			key.setId(getAttributeText("id", element));
+			key.setUrl(getAttributeText("href", element));
+			key.setState(getFirstElementText("state", element));
+			key.setFingerprint(getFirstElementText("fingerprint", element));
+			key.setPem(trimPem(getPem(element))); //$NON-NLS-1$
+			key.setActions(getActions(element, key));
+		}
+		return key;
+	}
+
+	private String getPem(Element element) {
+		Element pemElement = getFirstElement("pem", element);
+		if (pemElement != null) {
+			return getFirstElementText("pem", pemElement);
+		}
+		return null;
+	}
+
+	private String trimPem(String pem) throws IOException {
+		if (pem == null
+				|| pem.length() <= 0) {
+			return null;
+		}
+		StringBuffer sb = new StringBuffer();
+		String line = null;
+		BufferedReader reader = new BufferedReader(new StringReader(pem));
+		while ((line = reader.readLine()) != null) {
+			// We must trim off the white-space from the xml
+			// Complete white-space lines are to be ignored.
+			String trimmedLine = line.trim();
+			if (trimmedLine.length() > 0) {
+				sb.append(trimmedLine).append('\n');
+			}
+		}
+		return sb.toString();
+	}
+
+	@Override
+	protected Action<Key> unmarshallAction(Element element) throws DeltaCloudClientException {
+		Action<Key> keyAction = new Action<Key>();
+		new ActionUnmarshaller<Key>().unmarshall(element, keyAction);
+		return keyAction;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeysUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeysUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeysUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/KeysUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,41 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.Key;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * @author André Dietisheim
+ */
+public class KeysUnmarshaller extends AbstractDeltaCloudObjectsUnmarshaller<Key> {
+
+	public KeysUnmarshaller() {
+		super("keys", "key");
+	}
+
+	@Override
+	protected Key unmarshallChild(Node node) throws DeltaCloudClientException {
+		Key key = new KeyUnmarshaller().unmarshall((Element) node, new Key());
+		return key;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,41 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.Realm;
+import org.w3c.dom.Element;
+
+/**
+ * @author André Dietisheim
+ */
+public class RealmUnmarshaller extends AbstractDOMUnmarshaller<Realm> {
+
+	public RealmUnmarshaller() {
+		super("realm", Realm.class);
+	}
+
+	protected Realm doUnmarshall(Element element, Realm realm) throws Exception {
+		realm.setId(getAttributeText("id", element));
+		realm.setName(getFirstElementText("name", element));
+		realm.setLimit(getFirstElementText("limit", element));
+		realm.setState(getFirstElementText("state", element));
+		return realm;
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmsUnmarshaller.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmsUnmarshaller.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmsUnmarshaller.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/unmarshal/RealmsUnmarshaller.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,40 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.unmarshal;
+
+import org.apache.deltacloud.client.DeltaCloudClientException;
+import org.apache.deltacloud.client.Realm;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * @author André Dietisheim
+ */
+public class RealmsUnmarshaller extends AbstractDeltaCloudObjectsUnmarshaller<Realm> {
+
+	public RealmsUnmarshaller() {
+		super("realms", "realm");
+	}
+
+	@Override
+	protected Realm unmarshallChild(Node node) throws DeltaCloudClientException {
+		return new RealmUnmarshaller().unmarshall((Element) node, new Realm());
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/Assert.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/Assert.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/Assert.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/Assert.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,41 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.utils;
+
+/**
+ * Various assertion utility methods.
+ *
+ * @author André Dietisheim
+ */
+public class Assert {
+
+	public static void isValidArgument(boolean assertionResult) {
+		if (!assertionResult) {
+			throw new IllegalArgumentException();
+		}
+	}
+
+	public static void isTrue(boolean assertionResult) {
+		if (!assertionResult) {
+			throw new AssertionError();
+		}
+	}
+
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StreamUtils.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StreamUtils.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StreamUtils.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StreamUtils.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,52 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.utils;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+public class StreamUtils {
+
+	/**
+	 * Writes the content of the given input stream to the given output stream
+	 * and returns and input stream that may still be used to read from.
+	 *
+	 * @param outputStream the output stream to write to
+	 * @param inputStream the input stream to read from
+	 * @return a new, unread input stream
+	 * @throws IOException
+	 */
+	public static InputStream writeTo(InputStream inputStream, OutputStream outputStream) throws IOException {
+		List<Byte> data = new ArrayList<Byte>();
+		for (int character = -1; (character = inputStream.read()) != -1;) {
+			data.add((byte) character);
+			outputStream.write(character);
+		}
+		byte[] byteArray = new byte[data.size()];
+		for (int i = byteArray.length - 1; i >= 0; i--) {
+			byteArray[i] = data.get(i);
+		}
+		return new ByteArrayInputStream(byteArray);
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StringUtils.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StringUtils.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StringUtils.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/StringUtils.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,115 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.utils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author Andre Dietisheim
+ */
+public class StringUtils {
+
+	/**
+	 * Returns a formatted string for a collection of elements that get
+	 * formatted by a user supplied element formatter.
+	 *
+	 * @param elements
+	 *            the elements to be processed
+	 * @param elements
+	 *            the elements
+	 * @param elementFormatter
+	 *            the formatter to apply on each element to be processed
+	 * @return the formatted string
+	 */
+	public static <E> String getFormattedString(Collection<E> elements, IElementFormatter<E> elementFormatter) {
+		StringBuilder builder = new StringBuilder();
+		for (E element : elements) {
+			String formattedElement = elementFormatter.format(element);
+			if (formattedElement != null && formattedElement.length() > 0) {
+				builder.append(formattedElement);
+			}
+		}
+		if (builder.length() > 0) {
+			return builder.toString();
+		} else {
+			return "";
+		}
+	}
+
+	public interface IElementFormatter<E> {
+		public String format(E element);
+	}
+
+	/**
+	 * Returns a collection of formatted strings for the given collection of
+	 * elements and given formatter
+	 *
+	 * @param <E>
+	 *            the type of elements that shall be processed
+	 * @param elements
+	 *            the elements to be processed
+	 * @param elementFormatter
+	 *            the formatter to apply on each element to be processed
+	 * @return the formatted strings
+	 */
+	public static <E> Collection<String> getFormattedStrings(Collection<E> elements,
+			IElementFormatter<E> elementFormatter) {
+		List<String> strings = new ArrayList<String>();
+		for (E element : elements) {
+			String formattedElement = elementFormatter.format(element);
+			if (formattedElement != null && formattedElement.length() > 0) {
+				strings.add(formattedElement);
+			}
+		}
+		return strings;
+	}
+
+	public static String null2EmptyString(String stringValue) {
+		if (stringValue == null) {
+			return "";
+		}
+		return stringValue;
+	}
+
+	public static String emptyString2Null(String stringValue) {
+		if (stringValue != null
+				&& stringValue.length() == 0) {
+			return null;
+		}
+		return stringValue;
+	}
+
+	public static boolean isEmpty(String stringValue) {
+		return stringValue == null || stringValue.isEmpty();
+	}
+
+
+	public static String toString(InputStream inputStream) throws IOException {
+		StringBuilder builder = new StringBuilder();
+		for(int character = -1; (character = inputStream.read()) != -1; ) {
+			builder.append((char) character);
+		}
+		return builder.toString();
+	}
+}

Added: incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/UrlBuilder.java
URL: http://svn.apache.org/viewvc/incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/UrlBuilder.java?rev=1130080&view=auto
==============================================================================
--- incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/UrlBuilder.java (added)
+++ incubator/deltacloud/trunk/clients/java/org.apache.deltacloud.client/src/org/apache/deltacloud/client/utils/UrlBuilder.java Wed Jun  1 10:03:40 2011
@@ -0,0 +1,152 @@
+/*************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************************/
+
+package org.apache.deltacloud.client.utils;
+
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.Collection;
+
+/**
+ * A builder for an url. Currently no state checking is done, the user is
+ * responsible to build something that makes sense.
+ *
+ * @author André Dietisheim
+ */
+public class UrlBuilder {
+	private static final String URL_ENCODING = "UTF-8";
+	private static final String HOST_PROTOCOL_DELIMITER = ":";
+	private static final String HTTP_PROTOCOL_PREFIX = "http://";
+	private static final char PARAMETER_URL_DELIMITER = '?';
+	private static final char PARAMETER_DELIMITER = '&';
+	private static final char PARAMETER_NAME_VALUE_DELIMITER = '=';
+	private static final char PATH_SEPARATOR = '/';
+
+	private StringBuilder urlStringBuilder = new StringBuilder();
+
+	private boolean parametersAdded = false;
+
+	public UrlBuilder() {
+	}
+
+	public UrlBuilder(String baseUrl) {
+		urlStringBuilder.append(baseUrl);
+	}
+
+	public UrlBuilder(URL baseUrl) {
+		urlStringBuilder.append(baseUrl.toString());
+	}
+
+	/**
+	 * adds a host to .
+	 *
+	 * @param host
+	 *            the host
+	 *
+	 * @return the url builder
+	 */
+	public UrlBuilder host(String host) {
+		urlStringBuilder.append(HTTP_PROTOCOL_PREFIX);
+		urlStringBuilder.append(host);
+		return this;
+	}
+
+	/**
+	 * Adds a port.
+	 *
+	 * @param port
+	 *            the port
+	 *
+	 * @return the url builder
+	 */
+	public UrlBuilder port(Object port) {
+		urlStringBuilder.append(HOST_PROTOCOL_DELIMITER);
+		urlStringBuilder.append(port);
+		return this;
+	}
+
+	/**
+	 * adds a path to the url.
+	 *
+	 * @param path
+	 *            the path
+	 *
+	 * @return the url builder
+	 */
+	public UrlBuilder path(String path) {
+		urlStringBuilder.append(PATH_SEPARATOR);
+		urlStringBuilder.append(path);
+		return this;
+	}
+
+	public UrlBuilder path(Collection<String> paths) {
+		for (String path : paths) {
+			path(path);
+		}
+		return this;
+	}
+
+	public UrlBuilder parameter(String name, String value) {
+		if (value != null) {
+			appendParameterDelimiter();
+			urlStringBuilder.append(name).append(PARAMETER_NAME_VALUE_DELIMITER).append(urlEncode(value));
+		}
+		return this;
+	}
+
+	private void appendParameterDelimiter() {
+		if (!parametersAdded) {
+			urlStringBuilder.append(PARAMETER_URL_DELIMITER);
+			parametersAdded = true;
+		} else {
+			urlStringBuilder.append(PARAMETER_DELIMITER);
+		}
+	}
+
+	public UrlBuilder parameters(String... parameters) {
+		for (String parameter : parameters) {
+			parameter(parameter);
+		}
+		return this;
+	}
+
+	public UrlBuilder parameter(String parameter) {
+		appendParameterDelimiter();
+		urlStringBuilder.append(urlEncode(parameter));
+		return this;
+	}
+
+	private String urlEncode(String value) {
+		try {
+			return URLEncoder.encode(value, URL_ENCODING);
+		} catch (UnsupportedEncodingException e) {
+			throw new RuntimeException(e);
+		}
+	}
+
+	public URL toUrl() throws MalformedURLException {
+		return new URL(urlStringBuilder.toString());
+	}
+
+	public String toString() {
+		return urlStringBuilder.toString();
+	}
+}