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:com.axelor.controller.ConnectionToPrestashop.java

@Transactional
public Customer getCustomer(int customerId) {
    com.axelor.pojo.Customer pojoCustomer = new com.axelor.pojo.Customer();
    pojoCustomer.setFirstname("FIRSTNAME");
    pojoCustomer.setLastname("LASTNAME");
    pojoCustomer.setCompany("COMPANY");
    pojoCustomer.setPasswd("PASSWORD");
    pojoCustomer.setEmail("EMAIL");
    pojoCustomer.setBirthday("1000-01-01");
    pojoCustomer.setActive(0);/*from w  w w. j  av a  2  s . c  om*/
    pojoCustomer.setDeleted(0);
    pojoCustomer.setId_default_group(0);
    pojoCustomer.setAssociations("associations");
    pojoCustomer.setDate_upd("dateUpd");
    try {
        System.out.println("API KEY :: " + apiKey);
        URL url = new URL("http://localhost/client-lib/crud/action.php?resource=customers&action=retrieve&id="
                + customerId + "&Akey=" + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

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

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

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

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

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

/**
 * Saves the mets document into a file//from   w  w  w  .j a  v  a2s. 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:de.fischer.thotti.core.runner.NDRunner.java

protected void saveTestResult(TestSuiteResult result) {
    Package pkg = TestSuiteResult.class.getPackage();

    File resultFile = generateResultFileName();

    JAXBContext jaxbContext = null;

    try {/* w  ww.j a  v  a 2s  .com*/
        jaxbContext = JAXBContext.newInstance(pkg.getName());

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

        marshaller.marshal(result, resultFile);
    } catch (JAXBException e) {
        // @todo?
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

/**
 * Writes the object Document into the file.
 *
 * @param o/*from   www .j  a v  a2  s  .c om*/
 * @param file
 */
private void marshalXMLToSingleFile(Object o, File file) {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(o, file);
        return;
    } catch (JAXBException ex) {
        Logger.getLogger(ExportUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    throw new RuntimeException("ExportUtil: Something went wrong while marshalling the XML");
}

From source file:ddf.security.pdp.realm.xacml.processor.BalanaClient.java

/**
 * Marshalls the XACML request to a string.
 *
 * @param xacmlRequestType The XACML request to marshal.
 * @return A string representation of the XACML request.
 *//*from w  ww . jav  a2 s.co m*/
private String marshal(RequestType xacmlRequestType) throws PdpException {
    if (null == parser) {
        throw new IllegalStateException("XMLParser must be configured.");
    }
    String xacmlRequest = null;
    try {
        List<String> ctxPath = new ArrayList<>(1);
        ctxPath.add(ResponseType.class.getPackage().getName());
        ParserConfigurator configurator = parser.configureParser(ctxPath, BalanaClient.class.getClassLoader());
        configurator.addProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectFactory objectFactory = new ObjectFactory();
        parser.marshal(configurator, objectFactory.createRequest(xacmlRequestType), os);
        xacmlRequest = os.toString("UTF-8");
    } catch (ParserException | UnsupportedEncodingException e) {
        String message = "Unable to marshal XACML request.";
        LOGGER.error(message, e);
        throw new PdpException(message, e);
    }

    LOGGER.debug("\nXACML 3.0 Request:\n{}", xacmlRequest);

    return xacmlRequest;
}

From source file:ddf.security.pdp.realm.xacml.processor.XacmlClient.java

/**
 * Marshalls the XACML request to a string.
 *
 * @param xacmlRequestType The XACML request to marshal.
 * @return A string representation of the XACML request.
 *///from www.java  2s  .  c  o m
private String marshal(RequestType xacmlRequestType) throws PdpException {
    if (null == parser) {
        throw new IllegalStateException("XMLParser must be configured.");
    }
    String xacmlRequest = null;
    try {
        List<String> ctxPath = new ArrayList<>(1);
        ctxPath.add(ResponseType.class.getPackage().getName());
        ParserConfigurator configurator = parser.configureParser(ctxPath, XacmlClient.class.getClassLoader());
        configurator.addProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectFactory objectFactory = new ObjectFactory();
        parser.marshal(configurator, objectFactory.createRequest(xacmlRequestType), os);
        xacmlRequest = os.toString("UTF-8");
    } catch (ParserException | UnsupportedEncodingException e) {
        String message = "Unable to marshal XACML request.";
        LOGGER.error(message, e);
        throw new PdpException(message, e);
    }

    LOGGER.debug("\nXACML 3.0 Request:\n{}", xacmlRequest);

    return xacmlRequest;
}

From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java

public static void testLoadOGCServiceMetadata() {
    // String xmlFile =
    // "J:/dev/atoll-v2/atoll-motu/atoll-motu-processor/src/test/resources/xml/TestServiceMetadata.xml";
    String xmlFile = "C:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/TestServiceMetadataOK.xml";

    String schemaPath = "schema/iso19139";

    try {//from   w w w  .j ava2  s .  c om
        List<String> errors = validateServiceMetadataFromString(xmlFile, schemaPath);
        if (errors.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            for (String str : errors) {
                stringBuffer.append(str);
                stringBuffer.append("\n");
            }
            throw new MotuException(String.format("ERROR - XML file '%s' is not valid - See errors below:\n%s",
                    xmlFile, stringBuffer.toString()));
        } else {
            System.out.println(String.format("XML file '%s' is valid", xmlFile));
        }

    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream in = null;
    try {
        in = Organizer.getUriAsInputStream(xmlFile);
    } catch (MotuException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    JAXBContext jc = null;
    try {
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        // jc = JAXBContext.newInstance("org.isotc211.iso19139.d_2006_05_04.srv");
        jc = JAXBContext
                .newInstance(new Class[] { org.isotc211.iso19139.d_2006_05_04.srv.ObjectFactory.class });
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Source srcFile = new StreamSource(xmlFile);
        JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(srcFile);
        // JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(in);
        SVServiceIdentificationType serviceIdentificationType = (SVServiceIdentificationType) element
                .getValue();
        // serviceIdentificationType = (SVServiceIdentificationType) unmarshaller.unmarshal(in);
        System.out.println(serviceIdentificationType.toString());

        List<SVOperationMetadataPropertyType> operationMetadataPropertyTypeList = serviceIdentificationType
                .getContainsOperations();

        for (SVOperationMetadataPropertyType operationMetadataPropertyType : operationMetadataPropertyTypeList) {

            SVOperationMetadataType operationMetadataType = operationMetadataPropertyType
                    .getSVOperationMetadata();
            System.out.println("---------------------------------------------");
            if (operationMetadataType == null) {
                continue;
            }
            System.out.println(operationMetadataType.getOperationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getInvocationName().getCharacterString().getValue());
            System.out.println(operationMetadataType.getOperationDescription().getCharacterString().getValue());

            CIOnlineResourcePropertyType onlineResourcePropertyType = operationMetadataType.getConnectPoint()
                    .get(0);
            if (onlineResourcePropertyType != null) {
                System.out.println(operationMetadataType.getConnectPoint().get(0).getCIOnlineResource()
                        .getLinkage().getURL());
            }

            List<SVParameterPropertyType> parameterPropertyTypeList = operationMetadataType.getParameters();

            for (SVParameterPropertyType parameterPropertyType : parameterPropertyTypeList) {
                SVParameterType parameterType = parameterPropertyType.getSVParameter();

                if (parameterType.getName().getAName().getCharacterString() != null) {
                    System.out.println(parameterType.getName().getAName().getCharacterString().getValue());
                } else {
                    System.out.println("WARNING - A parameter has no name");

                }
                if (parameterType.getDescription() != null) {
                    if (parameterType.getDescription().getCharacterString() != null) {
                        System.out.println(parameterType.getDescription().getCharacterString().getValue());
                    } else {
                        System.out.println("WARNING - A parameter has no description");

                    }
                } else {
                    System.out.println("WARNING - A parameter has no description");

                }
            }

        }
        FileWriter writer = new FileWriter("c:/tempVFS/test.xml");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(element, writer);

        writer.flush();
        writer.close();

        System.out.println("End testLoadOGCServiceMetadata");
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.dgwave.osrs.OsrsClient.java

protected String getString(OsrsRequest request) throws OsrsException {
    OPSEnvelope envelope = getEmptyEnvelope();
    Map<String, Object> attrs = request.getAttributes();

    Item pro = oj.createItem();/*  ww w  .j a  va  2 s.c  o  m*/
    pro.setKey("protocol");
    pro.setStringValue(this.protocol);
    Item obj = oj.createItem();
    obj.setKey("object");
    obj.setStringValue(request.getObject());
    Item act = oj.createItem();
    act.setKey("action");
    act.setStringValue(request.getAction());
    Item att = oj.createItem();
    att.setKey("attributes");
    att.addDtAssoc(processAttrs(attrs));

    DtAssoc c = oj.createDtAssoc();
    c.addItem(pro);
    c.addItem(act);
    c.addItem(obj);
    c.addItem(att);
    ((List<Object>) envelope.getBody().getDataBlock().getDtAass()).add(c);

    try {
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        m.setProperty("com.sun.xml.internal.bind.xmlHeaders",
                "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" + "<!DOCTYPE OPS_envelope SYSTEM '"
                        + OSRSDIR + OSRSCONFIG + "ops.dtd'>");
        //StringWriter writer = new StringWriter();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        m.marshal(envelope, baos);

        return baos.toString();
    } catch (Exception e) {
        throw new OsrsException("Error creating envelope from request", e);
    }
}

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

protected String toXml(Object o) {
    try {//www. ja v a2s  . c om
        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:com.evolveum.midpoint.testing.model.client.sample.RunScript.java

private static String marshalObject(Object object) throws JAXBException, FileNotFoundException {
    JAXBContext jc = getJaxbContext();
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter sw = new StringWriter();
    marshaller.marshal(object, sw);//from   ww  w.  j ava 2  s  . c  o  m
    return sw.toString();
}