View Javadoc

1   /****************************************************************************
2    * Copyright (c) 2005, 2006, 2007, 2008, 2009 Imola Informatica.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the LGPL License v2.1
5    * which accompanies this distribution, and is available at
6    * http://www.gnu.org/licenses/lgpl.html
7    ****************************************************************************/
8   package it.imolinfo.jbi4corba.webservice.runtime;
9   
10  import it.imolinfo.jbi4corba.Logger;
11  import it.imolinfo.jbi4corba.LoggerFactory;
12  import it.imolinfo.jbi4corba.exception.Jbi4CorbaException;
13  import it.imolinfo.jbi4corba.exception.Jbi4CorbaRuntimeException;
14  import it.imolinfo.jbi4corba.exception.ServiceCreationException;
15  import it.imolinfo.jbi4corba.jbi.Messages;
16  import it.imolinfo.jbi4corba.jbi.component.runtime.RuntimeContext;
17  import it.imolinfo.jbi4corba.jbi.cxf.CXFUtils;
18  import it.imolinfo.jbi4corba.jbi.cxf.Jbi4CorbaConsumerExceptionInterceptor;
19  import it.imolinfo.jbi4corba.jbi.endpoint.ConsumerEndpoint;
20  import it.imolinfo.jbi4corba.jbi.processor.JbiMessage;
21  import it.imolinfo.jbi4corba.jbi.processor.MessageDenormalizer;
22  import it.imolinfo.jbi4corba.jbi.processor.MessageNormalizer;
23  import it.imolinfo.jbi4corba.jbi.processor.transform.SourceTransformer;
24  import it.imolinfo.jbi4corba.jbi.processor.transform.StringSource;
25  import it.imolinfo.jbi4corba.webservice.descriptor.ConsumerServiceDescriptor;
26  import it.imolinfo.jbi4corba.webservice.generator.MethodSignature;
27  import it.imolinfo.jbi4corba.webservice.generator.Param;
28  import it.imolinfo.jbi4corba.webservice.generator.WsdlInformation;
29  
30  import java.io.ByteArrayInputStream;
31  import java.io.ByteArrayOutputStream;
32  import java.io.IOException;
33  import java.io.InputStream;
34  import java.io.OutputStream;
35  import java.lang.reflect.InvocationHandler;
36  import java.lang.reflect.Method;
37  import java.net.URI;
38  import java.net.URLClassLoader;
39  import java.util.ArrayList;
40  import java.util.Arrays;
41  import java.util.Collection;
42  import java.util.HashMap;
43  import java.util.Iterator;
44  import java.util.List;
45  import java.util.Map;
46  import java.util.ResourceBundle;
47  
48  import javax.jbi.component.ComponentContext;
49  import javax.jbi.messaging.DeliveryChannel;
50  import javax.jbi.messaging.ExchangeStatus;
51  import javax.jbi.messaging.InOnly;
52  import javax.jbi.messaging.InOut;
53  import javax.jbi.messaging.MessageExchangeFactory;
54  import javax.jbi.messaging.MessagingException;
55  import javax.jbi.messaging.NormalizedMessage;
56  import javax.jbi.servicedesc.ServiceEndpoint;
57  import javax.wsdl.WSDLException;
58  import javax.xml.namespace.QName;
59  import javax.xml.parsers.ParserConfigurationException;
60  import javax.xml.stream.XMLStreamException;
61  import javax.xml.stream.XMLStreamReader;
62  import javax.xml.transform.Source;
63  import javax.xml.transform.Transformer;
64  import javax.xml.transform.TransformerConfigurationException;
65  import javax.xml.transform.TransformerException;
66  import javax.xml.transform.TransformerFactory;
67  import javax.xml.transform.stream.StreamResult;
68  import javax.xml.ws.Holder;
69  
70  import net.java.hulp.measure.Probe;
71  
72  import org.apache.commons.lang.builder.ReflectionToStringBuilder;
73  import org.apache.cxf.endpoint.Endpoint;
74  import org.apache.cxf.frontend.MethodDispatcher;
75  import org.apache.cxf.frontend.SimpleMethodDispatcher;
76  import org.apache.cxf.helpers.DOMUtils;
77  import org.apache.cxf.interceptor.Fault;
78  import org.apache.cxf.interceptor.StaxOutInterceptor;
79  import org.apache.cxf.jaxws.JAXWSMethodDispatcher;
80  import org.apache.cxf.jaxws.JaxWsClientFactoryBean;
81  import org.apache.cxf.message.Exchange;
82  import org.apache.cxf.message.ExchangeImpl;
83  import org.apache.cxf.message.Message;
84  import org.apache.cxf.message.MessageImpl;
85  import org.apache.cxf.phase.PhaseInterceptorChain;
86  import org.apache.cxf.phase.PhaseManager;
87  import org.apache.cxf.service.Service;
88  import org.apache.cxf.service.model.BindingOperationInfo;
89  import org.apache.cxf.service.model.EndpointInfo;
90  import org.apache.cxf.service.model.OperationInfo;
91  import org.apache.cxf.staxutils.FragmentStreamReader;
92  import org.apache.cxf.staxutils.StaxUtils;
93  import org.w3c.dom.Document;
94  import org.w3c.dom.Element;
95  import org.xml.sax.SAXException;
96  
97  import com.sun.jbi.nms.wsdl11wrapper.WrapperProcessingException;
98  import java.lang.reflect.Array;
99  import java.lang.reflect.Field;
100 
101 /**
102  * This class is used at runtime to create the MessageExchange and sending the
103  * message on the bus.
104  * 
105  */
106 @SuppressWarnings("unchecked")
107 public class ConsumerInvocationHandler implements InvocationHandler {
108 
109     /** The logger for this class and its instances. */
110     private static final transient Logger LOG = LoggerFactory.getLogger(ConsumerInvocationHandler.class);
111     /** A kind of MEP. */
112     public static final URI IN_ONLY = URI.create("http://www.w3.org/2004/08/wsdl/in-only");
113     /** A kind of MEP. */
114     public static final URI IN_OUT = URI.create("http://www.w3.org/2004/08/wsdl/in-out");
115     /** A kind of MEP. */
116     public static final URI ROBUST_IN_ONLY = URI.create("http://www.w3.org/2004/08/wsdl/robust-in-only");
117     /**
118      * The responsible to translate localized messages.
119      */
120     private static final Messages MESSAGES = Messages.getMessages(ConsumerInvocationHandler.class);
121     private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
122 
123     // endpoint data
124     private ConsumerEndpoint endpoint;
125     private ServiceEndpoint mirroredEndpoint;
126     private DeliveryChannel channel;
127 
128     // local Source Transformer
129     private SourceTransformer sourceTransformer = new SourceTransformer();
130     /** The Consumer Service Descriptor. */
131     private ConsumerServiceDescriptor consumerServiceDescriptor;
132     /** message denormalizer. */
133     //private MessageDenormalizer messageDenormalizer;
134     /** message normalizer. */
135     //private MessageNormalizer messageNormalizer;
136     /** Probe. */
137     private Probe mMeasurement = null;
138     /** The CXF service */
139     private Service service = null;
140     /** The EndpointInfo */
141     private EndpointInfo ei = null;
142     /** The Endpoint */
143     private Endpoint ep = null;
144     /** Method Names to BindingOperationInfo and mapping */
145     private Map<String, BindingOperationInfo> methodToBio = new HashMap<String, BindingOperationInfo>();
146     /** true if the endpoint is a consumser in the "from IDL" case. */
147     boolean isFromIdl = false;
148 
149     /**
150      * Constructor.
151      *
152      * @param sd
153      *            The service descriptor used inside the class.
154      *
155      * @throws ServiceCreationException
156      *             The service creation exception
157      */
158     public ConsumerInvocationHandler(ConsumerServiceDescriptor sd)
159             throws ServiceCreationException {
160 
161         // Init the message normalizer/denormalizer
162 //		try {
163 //			//messageDenormalizer = new MessageDenormalizer();
164 //			//messageNormalizer = new MessageNormalizer();
165 //
166 //		} catch (Jbi4CorbaException e) {
167 //
168 //			Object[] logArgs = new Object[] { e.getMessage() };
169 //			LOG.error("CRB000749_XML_toString_Error", logArgs, e);
170 //			throw new ServiceCreationException("CRB000749_XML_toString_Error",
171 //					logArgs, e);
172 //		}
173 
174         consumerServiceDescriptor = sd;
175 
176         endpoint = consumerServiceDescriptor.getEndpoint();
177 
178         mirroredEndpoint = consumerServiceDescriptor.getProxiedService();
179 
180         isFromIdl = consumerServiceDescriptor.getServerCorbaClassesHolder().isGenerateClassesFromIDL();
181 
182         // Creates the endpoint factory
183         JaxWsClientFactoryBean endpointFactory;
184         try {
185             endpointFactory = CXFUtils.getJaxWsClientFactoryBean();
186         } catch (Jbi4CorbaException e1) {
187             String msg = MESSAGES.getString("CRB000750_Error_in_creating_the_EndpointFactory");
188             LOG.error(msg, e1);
189             throw new ServiceCreationException(msg, e1);
190         }
191 
192         if (LOG.isDebugEnabled()) {
193             LOG.debug("--- wsdl definition:\n" + consumerServiceDescriptor.getServiceWSDLDefinition() + "\n ---");
194         }
195 
196         // Creates the service, using the correct ClassLoader
197         // SWAP ClassLoader 1/2
198         ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
199         Thread.currentThread().setContextClassLoader(
200                 consumerServiceDescriptor.getServerCorbaClassesHolder().getUrlClassLoader());
201         try {
202 
203             // if we use the interface the endpoint registration fails.
204             Class impl = consumerServiceDescriptor.getServerCorbaClassesHolder().getWebServiceImpl();
205 
206             LOG.debug("Creating CXF service for class:" + impl + " in classloader: " + ((URLClassLoader) impl.getClassLoader()).getURLs()[0]);
207 
208             // Sets the service class
209             endpointFactory.setServiceClass(impl);
210 
211             if (sd.getEndpoint() != null) {
212 
213                 endpointFactory.setServiceName(sd.getEndpoint().getServiceName());
214                 // For Generate Service With Correct EndpointName
215                 endpointFactory.setEndpointName(new QName(sd.getEndpoint().getEndpointName()));
216 
217             }
218 
219             // If generated from IDL we have to set the same WSDL settings
220             // used in the WSDL generations
221             if (isFromIdl) {
222 
223                 endpointFactory.getServiceFactory().setAnonymousWrapperTypes(true);
224                 // To qualify schema elements
225                 endpointFactory.getServiceFactory().setQualifyWrapperSchema(true);
226                 endpointFactory.getServiceFactory().setWrapped(true);
227             }
228 
229             // Creates the endpoint
230             endpointFactory.create();
231 
232             // Gets the service model
233             service = endpointFactory.getServiceFactory().getService();
234 
235             // Gets the CXF EndpointInfo
236             try {
237                 ei = CXFUtils.getEndpointInfo(service);
238             } catch (IOException e1) {
239                 String msg = MESSAGES.getString("CRB000750_Error_in_creating_the_EndpointFactory");
240                 LOG.error(msg, e1);
241                 throw new ServiceCreationException(msg, e1);
242             }
243 
244             // Gets the CXF Endpoint
245             ep = CXFUtils.getEndpoint(service, ei);
246 
247             // Init the BindingOperationInfo/method mapper.
248             SimpleMethodDispatcher md = (SimpleMethodDispatcher) ep.getService().get(MethodDispatcher.class.getName());
249 
250             Collection<BindingOperationInfo> bios = ep.getBinding().getBindingInfo().getOperations();
251             Iterator<BindingOperationInfo> it = bios.iterator();
252             while (it.hasNext()) {
253                 BindingOperationInfo bio = (BindingOperationInfo) it.next();
254                 Method meth = md.getMethod(bio);
255                 LOG.debug("bio: " + bio + " binded to :" + meth);
256                 methodToBio.put(meth.toString(), bio);
257             }
258 
259         } catch (RuntimeException e) {
260             String msg = MESSAGES.getString("CRB000751_RuntimeExcection",
261                     new Object[]{e.getMessage()});
262             LOG.error(msg, e);
263             throw new ServiceCreationException(msg, e);
264         } finally {
265             // SWAP ClassLoader 2/2
266             Thread.currentThread().setContextClassLoader(oldCL);
267         }
268 
269         // Printing out the WSDL for logging pourpose
270         if (LOG.isDebugEnabled()) {
271             ByteArrayOutputStream baos = new ByteArrayOutputStream();
272             try {
273                 CXFUtils.writeDefinitionOnOutputStream(service, baos);
274             } catch (WSDLException e) {
275                 LOG.warn("CRB000763_Error_in_producing_the_WSDL_for_logging",
276                         new Object[]{e.getMessage()});
277                 e.printStackTrace();
278             }
279             LOG.debug("Crated CXF service: " + baos.toString());
280         }
281         
282 
283         ComponentContext context = RuntimeContext.getInstance().getComponentContext();
284         try {
285 
286             channel = context.getDeliveryChannel();
287 
288         } catch (MessagingException e) {
289             Object[] args = new Object[]{context};
290 
291             LOG.error("CRB000700_Unable_to_get_delivery_channel_from_context",
292                     args, e);
293             throw new ServiceCreationException(
294                     "CRB000700_Unable_to_get_delivery_channel_from_context",
295                     args, e);
296         }
297 
298         // if we are on servicemix we don't wrap
299         LOG.debug("context class name: " + context.getClass().getName());
300 
301     }
302 
303     /**
304      * @param proxy
305      *            The proxy
306      * @param method
307      *            The method
308      * @param args
309      *            The args
310      * @return The return
311      *
312      * @throws Throwable
313      *             This method should be raise only 2 kind of exception: -
314      *             Jbi4CorbaRuntimeException; - Jbi4CorbaException. The last one
315      *             is used to wrap a soap fault and the first one to wrap all
316      *             the other errors. To avoid classpath problems, the runtime
317      *             exception set the message exception with the original message
318      *             exception but doesn't include the original exception itself.
319      */
320     public Object invoke(Object proxy, Method method, Object[] args)
321             throws Throwable {
322         Method origMethod=method;
323         Object exchangeResult = null;
324         ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
325         Object[] returnedArgs = null;
326         //Not supported before jdk 1.6
327         //Object[] origArgs=Arrays.copyOf(args, args.length);
328         //4-09-2009 Changed by Luca to be checked
329         Object[] origArgs = new Object[args.length];
330         System.arraycopy(args, 0, origArgs, 0, args.length);
331         //--------------------------------------------------
332 
333         try {
334             try {
335                 LOG.debug("ConsumerInvocationHandler.invoke; invoked endpoint: " + endpoint + " Role " + endpoint.getRole() + " " + " with method: " + method + " and args: " + Arrays.toString(args));
336 
337                 LOG.debug("INVOKE");
338                 List argList = new ArrayList();
339                 for (int i = 0; i < args.length; i++) {
340                     argList.add(args[i]);
341                 }
342 
343                 // Chrono for Consumer-Normalization -start
344                 String topic = new String("Normalization");
345 
346                 mMeasurement = Probe.fine(getClass(), endpoint.getUniqueName(),
347                         topic);
348                 // To make the measurement thread safe, add the measurement
349                 // object
350                 // to context, and retrieve before stopping
351                 Exchange cxfExchange = new ExchangeImpl();
352                 cxfExchange.put("Measure-N", mMeasurement);
353 
354                 // OriginalCLassLoader
355                 // This Transformation is Only for Consumer IDL FIRST
356                 // ************************* TRANSFORMATION CORBA TO SERVICE
357                 // ******************************************************************
358                 RuntimeInformation rInfo = consumerServiceDescriptor.getRuntimeInformation();
359 
360 
361                 MethodSignature methodSignature = null;
362 
363                 // This must be done only when processing a "from IDL" consumer
364                 // Endpoint
365                 if (consumerServiceDescriptor.getServerCorbaClassesHolder().isGenerateClassesFromIDL()) {
366 
367                     Thread.currentThread().setContextClassLoader(
368                             consumerServiceDescriptor.getServerCorbaClassesHolder().getUrlClassLoader());
369 
370                     methodSignature = CorbaTransformationUtils.getMetodSignatureFromMethod(method,
371                             consumerServiceDescriptor.getServerCorbaClassesHolder().getMethodSignatures());
372 
373                     // In this case we have to specify the CXF service
374                     // method...not the CORBA one.
375 
376                     method = methodSignature.getChangedMethod();
377 
378                     if (methodSignature.isContainsHolder()) {
379 
380                         for (int i = 0; i < methodSignature.getParameters().size(); i++) {
381                             Param paramSig = (Param) methodSignature.getParameters().get(i);
382                             if (paramSig.isHolder()) {
383                                 argList.set(i, new Holder());
384                             }
385                         }
386                         CorbaTransformationUtils.changeHoldersFromCorbaToServiceObjects(
387                                 methodSignature, argList, args,
388                                 rInfo);
389                     }
390                     Object[] serviceArgs = null;
391                     serviceArgs = CorbaTransformationUtils.changeFromCorbaToServiceObjects(args, rInfo,
392                             methodSignature);
393                     for (int i = 0; i < methodSignature.getParameters().size(); i++) {
394                         Param paramSig = (Param) methodSignature.getParameters().get(i);
395                         if (!paramSig.isHolder()) {
396                             argList.set(i, serviceArgs[i]);
397                         }
398                     }
399 
400 
401                 }
402                 // **********************************************************************
403                 OutputStream xmlResult = fromObjectToXML(ep, method, argList);
404 
405                 LOG.debug("XML request: " + xmlResult.toString());
406 
407                 exchangeResult = null;
408                 QName portType = ei.getInterface().getName();
409 
410                 LOG.debug("Portype" + ei.getInterface().getName());
411 
412                 // Gets the BindingOperationInfo from the method name
413                 BindingOperationInfo bio = methodToBio.get(method.toString());
414 
415                 QName operation = bio.getOperationInfo().getName();
416                 LOG.debug("operation to call:" + operation);
417 
418                 // Tests if the operation is In-Only
419                 boolean isAsync = false;
420                 if (consumerServiceDescriptor.getServerCorbaClassesHolder().isGenerateClassesFromIDL()) {
421                     // is Async if the original from IDL was oneway
422                     isAsync = methodSignature.isOneway();
423                 } else {
424                     isAsync = isAsynch(portType, operation);
425                 }
426 
427                 if (isAsync) {
428                     Object[] logArgs = new Object[]{operation.getLocalPart()};
429                     LOG.debug("CRB000747_ConsumerInOnlyInvoke", logArgs);
430                     exchangeInOnly(cxfExchange, operation, xmlResult);
431                     return null;
432 
433 
434                 } else {
435 
436                     Object[] logArgs = new Object[]{operation.getLocalPart()};
437                     LOG.debug("CRB000748_ConsumerInOutInvoke", logArgs);
438                     exchangeResult = exchangeInOut(cxfExchange, operation,
439                             method, xmlResult);
440 
441                 }
442 
443 //				LOG.debug("exchangeResult="
444 //						+ exchangeResult
445 //						+ " of classloader:"
446 //						+ ((URLClassLoader) (exchangeResult.getClass()
447 //								.getClassLoader())).getURLs()[0]);
448 
449                 // If throwable, must be thrown
450                 if (exchangeResult instanceof Throwable) {
451                     String msg = MESSAGES.getString(
452                             "CRB000752_About_throwing_exception",
453                             new Object[]{exchangeResult});
454                     LOG.error(msg);
455 
456                     // Transform the Exception
457                     // This Transformation is Only for Consumer IDL FIRST
458                     if (consumerServiceDescriptor.getServerCorbaClassesHolder().isGenerateClassesFromIDL()) {
459                         Thread.currentThread().setContextClassLoader(
460                                 consumerServiceDescriptor.getServerCorbaClassesHolder().getOriginalClassLoader());
461 
462                         exchangeResult = (Throwable) CorbaTransformationUtils.changeFromServiceToCorbaObject(
463                                 exchangeResult, rInfo, exchangeResult.getClass());
464 
465                     }
466 
467                     throw new Throwable((Throwable) exchangeResult);
468                 }
469 
470                 LOG.debug("CRB000764_Received_message_invocation_for_endpoint");
471                 // Transform the Result in a Service Format
472 
473                 // ************************* TRANSFORMATION SERVICE TO CORBA
474                 // This is necessary only when processing "from idl" endpoints.
475 
476                 if (consumerServiceDescriptor.getServerCorbaClassesHolder().isGenerateClassesFromIDL()) {
477 
478                     Thread.currentThread().setContextClassLoader(
479                             consumerServiceDescriptor.getServerCorbaClassesHolder().getOriginalClassLoader());
480                     /*
481                      * se abbiamo un holder assumiamo che cxf ci abbia tornato una lista
482                      * il primo elemento รจ return gli altri sono i parametri tra cui gli eventuali holder
483                      * facciamo la conversione degli holder e del return
484                      */
485 
486                     if (methodSignature.isContainsHolder()) {
487                         List argsSubList = null;
488                         argsSubList = ((List) exchangeResult).subList(1, ((List) exchangeResult).size());
489 
490                         for (int p = 0; p < methodSignature.getParameters().size(); p++) {
491                             Param paramSig = (Param) methodSignature.getParameters().get(p);
492                             if (paramSig.isHolder()) {
493 
494                                 Object o = argsSubList.get(p);
495                                 argsSubList.set(p, new javax.xml.ws.Holder(o));
496 
497                             }
498                         }
499                         returnedArgs = CorbaTransformationUtils.changeHoldersFromServiceToCorbaObjects(
500                                 methodSignature, argsSubList, rInfo);
501                         LOG.debug("returned args: " + Arrays.toString(returnedArgs));
502                         LOG.debug("initial args: " + Arrays.toString(origArgs));
503                         for (int i = 0; i < origArgs.length; i++) {
504                             if (argsSubList.get(i) != null) {
505                                 // assumo che l'elemento i-esimo di args[] sia un holder
506                                 Class holderClass = origArgs[i].getClass();
507                                 Field valueField = holderClass.getField("value");
508                                 valueField.set(origArgs[i], valueField.get(returnedArgs[i]));
509                             }
510                         }
511                         exchangeResult = CorbaTransformationUtils.changeFromServiceToCorbaObject(((List) exchangeResult).get(0),
512                                 rInfo, methodSignature.getMethod().getReturnType());
513                     /*
514                      * se non ci sono holder trasformo solo retunr
515                      */
516                     } else {
517 
518                         exchangeResult = CorbaTransformationUtils.changeFromServiceToCorbaObject(exchangeResult,
519                                 rInfo, methodSignature.getMethod().getReturnType());
520                     }
521                 }
522             // **********************************************************************
523 
524             } catch (Throwable th) {
525                 if (LOG.isDebugEnabled()) {
526                     // For debug pourpouse
527                     th.printStackTrace();
528                 }
529                 throw th;
530             }
531             // Else, the object is returned.
532 
533             //patch for ossupport11 if return result is null and it is an type array the return a void array
534             if (method.getReturnType().isArray() && exchangeResult == null) {
535                 LOG.debug("result is array and value is null, not valid for corba, instancing a array of lenght 0 and type: " + origMethod.getReturnType().getComponentType());
536                 try {
537                     exchangeResult = Array.newInstance(origMethod.getReturnType().getComponentType(), 0);
538                     LOG.debug("echangeResult classloader: " + exchangeResult.getClass().getClassLoader());
539                 } catch (Throwable e) {
540                     LOG.error("error in creating default array: ", e);
541                     throw e;
542                 }
543             }
544 
545             String resultAsString = ReflectionToStringBuilder.toString(exchangeResult);
546             String outArgsAsString = ReflectionToStringBuilder.toString(origArgs);
547 
548             LOG.debug("returning from invokation: return value: " + resultAsString + " out parameters: " + outArgsAsString);
549 
550 
551             return exchangeResult;
552         } finally {
553             Thread.currentThread().setContextClassLoader(oldCL);
554         }
555     }
556 
557     /**
558      * This method implements the 'InOnly' Message Exchange MEP.
559      *
560      * @param executionContext
561      * @param op
562      * @param nodeResult
563      *
564      * @return The result of the exchange.
565      *
566      * @throws it.imolinfo.jbi4corba.jbi.processor.wsdl11wrapper.WrapperProcessingException
567      * @throws javax.xml.transform.TransformerException
568      * @throws javax.jbi.messaging.MessagingException
569      * @throws javax.xml.parsers.ParserConfigurationException
570      * @throws java.io.IOException
571      * @throws org.xml.sax.SAXException
572      */
573     protected Object exchangeInOnly(Exchange cxfExchange, QName operation,
574             OutputStream xmlResult) throws Jbi4CorbaRuntimeException {
575 
576         javax.jbi.messaging.InOnly jbiExchange = createInOnlyExchange(operation);
577         LOG.debug("Created InOnlyExchange: " + jbiExchange);
578 
579         // ==========================================
580         // Creating 'IN' message
581         // ==========================================
582         NormalizedMessage inMessage;
583         try {
584             inMessage = jbiExchange.createMessage();
585             LOG.debug("created inMessage: " + inMessage);
586         } catch (MessagingException e) {
587             Object[] params = new Object[]{jbiExchange};
588 
589             LOG.error("CRB000701_Unable_to_create_message_from_exchange",
590                     params, e);
591             throw new Jbi4CorbaRuntimeException(
592                     "CRB000701_Unable_to_create_message_from_exchange", params,
593                     e);
594         }
595 
596         if (LOG.isDebugEnabled()) {
597             LOG.debug("stringContent: " + xmlResult.toString());
598         }
599 
600         Source wrappedContent = null;
601         Source xmlSource = new StringSource(xmlResult.toString());
602         try {
603             MessageNormalizer messageNormalizer = new MessageNormalizer();
604             wrappedContent = messageNormalizer.normalize(xmlSource, endpoint,
605                     operation, true, false);
606         } catch (Jbi4CorbaException e) {
607             Object[] logArgs = new Object[]{e.getMessage()};
608             LOG.error("CRB000744_MessageWrapping_Error", logArgs, e);
609             throw new Jbi4CorbaRuntimeException(
610                     "CRB000744_MessageWrapping_Error", logArgs, e);
611         } finally {
612             // Chrono for Customer-Normalization -end(1)
613             // First retrieve Perf Measurement object from context
614             mMeasurement = (Probe) cxfExchange.get("Measure-N");
615             mMeasurement.end(); // Normalization Chrono stopped
616         }
617 
618         try {
619             inMessage.setContent(wrappedContent);
620         } catch (MessagingException e) {
621             Object[] logArgs = new Object[]{e.getMessage()};
622             LOG.error("CRB000745_NormalizedMessageSetContent_Error",
623                     logArgs, e);
624             throw new Jbi4CorbaRuntimeException(
625                     "CRB000745_NormalizedMessageSetContent_Error", logArgs, e);
626         }
627 
628         if (LOG.isDebugEnabled()) {
629             String in2string = null;
630             try {
631                 in2string = sourceTransformer.contentToString(inMessage);
632             } catch (MessagingException e) {
633                 Object[] logArgs = new Object[]{e.getMessage()};
634                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
635                 throw new Jbi4CorbaRuntimeException(
636                         "CRB000743_XML_toString_Error", logArgs, e);
637             } catch (TransformerException e) {
638                 Object[] logArgs = new Object[]{e.getMessage()};
639                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
640                 throw new Jbi4CorbaRuntimeException(
641                         "CRB000743_XML_toString_Error", logArgs, e);
642             } catch (ParserConfigurationException e) {
643                 Object[] logArgs = new Object[]{e.getMessage()};
644                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
645                 throw new Jbi4CorbaRuntimeException(
646                         "CRB000743_XML_toString_Error", logArgs, e);
647             } catch (IOException e) {
648                 Object[] logArgs = new Object[]{e.getMessage()};
649                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
650                 throw new Jbi4CorbaRuntimeException(
651                         "CRB000743_XML_toString_Error", logArgs, e);
652             } catch (SAXException e) {
653                 Object[] logArgs = new Object[]{e.getMessage()};
654                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
655                 throw new Jbi4CorbaRuntimeException(
656                         "CRB000743_XML_toString_Error", logArgs, e);
657             }
658             LOG.debug("JBI-inMessage.getContent()=" + in2string);
659         }
660 
661         try {
662             jbiExchange.setInMessage(inMessage);
663         } catch (MessagingException e) {
664             Object[] params = new Object[]{inMessage, jbiExchange};
665 
666             LOG.error("CRB000703_Unable_to_set_message_in_exchange", params, e);
667             throw new Jbi4CorbaRuntimeException(
668                     "CRB000703_Unable_to_set_message_in_exchange", params, e);
669         }
670 
671         // ==========================================
672         // Sending Asynchronously
673         // ==========================================
674 
675         if (LOG.isDebugEnabled()) {
676             String in2string = null;
677             try {
678                 in2string = sourceTransformer.contentToString(inMessage);
679             } catch (MessagingException e) {
680                 Object[] logArgs = new Object[]{e.getMessage()};
681                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
682                 throw new Jbi4CorbaRuntimeException(
683                         "CRB000743_XML_toString_Error", logArgs, e);
684             } catch (TransformerException e) {
685                 Object[] logArgs = new Object[]{e.getMessage()};
686                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
687                 throw new Jbi4CorbaRuntimeException(
688                         "CRB000743_XML_toString_Error", logArgs, e);
689             } catch (ParserConfigurationException e) {
690                 Object[] logArgs = new Object[]{e.getMessage()};
691                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
692                 throw new Jbi4CorbaRuntimeException(
693                         "CRB000743_XML_toString_Error", logArgs, e);
694             } catch (IOException e) {
695                 Object[] logArgs = new Object[]{e.getMessage()};
696                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
697                 throw new Jbi4CorbaRuntimeException(
698                         "CRB000743_XML_toString_Error", logArgs, e);
699             } catch (SAXException e) {
700                 Object[] logArgs = new Object[]{e.getMessage()};
701                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
702                 throw new Jbi4CorbaRuntimeException(
703                         "CRB000743_XML_toString_Error", logArgs, e);
704             }
705             LOG.debug("Sending asynch message: InMessage: " + in2string + " on exchange: " + jbiExchange.getExchangeId());
706         }
707 
708         try {
709             endpoint.sendAsynch(jbiExchange, channel);
710             endpoint.getEndpointStatus().incrementSentRequests();
711         } catch (MessagingException e) {
712             Object[] logArgs = new Object[]{jbiExchange, endpoint};
713             LOG.error("CRB000704_Unable_to_send_exchange_with_endpoint",
714                     logArgs, e);
715             throw new Jbi4CorbaRuntimeException(
716                     "CRB000704_Unable_to_send_exchange_with_endpoint", logArgs,
717                     e);
718         }
719 
720         LOG.debug("... message sending complete.");
721         LOG.debug("jbiExchange.getStatus()=" + jbiExchange.getStatus());
722         return null;
723     }
724 
725     /**
726      * This method implements the 'InOut' Message Exchange MEP.
727      *
728      * @param executionContext
729      * @param op
730      * @param nodeResult
731      *
732      * @return The result of the exchange.
733      *
734      * @throws it.imolinfo.jbi4corba.jbi.processor.wsdl11wrapper.WrapperProcessingException
735      * @throws javax.xml.transform.TransformerException
736      * @throws javax.jbi.messaging.MessagingException
737      * @throws javax.xml.parsers.ParserConfigurationException
738      * @throws java.io.IOException
739      * @throws org.xml.sax.SAXException
740      */
741     protected Object exchangeInOut(Exchange cxfExchange, QName operation,
742             Method method, OutputStream xmlResult)
743             throws Jbi4CorbaRuntimeException {
744 
745         javax.jbi.messaging.InOut jbiExchange = (InOut) createInOutExchange(operation);
746         LOG.debug("Created InOutExchange: " + jbiExchange);
747 
748         // executionContext.setJbiExchange(jbiExchange);
749         NormalizedMessage inMessage;
750         try {
751             inMessage = jbiExchange.createMessage();
752             LOG.debug("created inMessage: " + inMessage);
753         } catch (MessagingException e) {
754             Object[] params = new Object[]{jbiExchange};
755 
756             LOG.error("CRB000701_Unable_to_create_message_from_exchange",
757                     params, e);
758             throw new Jbi4CorbaRuntimeException(
759                     "CRB000701_Unable_to_create_message_from_exchange", params,
760                     e);
761         }
762 
763         if (LOG.isDebugEnabled()) {
764             LOG.debug("stringContent: " + xmlResult.toString());
765         }
766 
767         LOG.debug("The message needs wrapping");
768 
769         Source wrappedContent = null;
770         Source xmlSource = new StringSource(xmlResult.toString());
771         try {
772             MessageNormalizer messageNormalizer = new MessageNormalizer();
773             wrappedContent = messageNormalizer.normalize(xmlSource, endpoint,
774                     operation, true, false);
775         } catch (Jbi4CorbaException e) {
776             Object[] logArgs = new Object[]{e.getMessage()};
777             LOG.error("CRB000744_MessageWrapping_Error", logArgs, e);
778             throw new Jbi4CorbaRuntimeException(
779                     "CRB000744_MessageWrapping_Error", logArgs, e);
780         } finally {
781             // Chrono for Customer-Normalization -end(2)
782             // First retrieve Perf Measurement object from context
783             mMeasurement = (Probe) cxfExchange.get("Measure-N");
784             mMeasurement.end(); // Normalization Chrono stopped
785         }
786 
787         try {
788             inMessage.setContent(wrappedContent);
789         } catch (MessagingException e) {
790             Object[] logArgs = new Object[]{e.getMessage()};
791             LOG.error("CRB000745_NormalizedMessageSetContent_Error",
792                     logArgs, e);
793             throw new Jbi4CorbaRuntimeException(
794                     "CRB000745_NormalizedMessageSetContent_Error", logArgs, e);
795         }
796 
797         if (LOG.isDebugEnabled()) {
798             String in2string = null;
799             try {
800                 in2string = sourceTransformer.contentToString(inMessage);
801             } catch (MessagingException e) {
802                 Object[] logArgs = new Object[]{e.getMessage()};
803                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
804                 throw new Jbi4CorbaRuntimeException(
805                         "CRB000743_XML_toString_Error", logArgs, e);
806             } catch (TransformerException e) {
807                 Object[] logArgs = new Object[]{e.getMessage()};
808                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
809                 throw new Jbi4CorbaRuntimeException(
810                         "CRB000743_XML_toString_Error", logArgs, e);
811             } catch (ParserConfigurationException e) {
812                 Object[] logArgs = new Object[]{e.getMessage()};
813                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
814                 throw new Jbi4CorbaRuntimeException(
815                         "CRB000743_XML_toString_Error", logArgs, e);
816             } catch (IOException e) {
817                 Object[] logArgs = new Object[]{e.getMessage()};
818                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
819                 throw new Jbi4CorbaRuntimeException(
820                         "CRB000743_XML_toString_Error", logArgs, e);
821             } catch (SAXException e) {
822                 Object[] logArgs = new Object[]{e.getMessage()};
823                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
824                 throw new Jbi4CorbaRuntimeException(
825                         "CRB000743_XML_toString_Error", logArgs, e);
826             }
827             LOG.debug("JBI-inMessage.getContent()=" + in2string);
828         }
829 
830         try {
831 
832             jbiExchange.setInMessage(inMessage);
833 
834         } catch (MessagingException e) {
835             Object[] params = new Object[]{inMessage, jbiExchange};
836 
837             LOG.error("CRB000703_Unable_to_set_message_in_exchange", params, e);
838             throw new Jbi4CorbaRuntimeException(
839                     "CRB000703_Unable_to_set_message_in_exchange", params, e);
840         }
841 
842         if (LOG.isDebugEnabled()) {
843             String in2string2 = null;
844             try {
845                 in2string2 = sourceTransformer.contentToString(inMessage);
846             } catch (MessagingException e) {
847                 Object[] logArgs = new Object[]{e.getMessage()};
848                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
849                 throw new Jbi4CorbaRuntimeException(
850                         "CRB000743_XML_toString_Error", logArgs, e);
851             } catch (TransformerException e) {
852                 Object[] logArgs = new Object[]{e.getMessage()};
853                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
854                 throw new Jbi4CorbaRuntimeException(
855                         "CRB000743_XML_toString_Error", logArgs, e);
856             } catch (ParserConfigurationException e) {
857                 Object[] logArgs = new Object[]{e.getMessage()};
858                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
859                 throw new Jbi4CorbaRuntimeException(
860                         "CRB000743_XML_toString_Error", logArgs, e);
861             } catch (IOException e) {
862                 Object[] logArgs = new Object[]{e.getMessage()};
863                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
864                 throw new Jbi4CorbaRuntimeException(
865                         "CRB000743_XML_toString_Error", logArgs, e);
866             } catch (SAXException e) {
867                 Object[] logArgs = new Object[]{e.getMessage()};
868                 LOG.error("CRB000743_XML_toString_Error", logArgs, e);
869                 throw new Jbi4CorbaRuntimeException(
870                         "CRB000743_XML_toString_Error", logArgs, e);
871             }
872             LOG.debug("Sending synch message: InMessage: " + in2string2 + " on exchange: " + jbiExchange.getExchangeId());
873         }
874 
875         boolean sendingReturn = false;
876         try {
877             sendingReturn = sendSynch(jbiExchange);
878             endpoint.getEndpointStatus().incrementSentRequests();
879 
880         } catch (MessagingException e1) {
881             Object[] logArgs = new Object[]{jbiExchange, ""};
882             LOG.error("CRB000704_Unable_to_send_exchange_with_endpoint",
883                     logArgs, e1);
884             throw new Jbi4CorbaRuntimeException(
885                     "CRB000704_Unable_to_send_exchange_with_endpoint", logArgs,
886                     e1);
887         }
888         LOG.debug("... message response:" + sendingReturn);
889 
890         if (jbiExchange.getStatus() == ExchangeStatus.ERROR) {
891 
892             Exception err = jbiExchange.getError();
893             endpoint.getEndpointStatus().incrementReceivedErrors();
894 
895             LOG.error("CRB000705_Exchange_status_error", err);
896             if (err != null) {
897                 throw new Jbi4CorbaRuntimeException(err);
898             } else {
899                 throw new Jbi4CorbaRuntimeException("CRB000706_Unknown_error");
900             }
901 
902         } else if (jbiExchange.getStatus() == ExchangeStatus.ACTIVE) {
903             LOG.debug("exchange status ACTIVE");
904             endpoint.getEndpointStatus().incrementReceivedReplies();
905             try {
906 
907                 try {
908                     return exchangeStatusACTIVE(jbiExchange, method);
909                 } catch (MessagingException e) {
910                     Object[] logArgs = new Object[]{e.getMessage()};
911                     LOG.error("CRB000746_SetExchangeStatus_Error", logArgs, e);
912                     throw new Jbi4CorbaRuntimeException(
913                             "CRB000746_SetExchangeStatus_Error", logArgs, e);
914                 } catch (TransformerException e) {
915                     Object[] logArgs = new Object[]{e.getMessage()};
916                     LOG.error("CRB000746_SetExchangeStatus_Error", logArgs, e);
917                     throw new Jbi4CorbaRuntimeException(
918                             "CRB000746_SetExchangeStatus_Error", logArgs, e);
919                 } catch (ParserConfigurationException e) {
920                     Object[] logArgs = new Object[]{e.getMessage()};
921                     LOG.error("CRB000746_SetExchangeStatus_Error", logArgs, e);
922                     throw new Jbi4CorbaRuntimeException(
923                             "CRB000746_SetExchangeStatus_Error", logArgs, e);
924                 } catch (IOException e) {
925                     Object[] logArgs = new Object[]{e.getMessage()};
926                     LOG.error("CRB000746_SetExchangeStatus_Error", logArgs, e);
927                     throw new Jbi4CorbaRuntimeException(
928                             "CRB000746_SetExchangeStatus_Error", logArgs, e);
929                 } catch (SAXException e) {
930                     Object[] logArgs = new Object[]{e.getMessage()};
931                     LOG.error("CRB000746_SetExchangeStatus_Error", logArgs, e);
932                     throw new Jbi4CorbaRuntimeException(
933                             "CRB000746_SetExchangeStatus_Error", logArgs, e);
934                 } catch (WrapperProcessingException e) {
935                     Object[] logArgs = new Object[]{e.getMessage()};
936                     LOG.error("CRB000746_SetExchangeStatus_Error", logArgs, e);
937                     throw new Jbi4CorbaRuntimeException(
938                             "CRB000746_SetExchangeStatus_Error", logArgs, e);
939                 }
940 
941             } finally {
942 
943                 setJbiExchangeToDONE(jbiExchange);
944                 endpoint.getEndpointStatus().incrementSentDones();
945 
946                 try {
947                     channel.send(jbiExchange);
948                 } catch (MessagingException e) {
949                     Object[] params = new Object[]{jbiExchange, channel};
950 
951                     LOG.error("CRB000711_Unable_to_send_exchange_on_channel",
952                             params, e);
953                     throw new Jbi4CorbaRuntimeException(
954                             "CRB000711_Unable_to_send_exchange_on_channel",
955                             params, e);
956                 }
957 
958             }
959         } // jbiexchange in illegal status
960         else {
961             throw new IllegalStateException(MESSAGES.getString(
962                     "CRB000712_Unexpected_exchange_status", jbiExchange.getStatus()));
963         }
964     }
965 
966     /**
967      * This method is used to set the status of the JbiExchange to DONE.
968      *
969      * @param jbiExchange
970      *            The ME.
971      *
972      * @throws Jbi4CorbaRuntimeException
973      *             If is impossible set up the status.
974      */
975     protected void setJbiExchangeToDONE(
976             javax.jbi.messaging.MessageExchange jbiExchange)
977             throws Jbi4CorbaRuntimeException {
978 
979         try {
980             LOG.debug("Setting exchange to DONE");
981             // Sending DONE to provider
982             jbiExchange.setStatus(ExchangeStatus.DONE);
983 
984         } catch (MessagingException e) {
985             Object[] par = new Object[]{jbiExchange};
986 
987             LOG.error("CRB000710_Unable_to_set_status_DONE_for_exchange", par,
988                     e);
989             throw new Jbi4CorbaRuntimeException(
990                     "CRB000710_Unable_to_set_status_DONE_for_exchange", par, e);
991         }
992     }
993 
994     /**
995      * Exchange status active. Converts the XML to the object to be sent back.
996      *
997      * @param jbiExchange
998      *
999      * @return the object (or a <code>Throwable</code> if error)
1000      *
1001      * @throws MessagingException
1002      * @throws TransformerException
1003      * @throws ParserConfigurationException
1004      * @throws IOException
1005      * @throws SAXException
1006      * @throws WrapperProcessingException
1007      */
1008     protected Object exchangeStatusACTIVE(
1009             javax.jbi.messaging.InOut jbiExchange, Method method)
1010             throws MessagingException, TransformerException,
1011             ParserConfigurationException, IOException, SAXException,
1012             WrapperProcessingException {
1013 
1014         JbiMessage jbiMessage = null;
1015 
1016         if (jbiExchange.getFault() != null) {
1017             LOG.warn("CRB000707_Exchange_returned_a_fault", jbiExchange.getFault());
1018             // Fault Path
1019             // Unwraps the fault
1020             try {
1021                 LOG.debug("CRB000753_Before_messageDenormalizer");
1022                 MessageDenormalizer messageDenormalizer = new MessageDenormalizer();
1023                 jbiMessage = messageDenormalizer.denormalize(jbiExchange.getFault(), endpoint, jbiExchange.getOperation(),
1024                         false, true);
1025                 LOG.debug("CRB000754_Before_fromXMLToException");
1026 
1027                 String xmlException = sourceTransformer.toString(jbiMessage.getMessageSource());
1028 
1029                 Throwable corbaException = fromXMLToException(xmlException,
1030                         method);
1031                 LOG.debug("CRB000755_After_fromXMLToException",
1032                         new Object[]{corbaException});
1033 
1034                 return corbaException;
1035             } catch (Jbi4CorbaException ex) {
1036                 ex.printStackTrace();
1037                 throw new Jbi4CorbaRuntimeException("CRB000708_SOAP_fault",
1038                         new Object[]{ex}, null);
1039             } catch (RuntimeException th) {
1040                 String msg = MESSAGES.getString(
1041                         "CRB000756_Error_in_convertion_of_XML_to_object_to_be_sent_back",
1042                         new java.lang.Object[]{th.getMessage()});
1043                 LOG.error(msg, th);
1044                 throw new Jbi4CorbaRuntimeException(msg, th);
1045             }
1046         }
1047 
1048         // this is the normal path: deserialize the result
1049         // NormalizedMessage outMsg = jbiExchange.getMessage("out");
1050         NormalizedMessage outMsg = jbiExchange.getOutMessage();
1051 
1052         if (LOG.isDebugEnabled()) {
1053             LOG.debug("Received Message class:" + outMsg.getClass().getName());
1054             LOG.debug("Received Message content: " + sourceTransformer.contentToString(outMsg));
1055         }
1056 
1057         // this may be may in inonly mep
1058         if (outMsg == null) {
1059             throw new NullPointerException(MESSAGES.getString("CRB000709_Exchange_returned_a_null_message"));
1060         }
1061 
1062         // Chrono for Customer-Denormalization -start
1063         String topic = new String("Denormalization");
1064         mMeasurement = Probe.fine(getClass(), endpoint.getUniqueName(), topic);
1065         // this is a simple unwrap
1066 
1067         try {
1068             // The first "false" is isInput, the second is isFault
1069             MessageDenormalizer messageDenormalizer = new MessageDenormalizer();
1070             jbiMessage = messageDenormalizer.denormalize(outMsg, endpoint,
1071                     jbiExchange.getOperation(), false, false);
1072         } catch (Jbi4CorbaException e) {
1073             Object[] par = new Object[]{jbiExchange};
1074 
1075             LOG.error("CRB000710_Unable_to_set_status_DONE_for_exchange", par,
1076                     e);
1077             throw new Jbi4CorbaRuntimeException(
1078                     "CRB000710_Unable_to_set_status_DONE_for_exchange", par, e);
1079         }
1080 
1081         if (LOG.isDebugEnabled()) {
1082             LOG.debug("jbi unwrapped content:" + sourceTransformer.toString(jbiMessage.getMessageSource()));
1083         }
1084 
1085         Object result = fromXMLToObject(sourceTransformer.toString(jbiMessage.getMessageSource()), method);
1086 
1087         // Chrono for Customer-Denormalization -stop
1088         mMeasurement.end();
1089 
1090         if (LOG.isDebugEnabled()) {
1091             LOG.debug("Deserialized soap message returned: " + result);
1092         }
1093         return result;
1094 
1095     }
1096 
1097     /**
1098      * This method is used to send asynchronously a MessageExchange.
1099      *
1100      * @param jbiExchange
1101      *            The message to send.
1102      *
1103      *
1104      * @throws MessagingException
1105      */
1106     protected void sendASynch(InOnly jbiExchange) throws MessagingException {
1107         try {
1108             // synchronous send
1109             LOG.debug("Before sendASync. Sending message:");
1110             LOG.debug("Channel:" + channel.getClass().getName());
1111 
1112             LOG.debug("CRB000736_Sending_message");
1113 
1114             channel.send(jbiExchange);
1115 
1116             LOG.debug("After sendASync");
1117 
1118         } catch (MessagingException e) {
1119             Object[] params = new Object[]{jbiExchange, endpoint};
1120 
1121             LOG.error("CRB000704_Unable_to_send_exchange_with_endpoint",
1122                     params, e);
1123             throw new Jbi4CorbaRuntimeException(
1124                     "CRB000704_Unable_to_send_exchange_with_endpoint", params,
1125                     e);
1126         }
1127     }
1128 
1129     /**
1130      * This method is used to send synchronously a MessageExchange.
1131      *
1132      * @param jbiExchange
1133      *            The message to send.
1134      *
1135      * @return true for 'done'; false for 'error'.
1136      *
1137      * @throws MessagingException
1138      */
1139     protected boolean sendSynch(InOut jbiExchange) throws MessagingException {
1140         try {
1141             // synchronous send
1142             LOG.debug("Before sendSync. Sending message:");
1143             LOG.debug("Channel:" + channel.getClass().getName());
1144 
1145             LOG.debug("CRB000736_Sending_message");
1146 
1147             boolean ret = channel.sendSync(jbiExchange);
1148 
1149             LOG.debug("After sendSync (send sync returned: " + ret + ")");
1150 
1151             return ret;
1152         } catch (MessagingException e) {
1153             Object[] params = new Object[]{jbiExchange, endpoint};
1154 
1155             LOG.error("CRB000704_Unable_to_send_exchange_with_endpoint",
1156                     params, e);
1157             throw new Jbi4CorbaRuntimeException(
1158                     "CRB000704_Unable_to_send_exchange_with_endpoint", params,
1159                     e);
1160         }
1161     }
1162 
1163     /**
1164      * Xml-> Object conversion for the specified method using CXF.
1165      *
1166      * @param xmlOut
1167      * @param method
1168      *
1169      * @return The return
1170      */
1171     private Object fromXMLToObject(String xmlOut, Method method) {
1172 
1173         LOG.debug(">>>>> fromXMLToObject - begin" + ". xmlOut=" + xmlOut + ". method=" + method);
1174 
1175         List outObjs = null;
1176 
1177         // Gets the BindingOperationInfo from the method name
1178         BindingOperationInfo bio = null;
1179         if (isFromIdl) {
1180             // PATCH for a CXF
1181             bio = getBindingOperationInfo(method);
1182         } else {
1183             // Gets the BindingOperationInfo from the method
1184             JAXWSMethodDispatcher md = (JAXWSMethodDispatcher) ep.getService().get(MethodDispatcher.class.getName());
1185             bio = md.getBindingOperation(method, ep);
1186         }
1187         String parameterStyle = CXFUtils.getParameterStyle(bio);
1188         String bindingStyle = CXFUtils.getBindingStyle(bio);
1189 
1190 
1191         // Creates the CXF message
1192         Message message = new MessageImpl();
1193         Exchange exchange = new ExchangeImpl();
1194         exchange.setOneWay(false);
1195         exchange.put(BindingOperationInfo.class, bio);
1196         exchange.put(Service.class, ep.getService());
1197         exchange.put(Endpoint.class, ep);
1198         message.setExchange(exchange);
1199         exchange.setInMessage(message);
1200         exchange.setOutMessage(new MessageImpl());
1201 
1202         // Important! If not set, maps the object in the input message (the
1203         // opposite as the objectToXml method)..
1204         message.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
1205 
1206         // Sets the Source as In message
1207         try {
1208             message.setContent(InputStream.class,
1209                     convertMessageToInputStream(new StringSource(xmlOut)));
1210         } catch (TransformerConfigurationException e) {
1211             String msg = MESSAGES.getString(
1212                     "CRB000757_Error_converting_messeage_to_InputStream",
1213                     new java.lang.Object[]{xmlOut,});
1214             LOG.error(msg, e);
1215             throw new Jbi4CorbaRuntimeException(msg, e);
1216         } catch (IOException e) {
1217             String msg = MESSAGES.getString(
1218                     "CRB000757_Error_converting_messeage_to_InputStream",
1219                     new java.lang.Object[]{xmlOut,});
1220             LOG.error(msg, e);
1221             throw new Jbi4CorbaRuntimeException(msg, e);
1222         } catch (TransformerException e) {
1223             String msg = MESSAGES.getString(
1224                     "CRB000757_Error_converting_messeage_to_InputStream",
1225                     new java.lang.Object[]{xmlOut,});
1226             LOG.error(msg, e);
1227             throw new Jbi4CorbaRuntimeException(msg, e);
1228         }
1229 
1230         PhaseInterceptorChain inInterceptorChain = new PhaseInterceptorChain(
1231                 CXFUtils.getBus().getExtension(PhaseManager.class).getInPhases());
1232 
1233         CXFUtils.populateInInterceptorsForConsumer(inInterceptorChain,
1234                 parameterStyle, bindingStyle, isFromIdl);
1235 
1236         message.setInterceptorChain(inInterceptorChain);
1237 
1238         // Process the message
1239         inInterceptorChain.doIntercept(message);
1240 
1241         // Gets the returned objects
1242         outObjs = (List) message.getContent(List.class);
1243         LOG.debug("Object returned: " + outObjs);
1244 
1245         LOG.debug("Deserializing message ...");
1246         Object result = outObjs;
1247 //		if ((outObjs != null) && (outObjs.size() != 0)) {
1248 //			result = outObjs.get(0);
1249 //			LOG.debug("Returned result: " + result);
1250 //		}
1251 
1252         if (LOG.isDebugEnabled()) {
1253             String bodyAsString = (result == null) ? "null"
1254                     : ReflectionToStringBuilder.toString(result);
1255             LOG.debug("InMessage.bodyAsString=" + bodyAsString);
1256         }
1257 
1258 
1259         if (result != null && (result instanceof List)) {
1260 
1261             LOG.debug("Returned result: " + result.getClass().getName());
1262             List list = (List) result;
1263             if (list.isEmpty()) {
1264                 LOG.warn("CRB000715_Deserialized_list_empty", list);
1265                 LOG.debug("<<<<< fromXMLToObject - end");
1266                 return null;
1267             }
1268 
1269             if (list.size() == 1) {
1270                 LOG.debug("returned list contains one element, returning the element itself");
1271                 return list.get(0);
1272             }
1273 
1274 //			LOG.debug("returned list contains: " + list.size() + "elements.");
1275 //			if (list.size() != 1) {
1276 //				throw new Jbi4CorbaRuntimeException(
1277 //						"CRB000716_Deserialized_list_too_big",
1278 //						new Object[] { list }, null);
1279 //			}
1280 //
1281 //			result = list.get(0);
1282             if (LOG.isDebugEnabled()) {
1283                 String resultAsString = ReflectionToStringBuilder.toString(result);
1284                 LOG.debug("resultAsString=" + resultAsString);
1285             }
1286             return result;
1287 
1288         } else {
1289             LOG.debug("Deserializing message ... nothing to do because the body " + "of the InMessage is null OR because the body is not a List" + ". InMessage=" + result + ". InMessage 'is a' List=" + (result instanceof List));
1290         }
1291         LOG.debug("Deserializing message ... done");
1292 
1293         LOG.debug("<<<<< fromXMLToObject - end" + ". ExecutionContext.outResult=" + result + ". result=" + result);
1294         return result;
1295     }
1296 
1297     /**
1298      * Converts the method call in an XML message
1299      *
1300      * @param ep
1301      * @param methodCalled
1302      * @param params
1303      * @return
1304      */
1305     private Throwable fromXMLToException(String xmlFault, Method method)
1306             throws Jbi4CorbaRuntimeException {
1307 
1308         LOG.debug(">>>>> fromXMLToException - begin" + ". xmlOut=" + xmlFault + ". method=" + method);
1309 
1310         LOG.debug("CRB000758_fromXMLToException");
1311         LOG.debug("CRB000759_fromXMLToException_xmlFault",
1312                 new Object[]{xmlFault});
1313         LOG.debug("CRB000758_fromXMLToException");
1314 
1315         // Gets the BindingOperationInfo from the method name
1316         BindingOperationInfo bio = null;
1317         if (isFromIdl) {
1318             // PATCH for a CXF
1319             bio = getBindingOperationInfo(method);
1320         } else {
1321             // Gets the BindingOperationInfo from the method
1322             JAXWSMethodDispatcher md = (JAXWSMethodDispatcher) ep.getService().get(MethodDispatcher.class.getName());
1323             bio = md.getBindingOperation(method, ep);
1324         }
1325         QName operation = bio.getOperationInfo().getName();
1326         LOG.debug("operation to call:" + operation);
1327 
1328         // Creates the message
1329         Message message = new MessageImpl();
1330         Exchange exchange = new ExchangeImpl();
1331         exchange.setOneWay(false);
1332         exchange.put(BindingOperationInfo.class, bio);
1333         exchange.put(Service.class, ep.getService());
1334         exchange.put(Endpoint.class, ep);
1335         message.setExchange(exchange);
1336         exchange.setInMessage(message);
1337         exchange.setOutMessage(new MessageImpl());
1338 
1339         // Preapres the CXF fault to be processed
1340         // Mandatory to pass a message...
1341         String msg = "ERROR_IN_JBI_PROCESSING";
1342         Fault fault = new Fault(new org.apache.cxf.common.i18n.Message(msg,
1343                 (ResourceBundle) null));
1344 
1345         StringSource bodySource = new StringSource(xmlFault);
1346         XMLStreamReader xmlReader = StaxUtils.createXMLStreamReader(bodySource);
1347         Element detailContent = null;
1348         try {
1349             detailContent = StaxUtils.read(new FragmentStreamReader(xmlReader)).getDocumentElement();
1350         } catch (XMLStreamException e) {
1351             LOG.error("CRB000760_Error_in_reading_XML_fault", e);
1352             throw new Jbi4CorbaRuntimeException(msg, e);
1353         }
1354 
1355         // Here the faul xml is not wrapped into a detail element.
1356         // For CXF to correctly map the XML, we must wrap the message in a
1357         // <detail> eleemnt.
1358         Document detailDocument = DOMUtils.createDocument();
1359         Element detail = detailDocument.createElement("detail");
1360         detailDocument.adoptNode(detailContent);
1361         detail.appendChild(detailContent);
1362 
1363         fault.setDetail(detail);
1364 
1365         // Sets the fault on the message
1366         message.setContent(Exception.class, fault);
1367 
1368         // Handle the message using the ClientFaultConverter;
1369         PhaseInterceptorChain faultInterceptorChain = new PhaseInterceptorChain(
1370                 CXFUtils.getBus().getExtension(PhaseManager.class).getInPhases());
1371         message.setInterceptorChain(faultInterceptorChain);
1372         faultInterceptorChain.add(new Jbi4CorbaConsumerExceptionInterceptor());
1373 
1374         // Process the message
1375         faultInterceptorChain.doIntercept(message);
1376 
1377         // The ClientFaultConverter replaces the fault with the Exception object
1378         // in the message for the exception class...
1379         Throwable th = message.getContent(Exception.class);
1380 
1381         LOG.debug("CRB000761_Returnin_th_getName", new Object[]{th.getClass().getName()});
1382 
1383         return th;
1384     }
1385 
1386     /**
1387      * This method is used to create an InOut MessageExchange.
1388      *
1389      * @param op
1390      *            The QName of the OperationInfo is used to set the operation of
1391      *            the JBI MessageExchange.
1392      *
1393      * @return The InOut ME just created.
1394      */
1395     private javax.jbi.messaging.InOut createInOutExchange(QName operation) {
1396 
1397         javax.jbi.messaging.InOut jbiExchange = createInOutExchange();
1398 
1399         jbiExchange.setOperation(operation);
1400         jbiExchange.setEndpoint(mirroredEndpoint);
1401 
1402         if (LOG.isDebugEnabled()) {
1403             LOG.debug("Mirrored endpoint:" + mirroredEndpoint);
1404         }
1405         return jbiExchange;
1406     }
1407 
1408     /**
1409      * This method is used to create an InOut MessageExchange.
1410      *
1411      * @param op
1412      *            The QName of the OperationInfo is used to set the operation of
1413      *            the JBI MessageExchange.
1414      *
1415      * @return The InOnly ME just created.
1416      */
1417     private javax.jbi.messaging.InOnly createInOnlyExchange(QName operation) {
1418 
1419         javax.jbi.messaging.InOnly jbiExchange = createInOnlyExchange();
1420 
1421         jbiExchange.setOperation(operation);
1422         jbiExchange.setEndpoint(mirroredEndpoint);
1423 
1424         if (LOG.isDebugEnabled()) {
1425             LOG.debug("Mirrored endpoint:" + mirroredEndpoint);
1426         }
1427         return jbiExchange;
1428     }
1429 
1430     /**
1431      * This method is used to discover an asynchronous operation.
1432      *
1433      * @param portType
1434      *            The QName of the PortType.
1435      * @param operationName
1436      *            The name of the operation controlled.
1437      *
1438      * @return true, when the operation is asynchronous. false, when the
1439      *         operation is synchronous or when an error occurs.
1440      */
1441     protected boolean isAsynch(QName portType, QName operation) {
1442         if (portType == null || operation == null) {
1443             return false;
1444         }
1445 
1446         WsdlInformation wi = consumerServiceDescriptor.getServerCorbaClassesHolder().getWsdlInformation();
1447         if (wi == null) {
1448             return false;
1449         }
1450 
1451         List<QName> opList = wi.getAsynchOperationMap().get(portType);
1452 
1453         if (opList == null) {
1454             return false;
1455         }
1456 
1457         // true if the operation is found
1458         for (QName op : opList) {
1459             if (operation.equals(op)) {
1460                 return true;
1461             }
1462         }
1463 
1464         return false;
1465     }
1466 
1467     /**
1468      * Converts the method call in an XML message
1469      *
1470      * @param ep
1471      * @param methodCalled
1472      * @param params
1473      * @return the XML OutputStream
1474      */
1475     private OutputStream fromObjectToXML(Endpoint ep, Method methodCalled,
1476             List params) {
1477 
1478         LOG.debug("From Object to XML" + params + " " + ep + " " + methodCalled + " of classloader:" + ((URLClassLoader) (methodCalled.getDeclaringClass().getClassLoader())).getURLs()[0]);
1479 
1480         // Gets the BindingOperationInfo from the method name
1481         BindingOperationInfo bio = getBindingOperationInfo(methodCalled);
1482         QName operation = bio.getOperationInfo().getName();
1483         String parameterStyle = CXFUtils.getParameterStyle(bio);
1484         String bindingStyle = CXFUtils.getBindingStyle(bio);
1485 
1486         LOG.debug("operation to call:" + operation);
1487 
1488         // Creates the message
1489         Message message = new MessageImpl();
1490         Exchange exchange = new ExchangeImpl();
1491         exchange.setOneWay(false);
1492         exchange.put(BindingOperationInfo.class, bio);
1493         if (isFromIdl) {
1494             // If is from idl, it's always wrapped
1495             exchange.put(OperationInfo.class, bio.getWrappedOperation().getOperationInfo());
1496         }
1497         exchange.put(Service.class, ep.getService());
1498         exchange.put(Endpoint.class, ep);
1499         message.setExchange(exchange);
1500         exchange.setOutMessage(message);
1501         exchange.put(StaxOutInterceptor.FORCE_START_DOCUMENT, Boolean.TRUE);
1502 
1503         // We have to map the request (input operation).
1504         message.put(Message.REQUESTOR_ROLE, Boolean.TRUE);
1505 
1506         // Sets the in content
1507         message.setContent(List.class, params);
1508 
1509         // Sets the output stream
1510         OutputStream out = new ByteArrayOutputStream();
1511         message.setContent(OutputStream.class, out);
1512 
1513         PhaseInterceptorChain outInterceptorChain = new PhaseInterceptorChain(
1514                 CXFUtils.getBus().getExtension(PhaseManager.class).getOutPhases());
1515 
1516         CXFUtils.populateOutInterceptors(outInterceptorChain, parameterStyle,
1517                 bindingStyle, isFromIdl);
1518         // Process the message
1519         message.setInterceptorChain(outInterceptorChain);
1520         outInterceptorChain.doIntercept(message);
1521 
1522         return out;
1523     }
1524 
1525     /**
1526      * Returns the BIO of the service model from ths <code>Method</code> called.
1527      *
1528      * @param methodCalled
1529      * @return
1530      */
1531     private BindingOperationInfo getBindingOperationInfo(Method methodCalled) {
1532         BindingOperationInfo bio = methodToBio.get(methodCalled.toString());
1533         LOG.debug("BIO is unwrapped:" + bio.isUnwrapped());
1534 
1535         if (bio.isUnwrappedCapable()) {
1536             bio = bio.getWrappedOperation();
1537         }
1538         return bio;
1539     }
1540 
1541     /**
1542      * Creates the InOut Exchange.
1543      *
1544      * @return The return
1545      */
1546     protected javax.jbi.messaging.InOut createInOutExchange() {
1547 
1548         // ComponentContext context = endpoint
1549         ComponentContext context = RuntimeContext.getInstance().getComponentContext();
1550 
1551         LOG.debug("Component context class:" + context.getClass().getName());
1552         DeliveryChannel channel;
1553         try {
1554             channel = context.getDeliveryChannel();
1555 
1556             LOG.debug("Channel:" + channel.getClass().getName());
1557         } catch (MessagingException e) {
1558             Object[] args = new Object[]{context};
1559 
1560             LOG.error("CRB000719_Unable_to_get_delivery_channel_from_context",
1561                     args, e);
1562             throw new Jbi4CorbaRuntimeException(
1563                     "CRB000719_Unable_to_get_delivery_channel_from_context",
1564                     args, e);
1565         }
1566         MessageExchangeFactory factory = channel.createExchangeFactory();
1567 
1568         javax.jbi.messaging.InOut exchange;
1569         try {
1570             exchange = factory.createInOutExchange();
1571         } catch (MessagingException e) {
1572             Object[] args = new Object[]{factory};
1573 
1574             LOG.error("CRB000720_Unable_to_create_exchange_from_factory", args,
1575                     e);
1576             throw new Jbi4CorbaRuntimeException(
1577                     "CRB000720_Unable_to_create_exchange_from_factory", args, e);
1578         }
1579         return exchange;
1580     }
1581 
1582     /**
1583      * Creates the InOnly exchange.
1584      *
1585      * @return
1586      */
1587     protected javax.jbi.messaging.InOnly createInOnlyExchange() {
1588 
1589         ComponentContext context = RuntimeContext.getInstance().getComponentContext();
1590 
1591         LOG.debug("Component context class:" + context.getClass().getName());
1592         DeliveryChannel channel;
1593         try {
1594             channel = context.getDeliveryChannel();
1595             LOG.debug("Channel:" + channel.getClass().getName());
1596         } catch (MessagingException e) {
1597             Object[] args = new Object[]{context};
1598 
1599             LOG.error("CRB000719_Unable_to_get_delivery_channel_from_context",
1600                     args, e);
1601             throw new Jbi4CorbaRuntimeException(
1602                     "CRB000719_Unable_to_get_delivery_channel_from_context",
1603                     args, e);
1604         }
1605         MessageExchangeFactory factory = channel.createExchangeFactory();
1606 
1607         javax.jbi.messaging.InOnly exchange;
1608         try {
1609             exchange = factory.createInOnlyExchange();
1610         } catch (MessagingException e) {
1611             Object[] args = new Object[]{factory};
1612 
1613             LOG.error("CRB000720_Unable_to_create_exchange_from_factory", args,
1614                     e);
1615             throw new Jbi4CorbaRuntimeException(
1616                     "CRB000720_Unable_to_create_exchange_from_factory", args, e);
1617         }
1618         return exchange;
1619     }
1620 
1621     /**
1622      * This method is called by the ESB after the message is sent.
1623      *
1624      * @param exchange
1625      *            The message exchange
1626      * @throws Exception
1627      *             The exception
1628      *
1629      * @see ConsumerExchangeProcessor.
1630      */
1631     public void process(javax.jbi.messaging.MessageExchange exchange)
1632             throws Exception {
1633         LOG.debug(">>>>> process - begin. MessageExchange=" + exchange);
1634 
1635         if (IN_ONLY.equals(exchange.getPattern())) { // IN ONLY
1636 
1637             processInOnly(exchange);
1638 
1639         } else if (IN_OUT.equals(exchange.getPattern())) { // IN OUT
1640 
1641             processInOut(exchange);
1642 
1643         } else { // UNSUPPORTED MEP
1644             Object[] args = new Object[]{exchange.getPattern(),
1645                 exchange.getStatus(), exchange.getExchangeId()};
1646             LOG.error("CRB000740_ConsumerUnsupportedMep", args);
1647             throw new Jbi4CorbaException("CRB000740_ConsumerUnsupportedMep",
1648                     args);
1649         }
1650 
1651         LOG.debug("<<<<< process - end");
1652     }
1653 
1654     /**
1655      * This method is called during the ExchanProcessor when the MEP is InOnly.
1656      *
1657      * @param exchange
1658      *            The MessageExchange.
1659      *
1660      * @throws Jbi4CorbaException
1661      *             If the ExchangeStatus is 'Active'.
1662      */
1663     protected void processInOnly(javax.jbi.messaging.MessageExchange exchange)
1664             throws Jbi4CorbaException {
1665 
1666         if (exchange.getStatus() == ExchangeStatus.DONE) {
1667 
1668             LOG.debug("PROCESS_OK[Pattern=InOnly; Status=Done]");
1669 
1670         } else if (exchange.getStatus() == ExchangeStatus.ERROR) {
1671 
1672             Object[] args = new Object[]{exchange.getExchangeId()};
1673             LOG.error("CRB000737_ExchangeProcessorConsumerInOnlyError", args);
1674 
1675         } else if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
1676 
1677             Object[] args = new Object[]{"Active", exchange.getExchangeId()};
1678             LOG.error(
1679                     "CRB000738_ExchangeProcessorConsumerInOnlyUnexpectedStatus",
1680                     args);
1681             throw new Jbi4CorbaException(
1682                     "CRB000738_ExchangeProcessorConsumerInOnlyUnexpectedStatus",
1683                     args);
1684         }
1685 
1686     }
1687 
1688     /**
1689      * This method is called during the ExchanProcessor when the MEP is InOut.
1690      *
1691      * @param exchange
1692      *            The MessageExchange.
1693      *
1694      * @throws Jbi4CorbaException
1695      *             Always, because this MEP shoud not call the process.
1696      */
1697     protected void processInOut(javax.jbi.messaging.MessageExchange exchange)
1698             throws Jbi4CorbaException {
1699 
1700         Object[] args = new Object[]{exchange.getStatus(),
1701             exchange.getExchangeId()};
1702         LOG.error("CRB000739_UnexpectedExchangeProcessorForConsumerInOutMep",
1703                 args);
1704         throw new Jbi4CorbaException(
1705                 "CRB000739_UnexpectedExchangeProcessorForConsumerInOutMep",
1706                 args);
1707     }
1708 
1709     /**
1710      * Converts the message to an input stream.
1711      *
1712      * @param src
1713      * @return
1714      * @throws IOException
1715      * @throws TransformerConfigurationException
1716      * @throws TransformerException
1717      */
1718     private static InputStream convertMessageToInputStream(Source src)
1719             throws IOException, TransformerConfigurationException,
1720             TransformerException {
1721 
1722         final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
1723 
1724         ByteArrayOutputStream baos = new ByteArrayOutputStream();
1725         StreamResult result = new StreamResult(baos);
1726         transformer.transform(src, result);
1727 
1728         return new ByteArrayInputStream(baos.toByteArray());
1729     }
1730 }