Example usage for javax.xml.bind Marshaller JAXB_ENCODING

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

Introduction

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

Prototype

String JAXB_ENCODING

To view the source code for javax.xml.bind Marshaller JAXB_ENCODING.

Click Source Link

Document

The name of the property used to specify the output encoding in the marshalled XML data.

Usage

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static String marshal(Object obj, String rootElementName) {
    StringWriter sw = new StringWriter();
    try {//from w w w.j  a v  a  2 s.  co m
        JAXBContext jaxbCtx = JAXBContext.newInstance(obj.getClass().getPackage().getName());
        Marshaller marshaller = jaxbCtx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(new JAXBElement(new QName(rootElementName), obj.getClass(), obj), sw);
        sw.close();

    } catch (PropertyException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sw.toString();
}

From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java

private Marshaller createMarshaller(Map<String, Object> jaxbProperties) throws JAXBException {
    Marshaller marshaller = context.createMarshaller();
    // set default properties
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    DynamicNamespacePrefixMapper namespacePrefixMapper = getSchemaRegistry().getNamespacePrefixMapper().clone();
    namespacePrefixMapper.setAlwaysExplicit(true);
    marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", namespacePrefixMapper);
    // set custom properties
    if (jaxbProperties != null) {
        for (Entry<String, Object> property : jaxbProperties.entrySet()) {
            marshaller.setProperty(property.getKey(), property.getValue());
        }/*from  ww w .ja  v a2  s .  c o m*/
    }

    return marshaller;
}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

public static Marshaller getMarshallerFor(final Object obj, final JAXBContext jaxbContext) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());

    Map<Class<?>, Marshaller> marshallers = m_marshallers.get();
    if (jaxbContext == null) {
        if (marshallers == null) {
            marshallers = new WeakHashMap<Class<?>, Marshaller>();
            m_marshallers.set(marshallers);
        }// w  w w. j  a  va2s . c  om
        if (marshallers.containsKey(clazz)) {
            LogUtils.tracef(clazz, "found unmarshaller for %s", clazz);
            return marshallers.get(clazz);
        }
    }
    LogUtils.tracef(clazz, "creating unmarshaller for %s", clazz);

    try {
        final JAXBContext context;
        if (jaxbContext == null) {
            context = getContextFor(clazz);
        } else {
            context = jaxbContext;
        }
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        final Schema schema = getValidatorFor(clazz);
        marshaller.setSchema(schema);
        if (jaxbContext == null)
            marshallers.put(clazz, marshaller);

        return marshaller;
    } catch (JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
    }
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getExecutionresultString(String urlServer, String projectAreaAlias, String encoding,
        String executionWorkItemUrl, ScenarioState stateOf, Date _startDate, Date _endDate, String details)
        throws JAXBException, DatatypeConfigurationException {

    Date startDate = (Date) _startDate.clone();
    Date endDate = (Date) _endDate.clone();

    com.ibm.rqm.xml.bind.Executionresult.Executionworkitem workTest = new com.ibm.rqm.xml.bind.Executionresult.Executionworkitem();
    workTest.setHref(executionWorkItemUrl);

    State state = new State();
    Executionresult result = new Executionresult();
    if (stateOf.equals(ScenarioState.FAILED)) {
        state.setContent("com.ibm.rqm.execution.common.state.failed");
    } else {/* w  w w . j  ava  2 s.co m*/
        if (stateOf.equals(ScenarioState.PENDING)) {
            state.setContent("com.ibm.rqm.execution.common.state.blocked");
        } else {
            state.setContent("com.ibm.rqm.execution.common.state.passed");
        }
    }

    result.setState(state);
    result.setExecutionworkitem(workTest);

    // Datas de incio e fim do teste
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(startDate);
    XMLGregorianCalendar startDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setStarttime(startDateXml);

    c.setTime(endDate);
    XMLGregorianCalendar endDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setEndtime(endDateXml);

    // Details
    Details d = new Details();
    d.getContent().add(details);
    result.setDetails(d);

    JAXBContext jaxb = JAXBContext.newInstance(Executionresult.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter resourceString = new StringWriter();
    marshaller.marshal(result, resourceString);

    return resourceString.toString();
}

From source file:org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository.java

/**
 * Causes the dataPointMap to be persisted to a file
 * @param file file definition to persist the data set to
 * @return true if dataPointMap persisted correctly, false if not
 *///from w w w . ja  va2s  .c  o  m
public boolean persist() {
    File currentArchiveFile = null;
    File tmpCurrentArchiveFile = null;
    Resource tmpResource = null;

    if (!persistHistoricData) {
        LOG.debug("not persisting data as persistHistoricData=false");
        return false;
    }

    if (archiveFileName == null || archiveFileDirectoryLocation == null) {
        LOG.error("cannot save historical data to file as incorrect file location:"
                + " archiveFileDirectoryLocation=" + archiveFileDirectoryLocation + " archiveFileName="
                + archiveFileName);
        return false;
    }

    // set the date on which this file was persisted
    datePersisted = new Date();

    // used to get file name suffix
    SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormatString);

    // persist data to temporary file <archiveFileName.tmp>
    String tmpArchiveFileName = archiveFileName + ".tmp";
    String tmpArchiveFileLocation = archiveFileDirectoryLocation + File.separator + tmpArchiveFileName;
    LOG.debug("historical data will be written to temporary file :" + tmpArchiveFileLocation);

    try {
        tmpResource = resourceLoader.getResource(tmpArchiveFileLocation);
        tmpCurrentArchiveFile = new File(tmpResource.getURL().getFile());
    } catch (IOException e) {
        LOG.error("cannot save historical data to file at archiveFileLocation='" + tmpArchiveFileLocation
                + "' due to error:", e);
        return false;
    }

    LOG.debug(
            "persisting historical data to temporary file location:" + tmpCurrentArchiveFile.getAbsolutePath());

    // marshal the data
    PrintWriter writer = null;
    boolean marshalledCorrectly = false;
    try {
        // create  directory if doesn't exist
        File directory = new File(tmpCurrentArchiveFile.getParentFile().getAbsolutePath());
        directory.mkdirs();
        // create file if doesn't exist
        writer = new PrintWriter(tmpCurrentArchiveFile, "UTF-8");
        writer.close();

        // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix
        // need to provide bundles class loader
        ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader();
        JAXBContext jaxbContext = JAXBContext.newInstance(
                "org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator", cl);

        //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator");

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        // TODO CHANGE output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        // marshal this Data Repository
        jaxbMarshaller.marshal(this, tmpCurrentArchiveFile);

        marshalledCorrectly = true;
    } catch (JAXBException e) {
        LOG.error("problem marshalling file: ", e);
    } catch (Exception e) {
        LOG.error("problem marshalling file: ", e);
    } finally {
        if (writer != null)
            writer.close();
    }
    if (marshalledCorrectly == false)
        return false;

    // marshaling succeeded so rename tmp file
    String archiveFileLocation = archiveFileDirectoryLocation + File.separator + archiveFileName;
    LOG.info("historical data will be written to:" + archiveFileLocation);

    Resource resource = resourceLoader.getResource(archiveFileLocation);

    if (resource.exists()) {
        String oldArchiveFileName = archiveFileName + "." + dateFormatter.format(datePersisted);
        String oldArchiveFileLocation = archiveFileDirectoryLocation + File.separator + oldArchiveFileName;
        LOG.info("previous historical file at archiveFileLocation='" + archiveFileLocation
                + "' exists so being renamed to " + oldArchiveFileLocation);
        Resource oldresource = resourceLoader.getResource(oldArchiveFileLocation);
        try {
            currentArchiveFile = new File(resource.getURL().getFile());
            File oldArchiveFile = new File(oldresource.getURL().getFile());
            // rename current archive file to old archive file name
            if (!currentArchiveFile.renameTo(oldArchiveFile)) {
                throw new IOException("cannot rename current archive file:"
                        + currentArchiveFile.getAbsolutePath() + " to " + oldArchiveFile.getAbsolutePath());
            }
            // rename temporary archive file to current archive file name
            if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) {
                throw new IOException("cannot rename temporary current archive file:"
                        + tmpCurrentArchiveFile.getAbsolutePath() + " to "
                        + currentArchiveFile.getAbsolutePath());
            }
        } catch (IOException e) {
            LOG.error("Problem archiving old persistance file", e);
        }
        // remove excess files
        try {
            Resource directoryResource = resourceLoader.getResource(archiveFileDirectoryLocation);
            File archiveFolder = new File(directoryResource.getURL().getFile());
            File[] listOfFiles = archiveFolder.listFiles();

            String filename;
            //this will sort earliest to latest date
            TreeMap<Date, File> sortedFiles = new TreeMap<Date, File>();

            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    filename = listOfFiles[i].getName();
                    if ((!filename.equals(archiveFileName)) && (!filename.equals(tmpArchiveFileName))
                            && (filename.startsWith(archiveFileName))) {
                        String beforeTimeString = archiveFileName + ".";
                        String timeSuffix = filename.substring(beforeTimeString.length());
                        if (!"".equals(timeSuffix)) {
                            Date fileCreatedate = null;
                            try {
                                fileCreatedate = dateFormatter.parse(timeSuffix);
                            } catch (ParseException e) {
                                LOG.debug("cant parse file name suffix to time for filename:" + filename, e);
                            }
                            if (fileCreatedate != null) {
                                sortedFiles.put(fileCreatedate, listOfFiles[i]);
                            }
                        }
                    }
                }
            }

            while (sortedFiles.size() > archiveFileMaxNumber) {
                File removeFile = sortedFiles.remove(sortedFiles.firstKey());
                LOG.debug("deleting archive file:'" + removeFile.getName()
                        + "' so that number of archive files <=" + archiveFileMaxNumber);
                removeFile.delete();
            }
            for (File archivedFile : sortedFiles.values()) {
                LOG.debug("not deleting archive file:'" + archivedFile.getName()
                        + "' so that number of archive files <=" + archiveFileMaxNumber);
            }

            return true;
        } catch (IOException e) {
            LOG.error("Problem removing old persistance files", e);
        }
    } else {
        // if resource doesn't exist just rename the new tmp file to the archive file name
        try {
            currentArchiveFile = new File(resource.getURL().getFile());
            // rename temporary archive file to current archive file name
            if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) {
                throw new IOException("cannot rename temporary current archive file:"
                        + tmpCurrentArchiveFile.getAbsolutePath() + " to "
                        + currentArchiveFile.getAbsolutePath());
            }
            return true;
        } catch (IOException e) {
            LOG.error("cannot rename temporary current archive ", e);
        }
    }

    return false;

}

