Example usage for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT

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

Introduction

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

Prototype

String JAXB_FORMATTED_OUTPUT

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

Click Source Link

Document

The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation.

Usage

From source file:org.geosamples.samples.Samples.java

/**
 * Marshalls a Samples object to an XML string.
 *
 * @param samples = Samples object/*from www .jav  a 2 s . c  om*/
 * @param prettyPrint = boolean
 * @return XML document as String
 * @throws JAXBException
 */
private static String serializeSamplesToCompliantXMLWithPrettyPrintChoice(XMLDocumentInterface samples,
        boolean prettyPrint) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Samples.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, prettyPrint);

    final StringWriter stringWriter = new StringWriter();
    marshaller.marshal(samples, stringWriter);

    String xmlOutput = stringWriter.toString();

    String compliantXmlOutput = xmlOutput.replace("<samples>", GEOSAMPLES_COMPLIANT_XML_HEADER_SAMPLES);
    return compliantXmlOutput;
}

From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.VCSWSDAOImpl.java

public void generateVCSXML(String serverId, String startPath, String pathToVCSXML, String pathToServersXML)
        throws CompositeException {

    // Set the command and action name
    String command = "generateVCSXML";
    String actionName = "CREATE_XML";

    // Set the Module Action Objective for the VCS Module
    System.setProperty("MODULE_ACTION_OBJECTIVE", startPath);

    // For debugging
    if (logger.isDebugEnabled()) {
        logger.debug(/* w  w w  . ja v  a 2s .c o m*/
                "VCSWSDAOImpl.generateVCSXML(serverId , startPath, pathToVCSXML, pathToServersXML).  serverId="
                        + serverId + "  startPath=" + startPath + "  pathToVCSXML=" + pathToVCSXML
                        + "  pathToServersXML=" + pathToServersXML);
    }
    // -- these are class level to avoid excessive object creation
    distinctResourcesToAdd = new ArrayList<Resource>();
    resourcesRecursedFromVcsPath = new ArrayList<Resource>();
    distinctUsedResources = new ArrayList<Resource>();

    ArrayList<Resource> startResourceList;

    Resource startResource = null;

    VCSModule vcsModule = new VCSModule();
    VCSResourceType vcsResource = new VCSResourceType();

    // -- get server and port
    CompositeServer targetServer = WsApiHelperObjects.getServer(serverId, pathToServersXML);
    ResourcePortType port = CisApiFactory.getResourcePort(targetServer);

    //System.out.println("Starting with: " + startPath);

    // -- get parent resource
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("VCSWSDAOImpl.generateVCSXML().  Invoking port.getResource(\"" + startPath
                    + "\", null, \"SIMPLE)\".getResource().");
        }

        startResourceList = (ArrayList<Resource>) port.getResource(startPath, null, DetailLevel.SIMPLE)
                .getResource();

        if (logger.isDebugEnabled()) {
            logger.debug("VCSWSDAOImpl.generateVCSXML().  Success: port.getResource().");
        }
    } catch (GetResourceSoapFault e) {
        throw new ApplicationException("Error getting resource: " + e.getMessage());
    }

    // -- validate return result - however, should never be null or empty as
    //    conditions that would result in that would also result in exception above
    if (startResourceList == null) {
        throw new ApplicationException("The parent resource path provided is not valid.");
    }

    // -- this is the object representation of startPath 
    startResource = startResourceList.get(0);

    // -- perhaps check for something silly like this - system database or web service
    //if (startResource.getPath().startsWith("/services/databases/system")) {
    //   throw new ApplicationException("Can not include system database.");   
    //}      

    // -- is this a container or a resource? Is it from /services or from /shared, /home?
    ResourceType startResourceType = startResource.getType();

    // -- make sure main object of interest is included
    distinctResourcesToAdd.add(startResource);
    if (startResourceType.equals(ResourceType.CONTAINER)
            || (startResourceType.equals(ResourceType.DATA_SOURCE) && startPath.startsWith("/services/"))) {
        // -- we need to recurse and find all child objects. This
        //    populates resourcesRecursedFromVcsPath
        getChildResourcesRecursive(startResource, port);

        // -- not a container. Is it a link (/servers/...) or simply
        //    a resource under /shared or /home?
    } else {

        // -- if it's not a container, simply add.
        //    in this case, user is checking in resource,
        //    and all we need to do is find used resources
        resourcesRecursedFromVcsPath.add(startResource);

    }

    // -- OK, we now have all resources - now what resources to those resources depend
    //    on, or use. For a large project, this could take a few minutes
    for (Resource resourceToRecurse : resourcesRecursedFromVcsPath) {
        // -- this populates distinctUsedResources  
        getUsedResourcesRecursive(resourceToRecurse, port);
    }

    // -- when a sub-type shows you have a child of a data source,
    //    does it make more sense simply to work up to chain
    //    of parent objects to find data source and just add it?
    for (Resource potentialResourceToAdd : distinctUsedResources) {
        // -- may already be in folder hierarchy of startPath
        if (!distinctResourcesToAdd.contains(potentialResourceToAdd)
                && !resourcesRecursedFromVcsPath.contains(potentialResourceToAdd)) {
            distinctResourcesToAdd.add(potentialResourceToAdd);
        }
    }

    NumberFormat formatter = new DecimalFormat("00000");
    for (int i = 0; i < distinctResourcesToAdd.size(); i++) {

        Resource resourceToAdd = distinctResourcesToAdd.get(i);

        vcsResource = new VCSResourceType();
        vcsResource.setId("checkin_" + formatter.format(i + 1));
        vcsResource.setMessage("Entry generated by Composite PS Promotion and Deployment Tool");
        vcsResource.setResourcePath(resourceToAdd.getPath());
        vcsResource.setResourceType(resourceToAdd.getType().name());
        vcsResource.setRevision("HEAD");

        vcsModule.getVcsResource().add(vcsResource);
    }

    // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
    if (CommonUtils.isExecOperation()) {
        JAXBContext jaxbContext;
        Marshaller marshaller;
        try {
            jaxbContext = JAXBContext.newInstance("com.cisco.dvbu.ps.deploytool.modules");
            marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
            marshaller.marshal(vcsModule, new FileOutputStream(pathToVCSXML));
            //System.out.println("Wrote file: " + pathToVCSXML);
        } catch (JAXBException e) {
            throw new ApplicationException("Error retrieving XML: " + e.getMessage());
        } catch (FileNotFoundException e) {
            throw new ApplicationException("Unable to create XML file: " + e.getMessage());
        }
    } else {
        logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                + "] WAS NOT PERFORMED.\n");
    }
}

