Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package br.com.atl.passepartout;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.sql.Date;
- import javax.xml.bind.JAXBContext;
- import javax.xml.bind.JAXBException;
- import javax.xml.bind.Marshaller;
- import javax.xml.bind.PropertyException;
- import javax.xml.bind.Unmarshaller;
- public class UtilXml {
- // private static final Logger LOG = Logger.getAnonymousLogger();
- private static final String PATH = //
- Paths.get(System.getProperty("user.home"), "passepartout").toString();
- public static Object load(Class<?> cls) throws Exception {
- String fname = cls.getSimpleName() + ".xml";
- return load(cls, fname);
- }
- public static Object load(Class<?> cls, Date d) throws Exception {
- String fname = d.toString() + "-" + cls.getSimpleName() + ".xml";
- return load(cls, fname);
- }
- private static Object load(Class<?> cls, String fname) throws Exception {
- Path p = Paths.get(PATH, fname);
- if (!p.toFile().exists()) {
- p.toFile().getParentFile().mkdirs();
- p.toFile().createNewFile();
- Object o = cls.newInstance();
- save(cls, o, fname);
- }
- JAXBContext ctx = JAXBContext.newInstance(cls);
- Unmarshaller u = ctx.createUnmarshaller();
- Object o = u.unmarshal(p.toFile());
- return o;
- }
- public static void save(Class<?> cls, Object o) throws Exception {
- String fname = cls.getSimpleName() + ".xml";
- save(cls, o, fname);
- }
- public static void save(Class<?> cls, Object o, Date d) throws Exception {
- String fname = d.toString() + "-" + cls.getSimpleName() + ".xml";
- save(cls, o, fname);
- }
- private static void save(Class<?> cls, Object o, String fname)
- throws JAXBException, PropertyException {
- JAXBContext ctx = JAXBContext.newInstance(cls);
- Marshaller m = ctx.createMarshaller();
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- Path p = Paths.get(PATH, fname);
- m.marshal(o, p.toFile());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement