View Javadoc
1   /**
2    * Copyright 2010-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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  package org.kuali.common.util;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.io.Writer;
22  
23  import javax.xml.bind.JAXBContext;
24  import javax.xml.bind.JAXBException;
25  import javax.xml.bind.Marshaller;
26  import javax.xml.bind.Unmarshaller;
27  
28  import org.apache.commons.io.IOUtils;
29  
30  /**
31   * @deprecated
32   */
33  @Deprecated
34  public class JAXBUtil {
35  
36  	public static void write(Object instance, File file) {
37  		Writer writer = null;
38  		try {
39  			writer = LocationUtils.openWriter(file);
40  			write(instance, writer);
41  		} catch (IOException e) {
42  			throw new IllegalStateException("Unexpected IO error", e);
43  		} finally {
44  			IOUtils.closeQuietly(writer);
45  		}
46  	}
47  
48  	public static void write(Object instance, Writer writer) {
49  		try {
50  			JAXBContext context = JAXBContext.newInstance(instance.getClass());
51  			Marshaller marshaller = context.createMarshaller();
52  			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
53  			marshaller.marshal(instance, writer);
54  		} catch (JAXBException e) {
55  			throw new IllegalStateException("Unexpected JAXB error", e);
56  		}
57  	}
58  
59  	@SuppressWarnings("unchecked")
60  	public static <T> T getObject(InputStream in, Class<T> type) {
61  		try {
62  			JAXBContext context = JAXBContext.newInstance(type);
63  			Unmarshaller unmarshaller = context.createUnmarshaller();
64  			return (T) unmarshaller.unmarshal(in);
65  		} catch (JAXBException e) {
66  			throw new IllegalStateException("Unexpected JAXB error", e);
67  		}
68  	}
69  
70  	public static <T> T getObject(File file, Class<T> type) {
71  		return getObject(LocationUtils.getCanonicalPath(file), type);
72  	}
73  
74  	public static <T> T getObject(String location, Class<T> type) {
75  		InputStream in = null;
76  		try {
77  			in = LocationUtils.getInputStream(location);
78  			return getObject(in, type);
79  		} catch (IOException e) {
80  			throw new IllegalStateException("Unexpected JAXB error", e);
81  		} finally {
82  			IOUtils.closeQuietly(in);
83  		}
84  	}
85  }