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:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;//w  ww. j a  v a2 s .  com
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:tools.xor.logic.DefaultStoredProcedure.java

private void outputSP(AggregateView view) throws JAXBException, UnsupportedEncodingException {
    javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(AggregateView.class);
    javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N
    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(view, System.out);

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    marshaller.marshal(view, bOut);//from   w  ww.  j  a  v  a  2 s .c o  m
    bOut.toString("UTF-8");
}

From source file:vitro.vgw.communication.idas.IdasProxyImpl.java

private Object sendRequest(Object request) throws VitroGatewayException {

    Object result = null;/*from   w w w. jav  a 2  s.  c  om*/

    InputStream instream = null;

    try {
        HttpPost httpPost = new HttpPost(endPoint);

        JAXBContext jaxbContext = Utils.getJAXBContext();

        Marshaller mar = jaxbContext.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        mar.marshal(request, baos);

        String requestXML = baos.toString(HTTP.UTF_8);

        StringEntity entityPar = new StringEntity(requestXML, "application/xml", HTTP.UTF_8);

        httpPost.setEntity(entityPar);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {

            instream = entity.getContent();

            Unmarshaller unmarshaller = Utils.getJAXBContext().createUnmarshaller();
            Object idasResponse = unmarshaller.unmarshal(instream);

            if (idasResponse instanceof ExceptionReport) {
                throw Utils.parseException((ExceptionReport) idasResponse);
            }

            result = idasResponse;

        } else {
            throw new VitroGatewayException("Server response does not contain any body");
        }
    } catch (VitroGatewayException e) {
        throw e;
    } catch (Exception e) {
        throw new VitroGatewayException(e);
    } finally {
        if (instream != null) {
            try {
                instream.close();
            } catch (IOException e) {
                logger.error("Error while closing server response stream", e);
            }
        }
    }

    return result;

}

From source file:com.hp.octane.integrations.uft.items.UftTestDiscoveryResult.java

