Search in sources :

Example 56 with Transformer

use of javax.xml.transform.Transformer in project goci by EBISPOT.

the class ChromosomeRenderlet method render.

public void render(RenderletNexus nexus, C context, E entity) {
    int position = getPosition();
    int height = SVGCanvas.canvasHeight;
    int width = SVGCanvas.canvasWidth;
    double chromWidth = (double) width / 12;
    double chromHeight = (double) height / 2;
    double xCoordinate;
    double yCoordinate = 0;
    if (position < 12) {
        xCoordinate = position * chromWidth;
    } else {
        xCoordinate = (position - 12) * chromWidth;
        yCoordinate = (double) height / 2;
    }
    InputStream in = null;
    try {
        in = getSVGFile().openStream();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document chromSVG = db.parse(in);
        Element root = chromSVG.getDocumentElement();
        Element g = (Element) root.getElementsByTagName("g").item(0).cloneNode(true);
        setChromBands(g, nexus);
        StringBuilder builder = new StringBuilder();
        builder.append("translate(");
        builder.append(Double.toString(xCoordinate));
        builder.append(",");
        builder.append(Double.toString(yCoordinate));
        builder.append(")");
        g.setAttribute("transform", builder.toString());
        g.setAttribute("gwasname", getName());
        g.removeAttribute("title");
        SVGArea currentArea = new SVGArea(xCoordinate, yCoordinate, chromWidth, chromHeight, 0);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(g), new StreamResult(buffer));
        String str = buffer.toString();
        RenderingEvent<E> event = new RenderingEvent<E>(entity, str, currentArea, this);
        nexus.renderingEventOccurred(event);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Failed to read in template chromosome SVG from original resource", e);
    } catch (SAXException e) {
        throw new RuntimeException("Failed to read in template chromosome SVG from original resource", e);
    } catch (IOException e) {
        throw new RuntimeException("Failed to render chromosome SVG", e);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Failed to render chromosome SVG", e);
    } catch (TransformerException e) {
        throw new RuntimeException("Failed to render chromosome SVG", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            // tried our best!
            }
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) RenderingEvent(uk.ac.ebi.spot.goci.pussycat.renderlet.RenderingEvent) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SVGArea(uk.ac.ebi.spot.goci.pussycat.layout.SVGArea) TransformerException(javax.xml.transform.TransformerException)

Example 57 with Transformer

use of javax.xml.transform.Transformer 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 58 with Transformer

use of javax.xml.transform.Transformer 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 59 with Transformer

use of javax.xml.transform.Transformer 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 60 with Transformer

use of javax.xml.transform.Transformer in project opennms by OpenNMS.

the class XmlSystemReportFormatter method write.

@Override
public void write(final SystemReportPlugin plugin) {
    if (!hasDisplayable(plugin))
        return;
    if (m_handler == null) {
        try {
            StreamResult streamResult = new StreamResult(getOutputStream());
            SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            m_handler = tf.newTransformerHandler();
            Transformer serializer = m_handler.getTransformer();
            serializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "entry");
            m_handler.setResult(streamResult);
        } catch (final Exception e) {
            LOG.error("Unable to create XML stream writer.", e);
            m_handler = null;
        }
        try {
            m_handler.startDocument();
            m_handler.startElement("", "", "systemReportPlugins", null);
        } catch (final Exception e) {
            LOG.warn("Unable to start document.", e);
            m_handler = null;
        }
    }
    if (m_handler == null) {
        LOG.warn("Unable to write, no handler defined!");
        return;
    }
    try {
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", "name", "CDATA", plugin.getName());
        atts.addAttribute("", "", "description", "CDATA", plugin.getDescription());
        m_handler.startElement("", "", "plugin", atts);
        for (final Map.Entry<String, Resource> entry : plugin.getEntries().entrySet()) {
            final boolean displayable = isDisplayable(entry.getValue());
            atts = new AttributesImpl();
            atts.addAttribute("", "", "key", "CDATA", entry.getKey());
            if (!displayable) {
                atts.addAttribute("", "", "skipped", "CDATA", "true");
            }
            m_handler.startElement("", "", "entry", atts);
            if (displayable) {
                final String value = getResourceText(entry.getValue());
                if (value != null) {
                    m_handler.startCDATA();
                    m_handler.characters(value.toCharArray(), 0, value.length());
                    m_handler.endCDATA();
                }
            }
            m_handler.endElement("", "", "entry");
        }
        m_handler.endElement("", "", "plugin");
    } catch (final Exception e) {
        LOG.warn("An error occurred while attempting to write XML data.", e);
    }
}
Also used : Transformer(javax.xml.transform.Transformer) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StreamResult(javax.xml.transform.stream.StreamResult) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) Resource(org.springframework.core.io.Resource) Map(java.util.Map)

Aggregations

Transformer (javax.xml.transform.Transformer)449 StreamResult (javax.xml.transform.stream.StreamResult)354 DOMSource (javax.xml.transform.dom.DOMSource)272 TransformerFactory (javax.xml.transform.TransformerFactory)222 TransformerException (javax.xml.transform.TransformerException)175 StringWriter (java.io.StringWriter)153 Document (org.w3c.dom.Document)114 IOException (java.io.IOException)105 StreamSource (javax.xml.transform.stream.StreamSource)98 Source (javax.xml.transform.Source)97 DocumentBuilder (javax.xml.parsers.DocumentBuilder)70 File (java.io.File)66 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)64 SAXException (org.xml.sax.SAXException)62 Element (org.w3c.dom.Element)59 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)57 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)57 ByteArrayOutputStream (java.io.ByteArrayOutputStream)53 StringReader (java.io.StringReader)52 Result (javax.xml.transform.Result)52