Search in sources :

Example 16 with StreamResult

use of javax.xml.transform.stream.StreamResult in project openhab1-addons by openhab.

the class Helper method nodeToString.

/***
     * Converts a xml Node into String
     *
     * @param node to convert
     * @return converted string
     */
public static String nodeToString(Node node) {
    StringWriter sw = new StringWriter();
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException te) {
        logger.warn("nodeToString Transformer Exception", te);
    }
    return sw.toString();
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) TransformerException(javax.xml.transform.TransformerException)

Example 17 with StreamResult

use of javax.xml.transform.stream.StreamResult in project OpenAM by OpenRock.

the class ValidationErrorHandler method print.

/**
     * Prints a Node tree recursively.
     * @param node A DOM tree Node
     * @param encoding character encoding
     * @return An xml String representation of the DOM tree.
     */
public static String print(Node node, String encoding) {
    if (node == null) {
        return null;
    }
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty("omit-xml-declaration", "yes");
        transformer.setOutputProperty("encoding", encoding);
        DOMSource source = new DOMSource(node);
        ByteArrayOutputStream os = new ByteArrayOutputStream(2000);
        StreamResult result = new StreamResult(os);
        transformer.transform(source, result);
        return os.toString(encoding);
    } catch (Exception e) {
        return null;
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 18 with StreamResult

use of javax.xml.transform.stream.StreamResult in project OpenAM by OpenRock.

the class Client method sendRequest.

/**
     * Sends a request to a SOAP endpoint and returns the response. The server
     * only contains one servlet for different web services. So the SOAP
     * endpoint URL has format 'servlet_URL/key'.
     *
     * @param req the request message.
     * @param connectTo the SOAP endpoint URL
     * @param certAlias the cert alias of a client certificate
     * @param soapAction the SOAPAction header
     * @return a response from the SOAP endpoint
     * @throws SOAPFaultException if a SOAP Fault occurs
     * @throws SOAPBindingException if a error occurs while processing,
     *                                 sending or receiving Message
     */
public static Message sendRequest(Message req, String connectTo, String certAlias, String soapAction) throws SOAPBindingException, SOAPFaultException {
    URLConnection con = null;
    try {
        con = getConnection(connectTo, certAlias);
    } catch (Exception e) {
        Utils.debug.error("Client:sendRequest", e);
        throw new SOAPBindingException(e.getMessage());
    }
    if (soapAction == null || soapAction.length() == 0) {
        soapAction = "";
    }
    con.setRequestProperty(SOAPBindingConstants.SOAP_ACTION_HEADER, soapAction);
    Document doc = null;
    int securityProfileType = req.getSecurityProfileType();
    if (securityProfileType == Message.ANONYMOUS || securityProfileType == Message.BEARER_TOKEN) {
        doc = req.toDocument(true);
    } else {
        Element sigElem = SecurityUtils.signMessage(req);
        if (sigElem == null) {
            String msg = Utils.bundle.getString("cannotSignRequest");
            Utils.debug.error("Client.sendRequest: " + msg);
            throw new SOAPBindingException(msg);
        }
        doc = sigElem.getOwnerDocument();
    }
    if (Utils.debug.messageEnabled()) {
        Utils.debug.message("Client.sendRequest: signed request\n" + req);
    }
    OutputStream os = null;
    try {
        os = con.getOutputStream();
        Transformer transformer = XMLUtils.getTransformerFactory().newTransformer();
        transformer.setOutputProperty("omit-xml-declaration", "yes");
        transformer.transform(new DOMSource(doc.getDocumentElement()), new StreamResult(os));
    } catch (Exception e) {
        Utils.debug.error("Client:sendRequest", e);
        throw new SOAPBindingException(e.getMessage());
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (Exception e) {
                Utils.debug.error("Client:sendRequest", e);
            }
        }
    }
    Message resp = null;
    InputStream is = null;
    try {
        is = con.getInputStream();
        resp = new Message(is);
        if (resp.getSOAPFault() != null) {
            throw new SOAPFaultException(resp);
        }
        Utils.enforceProcessingRules(resp, req.getCorrelationHeader().getMessageID(), false);
    } catch (IOException e) {
        Utils.debug.error("Client:sendRequest", e);
        throw new SOAPBindingException(e.getMessage());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                Utils.debug.error("Client:sendRequest", e);
            }
        }
    }
    resp.setProtocol(con.getURL().getProtocol());
    if (resp.getSecurityProfileType() != Message.ANONYMOUS && !SecurityUtils.verifyMessage(resp)) {
        String msg = Utils.bundle.getString("cannotVerifySignature");
        Utils.debug.error("Client.sendRequest: " + msg);
        throw new SOAPBindingException(msg);
    }
    return resp;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Document(org.w3c.dom.Document) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 19 with StreamResult

use of javax.xml.transform.stream.StreamResult in project OpenAM by OpenRock.

the class XMLResourceExceptionHandler method write.

