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.intuit.tank.transform.scriptGenerator.ConverterUtil.java

public static String getWorkloadXML(HDWorkload hdWorkload) {
    StringWriter sw;// ww w . j  a  v  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();

}

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 v a  2  s.c o  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.cloudera.api.model.ApiModelTest.java

static String objectToXml(Object object) throws JAXBException, UnsupportedEncodingException {
    JAXBContext jc = JAXBContext.newInstance(object.getClass());
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    m.marshal(object, baos);//from   w w  w . ja  v  a 2  s . c  om
    return baos.toString(TEXT_ENCODING);
}

From source file:org.apache.directory.fortress.core.rest.RestUtils.java

/**
 * Marshall the request into an XML String.
 *
 * @param request//from w w  w  .j av a2  s  .  com
 * @return String containing xml request
 * @throws RestException
 */
public static String marshal(FortRequest request) throws RestException {
    String szRetValue;
    try {
        // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
        final JAXBContext context = cachedJaxbContext.getJaxbContext(FortRequest.class);
        // =============================================================================================================
        // Marshalling OBJECT to XML
        // =============================================================================================================
        // Create the marshaller, that will transform the object into XML
        final Marshaller marshaller = context.createMarshaller();
        // Create a stringWriter to hold the XML
        final StringWriter stringWriter = new StringWriter();
        // Marshal the javaObject and write the XML to the stringWriter
        marshaller.marshal(request, stringWriter);
        szRetValue = stringWriter.toString();
    } catch (JAXBException je) {
        String error = "marshal caught JAXBException=" + je;
        throw new RestException(GlobalErrIds.REST_MARSHALL_ERR, error, je);
    }
    return szRetValue;
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Write response directly as XML from Object. Note that by using this method the response
 * as HTML will not be generated and the response will be what you have defined.
 *
 * @param object Object to convert into XML to write in the response.
 * @throws IOException//w  w w  . j a  v a  2 s  .  c om
 */
public static void writeResponseAsXml(Object object) throws IOException, JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
    writeResponseAsXml(object, jaxbContext.createMarshaller());
}

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 *
 * @param errorCode/*  w  ww . j a v a 2s .c  om*/
 * @param object
 * @throws IOException
 * @throws JAXBException
 */
public static void writeResponseErrorAsXml(String errorCode, Object object) throws IOException, JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
    writeResponseErrorAsXml(errorCode, object, jaxbContext.createMarshaller());
}

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);/*from  w  w w  .java2 s. co 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:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * Standard test for XSD examples./*  w  ww.  j a  va2s .  c  o m*/
 * 
 * @param testName
 *            the prototype of XSD file name / package name
 * @param extraXewOptions
 *            to be passed to plugin
 * @param generateEpisode
 *            generate episode file and check the list of classes included into it
 * @param classesToCheck
 *            expected classes/files in target directory; these files content is checked if it is present in
 *            resources directory; {@code ObjectFactory.java} is automatically included
 */
static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode,
        String... classesToCheck) throws Exception {
    String resourceXsd = testName + ".xsd";
    String packageName = testName.replace('-', '_');

    // Force plugin to reinitialize the logger:
    System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY);

    URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd);

    File targetDir = new File(GENERATED_SOURCES_PREFIX);

    targetDir.mkdirs();

    PrintStream loggingPrintStream = new PrintStream(
            new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] "));

    String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d",
            targetDir.getPath(), xsdUrl.getFile());

    String episodeFile = new File(targetDir, "episode.xml").getPath();

    // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6
    if (generateEpisode) {
        opts = ArrayUtils.addAll(opts, "-episode", episodeFile);
    }

    assertTrue("XJC compilation failed. Checked console for more info.",
            Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0);

    if (generateEpisode) {
        // FIXME: Episode file actually contains only value objects
        Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile);

        if (Arrays.asList(classesToCheck).contains("package-info")) {
            classReferences.add(packageName + ".package-info");
        }

        assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size());

        for (String className : classesToCheck) {
            assertTrue(className + " class is missing in episode file;",
                    classReferences.contains(packageName + "." + className));
        }
    }

    targetDir = new File(targetDir, packageName);

    Collection<String> generatedJavaSources = new HashSet<String>();

    // *.properties files are ignored:
    for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) {
        // This is effectively the path of targetFile relative to targetDir:
        generatedJavaSources
                .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/'));
    }

    // This class is added and checked by default:
    classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory");

    assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length,
            generatedJavaSources.size());

    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className));
    }

    // Check the contents for those files which exist in resources:
    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className);

        if (sourceFile.exists()) {
            // To avoid CR/LF conflicts:
            assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""),
                    FileUtils.readFileToString(new File(targetDir, className)).replace("\r", ""));
        }
    }

    JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources);

    URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml");

    if (xmlTestFile != null) {
        StringWriter writer = new StringWriter();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl));

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Object bean = unmarshaller.unmarshal(xmlTestFile);
        marshaller.marshal(bean, writer);

        XMLUnit.setIgnoreComments(true);
        XMLUnit.setIgnoreWhitespace(true);
        Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString());

        assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true);
    }
}

