Search in sources :

Example 16 with Templates

use of javax.xml.transform.Templates in project cxf by apache.

the class XSLTJaxbProvider method getOutTemplates.

protected Templates getOutTemplates(Annotation[] anns, MediaType mt) {
    Templates t = createTemplatesFromContext();
    if (t != null) {
        return t;
    }
    t = outTemplates != null ? outTemplates : outMediaTemplates != null ? outMediaTemplates.get(mt.getType() + "/" + mt.getSubtype()) : null;
    if (t == null) {
        t = getAnnotationTemplates(anns);
    }
    return t;
}
Also used : Templates(javax.xml.transform.Templates)

Example 17 with Templates

use of javax.xml.transform.Templates in project Payara by payara.

the class WsUtil method generateFinalWsdl.

public void generateFinalWsdl(URL wsdlFileUrl, WebService webService, WebServerInfo wsi, OutputStream outputStream) throws Exception {
    Collection wsdlRelativeImports = new HashSet();
    Collection wsdlIncludes = new HashSet();
    Collection schemaRelativeImports = new HashSet();
    Collection schemaIncludes = new HashSet();
    if (webService.hasUrlPublishing()) {
        parseRelativeImports(wsdlFileUrl, wsdlRelativeImports, wsdlIncludes, schemaRelativeImports, schemaIncludes);
    }
    Collection endpoints = webService.getEndpoints();
    // a WSDL file can contain several ports associated to a service.
    // however Deployment descriptors can be expressed in two ways
    // to describe such a scenario in webservices.xml :
    // - One webservice-description with 2 port-components
    // - Two webservice-description with 1 port-component
    // The issue with #1, is that we need to configure the XSL with
    // the two ports so that the resulting unique WSDL has the correct
    // endpoint information and the JAXRPC stubs generated correctly.
    // So we need to check if this bundle is declaring more webservice
    // descriptor pointing to the same WSDL file...
    Collection endpointsCopy = new ArrayList();
    endpointsCopy.addAll(endpoints);
    BundleDescriptor bundle = webService.getBundleDescriptor();
    WebServicesDescriptor wsd = bundle.getWebServices();
    Collection webServices = wsd.getWebServices();
    if (webServices.size() > 1) {
        for (Iterator wsIter = webServices.iterator(); wsIter.hasNext(); ) {
            WebService aWS = (WebService) wsIter.next();
            if (webService.getName().equals(aWS.getName())) {
                continue;
            }
            // let's check if it points to the same WSDL file
            if ((webService.getWsdlFileUri() != null) && (aWS.getWsdlFileUri() != null) && (webService.getWsdlFileUri().equals(aWS.getWsdlFileUri()))) {
                endpointsCopy.addAll(aWS.getEndpoints());
            } else if ((webService.getWsdlFileUrl() != null) && (aWS.getWsdlFileUrl() != null) && ((webService.getWsdlFileUrl().toString()).equals(aWS.getWsdlFileUrl().toString()))) {
                endpointsCopy.addAll(aWS.getEndpoints());
            }
        }
    }
    // Load the wsdl file bytes with caching turned off.  This is
    // to avoid a jar url consistency problem that can arise if we
    // overwrite the module file later on in deployment.
    InputStream wsdlInputStream = new BufferedInputStream(wsdlFileUrl.openStream());
    Source XsltWsdlDocument = new StreamSource(wsdlInputStream);
    Templates templates = createTemplatesFor(endpointsCopy, wsdlRelativeImports, wsdlIncludes, schemaRelativeImports, schemaIncludes);
    Transformer transformer = templates.newTransformer();
    // WSDL is associated with webservice, but url is endpoint-specific,
    // so let WebService choose which endpoint to use.
    WebServiceEndpoint endpointForImport = webService.pickEndpointForRelativeImports();
    URL root = wsi.getWebServerRootURL(endpointForImport.isSecure());
    URL finalWsdlUrl = endpointForImport.composeFinalWsdlUrl(root);
    int wsdlImportNum = 0;
    for (Iterator iter = wsdlRelativeImports.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        transformer.setParameter(WSDL_IMPORT_NAMESPACE_PARAM_NAME + wsdlImportNum, next.getNamespace());
        // Convert each relative import into an absolute import, using
        // the final wsdl's Url as the context
        URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
        transformer.setParameter(WSDL_IMPORT_LOCATION_PARAM_NAME + wsdlImportNum, relativeUrl);
        wsdlImportNum++;
    }
    int schemaImportNum = 0;
    for (Iterator iter = schemaRelativeImports.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        transformer.setParameter(SCHEMA_IMPORT_NAMESPACE_PARAM_NAME + schemaImportNum, next.getNamespace());
        // Convert each relative import into an absolute import, using
        // the final wsdl's Url as the context
        URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
        transformer.setParameter(SCHEMA_IMPORT_LOCATION_PARAM_NAME + schemaImportNum, relativeUrl);
        schemaImportNum++;
    }
    int wsdlIncludeNum = 0;
    for (Iterator iter = wsdlIncludes.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
        transformer.setParameter(WSDL_INCLUDE_LOCATION_PARAM_NAME + wsdlIncludeNum, relativeUrl);
        wsdlIncludeNum++;
    }
    int schemaIncludeNum = 0;
    for (Iterator iter = schemaIncludes.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        URL relativeUrl = new URL(finalWsdlUrl, next.getLocation());
        transformer.setParameter(SCHEMA_INCLUDE_LOCATION_PARAM_NAME + schemaIncludeNum, relativeUrl);
        schemaIncludeNum++;
    }
    int endpointNum = 0;
    for (Iterator iter = endpointsCopy.iterator(); iter.hasNext(); ) {
        WebServiceEndpoint next = (WebServiceEndpoint) iter.next();
        // Get a URL for the root of the webserver, where the host portion
        // is a canonical host name.  Since this will be used to compose the
        // endpoint address that is written into WSDL, it's better to use
        // hostname as opposed to IP address.
        // The protocol and port will be based on whether the endpoint
        // has a transport guarantee of INTEGRAL or CONFIDENTIAL.
        // If yes, https will be used.  Otherwise, http will be used.
        URL rootURL = wsi.getWebServerRootURL(next.isSecure());
        URL actualAddress = next.composeEndpointAddress(rootURL);
        transformer.setParameter(ENDPOINT_ADDRESS_PARAM_NAME + endpointNum, actualAddress.toExternalForm());
        String endpointType = next.implementedByEjbComponent() ? "EJB" : "Servlet";
        logger.log(Level.INFO, LogUtils.ENDPOINT_REGISTRATION, new Object[] { "[" + endpointType + "] " + next.getEndpointName(), actualAddress });
        endpointNum++;
    }
    transformer.transform(XsltWsdlDocument, new StreamResult(outputStream));
    wsdlInputStream.close();
    outputStream.close();
    return;
}
Also used : Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) Templates(javax.xml.transform.Templates) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SDDocumentSource(com.sun.xml.ws.api.server.SDDocumentSource) UserDataConstraint(com.sun.enterprise.deployment.web.UserDataConstraint) SecurityConstraint(com.sun.enterprise.deployment.web.SecurityConstraint)

