KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jsr181 > Jsr181Endpoint


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.jsr181;
18
19 import java.io.ByteArrayInputStream JavaDoc;
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.lang.reflect.Method JavaDoc;
23 import java.net.URL JavaDoc;
24 import java.security.InvalidParameterException JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Map JavaDoc;
27
28 import javax.jbi.component.ComponentContext;
29 import javax.jbi.messaging.MessageExchange.Role;
30 import javax.jbi.servicedesc.ServiceEndpoint;
31 import javax.wsdl.Binding;
32 import javax.wsdl.Definition;
33 import javax.wsdl.Port;
34 import javax.wsdl.PortType;
35 import javax.wsdl.WSDLException;
36 import javax.wsdl.factory.WSDLFactory;
37 import javax.wsdl.xml.WSDLReader;
38 import javax.xml.namespace.QName JavaDoc;
39 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
40 import javax.xml.parsers.ParserConfigurationException JavaDoc;
41
42 import org.apache.servicemix.common.Endpoint;
43 import org.apache.servicemix.common.ExchangeProcessor;
44 import org.apache.servicemix.common.xbean.XBeanServiceUnit;
45 import org.apache.servicemix.jsr181.xfire.JbiFaultSerializer;
46 import org.apache.servicemix.jsr181.xfire.ServiceFactoryHelper;
47 import org.codehaus.xfire.XFire;
48 import org.codehaus.xfire.service.Service;
49 import org.codehaus.xfire.service.binding.ObjectServiceFactory;
50 import org.codehaus.xfire.service.invoker.BeanInvoker;
51 import org.codehaus.xfire.soap.SoapConstants;
52 import org.springframework.core.io.Resource;
53 import org.w3c.dom.Document JavaDoc;
54 import org.xml.sax.SAXException JavaDoc;
55
56 import com.ibm.wsdl.Constants;
57
58 /**
59  *
60  * @author gnodet
61  * @version $Revision: 441037 $
62  * @org.apache.xbean.XBean element="endpoint"
63  * description="A jsr181 endpoint"
64  *
65  */

