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:org.eclipsetrader.yahoo.internal.news.NewsProvider.java

protected void save() throws JAXBException, IOException {
    File file = YahooActivator.getDefault().getStateLocation().append(HEADLINES_FILE).toFile();
    if (file.exists()) {
        file.delete();/*from w w  w.  j  a v  a  2  s. c  o  m*/
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(HeadLine[].class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            Status status = new Status(IStatus.WARNING, YahooActivator.PLUGIN_ID, 0,
                    "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
            YahooActivator.getDefault().getLog().log(status);
            return true;
        }
    });
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, System.getProperty("file.encoding")); //$NON-NLS-1$

    JAXBElement<HeadLine[]> element = new JAXBElement<HeadLine[]>(new QName("list"), HeadLine[].class,
            oldItems.toArray(new HeadLine[oldItems.size()]));
    marshaller.marshal(element, new FileWriter(file));
}

From source file:org.eclipsetrader.yahoojapan.internal.news.NewsProvider.java

protected void save() throws JAXBException, IOException {
    File file = YahooJapanActivator.getDefault().getStateLocation().append(HEADLINES_FILE).toFile();
    if (file.exists()) {
        file.delete();/*ww  w  .  jav a  2s.  co m*/
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(HeadLine[].class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            Status status = new Status(IStatus.WARNING, YahooJapanActivator.PLUGIN_ID, 0,
                    "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
            YahooJapanActivator.getDefault().getLog().log(status);
            return true;
        }
    });
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, System.getProperty("file.encoding")); //$NON-NLS-1$

    JAXBElement<HeadLine[]> element = new JAXBElement<HeadLine[]>(new QName("list"), HeadLine[].class,
            oldItems.toArray(new HeadLine[oldItems.size()]));
    marshaller.marshal(element, new FileWriter(file));
}

From source file:org.energy_home.jemma.javagal.rest.util.Util.java

/**
 * Marshal class./*from  w  w w  .j  av a2 s .c  o  m*/
 * 
 * @param o
 *            the object to marshall.
 * 
 * @return the marshalled representation.
 */
@SuppressWarnings("unchecked")
synchronized public static <T> String marshal(Object o) {

    StringWriter stringWriter = new StringWriter();
    try {
        JAXBContext jc = JAXBContext.newInstance(o.getClass());
        Marshaller m = jc.createMarshaller();
        QName _qname = new QName("http://www.zigbee.org/GWGRESTSchema", o.getClass().getSimpleName());
        JAXBElement<T> je = new JAXBElement<T>(_qname, (Class<T>) o.getClass(), ((T) o));
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());
        m.setProperty("com.sun.xml.internal.bind.xmlDeclaration", Boolean.FALSE);
        m.marshal(je, stringWriter);
        String _tores = stringWriter.toString();

        return _tores;
    } catch (JAXBException e) {
        logger.error("Exception on marshal : " + e.getMessage());
        return EMPTY_STRING;
    }
}

From source file:org.excalibur.core.util.JAXBContextFactory.java

protected Document getDocument(E type) throws ParserConfigurationException, JAXBException {
    Document document = this.getDocumentFactory().newDocumentBuilder().newDocument();
    Marshaller marshaller = JAXBContext.newInstance(type.getClass()).createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, DEFAULT_XML_ENCODING);
    marshaller.marshal(type, document);/*  w ww  .  j  av a2  s  .  com*/
    return document;
}

From source file:org.excalibur.core.util.JAXBContextFactory.java

