Advertisement
sombriks

UtilXml.java

Mar 24th, 2014
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.88 KB | None | 0 0
  1. package br.com.atl.passepartout;
  2.  
  3. import java.nio.file.Path;
  4. import java.nio.file.Paths;
  5. import java.sql.Date;
  6.  
  7. import javax.xml.bind.JAXBContext;
  8. import javax.xml.bind.JAXBException;
  9. import javax.xml.bind.Marshaller;
  10. import javax.xml.bind.PropertyException;
  11. import javax.xml.bind.Unmarshaller;
  12.  
  13. public class UtilXml {
  14.    
  15. //  private static final Logger LOG = Logger.getAnonymousLogger();
  16.  
  17.     private static final String PATH = //
  18.     Paths.get(System.getProperty("user.home"), "passepartout").toString();
  19.  
  20.     public static Object load(Class<?> cls) throws Exception {
  21.         String fname = cls.getSimpleName() + ".xml";
  22.         return load(cls, fname);
  23.     }
  24.  
  25.     public static Object load(Class<?> cls, Date d) throws Exception {
  26.         String fname = d.toString() + "-" + cls.getSimpleName() + ".xml";
  27.         return load(cls, fname);
  28.     }
  29.  
  30.     private static Object load(Class<?> cls, String fname) throws Exception {
  31.         Path p = Paths.get(PATH, fname);
  32.         if (!p.toFile().exists()) {
  33.             p.toFile().getParentFile().mkdirs();
  34.             p.toFile().createNewFile();
  35.             Object o = cls.newInstance();
  36.             save(cls, o, fname);
  37.         }
  38.         JAXBContext ctx = JAXBContext.newInstance(cls);
  39.         Unmarshaller u = ctx.createUnmarshaller();
  40.         Object o = u.unmarshal(p.toFile());
  41.         return o;
  42.     }
  43.  
  44.     public static void save(Class<?> cls, Object o) throws Exception {
  45.         String fname = cls.getSimpleName() + ".xml";
  46.         save(cls, o, fname);
  47.     }
  48.  
  49.     public static void save(Class<?> cls, Object o, Date d) throws Exception {
  50.         String fname = d.toString() + "-" + cls.getSimpleName() + ".xml";
  51.         save(cls, o, fname);
  52.     }
  53.  
  54.     private static void save(Class<?> cls, Object o, String fname)
  55.             throws JAXBException, PropertyException {
  56.         JAXBContext ctx = JAXBContext.newInstance(cls);
  57.         Marshaller m = ctx.createMarshaller();
  58.         m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  59.         Path p = Paths.get(PATH, fname);
  60.         m.marshal(o, p.toFile());
  61.     }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement