View Javadoc

1   /*
2    * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
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 org.opensaml.xml.util;
18  
19  import org.opensaml.xml.Configuration;
20  import org.opensaml.xml.XMLObject;
21  import org.opensaml.xml.io.Marshaller;
22  import org.opensaml.xml.io.MarshallingException;
23  import org.opensaml.xml.io.Unmarshaller;
24  import org.opensaml.xml.io.UnmarshallingException;
25  import org.w3c.dom.Element;
26  
27  
28  /**
29   * A helper class for working with XMLObjects.
30   */
31  public final class XMLObjectHelper {
32  
33      /** Constructor. */
34      private XMLObjectHelper() { }
35      
36      /**
37       * Clone an XMLObject by brute force:
38       * 
39       * 1) Marshall the original object if necessary
40       * 2) Clone the resulting DOM Element
41       * 3) Unmarshall a new XMLObject tree around it.
42       * 
43       * @param originalXMLObject the object to be cloned
44       * @return a clone of the original object
45       * 
46       * @throws MarshallingException if original object can not be marshalled
47       * @throws UnmarshallingException if cloned object tree can not be unmarshalled
48       * 
49       * @param <T> the type of object being cloned
50       */
51      public static <T extends XMLObject> T cloneXMLObject(T originalXMLObject)
52              throws MarshallingException, UnmarshallingException {
53          
54          if (originalXMLObject == null) {
55              return null;
56          }
57          
58          Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(originalXMLObject);
59          Element origElement = marshaller.marshall(originalXMLObject);
60          
61          Element clonedElement = (Element) origElement.cloneNode(true);
62          
63          Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(clonedElement);
64          T clonedXMLObject = (T) unmarshaller.unmarshall(clonedElement);
65          
66          return clonedXMLObject;
67      }
68      
69  }