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:Main.java

/**
 * Creates a {@link Marshaller} based on the given {@link JAXBContext}
 * and configures it to use the given {@link Charset}, and allows to
 * output the XML code to be generated formatted and as an XML fragment.
 * //from www  .  jav  a 2s.  c om
 * @param ctx the {@link JAXBContext} to create a {@link Marshaller} for
 * @param charset the {@link Charset} the XML code should be formatted
 * @param formatted {@code true} if the XML code should be formatted,
 *       {@code false} otherwise
 * @param fragment {@code false} if the XML code should start with
 *       {@code <?xml }, or {@code true} if just fragment XML code should
 *       get generated
 * 
 * @return a preconfigured {@link Marshaller}
 * 
 * @throws IOException in case no {@link Marshaller} could get created
 */
public static Marshaller createMarshaller(JAXBContext ctx, Charset charset, boolean formatted, boolean fragment)
        throws IOException {
    if (charset == null) {
        return createMarshaller(ctx, Charset.defaultCharset(), formatted, fragment);
    }
    Objects.requireNonNull(ctx);
    try {
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, fragment);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, charset.name());
        return marshaller;
    } catch (JAXBException e) {
        throw new IOException(e);
    }
}

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. j a v  a2 s . c  om*/
 *            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:com.vangent.hieos.services.xds.bridge.utils.JUnitHelper.java

/**
 * Method description/*from   w w w .j a  v a2  s . c  o m*/
 *
 *
 *
 *
 * @param file
 * @param count
 * @param documentIds
 * @return
 *
 * @throws Exception
 */
