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:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

@Override
public void writeSession(Session session, OutputStream out) throws IOException {
    final JAXBElement<SessionType> ele = toSessionType(session);

    try {/*from w  w  w. ja v a 2  s . c  o  m*/
        final JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        marshaller.marshal(ele, out);
    } catch (JAXBException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:net.di2e.ecdr.commons.endpoint.rest.AbstractRestSearchEndpoint.java

@GET
@Path("/osd.xml")
@Produces("application/opensearchdescription+xml")
public Response getOSD() {
    OpenSearchDescription osd = new OpenSearchDescription();
    osd.setShortName(SystemInfo.getSiteName());
    osd.setDescription(getServiceDescription());
    osd.setTags("ecdr opensearch cdr ddf");
    if (StringUtils.isNotBlank(SystemInfo.getOrganization())) {
        osd.setDeveloper(SystemInfo.getOrganization());
    }//from  w w  w .  j  a v a2 s . c o  m
    if (StringUtils.isNotBlank(SystemInfo.getSiteContatct())) {
        osd.setContact(SystemInfo.getSiteContatct());
    }
    Query query = new Query();
    query.setRole("example");
    query.setSearchTerms("test");
    osd.getQuery().add(query);
    osd.setSyndicationRight(SyndicationRight.OPEN);
    osd.getLanguage().add(MediaType.MEDIA_TYPE_WILDCARD);
    osd.getInputEncoding().add(StandardCharsets.UTF_8.name());
    osd.getOutputEncoding().add(StandardCharsets.UTF_8.name());

    // url example
    for (QueryLanguage lang : queryLanguageList) {
        Url url = new Url();
        url.setType(MediaType.APPLICATION_ATOM_XML);
        url.setTemplate(generateTemplateUrl(lang));
        osd.getUrl().add(url);
    }

    addSourceDescriptions(osd);

    StringWriter writer = new StringWriter();
    InputStream is = null;
    try {
        JAXBContext context = JAXBContext.newInstance(OpenSearchDescription.class, SourceDescription.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(osd, writer);
        is = getClass().getResourceAsStream("/templates/osd_info.template");
        if (is != null) {
            String osdTemplate = IOUtils.toString(is);
            osdTemplate = replaceTemplateValues(osdTemplate);

            String responseStr = osdTemplate + writer.toString();
            return Response.ok(responseStr, MediaType.APPLICATION_XML_TYPE).build();
        } else {
            return Response.serverError().entity("COULD NOT LOAD OSD TEMPLATE.").build();
        }
    } catch (JAXBException | IOException e) {
        LOGGER.warn("Could not create OSD for client due to exception.", e);
        return Response.serverError().build();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:alter.vitro.vgw.service.resourceRegistry.ResourceAvailabilityService.java

/**
 * Processes synch updates to the sets of enabled/disabled received from the VSP.
 * and create a message to confirm them/*from ww  w. j av a2s  . com*/
 */
public String createSynchConfirmationForVSP(EnableNodesReqType 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 < lastRemotelyUpdatedEnableDisableStatusTimeStamp) {
            //ignore the message
            logger.info("Ignoring synch message with old timestamp");
            return null;
        } else {
            lastRemotelyUpdatedEnableDisableStatusTimeStamp = receivedTimestamp;
        }
    }
    // clear the cache of last request:
    this.getCacheOfLastReceivedEnableDisableMessage().clear();

    try {
        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 && forRequest != null) {

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

            response.setTimestamp(Long.toString(new Date().getTime()));
            if (forRequest.getEnabledNodesList() != null) {
                if (response.getConfirmedEnabledNodesList() == null) {
                    ConfirmedEnabledNodesListType theConfirmListType = new ConfirmedEnabledNodesListType();
                    response.setConfirmedEnabledNodesList(theConfirmListType);
                    //
                    if (forRequest.getEnabledNodesList().getEnabledNodesListItem() != null
                            && !forRequest.getEnabledNodesList().getEnabledNodesListItem().isEmpty()) {
                        // loop though items and confirm each one
                        for (EnabledNodesListItemType reqItem : forRequest.getEnabledNodesList()
                                .getEnabledNodesListItem()) {
                            boolean reqStatus = (reqItem.getStatus().compareToIgnoreCase("enabled") == 0) ? true
                                    : false;
                            boolean updatedByVGW = false;
                            long reqRemoteTimestamp = 0;
                            try {
                                reqRemoteTimestamp = Long.valueOf(reqItem.getOfRemoteTimestamp());
                            } catch (Exception exftme1) {
                                logger.error("Could not convert timestamp of remote synch enable request");
                                reqRemoteTimestamp = 0;
                            }
                            long localTimestampSynch = (new Date()).getTime(); //it does not matter ?
                            // ALSO HANDLE EACH ONE OF THE REQUESTS (TODO: CAN WE CONFIRM ALL, BUT NOT CONFROM TO ALL REQUESTs ???)
                            //
                            //
                            if (getCachedDiscoveredDevices() != null && !getCachedDiscoveredDevices().isEmpty()
                                    && getCachedDiscoveredDevices().containsKey(reqItem.getNodeId())) {
                                CSmartDevice tmpSmDev = getCachedDiscoveredDevices().get(reqItem.getNodeId());
                                if (!tmpSmDev.getRegistryProperties().isEnabled()
                                        && tmpSmDev.getRegistryProperties().isStatusWasDecidedByThisVGW()) {
                                    // if it was disabled by the VGW, then ignore any requests/cached or not by the VSP to change its status.
                                    reqStatus = tmpSmDev.getRegistryProperties().isEnabled();
                                    updatedByVGW = true;
                                } else {
                                    tmpSmDev.getRegistryProperties().setEnabled(reqStatus);
                                    tmpSmDev.getRegistryProperties()
                                            .setTimeStampEnabledStatusRemotelySynch(reqRemoteTimestamp);
                                    tmpSmDev.getRegistryProperties()
                                            .setTimeStampEnabledStatusSynch(localTimestampSynch);//is this used?
                                }
                            }
                            //
                            //
                            // AND STORE THE REQUEST TO THE CACHE OF LAST REQUEST, INDEPENDENTLY OF WHETHER WE CONFORMED
                            // BUT IF WE DID NOT CONFORM, WE SEND BACK OUR (VGW) VALUES
                            //
                            ResourceProperties reqResProps = new ResourceProperties(reqItem.getNodeId());
                            reqResProps.setEnabled(reqStatus);
                            reqResProps.setTimeStampEnabledStatusRemotelySynch(reqRemoteTimestamp);
                            reqResProps.setTimeStampEnabledStatusSynch(localTimestampSynch); //it does not matter ??
                            reqResProps.setStatusWasDecidedByThisVGW(updatedByVGW);

                            this.getCacheOfLastReceivedEnableDisableMessage().put(reqItem.getNodeId(),
                                    reqResProps);

                            // AND CONSTRUCT THE CONFIRMATION MESSAGE!
                            ConfirmedEnabledNodesListItemType confirmedItemTmp = new ConfirmedEnabledNodesListItemType();
                            confirmedItemTmp.setNodeId(reqItem.getNodeId());

                            String updatedByVGWStr = updatedByVGW ? "1" : "0";
                            String reqStatusStr = reqStatus ? "enabled" : "disabled";
                            confirmedItemTmp.setStatus(reqStatusStr);
                            confirmedItemTmp.setGwInitFlag(updatedByVGWStr);
                            confirmedItemTmp.setOfRemoteTimestamp(reqItem.getOfRemoteTimestamp());
                            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();
    }
    return retStr;
}

From source file:com.cybercom.svp.machine.gui.MachineForm.java

public static <T> String objToXml(final Class<T> clazz, Object object) throws JAXBException {

    JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter sw = new StringWriter();
    jaxbMarshaller.marshal(object, sw);//from w w  w .j  av a 2s  .  c o  m
    return sw.toString();
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

public Marshaller createMarshaller() throws IOException {
    try {/*from   w  w w. java  2s.  co m*/
        Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", true);
        return marshaller;
    } catch (JAXBException e) {
        throw new CalendarException("Unable to create marshaller", e);
    }
}

From source file:hermes.impl.DefaultXMLHelper.java

public void saveContent(MessageSet messages, OutputStream ostream) throws Exception {
    JAXBContext jc = JAXBContext.newInstance("hermes.xml");
    Marshaller m = jc.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(new JAXBElement<MessageSet>(new QName("", "content"), MessageSet.class, messages), ostream);
    ostream.flush();/*from  w w w. j  a  v a 2  s . c  om*/
}

From source file:hermes.impl.DefaultXMLHelper.java

public void saveContent(MessageSet messages, Writer writer) throws Exception {
    JAXBContext jc = JAXBContext.newInstance("hermes.xml");
    Marshaller m = jc.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(new JAXBElement<MessageSet>(new QName("", "content"), MessageSet.class, messages), writer);
    writer.flush();/*from  ww w .ja  v a 2 s  . com*/
}

From source file:com.intuit.tank.proxy.ProxyApp.java

/**
 * /*from  w w w  .  j a  v a 2  s  .  c o  m*/
 */
private void save() {
    if (currentFile != null) {
        saveAction.setEnabled(false);
        JAXBContext ctx;
        try {
            ctx = JAXBContext.newInstance(Session.class.getPackage().getName());
            Marshaller m = ctx.createMarshaller();
            m.setProperty("jaxb.formatted.output", Boolean.TRUE);
            Session session = new Session(model.getTransactions(),
                    configDialog.getConfiguration().isFollowRedirects());
            System.out.println("outputting to : " + currentFile.getCanonicalPath());
            m.marshal(session, currentFile);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error saving recording: " + e, "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java

private SOAPMessage createResponseSOAPMessage(Object obj) {
    SOAPMessage msg = null;//from  w  w  w.  ja v a  2  s.c  o m

    try {
        RegistryResponseType ebRegistryResponseType = null;

        if (obj instanceof it.cnr.icar.eric.server.interfaces.Response) {
            Response r = (Response) obj;
            ebRegistryResponseType = r.getMessage();

        } else if (obj instanceof java.lang.Throwable) {
            Throwable t = (Throwable) obj;
            ebRegistryResponseType = it.cnr.icar.eric.server.common.Utility.getInstance()
                    .createRegistryResponseFromThrowable(t, "RegistrySOAPServlet", "Unknown");
        }

        //Now add resp to SOAPMessage
        StringWriter sw = new StringWriter();
        //            javax.xml.bind.Marshaller marshaller = bu.rsFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (ebRegistryResponseType.getClass() == RegistryResponseType.class) {
            // if ComplexType is explicit, wrap it into Element
            // only RegistryResponeType is explicit -> equal test instead of isinstance
            JAXBElement<RegistryResponseType> ebRegistryResponse = bu.rsFac
                    .createRegistryResponse(ebRegistryResponseType);
            marshaller.marshal(ebRegistryResponse, sw);

        } else {
            // if ComplexType is anonymous, it can be marshalled directly 
            marshaller.marshal(ebRegistryResponseType, sw);
        }

        //Now get the RegistryResponse as a String
        String respStr = sw.toString();

        // Use Unicode (utf-8) to getBytes (server and client). Rely on platform default encoding is not safe.
        InputStream soapStream = it.cnr.icar.eric.server.common.Utility.getInstance()
                .createSOAPStreamFromRequestStream(new ByteArrayInputStream(respStr.getBytes("utf-8")));

        boolean signRequired = Boolean
                .valueOf(RegistryProperties.getInstance().getProperty("eric.interfaces.soap.signedResponse"))
                .booleanValue();

        msg = it.cnr.icar.eric.server.common.Utility.getInstance().createSOAPMessageFromSOAPStream(soapStream);

        if (signRequired) {

            AuthenticationServiceImpl auService = AuthenticationServiceImpl.getInstance();
            PrivateKey privateKey = auService.getPrivateKey(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR,
                    AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);
            java.security.cert.Certificate[] certs = auService
                    .getCertificateChain(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);

            CredentialInfo credentialInfo = new CredentialInfo(null, (X509Certificate) certs[0], certs,
                    privateKey);

            SOAPPart sp = msg.getSOAPPart();
            SOAPEnvelope se = sp.getEnvelope();

            WSS4JSecurityUtilBST.signSOAPEnvelopeOnServerBST(se, credentialInfo);

            //                msg = SoapSecurityUtil.getInstance().signSoapMessage(msg, credentialInfo);

        }

        // msg.writeTo(new FileOutputStream(new File("signedResponse.xml")));
        soapStream.close();
    } catch (IOException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (SOAPException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (javax.xml.bind.JAXBException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (ParseException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (RegistryException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    }

    return msg;
}

From source file:org.restsql.core.impl.AbstractSqlResourceMetaData.java

/** Returns XML representation. */
@Override/*from  w  w  w.j  a  v a  2 s. c  o m*/
public String toXml() {
    // Build extended metadata for serialization if first time through
    if (!extendedMetadataIsBuilt) {
        parentTableName = getQualifiedTableName(parentTable);
        childTableName = getQualifiedTableName(childTable);
        joinTableName = getQualifiedTableName(joinTable);
        parentPlusExtTableNames = getQualifiedTableNames(parentPlusExtTables);
        childPlusExtTableNames = getQualifiedTableNames(childPlusExtTables);
        allReadColumnNames = getQualifiedColumnNames(allReadColumns);
        childReadColumnNames = getQualifiedColumnNames(childReadColumns);
        parentReadColumnNames = getQualifiedColumnNames(parentReadColumns);
        extendedMetadataIsBuilt = true;
    }

    try {
        final JAXBContext context = JAXBContext.newInstance(AbstractSqlResourceMetaData.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        final StringWriter writer = new StringWriter();
        marshaller.marshal(this, writer);
        return writer.toString();
    } catch (final JAXBException exception) {
        return exception.toString();
    }
}