protected Marshaller createMarshaller(String packageName) throws JAXBException {
    final Marshaller marshaller = getContext(packageName).createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, DEFAULT_XML_ENCODING);

    if (!(this.getSchema() == null)) {
        marshaller.setSchema(getSchema());
    }//w w  w.  j a v a  2s . c om

    return marshaller;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private String exportAuditFileToXML(AuditFile auditFile) {
    try {//  www. ja v a2s. com
        final String cleanXMLAnotations = "xsi:type=\"xs:string\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"";
        final String cleanXMLAnotations2 = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
        final String cleanDateTimeMiliseconds = ".000<";
        final String cleanStandaloneAnnotation = "standalone=\"yes\"";

        final JAXBContext jaxbContext = JAXBContext.newInstance(AuditFile.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        StringWriter writer = new StringWriter();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "Windows-1252");
        marshaller.marshal(auditFile, writer);

        Charset charset = Charset.forName("Windows-1252");

        String xml = new String(charset.encode(writer.toString()).array(), "Windows-1252");
        xml = xml.replace(cleanXMLAnotations, "");
        xml = xml.replace(cleanXMLAnotations2, "");
        xml = xml.replace(cleanDateTimeMiliseconds, "<");
        xml = xml.replace(cleanStandaloneAnnotation, "");

        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(("SALTING WITH QUB:" + xml).getBytes("Windows-1252"));
            byte[] output = md.digest();
            String digestAscii = bytesToHex(output);
            xml = xml + "<!-- QUB-IT (remove this line,add the qubSALT, save with Windows-1252 encode): "
                    + digestAscii + " -->\n";
        } catch (Exception ex) {

        }
        return xml;
    } catch (JAXBException e) {
        return org.apache.commons.lang.StringUtils.EMPTY;
    } catch (UnsupportedEncodingException jex) {
        return org.apache.commons.lang.StringUtils.EMPTY;
    }
}

From source file:org.finra.dm.dao.helper.XmlHelper.java

/**
 * Returns XML representation of the object using the DM custom character escape handler.
 *
 * @param obj the Java object to be serialized
 * @param formatted specifies whether or not the marshalled XML data is formatted with line feeds and indentation
 *
 * @return the XML representation of this object
 * @throws JAXBException if a JAXB error occurred.
 */// www  .j  a va2  s  .com
public String objectToXml(Object obj, boolean formatted) throws JAXBException {
    JAXBContext requestContext = JAXBContext.newInstance(obj.getClass());
    Marshaller requestMarshaller = requestContext.createMarshaller();

    if (formatted) {
        requestMarshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
        requestMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    }

    // Specify a custom character escape handler to escape XML 1.1 restricted characters.
    requestMarshaller.setProperty(MarshallerProperties.CHARACTER_ESCAPE_HANDLER, dmCharacterEscapeHandler);

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

    return sw.toString();
}

From source file:org.finra.herd.dao.helper.XmlHelper.java

/**
 * Returns XML representation of the object using the herd custom character escape handler.
 *
 * @param obj the Java object to be serialized
 * @param formatted specifies whether or not the marshalled XML data is formatted with line feeds and indentation
 *
 * @return the XML representation of this object
 * @throws JAXBException if a JAXB error occurred.
 *//* w w w  . j  a  va 2  s  .c om*/
public String objectToXml(Object obj, boolean formatted) throws JAXBException {
    JAXBContext requestContext = JAXBContext.newInstance(obj.getClass());
    Marshaller requestMarshaller = requestContext.createMarshaller();

    if (formatted) {
        requestMarshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
        requestMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    }

    // Specify a custom character escape handler to escape XML 1.1 restricted characters.
    requestMarshaller.setProperty(MarshallerProperties.CHARACTER_ESCAPE_HANDLER, herdCharacterEscapeHandler);

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

    return sw.toString();
}

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

