KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > components > rest > RestServiceWrapper


1 /*
2  * $Id: RestServiceWrapper.java 3798 2006-11-04 04:07:14Z aperepel $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.components.rest;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15 import org.mule.util.properties.PropertyExtractor;
16 import org.mule.util.properties.MessagePropertyExtractor;
17 import org.mule.config.i18n.Message;
18 import org.mule.config.i18n.Messages;
19 import org.mule.impl.MuleMessage;
20 import org.mule.impl.endpoint.MuleEndpointURI;
21 import org.mule.providers.NullPayload;
22 import org.mule.routing.filters.MessagePropertyFilter;
23 import org.mule.routing.filters.RegExFilter;
24 import org.mule.umo.UMOEventContext;
25 import org.mule.umo.UMOFilter;
26 import org.mule.umo.UMOMessage;
27 import org.mule.umo.endpoint.UMOEndpointURI;
28 import org.mule.umo.lifecycle.Callable;
29 import org.mule.umo.lifecycle.Initialisable;
30 import org.mule.umo.lifecycle.InitialisationException;
31 import org.mule.umo.lifecycle.RecoverableException;
32
33 import java.net.MalformedURLException JavaDoc;
34 import java.net.URL JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.Map JavaDoc;
38
39 /**
40  * This component can used to proxy REST style services as local Mule Components. It
41  * can be configured with a service URL plus a number of properties that allow you to
42  * configure the parameters and error conditions on the service.
43  *
44  * @author <a HREF="mailto:ross.mason@symphonysoft.com">Ross Mason</a>
45  * @version $Revision: 3798 $
46  */

