View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  
22  package org.opencastproject.mediapackage;
23  
24  import static org.apache.commons.io.IOUtils.toInputStream;
25  
26  import org.opencastproject.util.XmlSafeParser;
27  import org.opencastproject.util.data.Function;
28  
29  import org.xml.sax.SAXException;
30  
31  import java.io.IOException;
32  import java.io.StringWriter;
33  import java.util.Collection;
34  import java.util.Iterator;
35  import java.util.LinkedList;
36  import java.util.List;
37  
38  import javax.xml.bind.JAXBException;
39  import javax.xml.bind.Marshaller;
40  import javax.xml.bind.Unmarshaller;
41  
42  /**
43   * Convenience implementation that supports serializing and deserializing media package elements.
44   */
45  public final class MediaPackageElementParser {
46  
47    /**
48     * Private constructor to prohibit instances of this static utility class.
49     */
50    private MediaPackageElementParser() {
51      // Nothing to do
52    }
53  
54    /**
55     * Serializes the media package element to a string.
56     *
57     * @param element
58     *         the element
59     * @return the serialized media package element
60     * @throws MediaPackageException
61     *         if serialization failed
62     */
63    public static String getAsXml(MediaPackageElement element) throws MediaPackageException {
64      if (element == null)
65        throw new IllegalArgumentException("Mediapackage element must not be null");
66      StringWriter writer = new StringWriter();
67      Marshaller m = null;
68      try {
69        m = MediaPackageImpl.context.createMarshaller();
70        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
71        m.marshal(element, writer);
72        return writer.toString();
73      } catch (JAXBException e) {
74        throw new MediaPackageException(e.getLinkedException() != null ? e.getLinkedException() : e);
75      }
76    }
77  
78    /** {@link #getAsXml(MediaPackageElement)} as function. */
79    public static <A extends MediaPackageElement> Function<A, String> getAsXml() {
80      return new Function.X<A, String>() {
81        @Override protected String xapply(MediaPackageElement elem) throws Exception {
82          return getAsXml(elem);
83        }
84      };
85    }
86  
87    /**
88     * Parses the serialized media package element and returns its object representation.
89     *
90     * @param xml
91     *         the serialized element
92     * @return the media package element instance
93     * @throws MediaPackageException
94     *         if de-serializing the element fails
95     */
96    public static MediaPackageElement getFromXml(String xml) throws MediaPackageException {
97      Unmarshaller m = null;
98      try {
99        m = MediaPackageImpl.context.createUnmarshaller();
100       return (MediaPackageElement) m.unmarshal(XmlSafeParser.parse(toInputStream(xml)));
101     } catch (JAXBException e) {
102       throw new MediaPackageException(e.getLinkedException() != null ? e.getLinkedException() : e);
103     } catch (IOException | SAXException e) {
104       throw new MediaPackageException(e);
105     }
106   }
107 
108   /**
109    * Serializes media package element list to a string.
110    *
111    * @param elements
112    *         element list to be serialized
113    * @return serialized media package element list
114    * @throws MediaPackageException
115    *         if serialization fails
116    */
117   public static String getArrayAsXml(Collection<? extends MediaPackageElement> elements) throws MediaPackageException {
118     // TODO write real serialization function
119     if (elements == null || elements.isEmpty()) return "";
120     try {
121       StringBuilder builder = new StringBuilder();
122       Iterator<? extends MediaPackageElement> it = elements.iterator();
123       builder.append(getAsXml(it.next()));
124       while (it.hasNext()) {
125         builder.append("###");
126         builder.append(getAsXml(it.next()));
127       }
128       return builder.toString();
129     } catch (Exception e) {
130       if (e instanceof MediaPackageException) {
131         throw (MediaPackageException) e;
132       } else {
133         throw new MediaPackageException(e);
134       }
135     }
136   }
137 
138   /**
139    * Parses the serialized media package element list.
140    *
141    * @param xml
142    *         String to be parsed
143    * @return parsed media package element list
144    * @throws MediaPackageException
145    *         if de-serialization fails
146    */
147   public static List<? extends MediaPackageElement> getArrayFromXml(String xml) throws MediaPackageException {
148     // TODO write real deserialization function
149     try {
150       List<MediaPackageElement> elements = new LinkedList<MediaPackageElement>();
151       String[] xmlArray = xml.split("###");
152       for (String xmlElement : xmlArray) {
153         if ("".equals(xmlElement.trim())) continue;
154         elements.add(getFromXml(xmlElement.trim()));
155       }
156       return elements;
157     } catch (Exception e) {
158       if (e instanceof MediaPackageException) {
159         throw (MediaPackageException) e;
160       } else {
161         throw new MediaPackageException(e);
162       }
163     }
164   }
165 
166   /**
167    * Same as getArrayFromXml(), but throwing a RuntimeException instead of a checked exception. Useful in streams.
168    *
169    * @param xml
170    *         String to be parsed
171    * @return parsed media package element list
172    *
173    * @throws MediaPackageRuntimeException
174    *         if de-serialization fails
175    */
176   public static List<? extends MediaPackageElement> getArrayFromXmlUnchecked(String xml) {
177     try {
178       return getArrayFromXml(xml);
179     } catch (MediaPackageException e) {
180       throw new MediaPackageRuntimeException(e);
181     }
182   }
183 
184 }