/**
 * Calls the registration server to add storage files to the business object data.
 *
 * @param businessObjectDataKey the business object data key
 * @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//  w  w  w  .j a  va 2  s . c o m
 *
 * @return the business object data create storage files response turned by the registration server.
 * @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
 * @throws KeyStoreException if a key store exception occurs
 * @throws NoSuchAlgorithmException if a no such algorithm exception occurs
 * @throws KeyManagementException if key management exception
 */
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE", justification = "We will use the standard carriage return character.")
public BusinessObjectDataStorageFilesCreateResponse addStorageFiles(BusinessObjectDataKey businessObjectDataKey,
        UploaderInputManifestDto manifest, S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto,
        String storageName) throws IOException, JAXBException, URISyntaxException, NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException {
    LOGGER.info("Adding storage files to the business object data ...");

    BusinessObjectDataStorageFilesCreateRequest request = new BusinessObjectDataStorageFilesCreateRequest();
    request.setNamespace(businessObjectDataKey.getNamespace());
    request.setBusinessObjectDefinitionName(businessObjectDataKey.getBusinessObjectDefinitionName());
    request.setBusinessObjectFormatUsage(businessObjectDataKey.getBusinessObjectFormatUsage());
    request.setBusinessObjectFormatFileType(businessObjectDataKey.getBusinessObjectFormatFileType());
    request.setBusinessObjectFormatVersion(businessObjectDataKey.getBusinessObjectFormatVersion());
    request.setPartitionValue(businessObjectDataKey.getPartitionValue());
    request.setSubPartitionValues(businessObjectDataKey.getSubPartitionValues());
    request.setBusinessObjectDataVersion(businessObjectDataKey.getBusinessObjectDataVersion());
    request.setStorageName(storageName);

    List<StorageFile> storageFiles = new ArrayList<>();
    request.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());
    }

    // Create a JAXB context and marshaller
    JAXBContext requestContext = JAXBContext.newInstance(BusinessObjectDataStorageFilesCreateRequest.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);

    BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse;
    try (CloseableHttpClient client = httpClientHelper.createHttpClient(
            regServerAccessParamsDto.isTrustSelfSignedCertificate(),
            regServerAccessParamsDto.isDisableHostnameVerification())) {
        URI uri = new URIBuilder().setScheme(getUriScheme())
                .setHost(regServerAccessParamsDto.getRegServerHost())
                .setPort(regServerAccessParamsDto.getRegServerPort())
                .setPath(HERD_APP_REST_URI_PREFIX + "/businessObjectDataStorageFiles").build();
        HttpPost post = new HttpPost(uri);

        post.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
        post.addHeader("Accepts", DEFAULT_ACCEPT);

        // If SSL is enabled, set the client authentication header.
        if (regServerAccessParamsDto.isUseSsl()) {
            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()));

        // getBusinessObjectDataStorageFilesCreateResponse() might return a null. That happens when the web client gets status code 200 back from
        // the service (add storage files 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.
        businessObjectDataStorageFilesCreateResponse = getBusinessObjectDataStorageFilesCreateResponse(
                httpClientOperations.execute(client, post));
    }

    LOGGER.info("Successfully added storage files to the registered business object data.");

    return businessObjectDataStorageFilesCreateResponse;
}

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

/**
 * Pre-registers business object data with the registration server.
 *
 * @param manifest the uploader input manifest file
 * @param storageName the storage name// w  w w  .j  ava 2 s . 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 registration server.
 * @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
 * @throws KeyStoreException if a key store exception occurs
 * @throws NoSuchAlgorithmException if a no such algorithm exception occurs
 * @throws KeyManagementException if key management exception
 */
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE", justification = "We will use the standard carriage return character.")
public BusinessObjectData preRegisterBusinessObjectData(UploaderInputManifestDto manifest, String storageName,
        Boolean createNewVersion) throws IOException, JAXBException, URISyntaxException,
        NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    LOGGER.info("Pre-registering business object data with the registration server...");

    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);
    request.setStatus(BusinessObjectDataStatusEntity.UPLOADING);

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

    // 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 = httpClientHelper.createHttpClient(
            regServerAccessParamsDto.isTrustSelfSignedCertificate(),
            regServerAccessParamsDto.isDisableHostnameVerification())) {
        URI uri = new URIBuilder().setScheme(getUriScheme())
                .setHost(regServerAccessParamsDto.getRegServerHost())
                .setPort(regServerAccessParamsDto.getRegServerPort())
                .setPath(HERD_APP_REST_URI_PREFIX + "/businessObjectData").build();
        HttpPost post = new HttpPost(uri);

        post.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
        post.addHeader("Accepts", DEFAULT_ACCEPT);

        // If SSL is enabled, set the client authentication header.
        if (regServerAccessParamsDto.isUseSsl()) {
            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 registration server");
    }

    LOGGER.info(String.format(
            "Successfully pre-registered business object data with the registration server. businessObjectDataId=%s",
            businessObjectData.getId()));

    return businessObjectData;
}