1
2
3
4
5
6
7 package org.mule.util;
8
9 import org.mule.api.MuleContext;
10 import org.mule.api.util.StreamCloser;
11 import org.mule.api.util.StreamCloserService;
12
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.util.Iterator;
16
17 import javax.xml.transform.sax.SAXSource;
18 import javax.xml.transform.stream.StreamSource;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.xml.sax.InputSource;
23
24
25
26
27
28 public class DefaultStreamCloserService implements StreamCloserService
29 {
30
31 private static final Log log = LogFactory.getLog(DefaultStreamCloserService.class);
32
33 private MuleContext muleContext;
34 private StreamCloser coreStreamTypesCloser = new CoreStreamTypesCloser();
35
36 public void closeStream(Object stream)
37 {
38 try
39 {
40 if (coreStreamTypesCloser.canClose(stream.getClass()))
41 {
42 coreStreamTypesCloser.close(stream);
43 }
44 else
45 {
46 Iterator closers = muleContext.getRegistry().lookupObjects(StreamCloser.class).iterator();
47 while (closers.hasNext())
48 {
49 StreamCloser closer = (StreamCloser) closers.next();
50 if (closer.canClose(stream.getClass()))
51 {
52 closer.close(stream);
53 }
54 else
55 {
56 log.debug("Unable to find an StreamCloser for the stream type: " + stream.getClass()
57 + ", the stream: " + stream + " will not be closed.");
58 }
59 }
60 }
61 }
62 catch (Exception e)
63 {
64 log.debug("Exception closing stream: " + stream, e);
65 }
66
67 }
68
69 public void setMuleContext(MuleContext context)
70 {
71 muleContext = context;
72 }
73
74 static class CoreStreamTypesCloser implements StreamCloser
75 {
76
77 public boolean canClose(Class streamType)
78 {
79 return InputStream.class.isAssignableFrom(streamType)
80 || InputSource.class.isAssignableFrom(streamType)
81 || StreamSource.class.isAssignableFrom(streamType)
82 || (SAXSource.class.isAssignableFrom(streamType) && !streamType.getName().endsWith(
83 "StaxSource"));
84 }
85
86 public void close(Object stream) throws IOException
87 {
88 if (stream instanceof InputStream)
89 {
90 try
91 {
92 ((InputStream) stream).close();
93 }
94 catch (IOException e)
95 {
96
97 }
98 }
99 else if (stream instanceof InputSource)
100 {
101 closeInputSourceStream((InputSource) stream);
102 }
103 else if (stream instanceof SAXSource)
104 {
105 closeInputSourceStream(((SAXSource) stream).getInputSource());
106 }
107 else if (stream instanceof StreamSource)
108 {
109 try
110 {
111 ((StreamSource) stream).getInputStream().close();
112 }
113 catch (IOException e)
114 {
115 }
116 }
117 }
118
119 private void closeInputSourceStream(InputSource payload) throws IOException
120 {
121 if (payload.getByteStream() != null)
122 {
123 payload.getByteStream().close();
124 }
125 else if (payload.getCharacterStream() != null)
126 {
127 payload.getCharacterStream().close();
128 }
129 }
130
131 }
132
133 }