View Javadoc

1   /*
2    * The contents of this file are subject to the terms
3    * of the Common Development and Distribution License
4    * (the "License").  You may not use this file except
5    * in compliance with the License.
6    *
7    * You can obtain a copy of the license at
8    * https://open-esb.dev.java.net/public/CDDLv1.0.html.
9    * See the License for the specific language governing
10   * permissions and limitations under the License.
11   *
12   * When distributing Covered Code, include this CDDL
13   * HEADER in each file and include the License file at
14   * https://open-esb.dev.java.net/public/CDDLv1.0.html.
15   * If applicable add the following below this CDDL HEADER,
16   * with the fields enclosed by brackets "[]" replaced with
17   * your own identifying information: Portions Copyright
18   * [year] [name of copyright owner]
19   */
20  
21  /*
22   * Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
23   */
24  
25  /*
26   * RuntimeHelper.java
27   *
28   */
29  
30  package it.imolinfo.jbi4ejb.jbi.component.runtime;
31  
32  //import it.imolinfo.jbi4ejb.Logger;
33  //import it.imolinfo.jbi4ejb.LoggerFactory;
34  //import it.imolinfo.jbi4ejb.jbi.Messages;
35  
36  import java.io.BufferedReader;
37  import java.io.IOException;
38  import java.io.InputStream;
39  import java.io.InputStreamReader;
40  import java.io.PrintWriter;
41  import java.io.Reader;
42  import java.io.StringReader;
43  import java.io.StringWriter;
44  import java.util.logging.Level;
45  
46  import java.util.logging.Logger;
47  import javax.jbi.component.ComponentContext;
48  import javax.jbi.messaging.DeliveryChannel;
49  import javax.jbi.messaging.InOut;
50  import javax.jbi.messaging.MessageExchangeFactory;
51  import javax.jbi.messaging.MessagingException;
52  import javax.jbi.messaging.NormalizedMessage;
53  import javax.jbi.servicedesc.ServiceEndpoint;
54  import javax.xml.namespace.QName;
55  import javax.xml.parsers.DocumentBuilder;
56  import javax.xml.parsers.DocumentBuilderFactory;
57  import javax.xml.transform.OutputKeys;
58  import javax.xml.transform.Source;
59  import javax.xml.transform.Transformer;
60  import javax.xml.transform.TransformerConfigurationException;
61  import javax.xml.transform.TransformerException;
62  import javax.xml.transform.TransformerFactory;
63  import javax.xml.transform.dom.DOMSource;
64  import javax.xml.transform.sax.SAXSource;
65  import javax.xml.transform.stream.StreamResult;
66  import org.w3c.dom.Document;
67  import org.xml.sax.EntityResolver;
68  import org.xml.sax.InputSource;
69  import org.xml.sax.SAXException;
70  import org.xml.sax.SAXParseException;
71  import org.xml.sax.helpers.DefaultHandler;
72  
73  /**
74   * Helper class that have easy accessors for the common functions in the component
75   * runtime.
76   *
77   * @author Sun Microsystems, Inc.
78   */
79  public final class RuntimeHelper {
80  	
81      public static Logger getLogger() {
82          return RuntimeContext.getInstance().getLogger();
83      }
84      
85      public static void logInfo(String msg) {
86          System.out.println(msg);
87          
88          getLogger().info(msg);
89      }
90  
91      public static void logVerbose(String msg) {
92          System.out.println(msg);
93          
94          getLogger().fine(msg);
95          //LOG.debug(msg);
96          
97      }
98      
99      public static void logWarning(Object logObj) {
100         System.out.println(logObj);
101         
102         if ( logObj instanceof Throwable) {
103             getLogger().log(Level.WARNING, ((Throwable)logObj).getMessage(), (Throwable)logObj);
104         } else {
105             getLogger().warning(logObj.toString());
106         }
107     }
108     
109     public static void logError(Object logObj) {
110         
111         System.out.println(logObj);
112         
113         if ( logObj instanceof Throwable) {
114             getLogger().log(Level.SEVERE, ((Throwable)logObj).getMessage(), (Throwable)logObj);
115         } else {
116             getLogger().severe(logObj.toString());
117         }
118     }
119     
120     public static void logDebug(Object logObj) {
121         
122         System.out.println(logObj);
123         
124         if ( logObj instanceof Throwable) {
125             getLogger().log(Level.FINER, ((Throwable)logObj).getMessage(), (Throwable)logObj);
126         } else {
127             getLogger().finer(logObj.toString());
128         }
129     }
130     
131     public static ComponentContext getComponentContext() {
132         return RuntimeContext.getInstance().getComponentContext();
133     }
134     
135     public static DeliveryChannel getDeliveryChannel() {
136         return RuntimeContext.getInstance().getDeliveryChannel();
137     }
138     
139     public static String getComponentName() {
140         return RuntimeContext.getInstance().getComponentName();
141     }
142     
143     /**
144      * helper method to find the active ServiceEndpiont for the service decribed with the
145      * serviceDescriptor. This method looks for the Active ServiceEndpoint using interface or
146      * servicename or service name and the endpointname.
147      */
148     public static ServiceEndpoint findServiceEndpoint(ServiceDescriptor serviceDescriptor) {
149         
150         QName serviceType = serviceDescriptor.getServiceType();
151         QName serviceName = serviceDescriptor.getServiceName();
152         String endpointName = serviceDescriptor.getEndpointName();
153         
154         ServiceEndpoint [] refs = null;
155         ServiceEndpoint serviceEndpoint = null;
156         
157         ComponentContext compContext = RuntimeHelper.getComponentContext();
158         
159         if ( compContext == null ) {
160             RuntimeHelper.logDebug("Component context is not yet initialized to Looking for ServiceEndpoint");
161             return null;
162         }
163         
164         // first, find the ServiceEndpoint using the abstract service ( serviceType - interface or portType )
165         // this way, consumer don't have to worry about who implemented the service.
166         // if ServiceEndpoint can not be found with abstract service, then search for it using
167         // service name or the service nam and the endpoint to look for specific implemenation.
168         
169         if ( serviceName != null && endpointName != null ) {
170             RuntimeHelper.logDebug(
171                 "Looking for ServiceEndpoint with service name and endpiont" +
172                 "ServiceName: " + serviceName +
173                 "EndpointName: " + endpointName);
174             serviceEndpoint =  compContext.getEndpoint(serviceName, endpointName);
175         }
176         
177         if ( serviceEndpoint == null && serviceName != null && endpointName == null) {
178             
179             RuntimeHelper.logDebug("Looking for ServiceEndpoint with service name " + serviceName);
180             refs = compContext.getEndpointsForService(serviceName);
181             if ( refs != null && refs.length > 0 ) {
182                 serviceEndpoint = refs[0];
183             }
184         }
185         
186         if ( serviceEndpoint == null && serviceType != null && serviceName == null && endpointName == null) {
187             RuntimeHelper.logDebug("Looking for ServiceEndpoint with service type " + serviceType);
188             refs = compContext.getEndpoints(serviceType);
189             if ( refs != null && refs.length > 0 ) {
190                 serviceEndpoint = refs[0];
191             }
192         }
193         
194         
195         
196         return serviceEndpoint;
197     }
198     /**
199      * this method creates a InOutMessageExchange Object and sets the required
200      * data on the MessageExchange object including the create and set the Normalized
201      * message object to hold the input message on the MessageExchange object.
202      */
203     public static InOut createInOutMessageExchange(QName operation, ServiceEndpoint serviceEndpoint)
204     throws MessagingException {
205         
206         InOut inOutME = null;
207         DeliveryChannel channel = RuntimeHelper.getDeliveryChannel();
208         
209         // create message exchange factory for the endpiont
210         MessageExchangeFactory factory =  channel.createExchangeFactory(serviceEndpoint);
211         
212         // create INOUT Message Exchange
213         inOutME = factory.createInOutExchange();
214         
215         inOutME.setOperation(operation);
216         
217         // create IN Nomralized Message
218         NormalizedMessage inMsg = inOutME.createMessage();
219         
220         // set IN Normalized message on message exchange
221         inOutME.setInMessage(inMsg);
222         
223         return inOutME;
224     }
225     
226     /**
227      * return the DOM Document
228      * @param xmlReader Reader
229      * @return dom document
230      * @throws Exception on parser exception or any other exception
231      */
232     public static Document buildDOMDocument(Reader xmlReader) throws Exception {
233         Document xmlDoc = null;
234         DocumentBuilderFactory docBuilderFactory =
235             DocumentBuilderFactory.newInstance();
236         docBuilderFactory.setValidating(false);
237         DocumentBuilder docBuilder =
238             docBuilderFactory.newDocumentBuilder();
239         docBuilder.setErrorHandler( new DefaultHandler() {
240             public void fatalError(SAXParseException e)
241             throws SAXException {
242                 throw new SAXException(e.getMessage());
243             }
244         });
245         
246         docBuilder.setEntityResolver(new EntityResolver() {
247             public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
248                 StringReader reader = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // NOI18N
249                 InputSource source = new InputSource(reader);
250                 source.setPublicId(publicId);
251                 source.setSystemId(systemId);
252                 return source;
253             }
254         });
255         
256         InputSource is = new InputSource(xmlReader);
257         xmlDoc = docBuilder.parse(is);
258         
259         return xmlDoc;
260     }
261     /**
262      * reads xml text from DOMSource to StringBuffer
263      */
264     public static StringBuffer readFromDOMSource(DOMSource domSource) {
265         
266         StringWriter writer = new StringWriter();
267         
268         TransformerFactory tFactory = TransformerFactory.newInstance();
269         Transformer trans = null;
270         try {
271             trans = tFactory.newTransformer();
272             trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
273                 "yes");
274             trans.setOutputProperty(OutputKeys.INDENT, "yes");
275             StreamResult result = new StreamResult(writer);
276             trans.transform(domSource, result);
277         } catch (TransformerConfigurationException ex) {
278             ex.printStackTrace();
279         } catch (TransformerException ex) {
280             ex.printStackTrace();
281         }
282         
283         return writer.getBuffer();
284     }
285     /**
286      * reads the xml text from InputSource into a StringBuffer
287      */
288     public  static StringBuffer readFromInputSource(InputSource inSource) {
289         
290         StringWriter writer = new StringWriter();
291         PrintWriter out = new PrintWriter(writer);
292         InputStream inStream = inSource.getByteStream();
293         Reader reader = inSource.getCharacterStream();
294         if ( reader == null ) {
295             reader = new InputStreamReader(inStream);
296         }
297         BufferedReader buff = new BufferedReader(reader);
298         try {
299             
300             for ( String line = null; (line = buff.readLine()) != null ; ) {
301                 out.println(line);
302             }
303         } catch (IOException ex) {
304             ex.printStackTrace();
305         }
306         
307         return writer.getBuffer();
308     }
309     /**
310      * reads xml from from DOM, SAX or Stream Source into a string buffer
311      */
312     public static StringBuffer readFromSource(Source source) {
313         if ( source instanceof DOMSource ) {
314             return readFromDOMSource((DOMSource)source);
315         } else {
316             InputSource inSource = SAXSource.sourceToInputSource(source);
317             if ( inSource != null ) {
318                 return readFromInputSource(inSource);
319             } else {
320                 return null;
321             }
322         }
323     }
324     /**
325      * creates a DOMSource from the xml text read from the reader.
326      */
327     public static DOMSource createDOMSource(Reader xmlReader) {
328         Document doc = null;
329         try {
330             doc = buildDOMDocument(xmlReader);
331         } catch (Exception ex) {
332             ex.printStackTrace();
333         }
334         return new DOMSource(doc);
335     }
336     /**
337      * converts the ex stracktrace to string.
338      */
339     public static StringBuffer getExceptionStackTrace(Exception ex) {
340         StringWriter strWriter = new StringWriter();
341         if ( ex != null ) {
342             PrintWriter out = new PrintWriter(strWriter);
343             ex.printStackTrace(out);
344         }
345         return strWriter.getBuffer();
346     }
347     /**
348      * may be used to set the exception as fault content.
349      */
350     public static String getExceptionAsXmlText(Exception ex) {
351         String message = ex.getMessage();
352         String stackTrace = getExceptionStackTrace(ex).toString();
353         String exXmlText =
354             "<exception>" +
355             "<message>" + message + "</message>" +
356             "<stack-trace>" + stackTrace + "</stack-trace>" +
357             "</exception>" ;
358         return exXmlText;
359     }
360     
361 }