Example 18 with Templates

use of javax.xml.transform.Templates in project Payara by payara.

the class WsUtil method createTemplatesFor.

/**
 * Create an xslt template for transforming the packaged webservice
 * WSDL to a final WSDL.
 */
private Templates createTemplatesFor(Collection endpoints, Collection wsdlRelativeImports, Collection wsdlIncludes, Collection schemaRelativeImports, Collection schemaIncludes) throws Exception {
    // create the stylesheet
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(bos, "UTF-8");
    writer.write("<xsl:transform version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:soap12=\"http://schemas.xmlsoap.org/wsdl/soap12/\">\n");
    int wsdlImportNum = 0;
    for (Iterator iter = wsdlRelativeImports.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        String importNamespaceParam = WSDL_IMPORT_NAMESPACE_PARAM_NAME + wsdlImportNum;
        String importLocationParam = WSDL_IMPORT_LOCATION_PARAM_NAME + wsdlImportNum;
        writer.write("<xsl:param name=\"" + importNamespaceParam + "\"/>\n");
        writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n");
        writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n");
        writer.write("<xsl:template match=\"wsdl:definitions/wsdl:import[@location='");
        writer.write(next.getLocation());
        writer.write("']\" mode=\"copy\">");
        writer.write("<wsdl:import>");
        writer.write("<xsl:attribute name=\"namespace\"><xsl:value-of select=\"$" + importNamespaceParam + "\"/>");
        writer.write("</xsl:attribute>");
        writer.write("<xsl:attribute name=\"location\"><xsl:value-of select=\"$" + importLocationParam + "\"/>");
        writer.write("</xsl:attribute>");
        writer.write("</wsdl:import></xsl:template>");
        wsdlImportNum++;
    }
    int wsdlIncludeNum = 0;
    for (Iterator iter = wsdlIncludes.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        String importLocationParam = WSDL_INCLUDE_LOCATION_PARAM_NAME + wsdlIncludeNum;
        writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n");
        writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n");
        writer.write("<xsl:template match=\"wsdl:definitions/wsdl:include[@location='");
        writer.write(next.getLocation());
        writer.write("']\" mode=\"copy\">");
        writer.write("<wsdl:include>");
        writer.write("<xsl:attribute name=\"location\"><xsl:value-of select=\"$" + importLocationParam + "\"/>");
        writer.write("</xsl:attribute>");
        writer.write("</wsdl:include></xsl:template>");
        wsdlIncludeNum++;
    }
    int schemaImportNum = 0;
    for (Iterator iter = schemaRelativeImports.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        String importNamespaceParam = SCHEMA_IMPORT_NAMESPACE_PARAM_NAME + schemaImportNum;
        String importLocationParam = SCHEMA_IMPORT_LOCATION_PARAM_NAME + schemaImportNum;
        writer.write("<xsl:param name=\"" + importNamespaceParam + "\"/>\n");
        writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n");
        writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n");
        writer.write("<xsl:template match=\"wsdl:definitions/wsdl:types/xsd:schema/xsd:import[@schemaLocation='");
        writer.write(next.getLocation());
        writer.write("']\" mode=\"copy\">");
        writer.write("<xsd:import>");
        writer.write("<xsl:attribute name=\"namespace\"><xsl:value-of select=\"$" + importNamespaceParam + "\"/>");
        writer.write("</xsl:attribute>");
        writer.write("<xsl:attribute name=\"schemaLocation\"><xsl:value-of select=\"$" + importLocationParam + "\"/>");
        writer.write("</xsl:attribute>");
        writer.write("</xsd:import></xsl:template>");
        schemaImportNum++;
    }
    int schemaIncludeNum = 0;
    for (Iterator iter = schemaIncludes.iterator(); iter.hasNext(); ) {
        Import next = (Import) iter.next();
        String importLocationParam = SCHEMA_INCLUDE_LOCATION_PARAM_NAME + schemaIncludeNum;
        writer.write("<xsl:param name=\"" + importLocationParam + "\"/>\n");
        writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n");
        writer.write("<xsl:template match=\"wsdl:definitions/wsdl:types/xsd:schema/xsd:include[@schemaLocation='");
        writer.write(next.getLocation());
        writer.write("']\" mode=\"copy\">");
        writer.write("<xsd:include>");
        writer.write("<xsl:attribute name=\"schemaLocation\"><xsl:value-of select=\"$" + importLocationParam + "\"/>");
        writer.write("</xsl:attribute>");
        writer.write("</xsd:include></xsl:template>");
        schemaIncludeNum++;
    }
    int endpointNum = 0;
    for (Iterator iter = endpoints.iterator(); iter.hasNext(); ) {
        WebServiceEndpoint endpoint = (WebServiceEndpoint) iter.next();
        if (!endpoint.hasWsdlPort()) {
            throw new Exception("No WSDL port specified for endpoint " + endpoint.getEndpointName());
        }
        if (!endpoint.hasServiceName()) {
            throw new Exception("Runtime settings error.  Cannot find " + "service name for endpoint " + endpoint.getEndpointName());
        }
        String actualAddressParam = ENDPOINT_ADDRESS_PARAM_NAME + endpointNum;
        writer.write("<xsl:param name=\"" + actualAddressParam + "\"/>\n");
        writer.write("<xsl:template match=\"/\"><xsl:apply-templates mode=\"copy\"/></xsl:template>\n");
        writer.write("<xsl:template match=\"wsdl:definitions[@targetNamespace='");
        writer.write(endpoint.getServiceName().getNamespaceURI());
        writer.write("']/wsdl:service[@name='");
        writer.write(endpoint.getServiceName().getLocalPart());
        writer.write("']/wsdl:port[@name='");
        writer.write(endpoint.getWsdlPort().getLocalPart());
        writer.write("']/" + endpoint.getSoapAddressPrefix() + ":address\" mode=\"copy\">");
        writer.write("<" + endpoint.getSoapAddressPrefix() + ":address><xsl:attribute name=\"location\"><xsl:value-of select=\"$" + actualAddressParam + "\"/>");
        writer.write("</xsl:attribute></" + endpoint.getSoapAddressPrefix() + ":address></xsl:template>");
        endpointNum++;
    }
    writer.write("<xsl:template match=\"@*|node()\" mode=\"copy\"><xsl:copy><xsl:apply-templates select=\"@*\" mode=\"copy\"/><xsl:apply-templates mode=\"copy\"/></xsl:copy></xsl:template>\n");
    writer.write("</xsl:transform>\n");
    writer.close();
    byte[] stylesheet = bos.toByteArray();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(new String(stylesheet));
    }
    Source stylesheetSource = new StreamSource(new ByteArrayInputStream(stylesheet));
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Templates templates = transformerFactory.newTemplates(stylesheetSource);
    return templates;
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) StreamSource(javax.xml.transform.stream.StreamSource) Templates(javax.xml.transform.Templates) UserDataConstraint(com.sun.enterprise.deployment.web.UserDataConstraint) SecurityConstraint(com.sun.enterprise.deployment.web.SecurityConstraint) InvocationTargetException(java.lang.reflect.InvocationTargetException) SAXException(org.xml.sax.SAXException) PrivilegedActionException(java.security.PrivilegedActionException) SOAPFaultException(javax.xml.rpc.soap.SOAPFaultException) InjectionException(com.sun.enterprise.container.common.spi.util.InjectionException) SAXParseException(org.xml.sax.SAXParseException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SDDocumentSource(com.sun.xml.ws.api.server.SDDocumentSource)

Example 19 with Templates

use of javax.xml.transform.Templates in project mvel by mvel.

the class Processor method process.

public int process() throws TransformerException, IOException, SAXException {
    ZipInputStream zis = new ZipInputStream(input);
    final ZipOutputStream zos = new ZipOutputStream(output);
    final OutputStreamWriter osw = new OutputStreamWriter(zos);
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    TransformerFactory tf = TransformerFactory.newInstance();
    if (!tf.getFeature(SAXSource.FEATURE) || !tf.getFeature(SAXResult.FEATURE)) {
        return 0;
    }
    SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
    Templates templates = null;
    if (xslt != null) {
        templates = saxtf.newTemplates(xslt);
    }
    // configuring outHandlerFactory
    // ///////////////////////////////////////////////////////
    EntryElement entryElement = getEntryElement(zos);
    ContentHandler outDocHandler = null;
    switch(outRepresentation) {
        case BYTECODE:
            outDocHandler = new OutputSlicingHandler(new ASMContentHandlerFactory(zos), entryElement, false);
            break;
        case MULTI_XML:
            outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw, true), entryElement, true);
            break;
        case SINGLE_XML:
            ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
            zos.putNextEntry(outputEntry);
            outDocHandler = new SAXWriter(osw, false);
            break;
    }
    // configuring inputDocHandlerFactory
    // /////////////////////////////////////////////////
    ContentHandler inDocHandler;
    if (templates == null) {
        inDocHandler = outDocHandler;
    } else {
        inDocHandler = new InputSlicingHandler("class", outDocHandler, new TransformerHandlerFactory(saxtf, templates, outDocHandler));
    }
    ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(inDocHandler);
    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.startDocument();
        inDocHandler.startElement("", "classes", "classes", new AttributesImpl());
    }
    int i = 0;
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
        update(ze.getName(), n++);
        if (isClassEntry(ze)) {
            processEntry(zis, ze, inDocHandlerFactory);
        } else {
            OutputStream os = entryElement.openEntry(getName(ze));
            copyEntry(zis, os);
            entryElement.closeEntry();
        }
        i++;
    }
    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.endElement("", "classes", "classes");
        inDocHandler.endDocument();
    }
    if (outRepresentation == SINGLE_XML) {
        zos.closeEntry();
    }
    zos.flush();
    zos.close();
    return i;
}
Also used : SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) TransformerFactory(javax.xml.transform.TransformerFactory) ZipEntry(java.util.zip.ZipEntry) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) Templates(javax.xml.transform.Templates) ContentHandler(org.xml.sax.ContentHandler) ZipInputStream(java.util.zip.ZipInputStream) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStreamWriter(java.io.OutputStreamWriter)

