List of usage examples for javax.xml.bind JAXBContext createUnmarshaller
public abstract Unmarshaller createUnmarshaller() throws JAXBException;
From source file:org.jasig.portlet.data.Importer.java
public static void main(String[] args) throws Exception { String dir = args[0];//from w w w .j a va2s .co m String importExportContext = args[1]; String sessionFactoryBeanName = args[2]; String modelClassName = args[3]; String serviceBeanName = args[4]; String serviceBeanMethodName = args[5]; ApplicationContext context = PortletApplicationContextLocator.getApplicationContext(importExportContext); SessionFactory sessionFactory = context.getBean(sessionFactoryBeanName, SessionFactory.class); Class<?> modelClass = Class.forName(modelClassName); Object service = context.getBean(serviceBeanName); JAXBContext jc = JAXBContext.newInstance(modelClass); File folder = new File(dir); File[] files = folder.listFiles(new ImportFileFilter()); for (File f : files) { StreamSource xml = new StreamSource(f.getAbsoluteFile()); Unmarshaller unmarshaller = jc.createUnmarshaller(); JAXBElement je1 = unmarshaller.unmarshal(xml, modelClass); Object object = je1.getValue(); Session session = sessionFactory.getCurrentSession(); Transaction transaction = session.beginTransaction(); Method method = service.getClass().getMethod(serviceBeanMethodName, modelClass); method.invoke(service, object); transaction.commit(); } }
From source file:eu.impact_project.iif.tw.cli.ToolWrapper.java
/** * Main method of the command line application * * @param args/*from w ww. j ava 2 s. c o m*/ * Arguments of the command line application * @throws GeneratorException * Exception if project generation fails */ public static void main(String[] args) throws GeneratorException { CommandLineParser cmdParser = new PosixParser(); try { // Parse the command line arguments CommandLine cmd = cmdParser.parse(OPTIONS, args); // If no args or help selected if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) { // OK help needed HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true); if (args.length == 0) logger.info("Reading default configuration files from working " + "directory ..."); else System.exit(0); } String toolspecPath = cmd.getOptionValue(TOOLSPEC_OPT, Constants.DEFAULT_TOOLSPEC); File toolspecFile = new File(toolspecPath); String propertiesPath = cmd.getOptionValue(PROPERTIES_OPT, Constants.DEFAULT_PROJECT_PROPERTIES); File propertiesFile = new File(propertiesPath); ioc.setXmlConf(toolspecFile); ioc.setProjConf(propertiesFile); } catch (ParseException excep) { // Problem parsing the command line args, just print the message and help logger.error("Problem parsing command line arguments.", excep); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true); System.exit(1); } if (!ioc.hasConfig()) { throw new GeneratorException("No configuration available."); } JAXBContext context; try { context = JAXBContext.newInstance("eu.impact_project.iif.tw.toolspec"); Unmarshaller unmarshaller = context.createUnmarshaller(); Toolspec toolspec = (Toolspec) unmarshaller.unmarshal(new File(ioc.getXmlConf())); // general tool specification properties logger.info("Toolspec model: " + toolspec.getModel()); logger.info("Tool id: " + toolspec.getId()); logger.info("Tool name: " + toolspec.getName()); logger.info("Tool version: " + toolspec.getVersion()); // List of services for the tool List<Service> services = toolspec.getServices().getService(); // For each service a different maven project will be generated for (Service service : services) { createService(service, toolspec.getVersion()); } } catch (IOException ex) { logger.error("An IOException occurred", ex); } catch (JAXBException ex) { logger.error("JAXBException", ex); throw new GeneratorException("Unable to create XML binding for toolspec"); } }
From source file:com.cws.esolutions.core.main.EmailUtility.java
public static final void main(final String[] args) { final String methodName = EmailUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {/*from w ww . jav a 2 s. c o m*/ DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", (Object) args); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(EmailUtility.CNAME, options, true); return; } try { CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); URL xmlURL = null; JAXBContext context = null; Unmarshaller marshaller = null; CoreConfigurationData configData = null; xmlURL = FileUtils.getFile(commandLine.getOptionValue("config")).toURI().toURL(); context = JAXBContext.newInstance(CoreConfigurationData.class); marshaller = context.createUnmarshaller(); configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL); EmailMessage message = new EmailMessage(); message.setMessageTo(new ArrayList<String>(Arrays.asList(commandLine.getOptionValues("to")))); message.setMessageSubject(commandLine.getOptionValue("subject")); message.setMessageBody((String) commandLine.getArgList().get(0)); message.setEmailAddr((StringUtils.isNotEmpty(commandLine.getOptionValue("from"))) ? new ArrayList<String>(Arrays.asList(commandLine.getOptionValue("from"))) : new ArrayList<String>(Arrays.asList(configData.getMailConfig().getMailFrom()))); if (DEBUG) { DEBUGGER.debug("EmailMessage: {}", message); } try { EmailUtils.sendEmailMessage(configData.getMailConfig(), message, false); } catch (MessagingException mx) { System.err.println( "An error occurred while sending the requested message. Exception: " + mx.getMessage()); } } catch (ParseException px) { px.printStackTrace(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(EmailUtility.CNAME, options, true); } catch (MalformedURLException mx) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(EmailUtility.CNAME, options, true); } catch (JAXBException jx) { jx.printStackTrace(); System.err.println("An error occurred while loading the provided configuration file. Cannot continue."); } }
From source file:Main.java
public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(User.class); XMLInputFactory xif = XMLInputFactory.newInstance(); FileInputStream fis = new FileInputStream("input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(fis); xsr.nextTag();/*from ww w . j a v a 2s . c o m*/ String noNamespaceSchemaLocation = xsr.getAttributeValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "noNamespaceSchemaLocation"); System.out.println(noNamespaceSchemaLocation); Unmarshaller um = context.createUnmarshaller(); User response = (User) um.unmarshal(xsr); }
From source file:com.l2jserver.model.template.SkillTemplateConverter.java
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException { Class.forName("com.mysql.jdbc.Driver"); final File target = new File("data/templates"); final JAXBContext c = JAXBContext.newInstance(SkillTemplate.class, LegacySkillList.class); final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD); System.out.println("Generating template XML files..."); c.generateSchema(new SchemaOutputResolver() { @Override//from w w w.j a v a 2s.c om public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { return new StreamResult(new File(target, suggestedFileName)); } }); try { final Unmarshaller u = c.createUnmarshaller(); final Marshaller m = c.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "skill"); m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "skill ../skill.xsd"); Collection<File> files = FileUtils.listFiles(new File(LEGACY_SKILL_FOLDER), new String[] { "xml" }, true); for (final File legacyFile : files) { LegacySkillList list = (LegacySkillList) u.unmarshal(legacyFile); for (final LegacySkill legacySkill : list.skills) { SkillTemplate t = fillSkill(legacySkill); final File file = new File(target, "skill/" + t.id.getID() + (t.getName() != null ? "-" + camelCase(t.getName()) : "") + ".xml"); templates.add(t); try { m.marshal(t, getXMLSerializer(new FileOutputStream(file))); } catch (MarshalException e) { System.err.println( "Could not generate XML template file for " + t.getName() + " - " + t.getID()); file.delete(); } } } System.out.println("Generated " + templates.size() + " templates"); System.gc(); System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory())); System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory())); System.out.println("Used: " + FileUtils.byteCountToDisplaySize( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory())); } finally { conn.close(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { List<Element> elementList = new ArrayList<Element>(); List<Item> itemList = new ArrayList<Item>(); Element element1 = new Element(); Element element2 = new Element(); Item item1 = new Item(); Item item2 = new Item(); Elements elements = new Elements(); item1.setId(1);/*from w w w. j a v a 2 s .c om*/ item1.setName("Test1"); item2.setId(2); item2.setName("Test2"); itemList.add(item1); itemList.add(item2); element1.setProperty1("prop1"); element1.setProperty2("prop2"); element1.setType(2); element1.setItems(itemList); element2.setProperty1("prop11"); element2.setProperty2("prop22"); element2.setType(22); element2.setItems(itemList); elementList.add(element1); elementList.add(element2); elements.setElements(elementList); System.out.println("------- Object to XML -----------\n"); JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(elements, System.out); System.out.println("\n------- XML to Object -----------\n"); String xml = "<elements><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop1</property1><property2>prop2</property2><type>2</type></element><element><items><item><id>1</id><name>Test1</name></item><item><id>2</id><name>Test2</name></item></items><property1>prop11</property1><property2>prop22</property2><type>22</type></element></elements>"; StringReader reader = new StringReader(xml); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Elements elementsOut = (Elements) jaxbUnmarshaller.unmarshal(reader); System.out.println(elementsOut); }
From source file:Main.java
public static Unmarshaller getUnmarshaller(Class jaxbClass) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(jaxbClass); return jaxbContext.createUnmarshaller(); }
From source file:Main.java
public static <T> T reload(InputStream is, Class<?>... clazz) throws JAXBException { //Create JAXB Context JAXBContext jc = JAXBContext.newInstance(clazz); Unmarshaller um = jc.createUnmarshaller(); return (T) um.unmarshal(is); }
From source file:Main.java
public static Object xmlToObject(Class clazz, String xml) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller um = context.createUnmarshaller(); return um.unmarshal(new StringReader(xml)); }
From source file:Main.java
public static <T> T loadXML(Class<T> type, File sourceFile) { try {/*from w w w . j a v a 2s. c o m*/ JAXBContext context = JAXBContext.newInstance(type); return (T) context.createUnmarshaller().unmarshal(sourceFile); } catch (JAXBException e) { throw new RuntimeException(e); } }