public void writeToFile(File fileToWriteTo) throws JAXBException {

    JAXBContext jaxbContext = JAXBContext.newInstance(UftTestDiscoveryResult.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(this, fileToWriteTo);
}

From source file:com.github.thesmartenergy.cnr.SmartChargingProvider.java

private SOAPMessage createSoapMessage(GetChargingPlans value) throws PEPException {
    try {//from   w  w w.  java  2s.  com
        JAXBContext jaxbContext = JAXBContext.newInstance(GetChargingPlans.class);
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        jaxbContext.createMarshaller().marshal(value, document);

        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        soapMessage.getSOAPBody().addDocument(document);
        Name headername = soapMessage.getSOAPPart().getEnvelope().createName("Action", "",
                "http://schemas.microsoft.com/ws/2005/05/addressing/none/");
        SOAPHeaderElement soapAction = soapMessage.getSOAPHeader().addHeaderElement(headername);
        soapAction.setMustUnderstand(true);
        soapAction.setTextContent("http://tempuri.org/ISmartCharging/GetChargingPlans");
        return soapMessage;
    } catch (DOMException | JAXBException | ParserConfigurationException | SOAPException ex) {
        throw new PEPException(ex);
    }
}

From source file:com.fusesource.example.camel.ingest.FileIngestorRouteBuilderTest.java

protected void createAndMoveFile(AggregateRecordType agt) throws Exception {
    File testFile = new File("./target/test.xml");

    if (testFile.exists()) {
        testFile.delete();/* ww  w.  jav  a 2s. c o m*/
    }

    ObjectFactory objFact = new ObjectFactory();
    JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller m = context.createMarshaller();
    m.marshal(objFact.createAggregateRecord(agt), testFile);
    // not really atomic, but it works for tests
    FileUtils.moveFile(testFile, new File(pollingFolder, "test.xml"));
}

From source file:com.provenance.cloudprovenance.sconverter.PolicyResponseConverter.java

public String marhsallObject(PolicyResponse pResponse) {

    JAXBContext jaxbContext;
    StringWriter sw = new StringWriter();

    try {//from ww  w.  j  a v a 2 s  .  c  o  m
        jaxbContext = JAXBContext.newInstance(instanceDir);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", cProvPrefixMapper);

        JAXBElement<PolicyResponse> el = pFactory.createPolicyResponse(pResponse);

        marshaller.marshal(el, sw);

        logger.info("Sucessfully marshalled the policy objects: " + el.getName());

    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return sw.toString();
}

From source file:com.sharksharding.util.xml.CreateCoreXml.java

public CreateCoreXml() {
    try {/*w w  w  .  ja v  a2 s . c  om*/
        JAXBContext jAXBContext = JAXBContext.newInstance(Beans.class);
        marshaller = jAXBContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:gov.nih.nci.cabig.caaers.web.study.ExportStudyController.java

@Override
protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object o,
        BindException e) throws Exception {

    Integer studyID = Integer.valueOf(request.getParameter("id"));
    Study study = studyDao.getById(studyID);
    studyDao.initialize(study);//from  w  w  w .  j  a  v  a2 s  .  co m

    // START study export pre-population
    study.setCoordinatingCenter(new CoordinatingCenter());
    study.getCoordinatingCenter().setStudyCoordinatingCenter(study.getStudyCoordinatingCenter());

    study.setFundingSponsor(new FundingSponsor());
    study.getFundingSponsor().setStudyFundingSponsor(study.getStudyFundingSponsors().get(0));

    for (OrganizationAssignedIdentifier id : study.getOrganizationAssignedIdentifiers()) {
        if (id.getOrganization().equals(study.getFundingSponsor().getStudyFundingSponsor().getOrganization())) {
            study.getFundingSponsor().setOrganizationAssignedIdentifier(id);
            study.getFundingSponsor().getOrganizationAssignedIdentifier().setPrimaryIndicator(true);
            break;
        }
    }
    for (OrganizationAssignedIdentifier id : study.getOrganizationAssignedIdentifiers()) {
        if (id.getOrganization()
                .equals(study.getCoordinatingCenter().getStudyCoordinatingCenter().getOrganization())) {
            study.getCoordinatingCenter().setOrganizationAssignedIdentifier(id);
            study.getCoordinatingCenter().getOrganizationAssignedIdentifier().setPrimaryIndicator(false);
            break;
        }
    }
    // END study export pre-population

    gov.nih.nci.cabig.caaers.integration.schema.study.Studies studies = converter
            .convertStudyDomainToStudyDto(study);

    //Marshall the Data Transfer Object according to Study.xsd schema,
    //and download it to the client machine.
    try {
        String tempDir = System.getProperty("java.io.tmpdir");
        String fileName = "ExportedStudy_" + study.getPrimaryIdentifierValue();
        fileName = RuleUtil.getStringWithoutSpaces(fileName);

        StringWriter sw = new StringWriter();
        JAXBContext jaxbContext = JAXBContext.newInstance("gov.nih.nci.cabig.caaers.integration.schema.study");

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(studies, sw);
        BufferedWriter out = new BufferedWriter(new FileWriter(tempDir + fileName + ".xml"));
        out.write(sw.toString());
        out.flush();
        out.close();

        response.setContentType("application/xml");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xml");
        response.setHeader("Content-length", String.valueOf(sw.toString().length()));
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-control", "private, must-revalidate");

        OutputStream outputStream = response.getOutputStream();
        File file = new File(tempDir + fileName + ".xml");
        FileInputStream fileIn = new FileInputStream(file);
        byte[] buffer = new byte[2048];
        int bytesRead = fileIn.read(buffer);
        while (bytesRead >= 0) {
            if (bytesRead > 0)
                outputStream.write(buffer, 0, bytesRead);
            bytesRead = fileIn.read(buffer);
        }
        outputStream.flush();
        outputStream.close();
        fileIn.close();

    } catch (Exception ex) {
        log.error(ex);
        ex.printStackTrace();
    }
    return null;
}

From source file:de.intevation.test.irixservice.UploadReportTest.java

@Test(expected = UploadReportException.class)
public void testInvalidDokpool() throws UploadReportException, JAXBException {
    ReportType report = getReportFromFile(VALID_REPORT);
    DokpoolMeta meta = new DokpoolMeta();
    meta.setDokpoolContentType("Invalid doc");
    DOMResult res = new DOMResult();
    Element ele = null;/*from w w  w.j a  v a  2s .c  o  m*/
    JAXBContext jaxbContext = JAXBContext.newInstance(DokpoolMeta.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    jaxbMarshaller.marshal(meta, res);
    ele = ((Document) res.getNode()).getDocumentElement();

    report.getAnnexes().getAnnotation().get(0).getAny().add(ele);
    testObj.uploadReport(report);
}