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:edu.kit.dama.rest.util.RestClientUtils.java

/**
 * Deserializes an entity from a stream provided by a ClientResponse.
 * <b>Attention:</b>May throw a DeserializationException if the
 * deserialization fails for some reason.
 *
 * @param <C> entity class//from  w w w  .ja  v a2s.  com
 * @param pEntityClass An array of classes needed to deserialize the entity.
 * @param pResponse The response which provides the entity input stream.
 *
 * @return The object.
 */
public static <C> C createObjectFromStream(final Class[] pEntityClass, final ClientResponse pResponse) {
    C returnValue = null;
    if (pEntityClass != null) {
        LOGGER.debug("createObjectFromStream");
        try {
            Unmarshaller unmarshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(pEntityClass)
                    .createUnmarshaller();
            returnValue = (C) unmarshaller.unmarshal(getInputStream(pResponse.getEntityInputStream()));
            if (LOGGER.isDebugEnabled()) {
                Marshaller marshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(pEntityClass)
                        .createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                marshaller.marshal(returnValue, sw);
                LOGGER.debug("createObjectFromStream: " + sw.toString());
            }
        } catch (JAXBException ex) {
            throw new DeserializationException("Failed to deserialize object from response " + pResponse, ex);
        }
    } else {
        LOGGER.debug("No response expected!");
    }
    return returnValue;
}

From source file:main.java.refinement_class.Useful.java

public static void mashal(Object o, String xml_file, Class c) {

    Marshaller marshaller;
    // create a JAXBContext
    JAXBContext jaxbContext;/*from  w w  w . j av  a 2 s . c om*/

    try {
        jaxbContext = JAXBContext.newInstance(c);

        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        marshaller.marshal(o, new FileOutputStream(xml_file));
    } catch (JAXBException e) {
        e.printStackTrace();
        LOG.error(e.toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        LOG.error(e.toString());
    }
}

From source file:com.ikon.util.impexp.RepositoryExporter.java

/**
 * Export document from openkm repository to filesystem.
 *//*  w  w w .  j  a va2 s .c om*/
public static ImpExpStats exportDocument(String token, String docPath, String destPath, String metadata,
        boolean history, Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException,
        DatabaseException, IOException, AccessDeniedException, ParseException, NoSuchGroupException {
    DocumentModule dm = ModuleManager.getDocumentModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Document docChild = dm.getProperties(token, docPath);
    Gson gson = new Gson();
    ImpExpStats stats = new ImpExpStats();

    // Version history
    if (history) {
        // Create dummy document file
        new File(destPath).createNewFile();

        // Metadata
        if (metadata.equals("JSON")) {
            DocumentMetadata dmd = ma.getMetadata(docChild);
            String json = gson.toJson(dmd);
            FileOutputStream fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT);
            IOUtils.write(json, fos);
            IOUtils.closeQuietly(fos);
        } else if (metadata.equals("XML")) {
            FileOutputStream fos = new FileOutputStream(destPath + ".xml");

            DocumentMetadata dmd = ma.getMetadata(docChild);
            JAXBContext jaxbContext;
            try {
                jaxbContext = JAXBContext.newInstance(DocumentMetadata.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

                // output pretty printed
                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                jaxbMarshaller.marshal(dmd, fos);
            } catch (JAXBException e) {
                log.error(e.getMessage(), e);
                FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage());
            }
        }

        for (Version ver : dm.getVersionHistory(token, docChild.getPath())) {
            String versionPath = destPath + "#v" + ver.getName() + "#";
            FileOutputStream vos = new FileOutputStream(versionPath);
            InputStream vis = dm.getContentByVersion(token, docChild.getPath(), ver.getName());
            IOUtils.copy(vis, vos);
            IOUtils.closeQuietly(vis);
            IOUtils.closeQuietly(vos);
            FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", docChild.getPath(),
                    ver.getName());

            // Metadata
            if (metadata.equals("JSON")) {
                VersionMetadata vmd = ma.getMetadata(ver, docChild.getMimeType());
                String json = gson.toJson(vmd);
                vos = new FileOutputStream(versionPath + Config.EXPORT_METADATA_EXT);
                IOUtils.write(json, vos);
                IOUtils.closeQuietly(vos);
            } else if (metadata.equals("XML")) {
                FileOutputStream fos = new FileOutputStream(destPath + ".xml");

                VersionMetadata vmd = ma.getMetadata(ver, docChild.getMimeType());
                JAXBContext jaxbContext;
                try {
                    jaxbContext = JAXBContext.newInstance(VersionMetadata.class);
                    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

                    // output pretty printed
                    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    jaxbMarshaller.marshal(vmd, fos);
                } catch (JAXBException e) {
                    log.error(e.getMessage(), e);
                    FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage());
                }
            }
        }
    } else {
        FileOutputStream fos = new FileOutputStream(destPath);
        InputStream is = dm.getContent(token, docChild.getPath(), false);
        IOUtils.copy(is, fos);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(fos);
        FileLogger.info(BASE_NAME, "Created document ''{0}''", docChild.getPath());

        // Metadata
        if (metadata.equals("JSON")) {
            DocumentMetadata dmd = ma.getMetadata(docChild);
            String json = gson.toJson(dmd);
            fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT);
            IOUtils.write(json, fos);
            IOUtils.closeQuietly(fos);
        } else if (metadata.equals("XML")) {
            fos = new FileOutputStream(destPath + ".xml");

            DocumentMetadata dmd = ma.getMetadata(docChild);
            JAXBContext jaxbContext;
            try {
                jaxbContext = JAXBContext.newInstance(DocumentMetadata.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

                // output pretty printed
                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                jaxbMarshaller.marshal(dmd, fos);
            } catch (JAXBException e) {
                log.error(e.getMessage(), e);
                FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage());
            }
        }
    }

    if (out != null) {
        out.write(deco.print(docChild.getPath(), docChild.getActualVersion().getSize(), null));
        out.flush();
    }

    // Stats
    stats.setSize(stats.getSize() + docChild.getActualVersion().getSize());
    stats.setDocuments(stats.getDocuments() + 1);

    return stats;
}

