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   /*
9   
10   * The contents of this file are subject to the terms
11  
12   * of the Common Development and Distribution License
13  
14   * (the "License").  You may not use this file except
15  
16   * in compliance with the License.
17  
18   *
19  
20   * You can obtain a copy of the license at
21  
22   * https://open-esb.dev.java.net/public/CDDLv1.0.html.
23  
24   * See the License for the specific language governing
25  
26   * permissions and limitations under the License.
27  
28   *
29  
30   * When distributing Covered Code, include this CDDL
31  
32   * HEADER in each file and include the License file at
33  
34   * https://open-esb.dev.java.net/public/CDDLv1.0.html.
35  
36   * If applicable add the following below this CDDL HEADER,
37  
38   * with the fields enclosed by brackets "[]" replaced with
39  
40   * your own identifying information: Portions Copyright
41  
42   * [year] [name of copyright owner]
43  
44   */
45  
46  
47  
48  /*
49  
50   * Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
51  
52   */
53  
54  
55  
56  /*
57  
58   * RuntimeHelper.java
59  
60   *
61  
62   */
63  
64  
65  package it.imolinfo.jbi4corba.jbi.component.runtime;
66  
67  import java.io.BufferedReader;
68  
69  import java.io.IOException;
70  
71  import java.io.InputStream;
72  
73  import java.io.InputStreamReader;
74  
75  import java.io.PrintWriter;
76  
77  import java.io.Reader;
78  
79  import java.io.StringReader;
80  
81  import java.io.StringWriter;
82  
83  import java.util.logging.Level;
84  
85  import java.util.logging.Logger;
86  
87  import javax.jbi.component.ComponentContext;
88  
89  import javax.jbi.messaging.DeliveryChannel;
90  
91  import javax.jbi.messaging.InOut;
92  
93  import javax.jbi.messaging.MessageExchangeFactory;
94  
95  import javax.jbi.messaging.MessagingException;
96  
97  import javax.jbi.messaging.NormalizedMessage;
98  
99  import javax.jbi.servicedesc.ServiceEndpoint;
100 
101 import javax.xml.namespace.QName;
102 
103 import javax.xml.parsers.DocumentBuilder;
104 
105 import javax.xml.parsers.DocumentBuilderFactory;
106 
107 import javax.xml.transform.OutputKeys;
108 
109 import javax.xml.transform.Source;
110 
111 import javax.xml.transform.Transformer;
112 
113 import javax.xml.transform.TransformerConfigurationException;
114 
115 import javax.xml.transform.TransformerException;
116 
117 import javax.xml.transform.TransformerFactory;
118 
119 import javax.xml.transform.dom.DOMSource;
120 
121 import javax.xml.transform.sax.SAXSource;
122 
123 import javax.xml.transform.stream.StreamResult;
124 
125 import org.w3c.dom.Document;
126 
127 import org.xml.sax.EntityResolver;
128 
129 import org.xml.sax.InputSource;
130 
131 import org.xml.sax.SAXException;
132 
133 import org.xml.sax.SAXParseException;
134 
135 import org.xml.sax.helpers.DefaultHandler;
136 
137 /**
138  * Helper class that have easy accessors for the common functions in the component
139  * runtime.
140  *
141  * @author <a href="mailto:mpiraccini@imolinfo.it">Marco Piraccini</a>
142  */
143 
144 public final class RuntimeHelper {
145 
146     
147 
148     public static Logger getLogger() {
149 
150         return RuntimeContext.getInstance().getLogger();
151 
152     }
153 
154     
155 
156     public static void logInfo(String msg) {
157 
158         //System.out.println(msg);
159 
160         getLogger().info(msg);
161 
162     }
163 
164     
165 
166     public static void logVerbose(String msg) {
167 
168         //System.out.println(msg);
169 
170         getLogger().fine(msg);
171 
172         
173 
174     }
175 
176     
177 
178     public static void logWarning(Object logObj) {
179 
180         //System.out.println(logObj);
181 
182         
183 
184         if ( logObj instanceof Throwable) {
185 
186             getLogger().log(Level.WARNING, ((Throwable)logObj).getMessage(), (Throwable)logObj);
187 
188         } else {
189 
190             getLogger().warning(logObj.toString());
191 
192         }
193 
194     }
195 
196     
197 
198     public static void logError(Object logObj) {
199 
200         
201 
202         //System.out.println(logObj);
203 
204         
205 
206         if ( logObj instanceof Throwable) {
207 
208             getLogger().log(Level.SEVERE, ((Throwable)logObj).getMessage(), (Throwable)logObj);
209 
210         } else {
211 
212             getLogger().severe(logObj.toString());
213 
214         }
215 
216     }
217 
218     
219 
220     public static void logDebug(Object logObj) {
221 
222         
223 
224         //System.out.println(logObj);
225 
226         
227 
228         if ( logObj instanceof Throwable) {
229 
230             getLogger().log(Level.FINER, ((Throwable)logObj).getMessage(), (Throwable)logObj);
231 
232         } else {
233 
234             getLogger().finer(logObj.toString());
235 
236         }
237 
238     }
239 
240     
241 
242     public static ComponentContext getComponentContext() {
243 
244         return RuntimeContext.getInstance().getComponentContext();
245 
246     }
247 
248     
249 
250     public static DeliveryChannel getDeliveryChannel() {
251 
252         return RuntimeContext.getInstance().getDeliveryChannel();
253 
254     }
255 
256     
257 
258     public static String getComponentName() {
259 
260         return RuntimeContext.getInstance().getComponentName();
261 
262     }
263 
264     
265 
266     /**
267 
268      * helper method to find the active ServiceEndpiont for the service decribed with the
269 
270      * serviceDescriptor. This method looks for the Active ServiceEndpoint using interface or
271 
272      * servicename or service name and the endpointname.
273 
274      */
275 
276     public static ServiceEndpoint findServiceEndpoint(ServiceDescriptor serviceDescriptor) {
277 
278         
279 
280         QName serviceType = serviceDescriptor.getServiceType();
281 
282         QName serviceName = serviceDescriptor.getServiceName();
283 
284         String endpointName = serviceDescriptor.getEndpointName();
285 
286         
287 
288         ServiceEndpoint [] refs = null;
289 
290         ServiceEndpoint serviceEndpoint = null;
291 
292         
293 
294         ComponentContext compContext = RuntimeHelper.getComponentContext();
295 
296         
297 
298         if ( compContext == null ) {
299 
300             RuntimeHelper.logDebug("Component context is not yet initialized to Looking for ServiceEndpoint");
301 
302             return null;
303 
304         }
305 
306         
307 
308         // first, find the ServiceEndpoint using the abstract service ( serviceType - interface or portType )
309 
310         // this way, consumer don't have to worry about who implemented the service.
311 
312         // if ServiceEndpoint can not be found with abstract service, then search for it using
313 
314         // service name or the service nam and the endpoint to look for specific implemenation.
315 
316         
317 
318         if ( serviceName != null && endpointName != null ) {
319 
320             RuntimeHelper.logDebug(
321 
322                 "Looking for ServiceEndpoint with service name and endpiont" +
323 
324                 "ServiceName: " + serviceName +
325 
326                 "EndpointName: " + endpointName);
327 
328             serviceEndpoint =  compContext.getEndpoint(serviceName, endpointName);
329 
330         }
331 
332         
333 
334         if ( serviceEndpoint == null && serviceName != null && endpointName == null) {
335 
336             
337 
338             RuntimeHelper.logDebug("Looking for ServiceEndpoint with service name " + serviceName);
339 
340             refs = compContext.getEndpointsForService(serviceName);
341 
342             if ( refs != null && refs.length > 0 ) {
343 
344                 serviceEndpoint = refs[0];
345 
346             }
347 
348         }
349 
350         
351 
352         if ( serviceEndpoint == null && serviceType != null && serviceName == null && endpointName == null) {
353 
354             RuntimeHelper.logDebug("Looking for ServiceEndpoint with service type " + serviceType);
355 
356             refs = compContext.getEndpoints(serviceType);
357 
358             if ( refs != null && refs.length > 0 ) {
359 
360                 serviceEndpoint = refs[0];
361 
362             }
363 
364         }
365 
366         
367 
368         
369 
370         
371 
372         return serviceEndpoint;
373 
374     }
375 
376     /**
377 
378      * this method creates a InOutMessageExchange Object and sets the required
379 
380      * data on the MessageExchange object including the create and set the Normalized
381 
382      * message object to hold the input message on the MessageExchange object.
383 
384      */
385 
386     public static InOut createInOutMessageExchange(QName operation, ServiceEndpoint serviceEndpoint)
387 
388     throws MessagingException {
389 
390         
391 
392         InOut inOutME = null;
393 
394         DeliveryChannel channel = RuntimeHelper.getDeliveryChannel();
395 
396         
397 
398         // create message exchange factory for the endpiont
399 
400         MessageExchangeFactory factory =  channel.createExchangeFactory(serviceEndpoint);
401 
402         
403 
404         // create INOUT Message Exchange
405 
406         inOutME = factory.createInOutExchange();
407 
408         
409 
410         inOutME.setOperation(operation);
411 
412         
413 
414         // create IN Nomralized Message
415 
416         NormalizedMessage inMsg = inOutME.createMessage();
417 
418         
419 
420         // set IN Normalized message on message exchange
421 
422         inOutME.setInMessage(inMsg);
423 
424         
425 
426         return inOutME;
427 
428     }
429 
430     
431 
432     /**
433 
434      * return the DOM Document
435 
436      * @param xmlReader Reader
437 
438      * @return dom document
439 
440      * @throws Exception on parser exception or any other exception
441 
442      */
443 
444     public static Document buildDOMDocument(Reader xmlReader) throws Exception {
445 
446         Document xmlDoc = null;
447 
448         DocumentBuilderFactory docBuilderFactory =
449 
450             DocumentBuilderFactory.newInstance();
451 
452         docBuilderFactory.setNamespaceAware(true);
453 
454         docBuilderFactory.setValidating(false);
455 
456         DocumentBuilder docBuilder =
457 
458             docBuilderFactory.newDocumentBuilder();
459 
460         docBuilder.setErrorHandler( new DefaultHandler() {
461 
462             public void fatalError(SAXParseException e)
463 
464             throws SAXException {
465 
466                 throw new SAXException(e.getMessage());
467 
468             }
469 
470         });
471 
472         
473 
474         docBuilder.setEntityResolver(new EntityResolver() {
475 
476             public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
477 
478                 StringReader reader = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // NOI18N
479 
480                 InputSource source = new InputSource(reader);
481 
482                 source.setPublicId(publicId);
483 
484                 source.setSystemId(systemId);
485 
486                 return source;
487 
488             }
489 
490         });
491 
492         
493 
494         InputSource is = new InputSource(xmlReader);
495 
496         xmlDoc = docBuilder.parse(is);
497 
498         
499 
500         return xmlDoc;
501 
502     }
503 
504     /**
505 
506      * reads xml text from DOMSource to StringBuffer
507 
508      */
509 
510     public static StringBuffer readFromDOMSource(DOMSource domSource) {
511 
512         
513 
514         StringWriter writer = new StringWriter();
515 
516         
517 
518         TransformerFactory tFactory = TransformerFactory.newInstance();
519 
520         Transformer trans = null;
521 
522         try {
523 
524             trans = tFactory.newTransformer();
525 
526             trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
527 
528                 "yes");
529 
530             trans.setOutputProperty(OutputKeys.INDENT, "yes");
531 
532             StreamResult result = new StreamResult(writer);
533 
534             trans.transform(domSource, result);
535 
536         } catch (TransformerConfigurationException ex) {
537 
538             ex.printStackTrace();
539 
540         } catch (TransformerException ex) {
541 
542             ex.printStackTrace();
543 
544         }
545 
546         
547 
548         return writer.getBuffer();
549 
550     }
551 
552     /**
553 
554      * reads the xml text from InputSource into a StringBuffer
555 
556      */
557 
558     public  static StringBuffer readFromInputSource(InputSource inSource) {
559 
560         
561 
562         StringWriter writer = new StringWriter();
563 
564         PrintWriter out = new PrintWriter(writer);
565 
566         InputStream inStream = inSource.getByteStream();
567 
568         Reader reader = inSource.getCharacterStream();
569 
570         if ( reader == null ) {
571 
572             reader = new InputStreamReader(inStream);
573 
574         }
575 
576         BufferedReader buff = new BufferedReader(reader);
577 
578         try {
579 
580             
581 
582             for ( String line = null; (line = buff.readLine()) != null ; ) {
583 
584                 out.println(line);
585 
586             }
587 
588         } catch (IOException ex) {
589 
590             ex.printStackTrace();
591 
592         }
593 
594         
595 
596         return writer.getBuffer();
597 
598     }
599 
600     /**
601 
602      * reads xml from from DOM, SAX or Stream Source into a string buffer
603 
604      */
605 
606     public static StringBuffer readFromSource(Source source) {
607 
608         if ( source instanceof DOMSource ) {
609 
610             return readFromDOMSource((DOMSource)source);
611 
612         } else {
613 
614             InputSource inSource = SAXSource.sourceToInputSource(source);
615 
616             if ( inSource != null ) {
617 
618                 return readFromInputSource(inSource);
619 
620             } else {
621 
622                 return null;
623 
624             }
625 
626         }
627 
628     }
629 
630     /**
631 
632      * creates a DOMSource from the xml text read from the reader.
633 
634      */
635 
636     public static DOMSource createDOMSource(Reader xmlReader) {
637 
638         Document doc = null;
639 
640         try {
641 
642             doc = buildDOMDocument(xmlReader);
643 
644         } catch (Exception ex) {
645 
646             ex.printStackTrace();
647 
648         }
649 
650         return new DOMSource(doc);
651 
652     }
653 
654     /**
655 
656      * converts the ex stracktrace to string.
657 
658      */
659 
660     public static StringBuffer getExceptionStackTrace(Exception ex) {
661 
662         StringWriter strWriter = new StringWriter();
663 
664         if ( ex != null ) {
665 
666             PrintWriter out = new PrintWriter(strWriter);
667 
668             ex.printStackTrace(out);
669 
670         }
671 
672         return strWriter.getBuffer();
673 
674     }
675 
676     /**
677 
678      * may be used to set the exception as fault content.
679 
680      */
681 
682     public static String getExceptionAsXmlText(Exception ex) {
683 
684         String message = ex.getMessage();
685 
686         String stackTrace = getExceptionStackTrace(ex).toString();
687 
688         String exXmlText =
689 
690             "<exception>" +
691 
692             "<message>" + message + "</message>" +
693 
694             "<stack-trace>" + stackTrace + "</stack-trace>" +
695 
696             "</exception>" ;
697 
698         return exXmlText;
699 
700     }
701 
702     
703 
704 }
705