public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception {

    ObjectFactory factory = new ObjectFactory();
    SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest();

    IdType pid = factory.createIdType();

    pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478");
    sdr.setPatientId(pid);

    ClassLoader classLoader = JUnitHelper.class.getClassLoader();

    DocumentsType documents = factory.createDocumentsType();

    for (int i = 0; i < count; ++i) {

        DocumentType document = factory.createDocumentType();

        if ((documentIds != null) && (documentIds.length > i)) {
            document.setId(documentIds[i]);
        }

        CodeType type = factory.createCodeType();

        type.setCode("51855-5");
        type.setCodeSystem("2.16.840.1.113883.6.1");

        document.setType(type);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        InputStream is = classLoader.getResourceAsStream(file);

        assertNotNull(is);

        IOUtils.copy(is, bos);

        document.setContent(bos.toByteArray());

        documents.getDocument().add(document);
    }

    sdr.setDocuments(documents);

    QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest");
    JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class);
    Marshaller marshaller = jc.createMarshaller();

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr);

    StringWriter sw = new StringWriter();

    marshaller.marshal(element, sw);

    String xml = sw.toString();

    logger.debug(xml);

    OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml);

    List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content",
            URIConstants.XDSBRIDGE_URI);

    for (OMElement contentNode : list) {

        OMText binaryNode = (OMText) contentNode.getFirstOMChild();

        if (binaryNode != null) {
            binaryNode.setOptimize(true);
        }
    }

    return result;
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getTestplanString(String urlServer, String projectAreaAlias, String encoding,
        String testCaseId, Testplan currentPlan) throws JAXBException {

    // Adiciona o novo test case se no existir
    boolean exists = false;
    String newTestCaseId = urlServer + "resources/" + projectAreaAlias + "/testcase/" + testCaseId;

    if (currentPlan.getTestcase() != null) {
        for (com.ibm.rqm.xml.bind.Testplan.Testcase link : currentPlan.getTestcase()) {
            if (link.getHref().equals(newTestCaseId)) {
                exists = true;/*from w  w  w  .  j  ava  2s. co  m*/
                break;
            }
        }
    }

    if (!exists) {
        com.ibm.rqm.xml.bind.Testplan.Testcase testcase = new com.ibm.rqm.xml.bind.Testplan.Testcase();
        testcase.setHref(newTestCaseId);
        currentPlan.getTestcase().add(testcase);
    }

    JAXBContext jaxb = JAXBContext.newInstance(Testplan.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter testPlanString = new StringWriter();
    marshaller.marshal(currentPlan, testPlanString);

    return testPlanString.toString();
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getExecutionworkitemString(String urlServer, String projectAreaAlias, String encoding,
        String testCaseId, String testPlanId) throws JAXBException {

    // Workitem/*from w  w  w.  j  a v a  2s .  c  o m*/
    com.ibm.rqm.xml.bind.Executionworkitem.Testcase workTest = new com.ibm.rqm.xml.bind.Executionworkitem.Testcase();
    workTest.setHref(urlServer + "resources/" + projectAreaAlias + "/testcase/" + testCaseId);

    // Testplan
    com.ibm.rqm.xml.bind.Executionworkitem.Testplan testPlan = new com.ibm.rqm.xml.bind.Executionworkitem.Testplan();
    testPlan.setHref(
            urlServer + "resources/" + projectAreaAlias + "/testplan/urn:com.ibm.rqm:testplan:" + testPlanId);

    // Criao do Execution Work Item
    Executionworkitem work = new Executionworkitem();
    work.setFrequency("Once");
    work.setRegression(false);
    work.setTitle("Registro de Execuo Automatizado - Plano de Teste " + testPlanId);
    work.setWeight(100);
    work.setTestcase(workTest);
    work.setTestplan(testPlan);

    JAXBContext jaxb = JAXBContext.newInstance(Executionworkitem.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter resourceString = new StringWriter();
    marshaller.marshal(work, resourceString);

    return resourceString.toString();
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getTestcaseString(String urlServer, String projectAreaAlias, String encoding, String name,
        String steps, Testcase currentTestCase) throws JAXBException {

    Richtext textDesgin = new Richtext();
    textDesgin.getContent().add(escapeHTMLForAlm(steps));

    currentTestCase.setTitle(name);//from   w w w . ja va 2s.co m
    currentTestCase.setSuspect(false);
    currentTestCase.setWeight(100);
    currentTestCase.setComIbmRqmPlanningEditorSectionTestCaseDesign(textDesgin);

    // Valor da Categoria
    String categoryTipoExecucao = BehaveConfig.getIntegration_CategoryTipoExecucao();

    // Verifica se no caso de teste vindo da ALM existe a categoria
    // "Tipo de Execuo", se no existe cria.
    boolean objExists = false;
    for (Testcase.Category c : currentTestCase.getCategory()) {
        if (c.getTerm().toLowerCase().trim().equals("tipo de execuo")) {
            objExists = true;
            // Altera para "Automtica"
            c.setValue(categoryTipoExecucao);
            break;
        }
    }

    if (!objExists) {
        Testcase.Category newC = new Testcase.Category();
        newC.setTerm("Tipo de Execuo");
        newC.setValue(categoryTipoExecucao);
        currentTestCase.getCategory().add(newC);
    }

    JAXBContext jaxb = JAXBContext.newInstance(Testcase.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter testCaseString = new StringWriter();
    marshaller.marshal(currentTestCase, testCaseString);

    return testCaseString.toString();
}

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 ww. ja  v  a  2  s  . 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: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);//from  ww w .  j  av  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:com.silverpeas.admin.components.Instanciateur.java

public static void saveComponent(WAComponent waComponent, String fileName, boolean workflow)
        throws JAXBException {
    JAXBContext context = JAXBContext.newInstance("com.silverpeas.admin.components");
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
            "http://silverpeas.org/xml/ns/component http://www.silverpeas.org/xsd/component.xsd");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    String path = getXMLPackage() + File.separatorChar;
    if (workflow) {
        path += "workflows" + File.separatorChar;
    }/*w w w  .  j  a  va 2  s . c o m*/
    File file = new File(path + fileName);
    marshaller.marshal(objectFactory.createWAComponent(waComponent), file);
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getExecutionresultString(String urlServer, String projectAreaAlias, String encoding,
        String executionWorkItemUrl, ScenarioState stateOf, Date _startDate, Date _endDate, String details)
        throws JAXBException, DatatypeConfigurationException {

    Date startDate = (Date) _startDate.clone();
    Date endDate = (Date) _endDate.clone();

    com.ibm.rqm.xml.bind.Executionresult.Executionworkitem workTest = new com.ibm.rqm.xml.bind.Executionresult.Executionworkitem();
    workTest.setHref(executionWorkItemUrl);

    State state = new State();
    Executionresult result = new Executionresult();
    if (stateOf.equals(ScenarioState.FAILED)) {
        state.setContent("com.ibm.rqm.execution.common.state.failed");
    } else {//w  ww . ja  va 2s.  c om
        if (stateOf.equals(ScenarioState.PENDING)) {
            state.setContent("com.ibm.rqm.execution.common.state.blocked");
        } else {
            state.setContent("com.ibm.rqm.execution.common.state.passed");
        }
    }

    result.setState(state);
    result.setExecutionworkitem(workTest);

    // Datas de incio e fim do teste
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(startDate);
    XMLGregorianCalendar startDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setStarttime(startDateXml);

    c.setTime(endDate);
    XMLGregorianCalendar endDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setEndtime(endDateXml);

    // Details
    Details d = new Details();
    d.getContent().add(details);
    result.setDetails(d);

    JAXBContext jaxb = JAXBContext.newInstance(Executionresult.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter resourceString = new StringWriter();
    marshaller.marshal(result, resourceString);

    return resourceString.toString();
}