From source file:com.evolveum.midpoint.testing.model.client.sample.Main.java

private static QueryType createUserQuery2(String username) throws JAXBException {
    QueryType query = new QueryType();

    SearchFilterType filter = new SearchFilterType();

    PropertyComplexValueFilterClauseType fc = new PropertyComplexValueFilterClauseType();
    ItemPathType path = new ItemPathType();
    path.setValue("declare namespace c=\"http://midpoint.evolveum.com/xml/ns/public/common/common-3\"; c:name");
    fc.setPath(path);/*w  ww . java2 s.  c  o  m*/
    fc.setValue(username);

    ObjectFactory factory = new ObjectFactory();
    JAXBElement<PropertyComplexValueFilterClauseType> equal = factory.createEqual(fc);

    JAXBContext jaxbContext = JAXBContext.newInstance("com.evolveum.midpoint.xml.ns._public.common.api_types_3:"
            + "com.evolveum.midpoint.xml.ns._public.common.common_3:"
            + "com.evolveum.prism.xml.ns._public.annotation_3:" + "com.evolveum.prism.xml.ns._public.query_3:"
            + "com.evolveum.prism.xml.ns._public.types_3:");
    Marshaller marshaller = jaxbContext.createMarshaller();
    DOMResult result = new DOMResult();
    marshaller.marshal(equal, result);
    filter.setFilterClause(((Document) result.getNode()).getDocumentElement());

    query.setFilter(filter);
    return query;
}

From source file:labr_client.xml.ObjToXML.java

public static String marshallRequest(LabrRequest request) {
    String xml = "";
    String date = String.format("%1$tY%1$tm%1$td", new Date());
    String time = String.format("%1$tH%1$tM%1$tS", new Date());
    try {/*w  w  w .  j  a  v a  2  s  . c om*/
        JAXBContext context = JAXBContext.newInstance(LabrRequest.class);
        Marshaller m = context.createMarshaller();
        //for pretty-print XML in JAXB
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        File labrRequest = new File("data/tmp/" + date + time + ".xml");
        m.marshal(request, labrRequest);
        xml = FileUtils.readFileToString(labrRequest);

    } catch (JAXBException | IOException ex) {
        Logger.getLogger(ObjToXML.class.getName()).log(Level.SEVERE, null, ex);
    }
    return xml;
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void writeAsterixConfigurationFile(AsterixInstance asterixInstance)
        throws IOException, JAXBException {
    String asterixInstanceName = asterixInstance.getName();
    Cluster cluster = asterixInstance.getCluster();
    String metadataNodeId = asterixInstance.getMetadataNodeId();

    AsterixConfiguration configuration = asterixInstance.getAsterixConfiguration();
    configuration.setInstanceName(asterixInstanceName);
    configuration.setMetadataNode(asterixInstanceName + "_" + metadataNodeId);
    String storeDir = null;/* w w  w.ja  v  a  2 s  . c o m*/
    List<Store> stores = new ArrayList<Store>();
    for (Node node : cluster.getNode()) {
        storeDir = node.getStore() == null ? cluster.getStore() : node.getStore();
        stores.add(new Store(asterixInstanceName + "_" + node.getId(), storeDir));
    }
    configuration.setStore(stores);

    List<Coredump> coredump = new ArrayList<Coredump>();
    String coredumpDir = null;
    List<TransactionLogDir> txnLogDirs = new ArrayList<TransactionLogDir>();
    String txnLogDir = null;
    for (Node node : cluster.getNode()) {
        coredumpDir = node.getLogDir() == null ? cluster.getLogDir() : node.getLogDir();
        coredump.add(new Coredump(asterixInstanceName + "_" + node.getId(),
                coredumpDir + File.separator + asterixInstanceName + "_" + node.getId()));

        txnLogDir = node.getTxnLogDir() == null ? cluster.getTxnLogDir() : node.getTxnLogDir();
        txnLogDirs.add(new TransactionLogDir(asterixInstanceName + "_" + node.getId(), txnLogDir));
    }
    configuration.setCoredump(coredump);
    configuration.setTransactionLogDir(txnLogDirs);

    File asterixConfDir = new File(AsterixEventService.getAsterixDir() + File.separator + asterixInstanceName);
    asterixConfDir.mkdirs();

    JAXBContext ctx = JAXBContext.newInstance(AsterixConfiguration.class);
    Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    FileOutputStream os = new FileOutputStream(asterixConfDir + File.separator + ASTERIX_CONFIGURATION_FILE);
    marshaller.marshal(configuration, os);
    os.close();
}

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;
    }//from w ww.j  a  v a  2 s. co  m
    File file = new File(path + fileName);
    marshaller.marshal(objectFactory.createWAComponent(waComponent), file);
}