From source file:edu.purdue.cybercenter.dm.service.TermService.java

public String convertTermToXml(Term term) {
    String xmlTerm = null;//w ww  .  j av a 2  s .c o m
    try (OutputStream os = new ByteArrayOutputStream()) {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(CharacterEscapeHandler.class.getName(), CDataEscapeHandler.theInstance);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, VOCABULARY_SCHEMA_LOCATION);
        marshaller.marshal(term, os);
        xmlTerm = os.toString();
    } catch (JAXBException ex) {
        throw new RuntimeException("Unable to generate xml term definition", ex);
    } catch (IOException ex) {
        throw new RuntimeException("Unable to write xml term definition", ex);
    }
    return xmlTerm;
}

From source file:org.onebusaway.siri.core.SiriCommon.java

/**
 * Marshall the specified object to the target {@link Writer} using JAXB.
 * //from  www .  ja  v a  2  s .  c o  m
 * @param object
 * @param writer
 * @param formatOutput if true, the serialized XML will be pretty-printed
 */
public void marshall(Object object, Writer writer, boolean formatOutput) {
    try {
        Marshaller m = _jaxbContext.createMarshaller();
        if (formatOutput) {
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        }
        m.marshal(object, writer);
    } catch (JAXBException ex) {
        throw new SiriSerializationException(ex);
    }
}

