Example usage for javax.xml.bind Marshaller setProperty

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

Introduction

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

Prototype

public void setProperty(String name, Object value) throws PropertyException;

Source Link

Document

Set the particular property in the underlying implementation of Marshaller .

Usage

From source file:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Get this header as an XML string.//from   w  w w.  j  av  a  2s. c o  m
 * Since this class contains a dual model supporting two type of headers (swift and ISO), if both
 * headers are present in the object the BusinessApplicationHeaderV01 will be used.
 * 
 * @param prefix optional prefix for namespace (empty by default)
 * @param includeXMLDeclaration true to include the XML declaration (false by default)
 * @return header serialized into XML string or null if neither header version is present
 * @since 7.8
 */
public String xml(final String prefix, boolean includeXMLDeclaration) {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        final StringWriter sw = new StringWriter();
        marshaller.marshal(_element(header), new XmlEventWriter(sw, prefix, includeXMLDeclaration, "AppHdr"));
        return sw.getBuffer().toString();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

From source file:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Gets the header as an Element object.
 *  //from   w ww .  j  a v a 2  s  .  co  m
 * @return Element this header parsed into Element or null if header is null
 * @since 7.8
 */
public Element element() {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        DOMResult res = new DOMResult();
        marshaller.marshal(_element(header), res);
        Document doc = (Document) res.getNode();
        return (Element) doc.getFirstChild();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

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

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    OutputStream docOS = null;/* w w w  . ja  v a  2s  .c o m*/
    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:de.thorstenberger.taskmodel.complex.complextaskdef.impl.ComplexTaskDefDAOImpl.java

public void save(ComplexTaskDefRoot ctdr, OutputStream os) throws TaskApiException {
    BufferedOutputStream bos = new BufferedOutputStream(os);

    Marshaller marshaller = null;
    try {//from w ww . ja va  2s .co  m
        JAXBContext jc = createJAXBContext();
        marshaller = JAXBUtils.getJAXBMarshaller(jc);
        Validator validator = jc.createValidator();
        ComplexTaskDef ctd = ((ComplexTaskDefRootImpl) ctdr).getJAXBContent();
        validator.validate(ctd);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        marshaller.marshal(ctd, bos);

    } catch (JAXBException e) {
        throw new TaskModelPersistenceException(e);
    } finally {
        try {
            bos.close();
        } catch (IOException e) {
            throw new TaskModelPersistenceException(e);
        }
        if (marshaller != null)
            JAXBUtils.releaseJAXBMarshaller(jc, marshaller);
    }

}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.QUELLE.QuelleService.java

@POST
@Path("/submitCloudDescription")
@Consumes(MediaType.APPLICATION_XML)// w  w w.jav  a 2 s. c  o  m
public boolean submitCloudProviderDescription(CloudProvider provider,
        @DefaultValue("true") @QueryParam("overwrite") boolean overwrite) {
    File saveAs = new File(SalsaConfiguration.getCloudProviderDescriptionDir() + File.separator
            + provider.getName() + cloudDescriptionFileExtension);
    if (saveAs.exists() && overwrite == false) {
        EngineLogger.logger.debug("Do not overwrite file : " + saveAs);
        return false;
    }
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(CloudProvider.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(provider, saveAs);
    } catch (JAXBException e) {
        EngineLogger.logger.debug("Fail to pass the cloud description !");
        e.printStackTrace();
    }
    EngineLogger.logger.debug("Saved/Updated cloud description in : " + saveAs);
    return true;
}

From source file:com.castlemock.web.basis.model.RepositoryImpl.java

/**
 * The method provides the functionality to export an entity and convert it to a String
 * @param id The id of the entityy that will be converted and exported
 * @return The entity with the provided id as a String
 *//* www. j av  a 2  s  . c o m*/
@Override
public String exportOne(final I id) {
    try {
        final T type = collection.get(id);
        final JAXBContext context = JAXBContext.newInstance(entityClass);
        final Marshaller marshaller = context.createMarshaller();
        final StringWriter writer = new StringWriter();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(type, writer);
        return writer.toString();
    } catch (JAXBException e) {
        throw new IllegalStateException("Unable to export type", e);
    }
}

From source file:de.fischer.thotti.core.runner.NDRunner.java

protected void saveTestResult(TestSuiteResult result) {
    Package pkg = TestSuiteResult.class.getPackage();

    File resultFile = generateResultFileName();

    JAXBContext jaxbContext = null;

    try {/*from  w w w. j a v a 2  s .  c  om*/
        jaxbContext = JAXBContext.newInstance(pkg.getName());

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

        marshaller.marshal(result, resultFile);
    } catch (JAXBException e) {
        // @todo?
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

/**
 * Writes the object Document into the file.
 *
 * @param o/*from   w  w  w .j  ava  2 s  .c o  m*/
 * @param file
 */
private void marshalXMLToSingleFile(Object o, File file) {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(o, file);
        return;
    } catch (JAXBException ex) {
        Logger.getLogger(ExportUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    throw new RuntimeException("ExportUtil: Something went wrong while marshalling the XML");
}

From source file:it.cnr.icar.eric.server.event.EmailNotifier.java

protected void sendNotification(ServerRequestContext context, NotifyActionType notifyAction,
        NotificationType notification, AuditableEventType ae) throws RegistryException {
    log.trace("Sending email notification");

    String endpoint = notifyAction.getEndPoint();

    if ((endpoint == null) || !endpoint.startsWith("mailto:")) {
        throw new RegistryException(ServerResourceBundle.getInstance()
                .getString("message.emailNotificationWOmailto", new Object[] { endpoint }));
    }//from   w  w w .ja  va  2  s. c  o  m

    try {
        // get the body of the message , not yet defined !
        StringWriter sw = new StringWriter();
        //            Marshaller marshaller = BindingUtility.getInstance().rimFac.createMarshaller();
        Marshaller marshaller = BindingUtility.getInstance().getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        //marshaller.marshal(notification, sw);
        ObjectFactory of = new ObjectFactory();
        marshaller.marshal(of.createNotification(notification), sw);

        //Now get the RegistryResponse as a String

        //Produce verbose response
        String notif = sw.toString();
        String action = ae.getEventType();
        String userId = ae.getUser();

        String userInfo;
        if (userId != null) {
            UserType user = (UserType) context.getRegistryObject(userId, "User_");
            userInfo = ServerResourceBundle.getInstance().getString("message.user",
                    new String[] { getUserInfo(user) });
        } else {
            userInfo = ServerResourceBundle.getInstance().getString("message.userUnknown");
        }

        SubscriptionType subscription = (SubscriptionType) context
                .getRegistryObject(notification.getSubscription(), "Subscription");
        String xsltId = getStyleSheetId(subscription);
        RepositoryItem repositoryItem = null;

        // empty string for notification property == use old format
        if (!"".equals(xsltId)) {
            //Dont use transform if there are any problems
            try {
                repositoryItem = RepositoryManagerFactory.getInstance().getRepositoryManager()
                        .getRepositoryItem(xsltId);
            } catch (Exception e) {
                log.warn(ServerResourceBundle.getInstance().getString("message.rawEmailNotification"), e);
            }
        }

        String contentType;
        String message;
        if (repositoryItem == null) {
            //No style sheet so skip the tranformation
            contentType = "text/xml";
            message = sw.toString();
        } else {
            contentType = "text/html";
            try {
                message = transformContent(context, xsltId, notif, action, userInfo);
            } catch (RegistryException e) {
                contentType = "text/xml";
                message = sw.toString();
            }
        }

        // set parameters and send the mail
        String subject = ServerResourceBundle.getInstance().getString("message.registryNotification",
                new Object[] { notification.getId() });
        postMail(endpoint, message, subject, contentType);
    } catch (MessagingException e) {
        throw new RegistryException(e);
    } catch (JAXBException e) {
        throw new RegistryException(e);
    }
}

From source file:com.moss.veracity.core.data.PersistenceManager.java

private void write(Object o, DatabaseEntry entry) throws JAXBException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Marshaller m = jaxbContext.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(o, out);//from   www. j a va  2s  . c  o m

    entry.setData(out.toByteArray());
}