KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xml > internal > security > c14n > Canonicalizer


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */

17 package com.sun.org.apache.xml.internal.security.c14n;
18
19
20
21 import java.io.ByteArrayInputStream JavaDoc;
22 import java.io.OutputStream JavaDoc;
23 import java.util.HashMap JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Set JavaDoc;
26
27 import javax.xml.parsers.DocumentBuilder JavaDoc;
28 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
29
30 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
31 import org.w3c.dom.Document JavaDoc;
32 import org.w3c.dom.Node JavaDoc;
33 import org.w3c.dom.NodeList JavaDoc;
34 import org.xml.sax.InputSource JavaDoc;
35
36
37 /**
38  *
39  *
40  * @author Christian Geuer-Pollmann
41  */

42 public class Canonicalizer {
43
44    //J-
45
/** The output encoding of canonicalized data */
46    public static final String JavaDoc ENCODING = "UTF8";
47
48    
49    /**
50      * XPath Expresion for selecting every node and continuos comments joined in only one node
51      */

52     public static final String JavaDoc XPATH_C14N_WITH_COMMENTS_SINGLE_NODE = "(.//. | .//@* | .//namespace::*)";
53    
54
55    /**
56      * The URL defined in XML-SEC Rec for inclusive c14n <b>without</b> comments.
57      */

58    public static final String JavaDoc ALGO_ID_C14N_OMIT_COMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
59    /**
60     * The URL defined in XML-SEC Rec for inclusive c14n <b>with</b> comments.
61     */

62    public static final String JavaDoc ALGO_ID_C14N_WITH_COMMENTS = ALGO_ID_C14N_OMIT_COMMENTS + "#WithComments";
63    /**
64     * The URL defined in XML-SEC Rec for exclusive c14n <b>without</b> comments.
65     */

66    public static final String JavaDoc ALGO_ID_C14N_EXCL_OMIT_COMMENTS = "http://www.w3.org/2001/10/xml-exc-c14n#";
67    /**
68     * The URL defined in XML-SEC Rec for exclusive c14n <b>with</b> comments.
69     */

70    public static final String JavaDoc ALGO_ID_C14N_EXCL_WITH_COMMENTS = ALGO_ID_C14N_EXCL_OMIT_COMMENTS + "WithComments";
71
72    static boolean _alreadyInitialized = false;
73    static Map JavaDoc _canonicalizerHash = null;
74
75    protected CanonicalizerSpi canonicalizerSpi = null;
76    //J+
77

78    /**
79     * Method init
80     *
81     */

82    public static void init() {
83
84       if (!Canonicalizer._alreadyInitialized) {
85          Canonicalizer._canonicalizerHash = new HashMap JavaDoc(10);
86          Canonicalizer._alreadyInitialized = true;
87       }
88    }
89
90    /**
91     * Constructor Canonicalizer
92     *
93     * @param algorithmURI
94     * @throws InvalidCanonicalizerException
95     */

96    private Canonicalizer(String JavaDoc algorithmURI)
97            throws InvalidCanonicalizerException {
98
99       try {
100          Class JavaDoc implementingClass = getImplementingClass(algorithmURI);
101
102          this.canonicalizerSpi =
103             (CanonicalizerSpi) implementingClass.newInstance();
104          this.canonicalizerSpi.reset=true;
105       } catch (Exception JavaDoc e) {
106          Object JavaDoc exArgs[] = { algorithmURI };
107
108          throw new InvalidCanonicalizerException(
109             "signature.Canonicalizer.UnknownCanonicalizer", exArgs);
110       }
111    }
112
113    /**
114     * Method getInstance
115     *
116     * @param algorithmURI
117     * @return a Conicicalizer instance ready for the job
118     * @throws InvalidCanonicalizerException
119     */

120    public static final Canonicalizer getInstance(String JavaDoc algorithmURI)
121            throws InvalidCanonicalizerException {
122
123       Canonicalizer c14nizer = new Canonicalizer(algorithmURI);
124
125       return c14nizer;
126    }
127
128    /**
129     * Method register
130     *
131     * @param algorithmURI
132     * @param implementingClass
133     * @throws AlgorithmAlreadyRegisteredException
134     */

135    public static void register(String JavaDoc algorithmURI, String JavaDoc implementingClass)
136            throws AlgorithmAlreadyRegisteredException {
137
138       // check whether URI is already registered
139
Class JavaDoc registeredClass = getImplementingClass(algorithmURI);
140
141       if (registeredClass != null) {
142          Object JavaDoc exArgs[] = { algorithmURI, registeredClass };
143
144          throw new AlgorithmAlreadyRegisteredException(
145             "algorithm.alreadyRegistered", exArgs);
146       }
147
148       try {
149         _canonicalizerHash.put(algorithmURI, Class.forName(implementingClass));
150     } catch (ClassNotFoundException JavaDoc e) {
151         throw new RuntimeException JavaDoc("c14n class not found");
152     }
153    }
154
155    /**
156     * Method getURI
157     *
158     * @return the URI defined for this c14n instance.
159     */

160    public final String JavaDoc getURI() {
161       return this.canonicalizerSpi.engineGetURI();
162    }
163
164    /**
165     * Method getIncludeComments
166     *
167     * @return true if the c14n respect the comments.
168     */

169    public boolean getIncludeComments() {
170       return this.canonicalizerSpi.engineGetIncludeComments();
171    }
172
173    /**
174     * This method tries to canonicalize the given bytes. It's possible to even
175     * canonicalize non-wellformed sequences if they are well-formed after being
176     * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
177     *
178     * @param inputBytes
179     * @return the result of the conicalization.
180     * @throws CanonicalizationException
181     * @throws java.io.IOException
182     * @throws javax.xml.parsers.ParserConfigurationException
183     * @throws org.xml.sax.SAXException
184     */

185    public byte[] canonicalize(byte[] inputBytes)
186            throws javax.xml.parsers.ParserConfigurationException JavaDoc,
187                   java.io.IOException JavaDoc, org.xml.sax.SAXException JavaDoc,
188                   CanonicalizationException {
189
190       ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(inputBytes);
191       InputSource JavaDoc in = new InputSource JavaDoc(bais);
192       DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
193
194       dfactory.setNamespaceAware(true);
195
196       // needs to validate for ID attribute nomalization
197
dfactory.setValidating(true);
198
199       DocumentBuilder JavaDoc db = dfactory.newDocumentBuilder();
200
201       /*
202        * for some of the test vectors from the specification,
203        * there has to be a validatin parser for ID attributes, default
204        * attribute values, NMTOKENS, etc.
205        * Unfortunaltely, the test vectors do use different DTDs or
206        * even no DTD. So Xerces 1.3.1 fires many warnings about using
207        * ErrorHandlers.
208        *
209        * Text from the spec:
210        *
211        * The input octet stream MUST contain a well-formed XML document,
212        * but the input need not be validated. However, the attribute
213        * value normalization and entity reference resolution MUST be
214        * performed in accordance with the behaviors of a validating
215        * XML processor. As well, nodes for default attributes (declared
216        * in the ATTLIST with an AttValue but not specified) are created
217        * in each element. Thus, the declarations in the document type
218        * declaration are used to help create the canonical form, even
219        * though the document type declaration is not retained in the
220        * canonical form.
221        *
222        */

223       db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils
224
         .IgnoreAllErrorHandler());
225
226       Document JavaDoc document = db.parse(in);
227       byte result[] = this.canonicalizeSubtree(document);
228
229       return result;
230    }
231
232    /**
233     * Canonicalizes the subtree rooted by <CODE>node</CODE>.
234     *
235     * @param node The node to canicalize
236     * @return the result of the c14n.
237     *
238     * @throws CanonicalizationException
239     */