From source file:org.eclipse.winery.repository.Utils.java

public static ServiceTemplateId cloneServiceTemplate(ServiceTemplateId serviceTemplate, String newName,
        String artifactName) throws JAXBException, IllegalArgumentException, IOException {

    ServiceTemplateId newServiceTemplateId = new ServiceTemplateId(serviceTemplate.getNamespace().getDecoded(),
            newName, false);/*from  w  ww.j  a v a  2s. c  om*/

    RepositoryFileReference fileRef = new RepositoryFileReference(newServiceTemplateId,
            "ServiceTemplate.tosca");

    Definitions defs = new ServiceTemplateResource(serviceTemplate).getDefinitions();

    defs.setId(newName + "Definitions");
    defs.setName(newName + "Definitions generated from Artifact " + artifactName);

    TServiceTemplate oldSTModel = null;

    for (TExtensibleElements el : defs.getServiceTemplateOrNodeTypeOrNodeTypeImplementation()) {
        if (el instanceof TServiceTemplate) {
            oldSTModel = (TServiceTemplate) el;
        }
    }

    oldSTModel.setId(newName);
    oldSTModel.setName(newName + " generated from Artifact " + artifactName);

    // remove xaaspackager tags
    Collection<TTag> toRemove = new ArrayList<TTag>();

    for (TTag tag : oldSTModel.getTags().getTag()) {
        switch (tag.getName()) {
        case "xaasPackageNode":
        case "xaasPackageArtifactType":
        case "xaasPackageDeploymentArtifact":
            toRemove.add(tag);
            break;
        default:
            break;
        }
    }

    oldSTModel.getTags().getTag().removeAll(toRemove);

    JAXBContext context = JAXBContext.newInstance(Definitions.class);
    Marshaller m = context.createMarshaller();
    StringWriter sw = new StringWriter();
    m.marshal(defs, sw);

    String xmlString = sw.toString();

    Repository.INSTANCE.putContentToFile(fileRef, xmlString,
            MediaType.valueOf(MimeTypes.MIMETYPE_TOSCA_DEFINITIONS));

    return newServiceTemplateId;
}

From source file:com.fujitsu.dc.test.utils.DavResourceUtils.java

/**
 * BoxACL?./*from   w ww . ja  va  2  s .  com*/
 * <p>
 * 
 * <pre>
 * Acl acl = new Acl();
 * acl.getAce().add(DavResourceUtils.createAce(false, roleRead, &quot;read&quot;));
 * acl.getAce().add(DavResourceUtils.createAce(false, roleWrite, &quot;write&quot;));
 * acl.setXmlbase(String.format(&quot;%s/%s/__role/%s/&quot;,
 *         UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME));
 * DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, COL_NAME, acl, HttpStatus.SC_OK);
 * </pre>
 * </p>
 * @param token 
 * @param cell ??
 * @param box ??
 * @param col ??
 * @param acl ?ACL
 * @param code ?
 * @return ?
 * @throws JAXBException ACL????????
 */
public static TResponse setAcl(String token, String cell, String box, String col, Acl acl, int code)
        throws JAXBException {
    StringWriter writer = new StringWriter();
    JAXBContext context = JAXBContext.newInstance(Acl.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(acl, writer);
    return Http.request("box/acl-setting-none-body.txt").with("cell", cell).with("box", box)
            .with("colname", col).with("token", token).with("body", writer.toString()).returns().debug()
            .statusCode(code);
}