From source file:com.axelor.controller.ConnectionToPrestashop.java

@Transactional
public com.axelor.pojo.Address getAddress(int addressId) {
    com.axelor.pojo.Address pojoAddress = new com.axelor.pojo.Address();
    pojoAddress.setId_customer(0);/*from   w ww  . ja  v a2  s .c o m*/
    pojoAddress.setId_country(0);
    pojoAddress.setId_state(0);
    pojoAddress.setPrestashopAddressId(0);
    pojoAddress.setFirstname("FIRSTNAME");
    pojoAddress.setLastname("LASTNAME");
    pojoAddress.setPhone_mobile("0000000000");
    pojoAddress.setAddress1("ADDRESS1");
    pojoAddress.setAddress2("ADDRESS2");
    pojoAddress.setCity("CITY");
    pojoAddress.setPostcode("000000");
    pojoAddress.setAlias("ALIAS");
    pojoAddress.setDate_upd("dateUpd");
    try {
        System.out.println("API KEY :: " + apiKey);
        URL url = new URL("http://localhost/client-lib/crud/action.php?resource=addresses&action=retrieve&id="
                + addressId + "&Akey=" + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        JAXBContext jaxbContext = JAXBContext.newInstance(com.axelor.pojo.Address.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        OutputStream outputStream = connection.getOutputStream();
        jaxbMarshaller.marshal(pojoAddress, outputStream);

        connection.connect();
        InputStream inputStream = connection.getInputStream();
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        pojoAddress = (com.axelor.pojo.Address) jaxbUnmarshaller
                .unmarshal(new UnmarshalInputStream(connection.getInputStream()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return pojoAddress;
}

From source file:com.phresco.pom.util.PomProcessor.java

/**
 * Save./*from w  ww .  j  a  va 2  s.  c  o m*/
 *
 * @throws JAXBException the jAXB exception
 */
public void save() throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Model.class);
    Marshaller marshal = jaxbContext.createMarshaller();
    marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshal.marshal(model, file);
}

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

/**
 *
 * Generates and saves info.xml//from   ww w.j av a2s.co  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;
    }
}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 *
 * @param httpServletRequest/*w  ww.j  a  va 2  s.co  m*/
 * @param httpServletResponse
 * @throws IOException
 */
private void authorize(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format) throws IOException {

    ObjectMapper mapper = new ObjectMapper();

    // Error handling mit suppress_response_codes=true
    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    }
    // Error handling mit suppress_response_codes=false (=default)
    else {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

    // Json fr Response body
    RequestError requestError = new RequestError();
    requestError.setError(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
    requestError.setDescription(this.config
            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
    requestError.setErrorUri(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

    // XML-Ausgabe mit JAXB
    if (format.equals("xml")) {

        try {

            JAXBContext context = JAXBContext.newInstance(RequestError.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Write to HttpResponse
            httpServletResponse.setContentType("application/xml;charset=UTF-8");
            m.marshal(requestError, httpServletResponse.getWriter());

        } catch (JAXBException e) {
            this.logger.error(e.getMessage(), e.getCause());
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error: Error while rendering the results.");
        }
    }

    // JSON-Ausgabe mit Jackson
    if (format.equals("json")) {

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        mapper.writeValue(httpServletResponse.getWriter(), requestError);
    }
}

From source file:it.cnr.icar.eric.common.BindingUtility.java

public void checkRegistryResponse(RegistryResponseType resp) throws JAXRException {
    if (!(resp.getStatus().equals(CANONICAL_RESPONSE_STATUS_TYPE_ID_Success))) {
        StringWriter sw = new StringWriter();
        try {/*from   w  w  w .j  a  va  2s  . co  m*/

            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            marshaller.marshal(resp, sw);
            throw new JAXRException(sw.toString());
        } catch (Exception e) {
            throw new JAXRException(e);
        }
    }
}