@Override
public void write(MessageContext context, AuthenticationException exception) {
    Reject.ifNull(exception);
    try {
        ResourceException jre;
        if (exception instanceof AuthenticationFailedException) {
            jre = new PermanentException(Status.UNAUTHORIZED.getCode(), exception.getMessage(), null);
        } else if (exception.getCause() instanceof ResourceException) {
            jre = (ResourceException) exception.getCause();
        } else {
            LOGGER.error(exception.getMessage(), exception);
            jre = new InternalServerErrorException("Authentication Failed", exception);
        }
        AuditTrail auditTrail = context.getAuditTrail();
        List<Map<String, Object>> failureReasonList = auditTrail.getFailureReasons();
        if (failureReasonList != null && !failureReasonList.isEmpty()) {
            jre.setDetail(json(object(field("failureReasons", failureReasonList))));
        }
        Response response = context.getResponse();
        response.setStatus(Status.valueOf(jre.getCode()));
        context.<Response>getResponse().getHeaders().put(ContentTypeHeader.valueOf(MediaType.XML_UTF_8.toString()));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Transformer transformer = XMLUtils.getTransformerFactory().newTransformer();
        transformer.transform(new DOMSource(asXMLDOM(jre.includeCauseInJsonValue().toJsonValue().asMap())), new StreamResult(outputStream));
        response.getEntity().setBytes(outputStream.toByteArray());
    } catch (TransformerException e1) {
        throw new IllegalStateException("Could not write XML to response", e1);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) AuthenticationFailedException(org.forgerock.caf.authentication.framework.AuthenticationFailedException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Response(org.forgerock.http.protocol.Response) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException) AuditTrail(org.forgerock.caf.authentication.framework.AuditTrail) Map(java.util.Map) TransformerException(javax.xml.transform.TransformerException)

Example 20 with StreamResult

use of javax.xml.transform.stream.StreamResult in project OpenAM by OpenRock.

the class MarshallerImpl method marshal.

public void marshal(Object obj, Result result) throws JAXBException {
    //XMLSerializable so = Util.toXMLSerializable(obj);
    XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj);
    if (so == null)
        throw new MarshalException(Messages.format(Messages.NOT_MARSHALLABLE));
    if (result instanceof SAXResult) {
        write(so, ((SAXResult) result).getHandler());
        return;
    }
    if (result instanceof DOMResult) {
        Node node = ((DOMResult) result).getNode();
        if (node == null) {
            try {
                DocumentBuilder db = XMLUtils.getSafeDocumentBuilder(false);
                Document doc = db.newDocument();
                ((DOMResult) result).setNode(doc);
                write(so, new SAX2DOMEx(doc));
            } catch (ParserConfigurationException pce) {
                throw new JAXBAssertionError(pce);
            }
        } else {
            write(so, new SAX2DOMEx(node));
        }
        return;
    }
    if (result instanceof StreamResult) {
        StreamResult sr = (StreamResult) result;
        XMLWriter w = null;
        if (sr.getWriter() != null)
            w = createWriter(sr.getWriter());
        else if (sr.getOutputStream() != null)
            w = createWriter(sr.getOutputStream());
        else if (sr.getSystemId() != null) {
            String fileURL = sr.getSystemId();
            if (fileURL.startsWith("file:///")) {
                if (fileURL.substring(8).indexOf(":") > 0)
                    fileURL = fileURL.substring(8);
                else
                    fileURL = fileURL.substring(7);
            }
            try {
                w = createWriter(new FileOutputStream(fileURL));
            } catch (IOException e) {
                throw new MarshalException(e);
            }
        }
        if (w == null)
            throw new IllegalArgumentException();
        write(so, w);
        return;
    }
    // unsupported parameter type
    throw new MarshalException(Messages.format(Messages.UNSUPPORTED_RESULT));
}
Also used : MarshalException(javax.xml.bind.MarshalException) DOMResult(javax.xml.transform.dom.DOMResult) StreamResult(javax.xml.transform.stream.StreamResult) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) XMLWriter(com.sun.xml.bind.marshaller.XMLWriter) SAXResult(javax.xml.transform.sax.SAXResult) JAXBAssertionError(com.sun.xml.bind.JAXBAssertionError) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) SAX2DOMEx(com.sun.xml.bind.marshaller.SAX2DOMEx) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

StreamResult (javax.xml.transform.stream.StreamResult)1328 DOMSource (javax.xml.transform.dom.DOMSource)881 Transformer (javax.xml.transform.Transformer)775 StringWriter (java.io.StringWriter)447 TransformerFactory (javax.xml.transform.TransformerFactory)445 Document (org.w3c.dom.Document)415 TransformerException (javax.xml.transform.TransformerException)366 ByteArrayOutputStream (java.io.ByteArrayOutputStream)337 DocumentBuilder (javax.xml.parsers.DocumentBuilder)332 ByteArrayInputStream (java.io.ByteArrayInputStream)288 IOException (java.io.IOException)266 InputStream (java.io.InputStream)249 Test (org.junit.Test)246 StreamSource (javax.xml.transform.stream.StreamSource)213 XMLStreamReader (javax.xml.stream.XMLStreamReader)185 Source (javax.xml.transform.Source)183 File (java.io.File)175 Element (org.w3c.dom.Element)157 InboundXMLSec (org.apache.xml.security.stax.ext.InboundXMLSec)149 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)149