Example usage for javax.xml.bind JAXBContext createMarshaller

List of usage examples for javax.xml.bind JAXBContext createMarshaller

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext createMarshaller.

Prototype

public abstract Marshaller createMarshaller() throws JAXBException;

Source Link

Document

Create a Marshaller object that can be used to convert a java content tree into XML data.

Usage

From source file:JAXBTest.java

public static void main(String[] args) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
    Root root = new Root();

    Person fred = new Person();
    fred.setName("Fred");
    root.setFriend(Arrays.asList(fred));

    Thing xbox = new Thing();
    xbox.setDescription("Xbox 360");
    root.setStuff(Arrays.asList(xbox));

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(root, System.out);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Customer.class);

    Customer customer = new Customer();
    customer.setFirstName("Jane");
    customer.setLastName("Doe");

    PhoneNumber workPhone = new PhoneNumber();
    workPhone.setType("work");
    workPhone.setNumber("555-1111");
    customer.getPhoneNumbers().add(workPhone);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    JAXBElement<Customer> rootElement = new JAXBElement<Customer>(new QName("customer"), Customer.class,
            customer);/*w w w .j ava2 s  .c om*/
    marshaller.marshal(rootElement, System.out);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    // Create the JAXBContext
    JAXBContext jc = JAXBContext.newInstance(Main.class);

    // Create the Object
    Main foo = new Main();
    foo.setBar("Hello World");

    // Create the Document
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.newDocument();

    // Marshal the Object to a Document
    Marshaller marshaller = jc.createMarshaller();
    marshaller.marshal(foo, document);/*w  w  w.j a  v a 2 s .c  om*/

    // Output the Document
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(System.out);
    t.transform(source, result);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Foo.class);

    Foo foo = new Foo();
    List<Bar> bars = new ArrayList<Bar>();
    foo.setBars(bars);//from   ww  w . j av a  2  s.c  o m

    Bar<String> stringBar = new Bar<String>();
    stringBar.setValue("string data");
    bars.add(stringBar);

    Bar<byte[]> binaryBar = new Bar<byte[]>();
    binaryBar.setValue("binary data".getBytes());
    bars.add(binaryBar);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(foo, System.out);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Root.class);

    Root rootA = new Root();
    rootA.setName("A");

    Root rootB = new Root();
    rootB.setName("B");
    rootA.setChild(rootB);/*from  www  . j a  v a 2s.  c om*/

    Root rootC = new Root();
    rootC.setName("C");
    rootB.setChild(rootC);

    Root rootD = new Root();
    rootD.setName("D");
    rootC.setChild(rootD);

    Root rootE = new Root();
    rootE.setName("E");
    rootD.setChild(rootE);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    DepthListener depthListener = new DepthListener(3);
    marshaller.setListener(depthListener);
    marshaller.setAdapter(new RootAdapter(depthListener));
    marshaller.marshal(rootA, System.out);
}

From source file:edu.duke.cabig.c3pr.webservice.helpers.WebServiceRelatedTestCase.java

public static void main(String[] args) throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(StudyProtocolVersion.class, CD.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    final StudyProtocolVersion study = new StudyUtilityImplTest().createStudy();
    JAXBElement<StudyProtocolVersion> jaxbElement = new JAXBElement<StudyProtocolVersion>(
            new QName("http://enterpriseservices.nci.nih.gov/Common", "study"), StudyProtocolVersion.class,
            study);/*from  w w  w .  j a  v a 2s. co m*/
    m.marshal(jaxbElement, System.out);
}

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//  w w  w .  j  a v a2 s .com
        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:com.l2jserver.model.template.NPCTemplateConverter.java

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
    controllers.put("L2Teleporter", TeleporterController.class);
    controllers.put("L2CastleTeleporter", TeleporterController.class);
    controllers.put("L2Npc", BaseNPCController.class);
    controllers.put("L2Monster", MonsterController.class);
    controllers.put("L2FlyMonster", MonsterController.class);
    Class.forName("com.mysql.jdbc.Driver");

    final File target = new File("generated/template/npc");

    System.out.println("Scaning legacy HTML files...");
    htmlScannedFiles = FileUtils.listFiles(L2J_HTML_FOLDER, new String[] { "html", "htm" }, true);

    final JAXBContext c = JAXBContext.newInstance(NPCTemplate.class, Teleports.class);

    final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
    {/*from ww  w .  ja  v a 2  s  .  c  om*/
        System.out.println("Converting teleport templates...");
        teleportation.teleport = CollectionFactory.newList();

        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement("SELECT * FROM teleport");
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            final TeleportationTemplate template = new TeleportationTemplate();

            template.id = new TeleportationTemplateID(rs.getInt("id"), null);
            template.name = rs.getString("Description");
            TemplateCoordinate coord = new TemplateCoordinate();
            coord.x = rs.getInt("loc_x");
            coord.y = rs.getInt("loc_y");
            coord.z = rs.getInt("loc_z");
            template.point = coord;
            template.price = rs.getInt("price");
            template.item = rs.getInt("itemId");
            if (rs.getBoolean("fornoble")) {
                template.restrictions = new Restrictions();
                template.restrictions.restriction = Arrays.asList("NOBLE");
            }
            teleportation.teleport.add(template);
        }
        m.marshal(teleportation, getXMLSerializer(new FileOutputStream(new File(target, "../teleports.xml"))));
        // System.exit(0);
    }

    System.out.println("Generating template XML files...");
    // c.generateSchema(new SchemaOutputResolver() {
    // @Override
    // public Result createOutput(String namespaceUri,
    // String suggestedFileName) throws IOException {
    // // System.out.println(new File(target, suggestedFileName));
    // // return null;
    // return new StreamResult(new File(target, suggestedFileName));
    // }
    // });

    try {
        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement(
                "SELECT npc.*, npcskills.level AS race " + "FROM npc " + "LEFT JOIN npcskills "
                        + "ON(npc.idTemplate = npcskills.npcid AND npcskills.skillid = ?)");
        st.setInt(1, 4416);
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            Object[] result = fillNPC(rs);
            NPCTemplate t = (NPCTemplate) result[0];
            String type = (String) result[1];

            String folder = createFolder(type);
            if (folder.isEmpty()) {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../npc.xsd");
            } else {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../../npc.xsd");
            }

            final File file = new File(target, "npc/" + folder + "/" + t.getID().getID()
                    + (t.getInfo().getName() != null ? "-" + camelCase(t.getInfo().getName().getValue()) : "")
                    + ".xml");
            file.getParentFile().mkdirs();
            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.getInfo().getName().getValue() + " - " + 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

private static <T> Marshaller setUpMarshaller(Class<T> jaxbElementClass) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(jaxbElementClass);
    return jaxbContext.createMarshaller();
}

From source file:Main.java

public static void writeXML(Class<?> class1, Object obj, File outputFile)
        throws JAXBException, FileNotFoundException {
    JAXBContext context = JAXBContext.newInstance(class1);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(obj, outputFile);//from   www . j  a v a2  s . c om
}