From source file:labr_client.xml.ObjToXML.java

public static String marshallRequest(KmehrMessage message) {
    String xml = "";
    String date = String.format("%1$tY%1$tm%1$td", new Date());
    String time = String.format("%1$tH%1$tM%1$tS", new Date());
    try {/*from   ww w  .j  a  v  a 2 s .  co m*/
        JAXBContext context = JAXBContext.newInstance(LabrRequest.class);
        Marshaller m = context.createMarshaller();
        //for pretty-print XML in JAXB
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        File kmehrMessage = new File("data/tmp/kmehr" + date + time + ".xml");
        m.marshal(message, kmehrMessage);
        xml = FileUtils.readFileToString(kmehrMessage);

    } catch (JAXBException | IOException ex) {
        Logger.getLogger(ObjToXML.class.getName()).log(Level.SEVERE, null, ex);
    }
    return xml;
}

From source file:cz.lbenda.dataman.db.ExportTableData.java

/** Write rows from sql query to output stream
 * @param sqlQueryRows rows//from  w  w w  .j a  va  2 s.co m
 * @param outputStream stream to which are data write */
public static void writeSqlQueryRowsToXMLv1(SQLQueryRows sqlQueryRows, OutputStream outputStream) {
    ObjectFactory of = new ObjectFactory();
    ExportType export = of.createExportType();
    export.setSql(sqlQueryRows.getSQL());
    export.setVersion("1");
    ColumnsType columnsType = of.createColumnsType();
    export.setColumns(columnsType);
    Map<ColumnDesc, ColumnType> ctsMap = new HashMap<>();

    sqlQueryRows.getMetaData().getColumns().forEach(cd -> {
        ColumnType ct = of.createColumnType();
        ctsMap.put(cd, ct);
        ct.setId(columnId(cd));
        ct.setCatalog(cd.getCatalog());
        ct.setSchema(cd.getSchema());
        ct.setTable(cd.getTable());
        ct.setColumn(cd.getName());
        ct.setDataType(DbStructureFactory.columnTypeToDataTypeType(cd.getDataType()));
        ct.setLength(cd.getSize());
        ct.setScale(cd.getScale());
        ct.setValue(cd.getLabel());
        columnsType.getColumn().add(ct);
    });

    sqlQueryRows.getRows().forEach(row -> {
        RowType rowType = of.createRowType();
        sqlQueryRows.getMetaData().getColumns().forEach(cd -> {
            FieldType field = of.createFieldType();
            field.setColumn(ctsMap.get(cd));
            if (row.isColumnNull(cd)) {
                field.setNull(true);
            } else {
                field.setValue(row.getColumnValueStr(cd));
            }
            rowType.getField().add(field);
        });
        export.getRow().add(rowType);
    });

    try {
        JAXBContext jc = JAXBContext.newInstance(cz.lbenda.dataman.schema.export.ObjectFactory.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
        m.marshal(of.createExport(export), outputStream);
    } catch (JAXBException e) {
        LOG.error("Problem with write exporting data: " + e.toString(), e);
        throw new RuntimeException("Problem with write exporting data: " + e.toString(), e);
    }
}

From source file:com.intuit.tank.transform.scriptGenerator.ConverterUtil.java

public static String getWorkloadXML(HDWorkload hdWorkload) {
    StringWriter sw;/*from  w w  w.jav a  2s .co  m*/
    try {
        JAXBContext context = JAXBContext.newInstance(HDWorkload.class.getPackage().getName());
        Marshaller createMarshaller = context.createMarshaller();
        createMarshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
        sw = new StringWriter();
        createMarshaller.marshal(hdWorkload, sw);
        sw.flush();
        sw.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    return sw.toString();

}