240    public byte[] canonicalizeSubtree(Node JavaDoc node)
241            throws CanonicalizationException {
242       return this.canonicalizerSpi.engineCanonicalizeSubTree(node);
243    }
244
245    /**
246     * Canonicalizes the subtree rooted by <CODE>node</CODE>.
247     *
248     * @param node
249     * @param inclusiveNamespaces
250     * @return the result of the c14n.
251     * @throws CanonicalizationException
252     */

253    public byte[] canonicalizeSubtree(Node JavaDoc node, String JavaDoc inclusiveNamespaces)
254            throws CanonicalizationException {
255       return this.canonicalizerSpi.engineCanonicalizeSubTree(node,
256               inclusiveNamespaces);
257    }
258
259    /**
260     * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
261     * as a list of XPath nodes, not as a list of subtrees.
262     *
263     * @param xpathNodeSet
264     * @return the result of the c14n.
265     * @throws CanonicalizationException
266     */

267    public byte[] canonicalizeXPathNodeSet(NodeList JavaDoc xpathNodeSet)
268            throws CanonicalizationException {
269       return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
270    }
271
272    /**
273     * Canonicalizes an XPath node set. The <CODE>xpathNodeSet</CODE> is treated
274     * as a list of XPath nodes, not as a list of subtrees.
275     *
276     * @param xpathNodeSet
277     * @param inclusiveNamespaces
278     * @return the result of the c14n.
279     * @throws CanonicalizationException
280     */

281    public byte[] canonicalizeXPathNodeSet(
282            NodeList JavaDoc xpathNodeSet, String JavaDoc inclusiveNamespaces)
283               throws CanonicalizationException {
284       return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
285               inclusiveNamespaces);
286    }
287
288    /**
289     * Canonicalizes an XPath node set.
290     *
291     * @param xpathNodeSet
292     * @return the result of the c14n.
293     * @throws CanonicalizationException
294     */

295    public byte[] canonicalizeXPathNodeSet(Set JavaDoc xpathNodeSet)
296            throws CanonicalizationException {
297        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
298    }
299
300    /**
301     * Canonicalizes an XPath node set.
302     *
303     * @param xpathNodeSet
304     * @param inclusiveNamespaces
305     * @return the result of the c14n.
306     * @throws CanonicalizationException
307     */

308    public byte[] canonicalizeXPathNodeSet(
309            Set JavaDoc xpathNodeSet, String JavaDoc inclusiveNamespaces)
310               throws CanonicalizationException {
311        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
312               inclusiveNamespaces);
313    }
314
315    /**
316     * Sets the writter where the cannocalization ends. ByteArrayOutputStream if
317     * none is setted.
318     * @param os
319     */

320    public void setWriter(OutputStream JavaDoc os) {
321         this.canonicalizerSpi.setWriter(os);
322    }
323
324    /**
325     * Returns the name of the implementing {@link CanonicalizerSpi} class
326     *
327     * @return the name of the implementing {@link CanonicalizerSpi} class
328     */

329    public String JavaDoc getImplementingCanonicalizerClass() {
330       return this.canonicalizerSpi.getClass().getName();
331    }
332
333    /**
334     * Method getImplementingClass
335     *
336     * @param URI
337     * @return the name of the class that implements the give URI
338     */

339    private static Class JavaDoc getImplementingClass(String JavaDoc URI) {
340       return (Class JavaDoc) _canonicalizerHash.get(URI);
341    }
342    
343    /**
344     * Set the canonicalizator behaviour to not reset.
345     *
346     */

347    public void notReset() {
348         this.canonicalizerSpi.reset=false;
349    }
350 }
351
Popular Tags