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:main.java.refinement_class.Useful.java

public static String mashal2(Object o, Class c) {

    Marshaller marshaller;
    // create a JAXBContext
    JAXBContext jaxbContext;//from w  ww  .  j ava2  s  .  com
    String xmlString = "";

    try {
        jaxbContext = JAXBContext.newInstance(c);
        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
        //  marshaller.marshal(o, new FileOutputStream(xml_file));

        StringWriter sw = new StringWriter();
        marshaller.marshal(o, sw);
        xmlString = sw.toString();
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return xmlString;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java

/**
 * Persists files streaming state in specified directory or system temp directory.
 *
 * @param fileAccessState/*from w  ww  .j  a va 2s  .  c o m*/
 *            streamed files access state
 * @param fileDir
 *            directory to save file
 * @param streamName
 *            stream name
 *
 * @return file containing persisted state
 *
 * @throws JAXBException
 *             if parsing fails
 */
static File writeState(FileAccessState fileAccessState, File fileDir, String streamName) throws JAXBException {
    if (fileAccessState == null) {
        return null;
    }

    JAXBContext jaxb = JAXBContext.newInstance(FileAccessState.class);
    final Marshaller marshaller = jaxb.createMarshaller();

    File fasFile = null;
    String fileName = getFileName(streamName);
    if (fileDir != null) {
        fasFile = new File(fileDir, fileName);
    }

    if (fileDir == null || !fasFile.canWrite()) {
        fasFile = new File(System.getProperty("java.io.tmpdir"), fileName);
    }
    marshaller.marshal(fileAccessState, fasFile);

    return fasFile;
}

From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java

public static void testLoadOGCServiceMetadata() {
    // String xmlFile =
    // "J:/dev/atoll-v2/atoll-motu/atoll-motu-processor/src/test/resources/xml/TestServiceMetadata.xml";
    String xmlFile = "C:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/TestServiceMetadataOK.xml";

    String schemaPath = "schema/iso19139";

    try {//from  ww w .j a va 2s .  c om
        List<String> errors = validateServiceMetadataFromString(xmlFile, schemaPath);
        if (errors.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            for (String str : errors) {
                stringBuffer.append(str);
                stringBuffer.append("\n");
            }
            throw new MotuException(String.format("ERROR - XML file '%s' is not valid - See errors below:\n%s",
                    xmlFile, stringBuffer.toString()));
        } else {
            System.out.println(String.format("XML file '%s' is valid", xmlFile));
        }

    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream in = null;
    try {
        in = Organizer.getUriAsInputStream(xmlFile);
    } catch (MotuException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JAXBContext jc = null;
    try {
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        jc = JAXBContext
                .newInstance(new Class[] { org.isotc211.iso19139.d_2006_05_04.srv.ObjectFactory.class });
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Source srcFile = new StreamSource(xmlFile);
        JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(srcFile);
        // JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(in);
        SVServiceIdentificationType serviceIdentificationType = (SVServiceIdentificationType) element
                .getValue();
        // serviceIdentificationType = (SVServiceIdentificationType) unmarshaller.unmarshal(in);
        System.out.println(serviceIdentificationType.toString());

        List<SVOperationMetadataPropertyType> operationMetadataPropertyTypeList = serviceIdentificationType
                .getContainsOperations();

        for (SVOperationMetadataPropertyType operationMetadataPropertyType : operationMetadataPropertyTypeList) {

            SVOperationMetadataType operationMetadataType = operationMetadataPropertyType
                    .getSVOperationMetadata();
            System.out.println("---------------------------------------------");
            if (operationMetadataType == null) {
                continue;
            }
            System.out.println(operationMetadataType.getOperationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getInvocationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getOperationDescription().getCharacterString().getValue());

            CIOnlineResourcePropertyType onlineResourcePropertyType = operationMetadataType.getConnectPoint()
                    .get(0);
            if (onlineResourcePropertyType != null) {
                System.out.println(operationMetadataType.getConnectPoint().get(0).getCIOnlineResource()
                        .getLinkage().getURL());
            }

            List<SVParameterPropertyType> parameterPropertyTypeList = operationMetadataType.getParameters();

            for (SVParameterPropertyType parameterPropertyType : parameterPropertyTypeList) {
                SVParameterType parameterType = parameterPropertyType.getSVParameter();

                if (parameterType.getName().getAName().getCharacterString() != null) {
                    System.out.println(parameterType.getName().getAName().getCharacterString().getValue());
                } else {
                    System.out.println("WARNING - A parameter has no name");

                }
                if (parameterType.getDescription() != null) {
                    if (parameterType.getDescription().getCharacterString() != null) {
                        System.out.println(parameterType.getDescription().getCharacterString().getValue());
                    } else {
                        System.out.println("WARNING - A parameter has no description");

                    }
                } else {
                    System.out.println("WARNING - A parameter has no description");

                }
            }

        }
        FileWriter writer = new FileWriter("c:/tempVFS/test.xml");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(element, writer);

        writer.flush();
        writer.close();

        System.out.println("End testLoadOGCServiceMetadata");
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.evolveum.midpoint.model.client.ModelClientUtil.java

public static <T> String marshallToSting(QName elementName, T object, boolean formatted) throws JAXBException {
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    if (formatted) {
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    }//from   w w w. j  a  v  a 2 s  .c o m
    java.io.StringWriter sw = new StringWriter();
    JAXBElement<T> element = new JAXBElement<T>(elementName, (Class<T>) object.getClass(), object);
    marshaller.marshal(element, sw);
    return sw.toString();
}

From source file:com.virtualparadigm.packman.processor.JPackageManagerBU.java

private static void marshallToFile(Collection<Package> installPackages, String filePath) {
    try {/*from www  .j av a  2s  .c  o  m*/
        Marshaller marshaller = jaxbContext.createMarshaller();

        // removes the xml header:
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        StringWriter stringWriter = new StringWriter();
        for (Package installPackage : installPackages) {
            marshaller.marshal(
                    new JAXBElement<Package>(new QName(null, "installPackage"), Package.class, installPackage),
                    stringWriter);

            stringWriter.append("\n");
        }

        FileUtils.writeStringToFile(new File(filePath), stringWriter.toString(), "UTF-8");
    } catch (Exception e) {
        logger.error("", e);
        //            e.printStackTrace();
    }
}

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);
    return baos.toString(TEXT_ENCODING);
}

From source file:com.evolveum.midpoint.model.client.ModelClientUtil.java

public static <O extends ObjectType> String marshallToSting(O object, boolean formatted) throws JAXBException {
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    if (formatted) {
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    }/*from  w  w  w .  java2 s  .co m*/
    java.io.StringWriter sw = new StringWriter();
    Class<O> type = (Class<O>) object.getClass();
    JAXBElement<O> element = new JAXBElement<O>(getElementName(type), type, object);
    marshaller.marshal(element, sw);
    return sw.toString();
}

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   ww  w . ja v  a 2 s  .  c o  m

    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:org.eclipse.winery.repository.Utils.java

public static <T> String getXMLAsString(Class<T> clazz, T obj, boolean includeProcessingInstruction) {
    JAXBElement<T> rootElement = Util.getJAXBElement(clazz, obj);
    Marshaller m = JAXBSupport.createMarshaller(includeProcessingInstruction);
    StringWriter w = new StringWriter();
    try {//w w  w  . j av a2  s  . c  o m
        m.marshal(rootElement, w);
    } catch (JAXBException e) {
        Utils.LOGGER.error("Could not put content to string", e);
        throw new IllegalStateException(e);
    }
    return w.toString();
}

From source file:com.jkoolcloud.tnt4j.streams.utils.StreamsCache.java

private static void persist(Map<String, CacheValue> cacheEntries) {
    try {//from ww w.  j a v a 2 s .c  om
        JAXBContext jc = JAXBContext.newInstance(CacheRoot.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        CacheRoot root = new CacheRoot();
        root.setEntriesMap(cacheEntries);
        File persistedFile = new File(DEFAULT_FILE_NAME);
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME),
                "StreamsCache.persisting.file", persistedFile.getAbsolutePath());
        marshaller.marshal(root, persistedFile);
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME),
                "StreamsCache.persisting.done", cacheEntries.size(), persistedFile.getAbsolutePath());
    } catch (JAXBException exc) {
        Utils.logThrowable(LOGGER, OpLevel.ERROR,
                StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME),
                "StreamsCache.persisting.failed", exc);
    }
}