KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > mx4j > tools > adaptor > http > DefaultProcessor


1 /*
2  * Copyright (C) The MX4J Contributors.
3  * All rights reserved.
4  *
5  * This software is distributed under the terms of the MX4J License version 1.0.
6  * See the terms of the MX4J License in the documentation provided with this software.
7  */

8
9 package mx4j.tools.adaptor.http;
10
11 import java.io.ByteArrayOutputStream JavaDoc;
12 import java.io.IOException JavaDoc;
13 import java.io.PrintWriter JavaDoc;
14 import java.util.Arrays JavaDoc;
15 import java.util.Comparator JavaDoc;
16
17 import mx4j.log.Log;
18 import mx4j.log.Logger;
19 import org.w3c.dom.Attr JavaDoc;
20 import org.w3c.dom.Document JavaDoc;
21 import org.w3c.dom.NamedNodeMap JavaDoc;
22 import org.w3c.dom.Node JavaDoc;
23 import org.w3c.dom.NodeList JavaDoc;
24
25 /**
26  * DefaultPostProcessor doesn't alter the result, just publising the xml file
27  *
28  * @version $Revision: 1.4 $
29  */

30 public class DefaultProcessor implements ProcessorMBean
31 {
32    private final static String JavaDoc ENCODING = "UTF-8";
33
34    private boolean canonical = false;
35
36    public String JavaDoc getName()
37    {
38       return "Default XML Processor";
39    }
40
41    private Logger getLogger()
42    {
43       return Log.getLogger(getClass().getName());
44    }
45
46    public void writeResponse(HttpOutputStream out, HttpInputStream in, Document JavaDoc document)
47            throws IOException JavaDoc
48    {
49       out.setCode(HttpConstants.STATUS_OKAY);
50       out.setHeader("Content-Type", "text/xml");
51       out.sendHeaders();
52
53       print(new PrintWriter JavaDoc(out), document);
54
55       ByteArrayOutputStream JavaDoc o = new ByteArrayOutputStream JavaDoc();
56
57       print(new PrintWriter JavaDoc(o), document);
58
59       Logger logger = getLogger();
60       if (logger.isEnabledFor(Logger.DEBUG)) logger.debug(new String JavaDoc(o.toByteArray()));
61    }
62
63    public void writeError(HttpOutputStream out, HttpInputStream in, Exception JavaDoc e)
64            throws IOException JavaDoc
65    {
66       if (e instanceof HttpException)
67       {
68          out.setCode(((HttpException)e).getCode());
69          out.setHeader("Content-Type", "text/xml");
70          out.sendHeaders();
71          print(new PrintWriter JavaDoc(out), ((HttpException)e).getResponseDoc());
72       }
73    }
74
75    public String JavaDoc preProcess(String JavaDoc path)
76    {
77       // The only special case. The root is routed to the the server request
78
if (path.equals("/"))
79       {
80          path = "/server";
81       }
82       return path;
83    }
84
85    public String JavaDoc notFoundElement(String JavaDoc path, HttpOutputStream out, HttpInputStream in)
86            throws IOException JavaDoc, HttpException
87    {
88       // no processing. Unknown elements are not found
89
throw new HttpException(HttpConstants.STATUS_NOT_FOUND, "Path " + path + " not found");
90    }
91
92    // ripped from Xerces samples
93
protected void print(PrintWriter JavaDoc out, Node JavaDoc node)
94    {
95       // is there anything to do?
96
if (node == null) return;
97
98       int type = node.getNodeType();
99       switch (type)
100       {
101          // print document
102
case Node.DOCUMENT_NODE:
103             {
104                if (!canonical)
105                {
106                   out.println("<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?>");
107                }
108
109                NodeList JavaDoc children = node.getChildNodes();
110                for (int iChild = 0; iChild < children.getLength(); iChild++)
111                {
112                   print(out, children.item(iChild));
113                }
114                out.flush();
115                break;
116             }
117
118             // print element with attributes
119
case Node.ELEMENT_NODE:
120             {
121                out.print('<');
122                out.print(node.getNodeName());
123
124                Attr JavaDoc attrs[] = sortAttributes(node.getAttributes());
125                for (int i = 0; i < attrs.length; i++)
126                {
127                   Attr JavaDoc attr = attrs[i];
128                   out.print(' ');
129                   out.print(attr.getNodeName());
130                   out.print("=\"");
131                   out.print(normalize(attr.getNodeValue()));
132                   out.print('"');
133                }
134                out.print('>');
135
136                NodeList JavaDoc children = node.getChildNodes();
137                if (children != null)
138                {
139                   int len = children.getLength();
140                   for (int i = 0; i < len; i++)
141                   {
142                      print(out, children.item(i));
143                   }
144                }
145                break;
146             }
147
148             // handle entity reference nodes
149
case Node.ENTITY_REFERENCE_NODE:
150             {
151                if (canonical)
152                {
153                   NodeList JavaDoc children = node.getChildNodes();
154                   if (children != null)
155                   {
156                      int len = children.getLength();
157                      for (int i = 0; i < len; i++)
158                      {
159                         print(out, children.item(i));
160                      }
161                   }
162                }
163                else
164                {
165                   out.print('&');
166                   out.print(node.getNodeName());
167                   out.print(';');
168                }
169                break;
170             }
171
172             // print cdata sections
173
case Node.CDATA_SECTION_NODE:
174             {
175                if (canonical)
176                {
177                   out.print(normalize(node.getNodeValue()));
178                }
179                else
180                {
181                   out.print("<![CDATA[");
182                   out.print(node.getNodeValue());
183                   out.print("]]>");
184                }
185                break;
186             }
187
188             // print text
189
case Node.TEXT_NODE:
190             {
191                out.print(normalize(node.getNodeValue()));
192                break;
193             }
194
195             // print processing instruction
196
case Node.PROCESSING_INSTRUCTION_NODE:
197             {
198                out.print("<?");
199                out.print(node.getNodeName());
200                String JavaDoc data = node.getNodeValue();
201                if (data != null && data.length() > 0)
202                {
203                   out.print(' ');
204                   out.print(data);
205                }
206                out.println("?>");
207                break;
208             }
209       }
210
211       // Close the element
212
if (type == Node.ELEMENT_NODE)
213       {
214          out.print("</");
215          out.print(node.getNodeName());
216          out.print('>');
217       }
218
219       out.flush();
220    }
221
222    /**
223     * Returns a sorted list of attributes.
224     *
225     * @param attrs Description of Parameter
226     * @return Description of the Returned Value
227     */

228    protected Attr JavaDoc[] sortAttributes(NamedNodeMap JavaDoc attrs)
229    {
230       int len = (attrs != null) ? attrs.getLength() : 0;
231       Attr JavaDoc array[] = new Attr JavaDoc[len];
232       for (int i = 0; i < len; ++i) array[i] = (Attr JavaDoc)attrs.item(i);
233
234       Arrays.sort(array, new Comparator JavaDoc()
235       {
236          public int compare(Object JavaDoc o1, Object JavaDoc o2)
237          {
238             Attr JavaDoc attr1 = (Attr JavaDoc)o1;
239             Attr JavaDoc attr2 = (Attr JavaDoc)o2;
240             return attr1.getNodeName().compareTo(attr2.getNodeName());
241          }
242       });
243       return array;
244    }
245
246    /**
247     * Normalizes the given string.
248     *
249     * @param s Description of Parameter
250     * @return Description of the Returned Value
251     */

252    protected String JavaDoc normalize(String JavaDoc s)
253    {
254       StringBuffer JavaDoc str = new StringBuffer JavaDoc();
255
256       int len = (s != null) ? s.length() : 0;
257       for (int i = 0; i < len; i++)
258       {
259          char ch = s.charAt(i);
260          switch (ch)
261          {
262             case '<':
263                {
264                   str.append("&lt;");
265                   break;
266                }
267
268             case '>':
269                {
270                   str.append("&gt;");
271                   break;
272                }
273
274             case '&':
275                {
276                   str.append("&amp;");
277                   break;
278                }
279
280             case '"':
281                {
282                   str.append("&quot;");
283                   break;
284                }
285
286             case '\'':
287                {
288                   str.append("&apos;");
289                   break;
290                }
291
292             case '\r':
293             case '\n':
294                {
295                   if (canonical)
296                   {
297                      str.append("&#");
298                      str.append(Integer.toString(ch));
299                      str.append(';');
300                   }
301                   else
302                   {
303                      str.append(ch);
304                   }
305                   break;
306                }
307
308             default:
309                {
310                   str.append(ch);
311                }
312          }
313       }
314
315       return str.toString();
316    }
317 }
318
Popular Tags