From source file:org.finra.dm.tools.common.databridge.DataBridgeWebClient.java

/**
 * Registers business object data with the Data Management Service.
 *
 * @param manifest the uploader input manifest file
 * @param s3FileTransferRequestParamsDto the S3 file transfer request parameters to be used to retrieve local path and S3 key prefix values
 * @param storageName the storage name/*from w  w  w  .  jav  a  2s.c om*/
 * @param createNewVersion if not set, only initial version of the business object data is allowed to be created
 *
 * @return the business object data returned by the Data Management Service.
 * @throws IOException if an I/O error was encountered.
 * @throws JAXBException if a JAXB error was encountered.
 * @throws URISyntaxException if a URI syntax error was encountered.
 */
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE", justification = "We will use the standard carriage return character.")
public BusinessObjectData registerBusinessObjectData(UploaderInputManifestDto manifest,
        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto, String storageName,
        Boolean createNewVersion) throws IOException, JAXBException, URISyntaxException {
    LOGGER.info("Registering business object data with the Data Management Service...");

    StorageUnitCreateRequest storageUnit = new StorageUnitCreateRequest();
    storageUnit.setStorageName(storageName);

    List<StorageFile> storageFiles = new ArrayList<>();
    storageUnit.setStorageFiles(storageFiles);

    String localPath = s3FileTransferRequestParamsDto.getLocalPath();
    String s3KeyPrefix = s3FileTransferRequestParamsDto.getS3KeyPrefix();
    List<ManifestFile> localFiles = manifest.getManifestFiles();

    for (ManifestFile manifestFile : localFiles) {
        StorageFile storageFile = new StorageFile();
        storageFiles.add(storageFile);
        // Since the S3 key prefix represents a directory it is expected to contain a trailing '/' character.
        storageFile.setFilePath((s3KeyPrefix + manifestFile.getFileName()).replaceAll("\\\\", "/"));
        storageFile.setFileSizeBytes(Paths.get(localPath, manifestFile.getFileName()).toFile().length());
        storageFile.setRowCount(manifestFile.getRowCount());
    }

    BusinessObjectDataCreateRequest request = new BusinessObjectDataCreateRequest();
    request.setNamespace(manifest.getNamespace());
    request.setBusinessObjectDefinitionName(manifest.getBusinessObjectDefinitionName());
    request.setBusinessObjectFormatUsage(manifest.getBusinessObjectFormatUsage());
    request.setBusinessObjectFormatFileType(manifest.getBusinessObjectFormatFileType());
    request.setBusinessObjectFormatVersion(Integer.parseInt(manifest.getBusinessObjectFormatVersion()));
    request.setPartitionKey(manifest.getPartitionKey());
    request.setPartitionValue(manifest.getPartitionValue());
    request.setSubPartitionValues(manifest.getSubPartitionValues());
    request.setCreateNewVersion(createNewVersion);

    List<StorageUnitCreateRequest> storageUnits = new ArrayList<>();
    request.setStorageUnits(storageUnits);
    storageUnits.add(storageUnit);

    // Add business object data attributes, if any.
    if (manifest.getAttributes() != null) {
        List<Attribute> attributes = new ArrayList<>();
        request.setAttributes(attributes);

        for (Map.Entry<String, String> entry : manifest.getAttributes().entrySet()) {
            Attribute attribute = new Attribute();
            attributes.add(attribute);
            attribute.setName(entry.getKey());
            attribute.setValue(entry.getValue());
        }
    }

    // Add business object data parents, if any.
    request.setBusinessObjectDataParents(manifest.getBusinessObjectDataParents());

    // Create a JAXB context and marshaller
    JAXBContext requestContext = JAXBContext.newInstance(BusinessObjectDataCreateRequest.class);
    Marshaller requestMarshaller = requestContext.createMarshaller();
    requestMarshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
    requestMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter sw = new StringWriter();
    requestMarshaller.marshal(request, sw);

    BusinessObjectData businessObjectData;
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        URI uri = new URIBuilder().setScheme(getUriScheme())
                .setHost(dmRegServerAccessParamsDto.getDmRegServerHost())
                .setPort(dmRegServerAccessParamsDto.getDmRegServerPort())
                .setPath(DM_APP_REST_URI_PREFIX + "/businessObjectData").build();
        HttpPost post = new HttpPost(uri);

        post.addHeader("Content-Type", "application/xml");
        post.addHeader("Accepts", "application/xml");

        // If SSL is enabled, set the client authentication header.
        if (dmRegServerAccessParamsDto.getUseSsl()) {
            post.addHeader(getAuthorizationHeader());
        }

        post.setEntity(new StringEntity(sw.toString()));

        LOGGER.info(String.format("    HTTP POST URI: %s", post.getURI().toString()));
        LOGGER.info(String.format("    HTTP POST Headers: %s", Arrays.toString(post.getAllHeaders())));
        LOGGER.info(String.format("    HTTP POST Entity Content:\n%s", sw.toString()));

        businessObjectData = getBusinessObjectData(httpClientOperations.execute(client, post),
                "register business object data with the Data Management Service");
    }

    LOGGER.info("Successfully registered business object data with the Data Management Service.");

    // getBusinessObjectData() might return a null. That happens when the web client gets status code 200 back from
    // the service (data registration is a success), but it fails to retrieve or deserialize the actual HTTP response.
    // Please note that processXmlHttpResponse() is responsible for logging the exception info as a warning.
    if (businessObjectData != null) {
        LOGGER.info("    ID: " + businessObjectData.getId());
    }

    return businessObjectData;
}

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

