Example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

List of usage examples for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.

Prototype

String OMIT_XML_DECLARATION

To view the source code for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.

Click Source Link

Document

omit-xml-declaration = "yes" | "no".

Usage

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

public Document invoke() throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + OpSource.class.getName() + ".invoke()");
    }/*from  w  w  w  . j av  a  2s  .co m*/
    try {
        URL url = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e1) {
            throw new CloudException(e1);
        }
        final String host = url.getHost();
        final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
        final String urlStr = url.toString();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        /**  HTTP Authentication */
        String uid = new String(provider.getContext().getAccessPublic());
        String pwd = new String(provider.getContext().getAccessPrivate());

        /** Type of authentication */
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.BASIC);

        httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs);
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null),
                new UsernamePasswordCredentials(uid, pwd));

        if (wire.isDebugEnabled()) {
            wire.debug("--------------------------------------------------------------> " + urlStr);
            wire.debug("");
        }

        AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr);
        method.setParams(new BasicHttpParams().setParameter(urlStr, url));
        /**  Set headers */
        method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key));

        /** POST/PUT method specific logic */
        if (method instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method;
            String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key);

            if (requestBody != null) {
                if (wire.isDebugEnabled()) {
                    wire.debug(requestBody);
                }

                AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes());
                entity.setContentType(parameters.get(OpSource.Content_Type_Key));
                entityEnclosingMethod.setEntity(entity);
            } else {
                throw new CloudException("The request body is null for a post request");
            }
        }

        /** Now parse the xml */
        try {

            HttpResponse httpResponse;
            int status;
            if (wire.isDebugEnabled()) {
                for (org.apache.http.Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
            }
            /**  Now execute the request */
            APITrace.trace(provider, method.toString() + " " + urlStr);
            httpResponse = httpclient.execute((HttpUriRequest) method);
            status = httpResponse.getStatusLine().getStatusCode();
            if (wire.isDebugEnabled()) {
                wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            org.apache.http.Header[] headers = httpResponse.getAllHeaders();

            HttpEntity entity = httpResponse.getEntity();
            if (wire.isDebugEnabled()) {
                wire.debug("HTTP xml status code ---------" + status);
                for (org.apache.http.Header h : headers) {
                    if (h.getValue() != null) {
                        wire.debug(h.getName() + ": " + h.getValue().trim());
                    } else {
                        wire.debug(h.getName() + ":");
                    }
                }
                /** Can not enable this line, otherwise the entity would be empty*/
                // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity));
                wire.debug("-----------------");
            }
            if (entity == null) {
                parseError(status, "Empty entity");
            }

            String responseBody = EntityUtils.toString(entity);

            if (status == HttpStatus.SC_OK) {
                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
                    if (input != null) {
                        Document doc = null;
                        try {
                            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
                            if (wire.isDebugEnabled()) {
                                try {
                                    TransformerFactory transfac = TransformerFactory.newInstance();
                                    Transformer trans = transfac.newTransformer();
                                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                    StringWriter sw = new StringWriter();
                                    StreamResult result = new StreamResult(sw);
                                    DOMSource source = new DOMSource(doc);
                                    trans.transform(source, result);
                                    String xmlString = sw.toString();
                                    wire.debug(xmlString);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            logger.debug(ex.toString(), ex);
                        }
                        return doc;
                    }
                } catch (IOException e) {
                    logger.error(
                            "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                /*
                catch( SAXException e ) {
                throw new CloudException(e);
                }                    
                catch( ParserConfigurationException e ) {
                throw new InternalException(e);
                }
                */
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new CloudException("An internal error occured: The endpoint was not found");
            } else {
                if (responseBody != null) {
                    parseError(status, responseBody);
                    Document parsedError = null;
                    if (!responseBody.contains("<HR")) {
                        parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8")));
                        if (wire.isDebugEnabled()) {
                            try {
                                TransformerFactory transfac = TransformerFactory.newInstance();
                                Transformer trans = transfac.newTransformer();
                                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                StringWriter sw = new StringWriter();
                                StreamResult result = new StreamResult(sw);
                                DOMSource source = new DOMSource(parsedError);
                                trans.transform(source, result);
                                String xmlString = sw.toString();
                                wire.debug(xmlString);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else
                        logger.debug("Error message was unparsable");
                    return parsedError;
                }
            }
        } catch (ParseException e) {
            throw new CloudException(e);
        } catch (SAXException e) {
            throw new CloudException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CloudException(e);
        } catch (ParserConfigurationException e) {
            throw new CloudException(e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + OpSource.class.getName() + ".invoke()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------------> " + endpoint);
        }
    }
    return null;
}

From source file:com.ibm.bi.dml.conf.DMLConfig.java

/**
 * //from  w  w w. ja  va2 s . c  om
 * @return
 * @throws DMLRuntimeException
 */
public synchronized String serializeDMLConfig() throws DMLRuntimeException {
    String ret = null;
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        //transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(xml_root);
        transformer.transform(source, result);
        ret = result.getWriter().toString();
    } catch (Exception ex) {
        throw new DMLRuntimeException("Unable to serialize DML config.", ex);
    }

    return ret;
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static String prettyPrintElement(Element elt, boolean omitXMLDeclaration, boolean bIndent) {
    Node firstChild = elt;/* w  ww  . j  a  v  a2  s .c o  m*/
    String encoding = "ISO-8859-1"; // default Encoding char set if non is
    // found in the PI

    if (omitXMLDeclaration && (firstChild.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE)
            && (firstChild.getNodeName().equals("xml"))) {
        String piValue = firstChild.getNodeValue();
        // extract from PI the encoding Char Set
        int encodingOffset = piValue.indexOf("encoding=\"");
        if (encodingOffset != -1) {
            encoding = piValue.substring(encodingOffset + 10);
            // remove the last "
            encoding = encoding.substring(0, encoding.length() - 1);
        }
    }
    StringWriter strWtr = new StringWriter();
    try {
        Transformer t = getNewTransformer();
        t.setOutputProperty(OutputKeys.ENCODING, encoding);
        t.setOutputProperty(OutputKeys.INDENT, bIndent ? "yes" : "no");
        t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, text
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no");
        t.transform(new DOMSource(elt), new StreamResult(strWtr));
        return strWtr.getBuffer().toString();
    } catch (Exception e) {
        System.err.println("XML.toString(Document): " + e);
        Engine.logEngine.error("Unexpected exception", e);
        return e.getMessage();
    }
}

From source file:de.tudarmstadt.ukp.lmf.writer.xml.LMFXmlWriter.java

/**
 * Creates XML TransformerHandler//  ww w  .  jav a  2 s  . c om
 * @param xmlOutPath
 * @param dtdPath
 * @return
 * @throws IOException
 * @throws TransformerException
 */
public TransformerHandler getXMLTransformerHandler(OutputStream out) {
    StreamResult streamResult = new StreamResult(out);
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = null;
    try {
        th = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        logger.error("Error on initiating TransformerHandler");
        e.printStackTrace();
    }
    Transformer serializer = th.getTransformer();
    serializer.setOutputProperty(OutputKeys.METHOD, "xml");
    serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    if (dtdPath != null)
        serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdPath);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    th.setResult(streamResult);
    return th;
}

From source file:com.photon.maven.plugins.android.standalonemojos.ManifestUpdateMojo.java

/**
 * Write manifest using JAXP transformer
 *///from  www.j a  va  2s.  co m
private void writeManifest(File manifestFile, Document doc) throws IOException, TransformerException {
    TransformerFactory xfactory = TransformerFactory.newInstance();
    Transformer xformer = xfactory.newTransformer();
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(doc);

    FileWriter writer = null;
    try {
        writer = new FileWriter(manifestFile, false);
        String xmldecl = String.format("<?xml version=\"%s\" encoding=\"%s\"?>%n", doc.getXmlVersion(),
                doc.getXmlEncoding());
        writer.write(xmldecl);
        Result result = new StreamResult(writer);

        xformer.transform(source, result);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:broadwick.Broadwick.java

/**
 * Get the XML string of the model with the given id from a list of configured models.
 * <p>//from  w  ww .  j a  va  2 s  .co m
 * @param id     the id of the model to be found.
 * @param models a list of XML <model> nodes.
 * @return the XML string for the model.
 */
private String getModelsConfiguration(final String id, final NodeList models) {
    try {
        for (int i = 0; i < models.getLength(); i++) {
            final NamedNodeMap attributes = models.item(i).getAttributes();
            final String nodeId = attributes.getNamedItem("id").getNodeValue();

            if (id.equals(nodeId)) {
                final TransformerFactory transFactory = TransformerFactory.newInstance();
                final Transformer transformer = transFactory.newTransformer();
                final StringWriter buffer = new StringWriter();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                transformer.transform(new DOMSource(models.item(i)), new StreamResult(buffer));
                return buffer.toString();
            }
        }
    } catch (TransformerException ex) {
        log.error("Could not get the configuration for the model [{}]. {}", id, ex.getLocalizedMessage());
    }
    return "";
}

From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java

private String toString(Node dom) throws TransformerException {
    Source source = new DOMSource(dom);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    /*/* ww w  .j  a v  a  2  s  .  com*/
     * We have to omit the ?xml declaration if we want to embed the
     * document.
     */
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(source, result);
    return stringWriter.getBuffer().toString();
}

From source file:org.wso2.identity.integration.test.oauth2.OAuth2ServiceSAML2BearerGrantTestCase.java

/**
 * Extract the SAML assertion from SAML response.
 * @param samlResponse SAML response./* ww  w.  j a  v a  2 s .  c  o m*/
 * @return Extracted SAML assertion.
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
private String getSAMLAssersion(String samlResponse)
        throws ParserConfigurationException, IOException, SAXException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(samlResponse));
    Document document = builder.parse(is);

    StringWriter sw = new StringWriter();
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.transform(
                new DOMSource(document.getDocumentElement().getElementsByTagName("saml2:Assertion").item(0)),
                new StreamResult(sw));
    } catch (TransformerException te) {
        Assert.fail("Error while parsing the SAML response.");
    }

    return Base64.encodeBase64String(sw.toString().getBytes(Charset.forName("UTF-8")));
}

From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java

static String toString(Node dom) throws TransformerException {
    Source source = new DOMSource(dom);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(source, result);
    return stringWriter.getBuffer().toString();
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static StringBuffer printDom(Node node, boolean indent, boolean omitXmlDeclaration) {
    StringWriter writer = new StringWriter();
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;/*from ww w  .  j a  v  a  2  s  . c  o  m*/
    try {
        trans = transfac.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new SystemException("Error in XML configuration: " + e.getMessage(), e);
    }
    trans.setOutputProperty(OutputKeys.INDENT, (indent ? "yes" : "no"));
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // XALAN-specific
    trans.setParameter(OutputKeys.ENCODING, "utf-8");
    // Note: serialized XML does not contain xml declaration
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, (omitXmlDeclaration ? "yes" : "no"));

    DOMSource source = new DOMSource(node);
    try {
        trans.transform(source, new StreamResult(writer));
    } catch (TransformerException e) {
        throw new SystemException("Error in XML transformation: " + e.getMessage(), e);
    }

    return writer.getBuffer();
}