66 public class Jsr181Endpoint extends Endpoint {
67
68     protected Object JavaDoc pojo;
69     protected String JavaDoc pojoClass;
70     protected String JavaDoc annotations;
71     protected String JavaDoc typeMapping;
72     protected String JavaDoc serviceInterface;
73     protected String JavaDoc style = "wrapped";
74     
75     protected ServiceEndpoint activated;
76     protected Service xfireService;
77     protected ExchangeProcessor processor;
78     protected Resource wsdlResource;
79     protected boolean mtomEnabled = false;
80     
81     public Jsr181Endpoint() {
82         processor = new Jsr181ExchangeProcessor(this);
83     }
84     
85     /**
86      * @return the style
87      */

88     public String JavaDoc getStyle() {
89         return style;
90     }
91
92     /**
93      * Service style: can be <code>rpc</code>, <code>document</code>,
94      * <code>wrapped</code> or <code>message</code>.
95      * Default to <code>wrapped</code>
96      * @param style the style to set
97      */

98     public void setStyle(String JavaDoc style) {
99         this.style = style;
100     }
101
102     /**
103      * @return the wsdlResource
104      */

105     public Resource getWsdlResource() {
106         return wsdlResource;
107     }
108
109     /**
110      * @param wsdlResource the wsdlResource to set
111      */

112     public void setWsdlResource(Resource wsdlResource) {
113         this.wsdlResource = wsdlResource;
114     }
115
116     /**
117      * @return Returns the pojo.
118      */

119     public Object JavaDoc getPojo() {
120         return pojo;
121     }
122
123     /**
124      * @param pojo The pojo to set.
125      */

126     public void setPojo(Object JavaDoc pojo) {
127         this.pojo = pojo;
128     }
129
130     /**
131      * @return the mtomEnabled
132      */

133     public boolean isMtomEnabled() {
134         return mtomEnabled;
135     }
136
137     /**
138      * @param mtomEnabled the mtomEnabled to set
139      */

140     public void setMtomEnabled(boolean mtomEnabled) {
141         this.mtomEnabled = mtomEnabled;
142     }
143
144     /**
145      * @return Returns the xfireService.
146      */

147     public Service getXFireService() {
148         return xfireService;
149     }
150
151     /* (non-Javadoc)
152      * @see org.servicemix.common.Endpoint#getRole()
153      * @org.apache.xbean.XBean hide="true"
154      */

155     public Role getRole() {
156         return Role.PROVIDER;
157     }
158
159     /* (non-Javadoc)
160      * @see org.servicemix.common.Endpoint#activate()
161      */

162     public void activate() throws Exception JavaDoc {
163         logger = this.serviceUnit.getComponent().getLogger();
164         ComponentContext ctx = this.serviceUnit.getComponent().getComponentContext();
165         activated = ctx.activateEndpoint(service, endpoint);
166         injectContext(new EndpointComponentContext(ctx));
167         processor.start();
168     }
169
170     /* (non-Javadoc)
171      * @see org.servicemix.common.Endpoint#deactivate()
172      */

173     public void deactivate() throws Exception JavaDoc {
174         ServiceEndpoint ep = activated;
175         activated = null;
176         processor.stop();
177         ComponentContext ctx = this.serviceUnit.getComponent().getComponentContext();
178         ctx.deactivateEndpoint(ep);
179         injectContext(null);
180     }
181
182     protected void injectContext(ComponentContext context) {
183         try {
184             Method JavaDoc mth = pojo.getClass().getMethod("setContext", new Class JavaDoc[] { ComponentContext.class });
185             mth.invoke(pojo, new Object JavaDoc[] { context });
186         } catch (Exception JavaDoc e) {
187             logger.debug("Unable to inject ComponentContext: " + e.getMessage());
188         }
189     }
190
191     public void registerService() throws Exception JavaDoc {
192         if (pojo == null) {
193             ClassLoader JavaDoc classLoader = ((XBeanServiceUnit) getServiceUnit()).getConfigurationClassLoader();
194             Class JavaDoc cl = Class.forName(pojoClass, true, classLoader);
195             pojo = cl.newInstance();
196         }
197         // Create factory
198
XFire xfire = getXFire();
199         ObjectServiceFactory factory = ServiceFactoryHelper.findServiceFactory(xfire, pojo.getClass(), annotations, typeMapping);
200         Class JavaDoc serviceClass = pojo.getClass();
201         if (serviceInterface != null) {
202             serviceClass = Class.forName(serviceInterface);
203         }
204
205         this.definition = loadDefinition();
206         if (definition != null) {
207             if (definition.getServices().size() != 1) {
208                 throw new InvalidParameterException JavaDoc("The deployed wsdl defines more than one service");
209             }
210             javax.wsdl.Service wsdlSvc = (javax.wsdl.Service) definition.getServices().values().iterator().next();
211             if (service == null) {
212                 service = wsdlSvc.getQName();
213             } else if (!service.equals(wsdlSvc.getQName())) {
214                 throw new InvalidParameterException JavaDoc("The name of the Service defined by the deployed wsdl does not match the service name of the jbi endpoint");
215             }
216             if (wsdlSvc.getPorts().size() != 1) {
217                 throw new InvalidParameterException JavaDoc("The Service defined in the deployed wsdl must define exactly one Port");
218             }
219             Port wsdlPort = (Port) wsdlSvc.getPorts().values().iterator().next();
220             if (endpoint == null) {
221                 endpoint = wsdlPort.getName();
222             } else if (!endpoint.equals(wsdlPort.getName())) {
223                 throw new InvalidParameterException JavaDoc("The name of the Port defined by the deployed wsdl does not match the endpoint name of the jbi endpoint");
224             }
225             Binding wsdlBinding = wsdlPort.getBinding();
226             if (wsdlBinding == null) {
227                 throw new InvalidParameterException JavaDoc("The Port defined in the deployed wsdl does not have any binding");
228             }
229             PortType wsdlPortType = wsdlBinding.getPortType();
230             if (wsdlPortType == null) {
231                 throw new InvalidParameterException JavaDoc("The Binding defined in the deployed wsdl does not have reference a PortType");
232             }
233             if (interfaceName == null) {
234                 interfaceName = wsdlPortType.getQName();
235             } else if (!interfaceName.equals(wsdlPortType.getQName())) {
236                 throw new InvalidParameterException JavaDoc("The name of the PortType defined by the deployed wsdl does not match the interface name of the jbi endpoint");
237             }
238             // Create the DOM document
239
description = WSDLFactory.newInstance().newWSDLWriter().getDocument(definition);
240         }
241         
242         String JavaDoc svcLocalName = (service != null) ? service.getLocalPart() : null;
243         String JavaDoc svcNamespace;
244         if (interfaceName != null) {
245             svcNamespace = interfaceName.getNamespaceURI();
246         } else if (service != null) {
247             svcNamespace = service.getNamespaceURI();
248         } else {
249             svcNamespace = null;
250         }
251         Map JavaDoc props = new HashMap JavaDoc();
252         props.put(ObjectServiceFactory.PORT_TYPE, interfaceName);
253         if (style != null) {
254             props.put(ObjectServiceFactory.STYLE, style);
255         }
256         props.put(ObjectServiceFactory.USE, SoapConstants.USE_LITERAL);
257         if (serviceInterface != null) {
258             props.put("annotations.allow.interface", "true");
259         }
260         xfireService = factory.create(serviceClass, svcLocalName, svcNamespace, props);
261         xfireService.setInvoker(new BeanInvoker(getPojo()));
262         xfireService.setFaultSerializer(new JbiFaultSerializer(getConfiguration()));
263         xfireService.setProperty(SoapConstants.MTOM_ENABLED, Boolean.toString(mtomEnabled));
264         xfire.getServiceRegistry().register(xfireService);
265         
266         // If the wsdl has not been provided,
267
// generate one
268
if (this.description == null) {
269             this.description = generateWsdl();
270         
271             // If the both interfaceName and serviceName are provided with non matching namespaces,
272
// the generated wsdl is bad. We have to keep only the port type definition.
273
if (this.service != null && interfaceName != null &&
274                 !this.service.getNamespaceURI().equals(interfaceName.getNamespaceURI())) {
275                 // Parse the WSDL
276
WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
277                 reader.setFeature(Constants.FEATURE_VERBOSE, false);
278                 definition = reader.readWSDL(null, description);
279                 // Get the service and port definition
280
javax.wsdl.Service svc = definition.getService(new QName JavaDoc(this.interfaceName.getNamespaceURI(), this.service.getLocalPart()));
281                 Port port = svc != null && svc.getPorts().size() == 1 ? (Port) svc.getPorts().values().iterator().next() : null;
282                 if (port != null) {
283                     // If the endpoint name has not been defined, retrieve it now
284
if (endpoint == null) {
285                         endpoint = port.getName();
286                     }
287                     // Now, remove binding and service infos and change target namespace
288
definition.removeBinding(port.getBinding().getQName());
289                     definition.removeService(svc.getQName());
290                     description = WSDLFactory.newInstance().newWSDLWriter().getDocument(definition);
291                 }
292             }
293             // Write WSDL
294
if (logger.isTraceEnabled()) {
295                 ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
296                 WSDLFactory.newInstance().newWSDLWriter().writeWSDL(definition, baos);
297                 logger.trace(baos.toString());
298             }
299         
300             // Check service name and endpoint name
301
QName JavaDoc serviceName = xfireService.getName();
302             QName JavaDoc interfName = xfireService.getServiceInfo().getPortType();
303             String JavaDoc endpointName = null;
304             if (service == null) {
305                 service = serviceName;
306             } else if (!service.equals(serviceName)) {
307                 logger.warn("The service name defined in the wsdl (" + serviceName +
308                             ") does not match the service name defined in the endpoint spec (" + service +
309                             "). WSDL description may be unusable.");
310             }
311             if (interfaceName == null) {
312                 interfaceName = interfName;
313             } else if (!interfaceName.equals(interfName)) {
314                 logger.warn("The interface name defined in the wsdl (" + interfName +
315                         ") does not match the service name defined in the endpoint spec (" + interfaceName +
316                         "). WSDL description may be unusable.");
317             }
318             definition = WSDLFactory.newInstance().newWSDLReader().readWSDL(null, description);
319             javax.wsdl.Service svc = definition.getService(serviceName);
320             if (svc != null) {
321                 if (svc.getPorts().values().size() == 1) {
322                     Port port = (Port) svc.getPorts().values().iterator().next();
323                     // Check if this is the same as defined in endpoint spec
324
endpointName = port.getName();
325                     if (endpoint == null) {
326                         endpoint = endpointName;
327                     } else if (!endpoint.equals(endpointName)) {
328                         // Override generated WSDL
329
port.setName(endpoint);
330                         description = WSDLFactory.newInstance().newWSDLWriter().getDocument(definition);
331                     }
332                 }
333             }
334             if (endpoint == null) {
335                 throw new IllegalArgumentException JavaDoc("endpoint name should be provided");
336             }
337         }
338     }
339     
340     protected Definition loadDefinition() throws IOException JavaDoc, WSDLException {
341         if (wsdlResource != null) {
342             URL JavaDoc resource = wsdlResource.getURL();
343             WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
344             reader.setFeature(Constants.FEATURE_VERBOSE, false);
345             return reader.readWSDL(null, resource.toString());
346         }
347         return null;
348     }
349     
350     protected Document JavaDoc generateWsdl() throws SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc {
351         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
352         getXFire().generateWSDL(xfireService.getSimpleName(), baos);
353         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
354         factory.setNamespaceAware(true);
355         Document JavaDoc doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream JavaDoc(baos.toByteArray()));
356         return doc;
357     }
358     
359     public XFire getXFire() {
360         Jsr181LifeCycle jsr181LifeCycle = (Jsr181LifeCycle) this.serviceUnit.getComponent().getLifeCycle();
361         XFire xfire = jsr181LifeCycle.getXFire();
362         return xfire;
363     }
364     
365     public Jsr181ConfigurationMBean getConfiguration() {
366         Jsr181LifeCycle jsr181LifeCycle = (Jsr181LifeCycle) this.serviceUnit.getComponent().getLifeCycle();
367         Jsr181ConfigurationMBean configuration = jsr181LifeCycle.getConfiguration();
368         return configuration;
369     }
370     
371     public String JavaDoc getPojoClass() {
372         return pojoClass;
373     }
374
375     public void setPojoClass(String JavaDoc pojoClass) {
376         this.pojoClass = pojoClass;
377     }
378
379     public String JavaDoc getAnnotations() {
380         return annotations;
381     }
382
383     public void setAnnotations(String JavaDoc annotations) {
384         this.annotations = annotations;
385     }
386
387     public String JavaDoc getTypeMapping() {
388         return typeMapping;
389     }
390
391     public void setTypeMapping(String JavaDoc typeMapping) {
392         this.typeMapping = typeMapping;
393     }
394
395     public ExchangeProcessor getProcessor() {
396         return processor;
397     }
398
399     public String JavaDoc getServiceInterface() {
400         return serviceInterface;
401     }
402
403     public void setServiceInterface(String JavaDoc serviceInterface) {
404         this.serviceInterface = serviceInterface;
405     }
406
407 }
408
Popular Tags