/**
 * Saves the mets document into a file//  ww  w  .  jav a  2  s . c  o  m
 *
 * @param mets
 * @param outputFile
 * @throws MetsExportException
 */
private void saveMets(Mets mets, File outputFile, IMetsElement metsElement) throws MetsExportException {
    String fileMd5Name;
    try {
        addFileGrpToMets(fileGrpMap);
        addStructLink();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Mets.class, OaiDcType.class,
                    ModsDefinition.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
            // marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
            // "http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2001/XMLSchema.xsd http://www.loc.gov/METS/ http://www.loc.gov/standards/mets/mets.xsd http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/mods.xsd http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd");
            marshaller.marshal(mets, outputFile);
            MessageDigest md;
            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new MetsExportException("Unable to create MD5 hash", false, e);
            }
            md.reset();
            InputStream is;
            try {
                is = new FileInputStream(outputFile);
            } catch (FileNotFoundException e) {
                throw new MetsExportException("Unable to open file:" + outputFile.getAbsolutePath(), false, e);
            }
            byte[] bytes = new byte[2048];
            int numBytes;
            long totalBytes = 0;
            try {
                while ((numBytes = is.read(bytes)) != -1) {
                    totalBytes = totalBytes + numBytes;

                    md.update(bytes, 0, numBytes);
                }
            } catch (IOException e) {
                throw new MetsExportException("Unable to generate MD5 hash", false, e);
            }
            byte[] digest = md.digest();
            String result = new String(Hex.encodeHex(digest));
            metsElement.getMetsContext().getFileList()
                    .add(new FileMD5Info("." + File.separator + outputFile.getName(), result, totalBytes));
            fileMd5Name = "MD5_" + MetsUtils.removeNonAlpabetChars(metsElement.getMetsContext().getPackageID())
                    + ".md5";
            File fileMd5 = new File(metsElement.getMetsContext().getOutputPath() + File.separator
                    + metsElement.getMetsContext().getPackageID() + File.separator + fileMd5Name);
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileMd5));
            for (FileMD5Info info : metsElement.getMetsContext().getFileList()) {
                osw.write(info.getMd5() + " " + info.getFileName() + "\n");
            }
            osw.close();
            is.close();

            // calculate md5 for md5file - it's inserted into info.xml
            is = new FileInputStream(fileMd5);
            FileMD5Info md5InfoMd5File = MetsUtils.getDigest(is);
            is.close();
            metsElement.getMetsContext().getFileList()
                    .add(new FileMD5Info("." + File.separator + fileMd5Name, null, fileMd5.length()));
            MetsUtils.saveInfoFile(metsElement.getMetsContext().getOutputPath(), metsElement.getMetsContext(),
                    md5InfoMd5File.getMd5(), fileMd5Name, outputFile);
        } catch (Exception ex) {
            throw new MetsExportException(metsElement.getOriginalPid(),
                    "Unable to save mets file:" + outputFile.getAbsolutePath(), false, ex);
        }
        List<String> validationErrors;
        try {
            validationErrors = MetsUtils.validateAgainstXSD(outputFile,
                    Mets.class.getResourceAsStream("mets.xsd"));
        } catch (Exception ex) {
            throw new MetsExportException("Error while validation document:" + outputFile, false, ex);
        }
        if (validationErrors.size() > 0) {
            MetsExportException metsException = new MetsExportException("Invalid mets file:" + outputFile,
                    false, null);
            metsException.getExceptions().get(0).setValidationErrors(validationErrors);
            for (String error : validationErrors) {
                LOG.fine(error);
            }
            throw metsException;
        }
        LOG.log(Level.FINE,
                "Element validated:" + metsElement.getOriginalPid() + "(" + metsElement.getElementType() + ")");
    } finally {
        JhoveUtility.destroyConfigFiles(metsElement.getMetsContext().getJhoveContext());
    }
    metsElement.getMetsContext().getGeneratedPSP().add(metsElement.getMetsContext().getPackageID());
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected String toXml(Object o) {
    try {/*from  w  w w.  ja  v a2 s.c  o  m*/
        StringWriter sw = new StringWriter();
        JAXBContext context = JAXBContext.newInstance(o.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
        marshaller.setSchema(null);
        marshaller.marshal(o, sw);
        return sw.toString();
    } catch (JAXBException e) {
        if (logger.isTraceEnabled())
            logger.trace(e.getMessage(), e);
        if (logger.isInfoEnabled())
            logger.info(e.getMessage());
    }
    return null;
}

From source file:carisma.ui.eclipse.CarismaGUI.java

public final static void saveXml(final AnalysisResult analysisResult) {
    IContainer container = analysisResult.getAnalysis().getIFile().getParent();
    IFile file = null;//w  ww  . j  av  a 2s  .  c  o  m
    if (container instanceof IFolder) {
        IFolder folder = (IFolder) container;
        file = folder.getFile(
                "xml-output-" + analysisResult.getName() + "-" + analysisResult.getTimestamp() + ".xml");

    } else if (container instanceof IProject) {
        IProject project = (IProject) container;
        file = project.getFile(
                "xml-output-" + analysisResult.getName() + "-" + analysisResult.getTimestamp() + ".xml");
    } else {
        Logger.log(LogLevel.ERROR, "Analyzed file is not part of a project.");
        return;
    }
    if (!(file.exists())) {

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            JAXBContext context = JAXBContext.newInstance(carisma.core.analysis.result.AnalysisResult.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            m.marshal(analysisResult, out);

            String store = new String(out.toByteArray(), StandardCharsets.UTF_8);

            InputStream is = new ByteArrayInputStream(store.getBytes(StandardCharsets.UTF_8));
            // file.create(Utils.createInputStreamFromString(store), true,
            // null);
            file.create(is, true, null);

            // JSONObject fromXml = XML.toJSONObject(store);
            // String jsonPrint = fromXml.toString(1);
            // System.out.println(jsonPrint);

            // carisma.core.analysis.result.exp.dbexport.exportXml(jsonPrint);

            out.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}

From source file:cz.cas.lib.proarc.desa.SIP2DESATransporter.java

/**
 * Initialize JAXB transformers/* ww w . j a va2s  . co m*/
 *
 * @throws JAXBException
 */
private void initJAXB() throws JAXBException {
    if (marshaller != null) {
        return;
    }
    JAXBContext jaxbContext = getPspipJaxb();
    marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    unmarshaller = jaxbContext.createUnmarshaller();
}