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:eu.impress.repository.service.BedAvailabilityServiceImpl.java

@Override
public String getBedAvailablityHAVE(String hospitalname) {

    String hospitalstatushave;//  www. j ava 2 s.  c  o  m
    BedStats bedStats = bedService.getHospitalAvailableBeds(hospitalname);
    HospitalStatus hospitalStatus = beansTransformation.BedStatstoHAVE(bedStats);

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(HospitalStatus.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        //jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        StringWriter sw = new StringWriter();
        //marshal the envelope 
        jaxbMarshaller.marshal(hospitalStatus, sw);
        hospitalstatushave = sw.toString();

    } catch (JAXBException e) {
        e.printStackTrace();
        return "Error Marshalling XML Object";
    }

    return hospitalstatushave;

}

From source file:eu.learnpad.core.impl.ca.XwikiBridgeInterfaceRestResource.java

@Override
public String putValidateCollaborativeContent(CollaborativeContentAnalysis contentFile) throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/ca/bridge/validatecollaborativecontent", this.restPrefix);
    PostMethod postMethod = new PostMethod(uri);

    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
    try {// w w w . ja  va2  s . c o  m
        StringWriter contentWriter = new StringWriter();
        JAXBContext context = JAXBContext.newInstance(CollaborativeContentAnalysis.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(contentFile, contentWriter);

        RequestEntity entity = new StringRequestEntity(contentWriter.toString(), MediaType.APPLICATION_XML,
                null);
        postMethod.setRequestEntity(entity);
    } catch (JAXBException | UnsupportedEncodingException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    try {
        httpClient.executeMethod(postMethod);
        return postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:eu.modaclouds.sla.service.rest.AbstractSLARest.java

protected String printMessage(int code, String text) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {/* www . j  a  v  a2s  .  c  om*/

        MessageResponse messageResponse = new MessageResponse();

        messageResponse.setCode(code);
        messageResponse.setMessage(text);

        JAXBContext jaxbContext = JAXBContext.newInstance(eu.atos.sla.parser.data.MessageResponse.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

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

        marshaller.marshal(messageResponse, out);
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return out.toString();

}

From source file:eu.impress.repository.service.BedAvailabilityServiceImpl.java

@Override
public String createBedAvailabilityDE() throws DatatypeConfigurationException {

    String DEmessageenvelope = "";
    String DEmessage = "";

    EDXLDistribution ed = EDXLlib.createEDXLEnvelope();

    try {//from   ww  w  .  j av  a  2 s  .  c  o m
        JAXBContext jaxbContext = JAXBContext.newInstance(EDXLDistribution.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        //jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        StringWriter sw = new StringWriter();
        //marshal the envelope 
        jaxbMarshaller.marshal(ed, sw);
        DEmessageenvelope = sw.toString();

        //could not unescape characters no matter what!
        //encapsulate the edxl have message into DE by avoiding jaxb 
        //DEmessage = EDXLlib.DEEncapsulation(DEmessageenvelope, edxlhave);
        DEmessage = DEmessageenvelope;

    } catch (JAXBException e) {
        e.printStackTrace();
        return "Error Marshalling XML Object";
    }

    return DEmessage;

}

From source file:de.tudarmstadt.ukp.dkpro.core.io.tiger.TigerXmlWriter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;//from w w  w  . jav a 2s .c om
    try {
        docOS = getOutputStream(aJCas, filenameSuffix);

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter(
                xmlOutputFactory.createXMLEventWriter(docOS));

        JAXBContext context = JAXBContext.newInstance(TigerSentence.class);
        Marshaller marshaller = context.createMarshaller();
        // We use the marshaller only for individual sentences. That way, we do not have to 
        // build the whole TIGER object graph before seralizing, which should safe us some
        // memory.
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        XMLEventFactory xmlef = XMLEventFactory.newInstance();
        xmlEventWriter.add(xmlef.createStartDocument());
        xmlEventWriter.add(xmlef.createStartElement("", "", "corpus"));
        xmlEventWriter.add(xmlef.createStartElement("", "", "body"));

        int sentenceNumber = 1;
        for (Sentence s : select(aJCas, Sentence.class)) {
            TigerSentence ts = convertSentence(s, sentenceNumber);
            marshaller.marshal(new JAXBElement<TigerSentence>(new QName("s"), TigerSentence.class, ts),
                    xmlEventWriter);
            sentenceNumber++;
        }

        xmlEventWriter.add(xmlef.createEndElement("", "", "body"));
        xmlEventWriter.add(xmlef.createEndElement("", "", "corpus"));
        xmlEventWriter.add(xmlef.createEndDocument());
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    } finally {
        closeQuietly(docOS);
    }
}

From source file:org.javelin.sws.ext.bind.jaxb.JaxbTest.java

@Test
public void marshalIllegalName() throws Exception {
    JAXBContext ctx = JAXBContext.newInstance(org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1.class);
    Marshaller m = ctx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    // and I thought it's illegal...
    m.marshal(new JAXBElement<String>(new QName("a", "a a"), String.class, "hello"), System.out);
}

From source file:android.databinding.tool.LayoutXmlProcessor.java

public void writeLayoutInfoFiles(File xmlOutDir) throws JAXBException {
    if (mWritten) {
        return;/* w  w  w .ja  v a  2  s . com*/
    }
    JAXBContext context = JAXBContext.newInstance(ResourceBundle.LayoutFileBundle.class);
    Marshaller marshaller = context.createMarshaller();

    for (List<ResourceBundle.LayoutFileBundle> layouts : mResourceBundle.getLayoutBundles().values()) {
        for (ResourceBundle.LayoutFileBundle layout : layouts) {
            writeXmlFile(xmlOutDir, layout, marshaller);
        }
    }
    mWritten = true;
}

From source file:io.onedecision.engine.decisions.impl.DecisionModelFactory.java

@Override
public void write(Definitions dm, Writer out) throws IOException {
    JAXBContext context;
    try {//www .j av  a  2  s.  co m
        context = JAXBContext.newInstance(Definitions.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        // Since no @XmlRootElement generated for Definitions need to create
        // element wrapper here. See
        // https://weblogs.java.net/blog/kohsuke/archive/2006/03/why_does_jaxb_p.html
        m.marshal(new JAXBElement<Definitions>(DEFINITIONS, Definitions.class, dm), out);
    } catch (JAXBException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.javelin.sws.ext.bind.jaxb.JaxbTest.java

@Test(expected = IllegalAnnotationsException.class)
public void marshalMixed() throws Exception {
    JAXBContext ctx = JAXBContext.newInstance(org.javelin.sws.ext.bind.jaxb.context4.MyClassJ4.class);
    Marshaller m = ctx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    org.javelin.sws.ext.bind.jaxb.context4.MyClassJ4 mc4 = new org.javelin.sws.ext.bind.jaxb.context4.MyClassJ4();
    m.marshal(new JAXBElement<org.javelin.sws.ext.bind.jaxb.context4.MyClassJ4>(new QName("a", "a"),
            org.javelin.sws.ext.bind.jaxb.context4.MyClassJ4.class, mc4), System.out);
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Generates and saves info.xml/*  w  w w  . j av  a  2 s.  c o  m*/
 *
 * @param path
 * @param mets
 */
public static void saveInfoFile(String path, MetsContext metsContext, String md5, String fileMd5Name,
        File metsFile) throws MetsExportException {
    File infoFile = new File(path + File.separator + metsContext.getPackageID() + File.separator + "info_"
            + metsContext.getPackageID() + ".xml");
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(new Date());
    XMLGregorianCalendar date2;
    try {
        date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    } catch (DatatypeConfigurationException e1) {
        throw new MetsExportException("Error while generating info.xml file", false, e1);
    }
    Info infoJaxb = new Info();
    infoJaxb.setCreated(date2);
    infoJaxb.setMainmets("./" + metsFile.getName());
    Checksum checkSum = new Checksum();
    checkSum.setChecksum(md5);
    checkSum.setType("MD5");
    addModsIdentifiersRecursive(metsContext.getRootElement(), infoJaxb);
    checkSum.setValue(fileMd5Name);
    infoJaxb.setChecksum(checkSum);
    Validation validation = new Validation();
    validation.setValue("W3C-XML");
    validation.setVersion(Float.valueOf("0.0"));
    infoJaxb.setValidation(validation);
    infoJaxb.setCreator(metsContext.getCreatorOrganization());
    infoJaxb.setPackageid(metsContext.getPackageID());
    if (Const.PERIODICAL_TITLE.equalsIgnoreCase(metsContext.getRootElement().getElementType())) {
        infoJaxb.setMetadataversion((float) 1.5);
    } else {
        infoJaxb.setMetadataversion((float) 1.1);
    }
    Itemlist itemList = new Itemlist();
    infoJaxb.setItemlist(itemList);
    itemList.setItemtotal(BigInteger.valueOf(metsContext.getFileList().size()));
    List<FileMD5Info> fileList = metsContext.getFileList();
    long size = 0;
    for (FileMD5Info fileName : fileList) {
        itemList.getItem()
                .add(fileName.getFileName().replaceAll(Matcher.quoteReplacement(File.separator), "/"));
        size += fileName.getSize();
    }
    int infoTotalSize = (int) (size / 1024);
    infoJaxb.setSize(infoTotalSize);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Info.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        // SchemaFactory factory =
        // SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // factory.setResourceResolver(MetsLSResolver.getInstance());
        // Schema schema = factory.newSchema(new
        // StreamSource(Info.class.getResourceAsStream("info.xsd")));
        // marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        marshaller.marshal(infoJaxb, infoFile);
    } catch (Exception ex) {
        throw new MetsExportException("Error while generating info.xml", false, ex);
    }

    List<String> validationErrors;
    try {
        validationErrors = MetsUtils.validateAgainstXSD(infoFile, Info.class.getResourceAsStream("info.xsd"));
    } catch (Exception e) {
        throw new MetsExportException("Error while validating info.xml", false, e);
    }

    if (validationErrors.size() > 0) {
        MetsExportException metsException = new MetsExportException(
                "Invalid info file:" + infoFile.getAbsolutePath(), false, null);
        metsException.getExceptions().get(0).setValidationErrors(validationErrors);
        for (String error : validationErrors) {
            LOG.fine(error);
        }
        throw metsException;
    }
}