View Javadoc

1   /*******************************************************************************
2    *  Imixs Workflow 
3    *  Copyright (C) 2001, 2011 Imixs Software Solutions GmbH,  
4    *  http://www.imixs.com
5    *  
6    *  This program is free software; you can redistribute it and/or 
7    *  modify it under the terms of the GNU General Public License 
8    *  as published by the Free Software Foundation; either version 2 
9    *  of the License, or (at your option) any later version.
10   *  
11   *  This program is distributed in the hope that it will be useful, 
12   *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
14   *  General Public License for more details.
15   *  
16   *  You can receive a copy of the GNU General Public
17   *  License at http://www.gnu.org/licenses/gpl.html
18   *  
19   *  Project: 
20   *  	http://www.imixs.org
21   *  	http://java.net/projects/imixs-workflow
22   *  
23   *  Contributors:  
24   *  	Imixs Software Solutions GmbH - initial API and implementation
25   *  	Ralph Soika - Software Developer
26   *******************************************************************************/
27  package org.imixs.workflow.services.rest;
28  
29  import java.io.BufferedWriter;
30  import java.io.OutputStreamWriter;
31  import java.io.PrintWriter;
32  import java.io.StringWriter;
33  import java.net.HttpURLConnection;
34  import java.net.URL;
35  
36  import javax.xml.bind.JAXBContext;
37  import javax.xml.bind.Marshaller;
38  
39  import org.imixs.workflow.util.Base64;
40  import org.imixs.workflow.xml.EntityCollection;
41  import org.imixs.workflow.xml.XMLItemCollection;
42  
43  /**
44   * This ServiceClient is a WebService REST Client which encapsulate the
45   * communication with a REST web serice based on the Imixs Workflow REST API.
46   * The Implementation is based on the JAXB API.
47   * 
48   * The ServiceClient supports methods for posting EntityCollections and
49   * XMLItemCollections.
50   * 
51   * The post method expects the rest service URI and a Dataobject based ont the
52   * Imixs Workflow XML API
53   * 
54   * @see org.imixs.workflow.jee.rest
55   * @author Ralph Soika
56   * 
57   */
58  public class RestClient {
59  
60  	// private String NAME_SPACE = "http://imixs.org/workflow/services";
61  
62  	private String serviceEndpoint;
63  
64  	private String sUser = null;
65  
66  	private String sPassword = null;
67  
68  	private String encoding = "UTF-8";
69  
70  	private int iLastHTTPResult = 0;
71  
72  	// Sets credentials
73  	public void setCredentials(String auser, String apw) {
74  		sUser = auser;
75  		sPassword = apw;
76  	}
77  
78  	public void setEncoding(String aEncoding) {
79  		encoding = aEncoding;
80  	}
81  
82  	/**
83  	 * This method posts an XMLItemCollection in the Imixs XML Format to a Rest
84  	 * Service URI Endpoint.
85  	 * 
86  	 * 
87  	 * @param uri
88  	 *            - Rest Endpoint RUI
89  	 * @param entityCol
90  	 *            - an Entity Collection
91  	 * @return HTTPResult
92  	 */
93  	public int postEntity(String uri, XMLItemCollection aItemCol)
94  			throws Exception {
95  		PrintWriter printWriter = null;
96  
97  		HttpURLConnection urlConnection = null;
98  		try {
99  			serviceEndpoint = uri;
100 			iLastHTTPResult = 500;
101 
102 			urlConnection = (HttpURLConnection) new URL(serviceEndpoint)
103 					.openConnection();
104 			urlConnection.setRequestMethod("POST");
105 			urlConnection.setDoOutput(true);
106 			urlConnection.setDoInput(true);
107 			urlConnection.setAllowUserInteraction(false);
108 
109 			// Authorization
110 			if (sUser != null) {
111 				urlConnection.setRequestProperty("Authorization", "Basic "
112 						+ this.getAccessByUser());
113 			}
114 			/** * HEADER ** */
115 			urlConnection.setRequestProperty("Content-Type",
116 					"application/xml; charset=" + encoding);
117 
118 			StringWriter writer = new StringWriter();
119 
120 			JAXBContext context = JAXBContext
121 					.newInstance(XMLItemCollection.class);
122 			Marshaller m = context.createMarshaller();
123 			m.marshal(aItemCol, writer);
124 
125 			// System.out.println(writer.toString());
126 
127 			// compute length
128 			urlConnection.setRequestProperty("Content-Length", ""
129 					+ Integer.valueOf(writer.toString().getBytes().length));
130 
131 			printWriter = new PrintWriter(new BufferedWriter(
132 					new OutputStreamWriter(urlConnection.getOutputStream(),
133 							encoding)));
134 
135 			printWriter.write(writer.toString());
136 			printWriter.close();
137 			String sHTTPResponse = urlConnection.getHeaderField(0);
138 			try {
139 				iLastHTTPResult = Integer.parseInt(sHTTPResponse.substring(9,
140 						12));
141 			} catch (Exception eNumber) {
142 				// eNumber.printStackTrace();
143 				iLastHTTPResult = 500;
144 			}
145 		} catch (Exception ioe) {
146 			// ioe.printStackTrace();
147 			throw ioe;
148 		} finally {
149 			// Release current connection
150 			if (printWriter != null)
151 				printWriter.close();
152 		}
153 
154 		return iLastHTTPResult;
155 	}
156 
157 	/**
158 	 * This method posts an Entitycollection in the Imixs XML Format to a Rest
159 	 * Service URI Endpoint.
160 	 * 
161 	 * 
162 	 * @param uri
163 	 *            - Rest Endpoint RUI
164 	 * @param entityCol
165 	 *            - an Entity Collection
166 	 * @return HTTPResult
167 	 */
168 	public int postCollection(String uri, EntityCollection aEntityCol)
169 			throws Exception {
170 		PrintWriter printWriter = null;
171 
172 		HttpURLConnection urlConnection = null;
173 		try {
174 			serviceEndpoint = uri;
175 			iLastHTTPResult = 500;
176 
177 			urlConnection = (HttpURLConnection) new URL(serviceEndpoint)
178 					.openConnection();
179 			urlConnection.setRequestMethod("POST");
180 			urlConnection.setDoOutput(true);
181 			urlConnection.setDoInput(true);
182 			urlConnection.setAllowUserInteraction(false);
183 
184 			// Authorization
185 			if (sUser != null) {
186 				urlConnection.setRequestProperty("Authorization", "Basic "
187 						+ this.getAccessByUser());
188 			}
189 
190 			/** * HEADER ** */
191 			urlConnection.setRequestProperty("Content-Type",
192 					"application/xml; charset=" + encoding);
193 
194 			StringWriter writer = new StringWriter();
195 
196 			JAXBContext context = JAXBContext
197 					.newInstance(EntityCollection.class);
198 			Marshaller m = context.createMarshaller();
199 			m.marshal(aEntityCol, writer);
200 
201 			// System.out.println(writer.toString());
202 
203 			// compute length
204 			urlConnection.setRequestProperty("Content-Length", ""
205 					+ Integer.valueOf(writer.toString().getBytes().length));
206 
207 			printWriter = new PrintWriter(new BufferedWriter(
208 					new OutputStreamWriter(urlConnection.getOutputStream(),
209 							encoding)));
210 
211 			printWriter.write(writer.toString());
212 			printWriter.close();
213 			String sHTTPResponse = urlConnection.getHeaderField(0);
214 			try {
215 				iLastHTTPResult = Integer.parseInt(sHTTPResponse.substring(9,
216 						12));
217 			} catch (Exception eNumber) {
218 				// eNumber.printStackTrace();
219 				iLastHTTPResult = 500;
220 			}
221 
222 			/*
223 			 * InputStream is = urlConnection.getInputStream(); // create the
224 			 * parser XMLStreamReader parser = XMLInputFactory.newInstance()
225 			 * .createXMLStreamReader(is); // create the builder //
226 			 * StAXOMBuilder builder = new StAXOMBuilder(parser); // now we can
227 			 * do something with the response... // get the root element (in
228 			 * this case the envelope) // OMElement responseElement =
229 			 * builder.getDocumentElement(); // ...
230 			 */
231 		} catch (Exception ioe) {
232 			// ioe.printStackTrace();
233 			throw ioe;
234 		} finally {
235 			// Release current connection
236 			if (printWriter != null)
237 				printWriter.close();
238 		}
239 
240 		return iLastHTTPResult;
241 	}
242 
243 	/*
244 	 * private Object createXMLTree(EntityCollection envList) {
245 	 * 
246 	 * QName opName = new QName(NAME_SPACE, "entityCollection"); // create
247 	 * Parameter for Operation
248 	 * 
249 	 * Object[] opArgs = new Object[] { envList }; // create OMElement for
250 	 * Request
251 	 * 
252 	 * // OMElement requestData = DataObjectUtil.getOMElement(opName, opArgs, //
253 	 * new String[] { "entitylist" }); // return requestData;
254 	 * 
255 	 * return null; }
256 	 */
257 
258 	/**
259 	 * Diese Methode setzt für den Zugriff auf eine URL eine Definierte UserID +
260 	 * Passwort
261 	 */
262 	private String getAccessByUser() {
263 		String sURLAccess = "";
264 		// UserID:Passwort
265 		String sUserCode = sUser + ":" + sPassword;
266 		// String convertieren
267 		// sURLAccess = Base64.encodeBase64(sUserCode.getBytes()).toString();
268 		char[] authcode = Base64.encode(sUserCode.getBytes());
269 
270 		sURLAccess = String.valueOf(authcode);
271 		return sURLAccess;
272 	}
273 
274 }