Example 20 with Templates

use of javax.xml.transform.Templates in project lionengine by b3dgs.

the class XmlTest method testTransformerError.

/**
 * Test transformer error.
 *
 * @throws IllegalArgumentException If error.
 * @throws IllegalAccessException If error.
 * @throws NoSuchFieldException If error.
 */
@Test(expected = LionEngineException.class)
public void testTransformerError() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    final Field field = DocumentFactory.class.getDeclaredField("transformerFactory");
    UtilReflection.setAccessible(field, true);
    final javax.xml.transform.TransformerFactory old = (TransformerFactory) field.get(DocumentFactory.class);
    try {
        field.set(DocumentFactory.class, new javax.xml.transform.TransformerFactory() {

            @Override
            public Transformer newTransformer() throws TransformerConfigurationException {
                throw new TransformerConfigurationException();
            }

            @Override
            public Transformer newTransformer(Source source) throws TransformerConfigurationException {
                return null;
            }

            @Override
            public Templates newTemplates(Source source) throws TransformerConfigurationException {
                return null;
            }

            @Override
            public Source getAssociatedStylesheet(Source source, String media, String title, String charset) throws TransformerConfigurationException {
                return null;
            }

            @Override
            public void setURIResolver(URIResolver resolver) {
            // Mock
            }

            @Override
            public URIResolver getURIResolver() {
                return null;
            }

            @Override
            public void setFeature(String name, boolean value) throws TransformerConfigurationException {
            // Mock
            }

            @Override
            public boolean getFeature(String name) {
                return false;
            }

            @Override
            public void setAttribute(String name, Object value) {
            // Mock
            }

            @Override
            public Object getAttribute(String name) {
                return null;
            }

            @Override
            public void setErrorListener(ErrorListener listener) {
            // Mock
            }

            @Override
            public ErrorListener getErrorListener() {
                return null;
            }
        });
        final Media output = Medias.create("out.xml");
        new Xml(Medias.create("normalize.xml")).save(output);
        Assert.assertTrue(output.getFile().delete());
    } finally {
        field.set(DocumentFactory.class, old);
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Media(com.b3dgs.lionengine.Media) Templates(javax.xml.transform.Templates) URIResolver(javax.xml.transform.URIResolver) Source(javax.xml.transform.Source) ErrorListener(javax.xml.transform.ErrorListener) Field(java.lang.reflect.Field) TransformerFactory(javax.xml.transform.TransformerFactory) Test(org.junit.Test)

Aggregations

Templates (javax.xml.transform.Templates)60 TransformerFactory (javax.xml.transform.TransformerFactory)25 StreamSource (javax.xml.transform.stream.StreamSource)25 Transformer (javax.xml.transform.Transformer)20 Source (javax.xml.transform.Source)19 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)17 StreamResult (javax.xml.transform.stream.StreamResult)16 TransformerException (javax.xml.transform.TransformerException)10 InputStream (java.io.InputStream)8 IOException (java.io.IOException)7 OutputStream (java.io.OutputStream)7 DOMResult (javax.xml.transform.dom.DOMResult)7 DOMSource (javax.xml.transform.dom.DOMSource)7 File (java.io.File)5 Result (javax.xml.transform.Result)5 SAXSource (javax.xml.transform.sax.SAXSource)5 FileOutputStream (java.io.FileOutputStream)4 StringReader (java.io.StringReader)4 BufferedOutputStream (java.io.BufferedOutputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3