Example usage for javax.xml.bind Marshaller marshal

List of usage examples for javax.xml.bind Marshaller marshal

Introduction

In this page you can find the example usage for javax.xml.bind Marshaller marshal.

Prototype

public void marshal(Object jaxbElement, javax.xml.stream.XMLEventWriter writer) throws JAXBException;

Source Link

Document

Marshal the content tree rooted at jaxbElement into a javax.xml.stream.XMLEventWriter .

Usage

From source file:Main.java

public static <T> Document marshal(Object jaxbElement, Class<T> jaxbFactory) throws JAXBException {
    if (!(jaxbElement instanceof JAXBElement<?>)) {
        throw new JAXBException("Must be a instance of JAXBElement<?>");
    }//  w ww  .  jav  a  2 s.  c  om
    Document doc = null;
    try {
        JAXBContext jc = JAXBContext.newInstance(jaxbFactory);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.newDocument();
        marshaller.marshal(jaxbElement, doc);

    } catch (PropertyException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return doc;
}

From source file:Main.java

/**
 * genXml/*w  w w .  ja  v a 2  s  .  c  o  m*/
 * 
 * @param o Object Class.
 * @param path : example c:\path\006DS_AMS20130630.xml
 */
public static void genXml(Object o, String path) {
    try {

        // create JAXB context and initializing Marshaller
        JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // for getting nice formatted output
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        //specify the location and name of xml file to be created
        File XMLfile = new File(path);

        // Writing to XML file
        jaxbMarshaller.marshal(o, XMLfile);
        // Writing to console
        jaxbMarshaller.marshal(o, System.out);

    } catch (JAXBException e) {
        // some exception occured
        e.printStackTrace();
    }
}

From source file:gov.hhs.fha.nhinc.lift.proxy.util.ProxyUtil.java

public static org.w3c.dom.Element marshal(Object obj) throws JAXBException {
    try {// w w w .j  a  va2  s  .  c o m
        Document doc = null;
        JAXBContext jc = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = jc.createMarshaller();
        javax.xml.parsers.DocumentBuilderFactory dbf;
        dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        doc = dbf.newDocumentBuilder().newDocument();
        marshaller.marshal(obj, doc);
        log.info("Marshal: " + doc.getNodeValue());
        return doc.getDocumentElement();
    } catch (ParserConfigurationException ex) {
        throw new JAXBException("Unable to create document: " + ex.getMessage());
    }
}

From source file:com.aionemu.packetsamurai.utils.collector.data.npcskills.NpcSkillsTool.java

public static void save() {
    ObjectFactory objFactory = new ObjectFactory();
    NpcSkillTemplates collection = objFactory.createNpcSkillTemplates();
    List<NpcSkillList> templateList = collection.getNpcskills();
    templateList.addAll(skillsByNpcId.values());
    Collections.sort(templateList);

    NpcSkillTemplate total = new NpcSkillTemplate();
    total.setSkillid(0);//  w w w.ja  v a2  s.c  o m

    List<NpcSkillList> toRemove = new ArrayList<NpcSkillList>();

    for (NpcSkillList skillList : templateList) {
        HashMap<IntRange, Integer> useCounts = new HashMap<IntRange, Integer>();
        HashMap<NpcSkillTemplate, Integer> skillCounts = new HashMap<NpcSkillTemplate, Integer>();
        NpcSkillTemplate totalAttacks = null;
        int index = 0;

        if (skillList.getNpcskill().contains(total)) {
            totalAttacks = skillList.getNpcskill().get(index);
            index = skillList.getNpcskill().indexOf(total);
            skillList.getNpcskill().remove(index);
        }

        int useTotal = 0;
        int skillUseTotal = 0;
        for (NpcSkillTemplate template : skillList.getNpcskill())
            skillUseTotal += template.getStats().useCount;

        if (totalAttacks != null) {
            useTotal = totalAttacks.getStats().useCount;
            if (skillUseTotal > useTotal)
                useTotal = skillUseTotal;
        } else {
            useTotal = skillUseTotal;
        }

        if (skillList.getNpcskill().size() == 0) {
            toRemove.add(skillList);
            continue;
        } else if (useTotal == 0) {
            // old data from XML
            continue;
        }

        for (NpcSkillTemplate template : skillList.getNpcskill()) {
            if (useTotal < MAX_HITS_PER_NPC) {
                if (template.getStats().maxHp > 90)
                    template.setMaxhp(100);
                else if (template.getMaxhp() == null || template.getMaxhp() < template.getStats().maxHp)
                    template.setMaxhp(template.getStats().maxHp);
                if (template.getStats().minHp < 10)
                    template.setMinhp(0);
                else if (template.getMinhp() == null || template.getMinhp() > template.getStats().minHp)
                    template.setMinhp(template.getStats().minHp);
            } else {
                IntRange hpRange = new IntRange(template.getStats().minHp, template.getStats().maxHp);
                if (useCounts.containsKey(hpRange)) {
                    int oldCounts = useCounts.get(hpRange);
                    useCounts.put(hpRange, oldCounts + template.getStats().useCount);
                } else
                    useCounts.put(hpRange, template.getStats().useCount);
                skillCounts.put(template, template.getStats().useCount);
            }

            if (useTotal >= MAX_HITS_PER_NPC)
                template.setProbability(Math.round((float) template.getStats().useCount * 100 / useTotal));
            else {
                template.setProbability(25);
            }
        }
    }

    templateList.removeAll(toRemove);

    try {
        JAXBContext jaxbContext = JAXBContext
                .newInstance("com.aionemu.packetsamurai.utils.collector.data.npcskills");
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(collection, new FileOutputStream("data/npc_skills/npc_skills.xml"));
    } catch (PropertyException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    PacketSamurai.getUserInterface().log("Skills [Npcs] - Saved : " + templateList.size() + " Npc Skills!");
}

From source file:io.apiman.test.common.echo.EchoServerVertx.java

private static void writeXmlAndEnd(HttpServerResponse rep, EchoResponse echo) {
    try (BufferOutputStream bufferOutputStream = new BufferOutputStream(500, rep)) {
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.marshal(echo, bufferOutputStream);
    } catch (JAXBException e) {
        e.printStackTrace();/*from  w  ww .  ja v  a 2  s.  co m*/
        throw new RuntimeException(e);
    }
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testGetUserLicenseQuery() throws Exception {
    GetUserQueryInputDTO input = new GetUserQueryInputDTO();
    input.setPresentationType("images");
    input.setAttributes(createUserObjAttributeDTO());

    JAXBContext context = JAXBContext.newInstance(GetUserQueryInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println(inputXML);
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client/*ww  w  .j a v  a 2s  .  c  om*/
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());

    // Call with XML
    String output = service.path("getUserLicenseQuery").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML)
            .entity(inputXML).post(String.class);

    System.out.println("query:" + output);
}

From source file:edu.harvard.lib.lcloud.SolrItem.java

protected static void marshalingExample(Item item) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Item.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(item, System.out);

}

From source file:edu.lternet.pasta.common.EmlUtility.java

/**
 * Creates and returns an EML 2.1.0 {@code <access} element string that
 * corresponds to the provided JAXB object.
 *
 * @param accessType/*w  w  w.  ja  v a  2  s.co m*/
 *            the JAXB object to be represented as a string.
 * @return an EML 2.1.0 {@code <access} element string that corresponds to
 *         the provided JAXB object.
 */
public static String toString(AccessType accessType) {

    try {

        ObjectFactory factory = new ObjectFactory();
        JAXBElement<AccessType> jaxb = factory.createAccess(accessType);

        StringWriter writer = new StringWriter();

        String packageName = AccessType.class.getPackage().getName();
        JAXBContext jc = JAXBContext.newInstance(packageName);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(jaxb, writer);

        return writer.toString();
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }

}

From source file:Main.java

public static void marshal(JAXBContext context, Object object, Writer writer, Map<String, Object> properties)
        throws JAXBException {
    if (object == null) {
        return;//from w w w  .  j  av  a2s .c o m
    }

    if (writer == null) {
        return;
    }

    if (context == null) {
        context = JAXBContext.newInstance(object.getClass());
    }

    Marshaller marshaller = context.createMarshaller();
    if (properties != null) {
        Iterator<Map.Entry<String, Object>> it = properties.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            marshaller.setProperty(entry.getKey(), entry.getValue());
        }
    }
    marshaller.marshal(object, writer);
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testGetUsersGroups() throws Exception {

    GetUserGroupsInputDTO input = new GetUserGroupsInputDTO();
    input.setAttributes(createUserObjAttributeDTO());
    input.setLocale("da");
    JAXBContext context = JAXBContext.newInstance(GetUserGroupsInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println("input xml:\n" + inputXML);

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client/*  w  w w . j a v a  2 s  .  c  o  m*/
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());
    // Call with XML
    //GetUsersLicensesOutputDTO output = service.path("getUserLicenses").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).entity(inputXML).post(GetUsersLicensesOutputDTO.class);

    // Call with @XmlRootElement
    GetUserGroupsOutputDTO output = service.path("getUserGroups").type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML).entity(input).post(GetUserGroupsOutputDTO.class);

    context = JAXBContext.newInstance(GetUserGroupsOutputDTO.class);
    outputStream = new ByteArrayOutputStream();
    m = context.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(output, outputStream);

    // serialize to XML
    String outputXML = outputStream.toString();
    System.out.println(outputXML);

    System.out.println("output, groups:" + output.getGroups());
}