Example usage for javax.xml.bind Marshaller setProperty

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

Introduction

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

Prototype

public void setProperty(String name, Object value) throws PropertyException;

Source Link

Document

Set the particular property in the underlying implementation of Marshaller .

Usage

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

protected String toXml(Object o) {
    try {// w  w w . ja  v a 2s  .  co 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:alter.vitro.vgw.service.resourceRegistry.ResourceAvailabilityService.java

public String createSynchConfirmationForVSPFromCurrentStatus_VGWInitiated() {
    String retStr = "";

    try {/*  w w  w .java2 s  .  com*/
        EnableNodesRespType response;

        javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext
                .newInstance("alter.vitro.vgw.service.query.xmlmessages.enablednodessynch.fromvgw");
        // create an object to marshal
        ObjectFactory theFactory = new ObjectFactory();
        response = theFactory.createEnableNodesRespType();

        if (response != null) {
            response.setVgwId(VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg());
            response.setMessageType(UserNodeResponse.COMMAND_TYPE_ENABLENODES_RESP);

            response.setTimestamp(Long.toString(new Date().getTime()));
            if (response.getConfirmedEnabledNodesList() == null) {
                ConfirmedEnabledNodesListType theConfirmListType = new ConfirmedEnabledNodesListType();
                response.setConfirmedEnabledNodesList(theConfirmListType);

                for (String devId : getCachedDiscoveredDevices().keySet()) {
                    CSmartDevice smDevTmp = getCachedDiscoveredDevices().get(devId);
                    // AND CONSTRUCT THE CONFIRMATION MESSAGE!
                    ConfirmedEnabledNodesListItemType confirmedItemTmp = new ConfirmedEnabledNodesListItemType();
                    confirmedItemTmp.setNodeId(smDevTmp.getId());
                    boolean updatedByVGW = smDevTmp.getRegistryProperties().isStatusWasDecidedByThisVGW();
                    boolean currStatus = smDevTmp.getRegistryProperties().isEnabled();
                    String updatedByVGWStr = updatedByVGW ? "1" : "0";
                    String currStatusStr = currStatus ? "enabled" : "disabled";
                    confirmedItemTmp.setStatus(currStatusStr);
                    confirmedItemTmp.setGwInitFlag(updatedByVGWStr);
                    confirmedItemTmp.setOfRemoteTimestamp(Long.toString(
                            smDevTmp.getRegistryProperties().getTimeStampEnabledStatusRemotelySynch()));
                    theConfirmListType.getConfirmedEnabledNodesListItem().add(confirmedItemTmp);
                }
            }
            javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            JAXBElement<EnableNodesRespType> myResponseMsgEl = theFactory.createEnableNodesResp(response);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            marshaller.marshal(myResponseMsgEl, baos);
            retStr = baos.toString(HTTP.UTF_8);
        }

    } catch (javax.xml.bind.JAXBException je) {
        je.printStackTrace();
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    logger.debug("Sending UPDATE FROM VGW (enable-disable): " + retStr);
    return retStr;
}

From source file:com.intuit.tank.tools.script.ScriptFilterRunner.java

private String toXml(ScriptTO turboScriptTO) {
    String ret = null;// w w  w .j  av  a  2s .c o  m
    try {
        JAXBContext ctx = JAXBContext.newInstance(ScriptTO.class.getPackage().getName());
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", true);
        StringWriter sw = new StringWriter();
        marshaller.marshal(turboScriptTO, sw);
        ret = sw.toString();
    } catch (JAXBException e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "Error reading file", JOptionPane.ERROR_MESSAGE);
    }
    return ret;
}

From source file:com.intuit.tank.tools.script.ScriptFilterRunner.java

/**
 * //  ww  w  .  j  ava  2s . c o m
 */
protected void saveXml() {
    Writer fw = null;
    try {
        fw = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");
        // fw = new FileWriter(xmlFile);
        JAXBContext ctx = JAXBContext.newInstance(ScriptTO.class.getPackage().getName());
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", true);
        marshaller.marshal(tankScript, fw);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "Error writing file", JOptionPane.ERROR_MESSAGE);
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:com.francetelecom.clara.cloud.logicalmodel.LogicalDeployment.java

/**
 * gets an XML representation of the model
 * @return/*from w w  w  .ja  v a2s. c o  m*/
 */
public String dumpXml() {

    logger.debug("dumping xml model for " + this + " into a String");
    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance(LogicalDeployment.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        m.marshal(this, baos);
        return baos.toString();

    } catch (JAXBException e) {
        logger.error("Unable to marshall model");
        throw new TechnicalException(e);
    }

}

From source file:com.qpark.eip.core.spring.PayloadLogger.java

/**
 * @return the {@link Marshaller}.//from www  . j  a  v  a 2  s.  com
 */
private Marshaller getMarshaller() {
    Marshaller marshaller = null;
    try {
        if (this.jaxbContext == null) {
            this.jaxbContext = JAXBContext.newInstance(this.contextPath);
        }
        marshaller = this.jaxbContext.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", true);
    } catch (final Exception e) {
        // noting to do here.
    }
    return marshaller;
}

From source file:alter.vitro.vgw.service.ContinuationOfProvisionService.java

/**
 * Processes synch updates to the sets of equivalency received from the VSP.
 */// w w  w  .j a  v  a2 s .  com
public String createSynchConfirmationForVSP(EquivListNodesReqType forRequest) {
    String retStr = "";
    // todo check also the timestamp of the Request with the lastUpdatedTimeStamp
    // and update the lastUpdatedTimeStamp if needed.
    if (forRequest != null) {
        long receivedTimestamp = 0;
        try {
            receivedTimestamp = Long.valueOf(forRequest.getTimestamp());
        } catch (Exception enmfrmtx) {
            logger.error("Exception while converting timestamp of synch message");
        }
        if (receivedTimestamp < lastUpdatedTimeStamp) {
            //ignore the message
            logger.info("Ignoring synch message with old timestamp");
            return null;
        } else {
            lastUpdatedTimeStamp = receivedTimestamp;
            // clean / purge existing cache of equivLists   and replacements
            getCachedSetsOfEquivalency().clear();
            getCachedReplacedResources().clear();
        }
    }

    try {
        EquivListNodesRespType response;

        javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext
                .newInstance("alter.vitro.vgw.service.query.xmlmessages.equivlistsynch.fromvgw");
        // create an object to marshal
        ObjectFactory theFactory = new ObjectFactory();
        response = theFactory.createEquivListNodesRespType();

        if (response != null && forRequest != null) {

            response.setVgwId(VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg());
            response.setMessageType(UserNodeResponse.COMMAND_TYPE_EQUIV_LIST_SYNCH_RESP);

            response.setTimestamp(Long.toString(new Date().getTime()));
            if (forRequest.getEquivNodesList() != null) {

                if (response.getConfirmedNodesList() == null) {
                    ConfirmedNodesListType theConfirmListType = new ConfirmedNodesListType();
                    response.setConfirmedNodesList(theConfirmListType);
                }
                //
                if (forRequest.getEquivNodesList().getEquivNodesListItem() != null
                        && !forRequest.getEquivNodesList().getEquivNodesListItem().isEmpty()) {
                    // loop though items and confirm each one
                    for (EquivNodesListItemType reqItem : forRequest.getEquivNodesList()
                            .getEquivNodesListItem()) {
                        ConfirmedNodesListItemType confirmedItemTmp = new ConfirmedNodesListItemType();
                        confirmedItemTmp.setListId(reqItem.getListId());
                        confirmedItemTmp.setOfRemoteTimestamp(reqItem.getOfRemoteTimestamp());
                        // process this addition to local cache
                        handleVSPUpdateForSetsOfEquivalency(reqItem);

                        response.getConfirmedNodesList().getConfirmedNodesListItem().add(confirmedItemTmp);
                    }
                }
            }

            //javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext.newInstance("alter.vitro.vgw.service.query.xmlmessages.equivlistsynch.fromvgw");
            //ObjectFactory theFactory = new ObjectFactory();
            javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            JAXBElement<EquivListNodesRespType> myResponseMsgEl = theFactory.createEquivListNodesResp(response);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            marshaller.marshal(myResponseMsgEl, baos);
            retStr = baos.toString(HTTP.UTF_8);
        }

    } catch (javax.xml.bind.JAXBException je) {
        je.printStackTrace();
    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    return retStr;
}

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 ww.  j av 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:com.esri.geoevent.test.performance.ui.OrchestratorController.java

/**
 * Saves the current fixtures file to disk.
 *
 * @param file File where to save the configuration file.
 * @throws JAXBException// ww w. j  a  v  a 2 s.c  o  m
 * @throws XMLStreamException
 * @throws IOException
 */
private void saveFile(File file) throws JAXBException, XMLStreamException, IOException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Fixtures.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    FileWriter fileWriter = new FileWriter(file);
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlWritter = factory.createXMLStreamWriter(fileWriter);
    marshaller.marshal(fixtures, xmlWritter);
    fileWriter.flush();
    fileWriter.close();
}

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

/**
 *
 * Generates and saves info.xml/*from w  w  w . j  av a 2s . c  o  m*/
 *
 * @param path
 * @param mets
 */
public static void saveInfoFile(String path, MetsContext metsContext, String md5, String fileMd5Name,
        File metsFile) throws MetsExportException {
    File infoFile = new File(path + File.separator + metsContext.getPackageID() + File.separator + "info_"
            + metsContext.getPackageID() + ".xml");
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(new Date());
    XMLGregorianCalendar date2;
    try {
        date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    } catch (DatatypeConfigurationException e1) {
        throw new MetsExportException("Error while generating info.xml file", false, e1);
    }
    Info infoJaxb = new Info();
    infoJaxb.setCreated(date2);
    infoJaxb.setMainmets("./" + metsFile.getName());
    Checksum checkSum = new Checksum();
    checkSum.setChecksum(md5);
    checkSum.setType("MD5");
    addModsIdentifiersRecursive(metsContext.getRootElement(), infoJaxb);
    checkSum.setValue(fileMd5Name);
    infoJaxb.setChecksum(checkSum);
    Validation validation = new Validation();
    validation.setValue("W3C-XML");
    validation.setVersion(Float.valueOf("0.0"));
    infoJaxb.setValidation(validation);
    infoJaxb.setCreator(metsContext.getCreatorOrganization());
    infoJaxb.setPackageid(metsContext.getPackageID());
    if (Const.PERIODICAL_TITLE.equalsIgnoreCase(metsContext.getRootElement().getElementType())) {
        infoJaxb.setMetadataversion((float) 1.5);
    } else {
        infoJaxb.setMetadataversion((float) 1.1);
    }
    Itemlist itemList = new Itemlist();
    infoJaxb.setItemlist(itemList);
    itemList.setItemtotal(BigInteger.valueOf(metsContext.getFileList().size()));
    List<FileMD5Info> fileList = metsContext.getFileList();
    long size = 0;
    for (FileMD5Info fileName : fileList) {
        itemList.getItem()
                .add(fileName.getFileName().replaceAll(Matcher.quoteReplacement(File.separator), "/"));
        size += fileName.getSize();
    }
    int infoTotalSize = (int) (size / 1024);
    infoJaxb.setSize(infoTotalSize);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Info.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        // SchemaFactory factory =
        // SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // factory.setResourceResolver(MetsLSResolver.getInstance());
        // Schema schema = factory.newSchema(new
        // StreamSource(Info.class.getResourceAsStream("info.xsd")));
        // marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        marshaller.marshal(infoJaxb, infoFile);
    } catch (Exception ex) {
        throw new MetsExportException("Error while generating info.xml", false, ex);
    }

    List<String> validationErrors;
    try {
        validationErrors = MetsUtils.validateAgainstXSD(infoFile, Info.class.getResourceAsStream("info.xsd"));
    } catch (Exception e) {
        throw new MetsExportException("Error while validating info.xml", false, e);
    }

    if (validationErrors.size() > 0) {
        MetsExportException metsException = new MetsExportException(
                "Invalid info file:" + infoFile.getAbsolutePath(), false, null);
        metsException.getExceptions().get(0).setValidationErrors(validationErrors);
        for (String error : validationErrors) {
            LOG.fine(error);
        }
        throw metsException;
    }
}