47 public class RestServiceWrapper implements Callable, Initialisable
48 {
49     public static final String JavaDoc REST_SERVICE_URL = "rest.service.url";
50
51     /**
52      * logger used by this class
53      */

54     protected transient Log logger = LogFactory.getLog(getClass());
55
56     private String JavaDoc serviceUrl;
57     private boolean urlFromMessage = false;
58     private Map JavaDoc reqiredParams = new HashMap JavaDoc();
59     private Map JavaDoc optionalParams = new HashMap JavaDoc();
60     private String JavaDoc httpMethod = "GET";
61     private String JavaDoc payloadParameterName;
62     private UMOFilter errorFilter;
63     private String JavaDoc errorExpression;
64
65     private PropertyExtractor propertyExtractor = new MessagePropertyExtractor();
66
67     public String JavaDoc getServiceUrl()
68     {
69         return serviceUrl;
70     }
71
72     public void setServiceUrl(String JavaDoc serviceUrl)
73     {
74         this.serviceUrl = serviceUrl;
75     }
76
77     public boolean isUrlFromMessage()
78     {
79         return urlFromMessage;
80     }
81
82     public void setUrlFromMessage(boolean urlFromMessage)
83     {
84         this.urlFromMessage = urlFromMessage;
85     }
86
87     public Map JavaDoc getReqiredParams()
88     {
89         return reqiredParams;
90     }
91
92     public void setReqiredParams(Map JavaDoc reqiredParams)
93     {
94         this.reqiredParams = reqiredParams;
95     }
96
97     public Map JavaDoc getOptionalParams()
98     {
99         return optionalParams;
100     }
101
102     public void setOptionalParams(Map JavaDoc optionalParams)
103     {
104         this.optionalParams = optionalParams;
105     }
106
107     public String JavaDoc getHttpMethod()
108     {
109         return httpMethod;
110     }
111
112     public void setHttpMethod(String JavaDoc httpMethod)
113     {
114         this.httpMethod = httpMethod;
115     }
116
117     public String JavaDoc getPayloadParameterName()
118     {
119         return payloadParameterName;
120     }
121
122     public void setPayloadParameterName(String JavaDoc payloadParameterName)
123     {
124         this.payloadParameterName = payloadParameterName;
125     }
126
127     public UMOFilter getErrorFilter()
128     {
129         return errorFilter;
130     }
131
132     public void setErrorFilter(UMOFilter errorFilter)
133     {
134         this.errorFilter = errorFilter;
135     }
136
137     public String JavaDoc getErrorExpression()
138     {
139         return errorExpression;
140     }
141
142     public void setErrorExpression(String JavaDoc errorExpression)
143     {
144         this.errorExpression = errorExpression;
145     }
146
147     public void initialise() throws InitialisationException, RecoverableException
148     {
149         if (serviceUrl == null && !urlFromMessage)
150         {
151             throw new InitialisationException(new Message(Messages.X_IS_NULL, "serviceUrl"), this);
152         }
153         else if (serviceUrl != null)
154         {
155             try
156             {
157                 new URL JavaDoc(serviceUrl);
158             }
159             catch (MalformedURLException JavaDoc e)
160             {
161                 throw new InitialisationException(e, this);
162             }
163         }
164
165         if (errorFilter == null)
166         {
167             if (errorExpression == null)
168             {
169                 // We'll set a default filter that checks the return code
170
errorFilter = new MessagePropertyFilter("http.status!=200");
171                 logger.info("Setting default error filter to MessagePropertyFilter('http.status!=200')");
172             }
173             else
174             {
175                 errorFilter = new RegExFilter(errorExpression);
176             }
177         }
178     }
179
180     public Object JavaDoc onCall(UMOEventContext eventContext) throws Exception JavaDoc
181     {
182         String JavaDoc tempUrl;
183         Object JavaDoc request = eventContext.getTransformedMessage();
184         Object JavaDoc requestBody = request;
185         if (urlFromMessage)
186         {
187             tempUrl = eventContext.getMessage().getStringProperty(REST_SERVICE_URL, null);
188             if (tempUrl == null)
189             {
190                 throw new IllegalArgumentException JavaDoc(new Message(Messages.X_PROPERTY_IS_NOT_SET_ON_EVENT,
191                     REST_SERVICE_URL).toString());
192             }
193         }
194         else
195         {
196             tempUrl = serviceUrl;
197         }
198         StringBuffer JavaDoc urlBuffer = new StringBuffer JavaDoc(tempUrl);
199
200         if (payloadParameterName != null)
201         {
202             requestBody = new NullPayload();
203         }
204         else if (request instanceof Map JavaDoc)
205         {
206             requestBody = new NullPayload();
207         }
208
209         setRESTParams(urlBuffer, eventContext.getMessage(), request, reqiredParams, false);
210         setRESTParams(urlBuffer, eventContext.getMessage(), request, optionalParams, true);
211
212         tempUrl = urlBuffer.toString();
213         logger.info("Invoking REST service: " + tempUrl);
214
215         UMOEndpointURI endpointURI = new MuleEndpointURI(tempUrl);
216         eventContext.getMessage().setProperty("http.method", httpMethod);
217
218         UMOMessage result = eventContext.sendEvent(new MuleMessage(requestBody, eventContext.getMessage()),
219             endpointURI);
220
221         if (isErrorPayload(result))
222         {
223             handleException(new RestServiceException(new Message(Messages.FAILED_TO_INVOKE_REST_SERVICE_X,
224                 tempUrl), result), result);
225         }
226         return result;
227     }
228
229     private void setRESTParams(StringBuffer JavaDoc url, UMOMessage msg, Object JavaDoc body, Map JavaDoc args, boolean optional)
230     {
231         char sep;
232
233         if (url.indexOf("?") > -1)
234         {
235             sep = '&';
236         }
237         else
238         {
239             sep = '?';
240         }
241
242         for (Iterator JavaDoc iterator = args.entrySet().iterator(); iterator.hasNext();)
243         {
244             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)iterator.next();
245             String JavaDoc name = (String JavaDoc)entry.getKey();
246             String JavaDoc exp = (String JavaDoc)entry.getValue();
247             Object JavaDoc value = propertyExtractor.getProperty(exp, msg);
248
249             if (value == null && !optional)
250             {
251                 throw new IllegalArgumentException JavaDoc(
252                     new Message(Messages.X_PROPERTY_IS_NOT_SET_ON_EVENT, exp).toString());
253             }
254
255             url.append(sep);
256             sep = '&';
257             url.append(name).append('=').append(value);
258         }
259
260         if (!optional && payloadParameterName != null)
261         {
262             url.append(sep).append(payloadParameterName).append('=').append(body.toString());
263         }
264     }
265
266     protected boolean isErrorPayload(UMOMessage message)
267     {
268         if (errorFilter != null)
269         {
270             return errorFilter.accept(message);
271         }
272         return false;
273     }
274
275     protected void handleException(RestServiceException e, UMOMessage result) throws Exception JavaDoc
276     {
277         throw e;
278     }
279 }
280
Popular Tags