1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jelly.tags.core;
17
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.UnsupportedEncodingException;
21
22 import org.apache.commons.jelly.JellyContext;
23 import org.apache.commons.jelly.JellyTagException;
24 import org.apache.commons.jelly.TagSupport;
25 import org.apache.commons.jelly.XMLOutput;
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28
29 /*** A tag that spawns the contained script in a separate thread
30 *
31 * @author <a href="mailto:vinayc@apache.org">Vinay Chandran</a>
32 */
33 public class ThreadTag extends TagSupport {
34 /*** Thread Name */
35 private String name = null;
36 /*** the destination of output */
37 private XMLOutput xmlOutput;
38 /*** Should we close the underlying output */
39 private boolean closeOutput;
40 /*** The Log to which logging calls will be made. */
41 private static final Log log = LogFactory.getLog(ThreadTag.class);
42
43 public ThreadTag() {
44 }
45
46
47
48 public void doTag(final XMLOutput output) throws JellyTagException {
49 if ( xmlOutput == null ) {
50
51 try {
52 xmlOutput = XMLOutput.createXMLOutput( System.out );
53 } catch (UnsupportedEncodingException e) {
54 throw new JellyTagException(e);
55 }
56 }
57
58
59 final JellyContext newContext = context.newJellyContext();
60
61 Thread thread = new Thread(
62 new Runnable() {
63 public void run() {
64 try {
65 getBody().run(newContext, xmlOutput);
66 if (closeOutput) {
67 xmlOutput.close();
68 }
69 else {
70 xmlOutput.flush();
71 }
72 }
73 catch (Exception e) {
74 if (log.isErrorEnabled()) log.error("error running thread tag", e);
75 }
76 }
77 }
78 );
79 if ( name != null ) {
80 thread.setName( name );
81 }
82 thread.start();
83 }
84
85 /***
86 * Sets the name of the thread.
87 * @param name The name to set
88 */
89 public void setName(String name) {
90 this.name = name;
91 }
92
93 /***
94 * Sets the destination of output
95 */
96 public void setXmlOutput(XMLOutput xmlOutput) {
97 this.closeOutput = false;
98 this.xmlOutput = xmlOutput;
99 }
100
101 /***
102 * Set the file which is generated from the output
103 * @param name The output file name
104 */
105 public void setFile(String name) throws IOException {
106 this.closeOutput = true;
107 setXmlOutput( XMLOutput.createXMLOutput(new FileOutputStream(name)) );
108 }
109 }