Java Code Examples for org.apache.cxf.staxutils.StaxUtils#toString()

The following examples show how to use org.apache.cxf.staxutils.StaxUtils#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSourcePayloadProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String getSourceAsString(Source s) throws Exception {
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        try (Writer out = new StringWriter()) {
            StreamResult streamResult = new StreamResult();
            streamResult.setWriter(out);
            transformer.transform(s, streamResult);
            return streamResult.getWriter().toString();
        }
    } catch (TransformerException te) {
        if ("javax.xml.transform.stax.StAXSource".equals(s.getClass().getName())) {
            //on java6, we will get this class if "stax" is configured
            //for the preferred type. However, older xalans don't know about it
            //we'll manually do it
            XMLStreamReader r = (XMLStreamReader)s.getClass().getMethod("getXMLStreamReader").invoke(s);
            return StaxUtils.toString(StaxUtils.read(r).getDocumentElement());
        }
        throw te;
    }
}
 
Example 2
Source File: NettyServerEngineFactoryParser.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Metadata parse(Element element, ParserContext context) {

        //Endpoint definition
        MutableBeanMetadata ef = context.createMetadata(MutableBeanMetadata.class);
        if (!StringUtils.isEmpty(getIdOrName(element))) {
            ef.setId(getIdOrName(element));
        } else {
            ef.setId("netty.engine.factory-holder-" + UUID.randomUUID().toString());
        }
        ef.setRuntimeClass(NettyHttpServerEngineFactoryHolder.class);

        try {
            // Print the DOM node
            String xmlString = StaxUtils.toString(element);
            ef.addProperty("parsedElement", createValue(context, xmlString));
            ef.setInitMethod("init");
            ef.setActivation(ComponentMetadata.ACTIVATION_EAGER);
            ef.setDestroyMethod("destroy");
            return ef;
        } catch (Exception e) {
            throw new RuntimeException("Could not process configuration.", e);
        }
    }
 
Example 3
Source File: AbstractXmlSchemaExtractorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected void validateTargetSchemas(XmlSchemaElement testElement) throws XmlSchemaSerializer.XmlSchemaSerializerException, IOException, SAXException {

        final String testNamespace = testElement.getQName().getNamespaceURI();
        final XmlSchema[] schemas = xmlSchemaExtractor.getTargetSchemas().getXmlSchemas();

        for (XmlSchema targetSchema : schemas) {
            final String targetNamespace = targetSchema.getTargetNamespace();
            // skip XSD and XML namespaces, which break in StaxUtils.toString below
            if (targetNamespace.equals(XMLConstants.XML_NS_URI) || targetNamespace.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
                continue;
            }
            final Document schemaDocument = targetSchema.getSchemaDocument();
            if (targetNamespace.isEmpty()) {
                // remove invalid xmlns:tns="" attribute or it breaks StaxUtils.toString below
                schemaDocument.getDocumentElement().removeAttribute("xmlns:tns");
            }
            final String schemaString = StaxUtils.toString(schemaDocument);

            // validate against schema XSD
            XmlSchemaTestHelper.validateSchema(schemaString);

            if (testNamespace.equals(targetNamespace)) {
                // must have element in test namespace
                assertThat(targetSchema.getElements()).isNotEmpty();
            }

            // all schemas must not be empty
            assertThat(targetSchema.getItems()).isNotEmpty();

            // check that all targetSchema types and elements are present in sourceSchema
            final List<Element> sourceNodes = sourceSchemaNodes.get(targetNamespace);
            if (sourceNodes == null) {
                if (!targetNamespace.equals(testElement.getQName().getNamespaceURI())) {
                    fail("Unexpected missing source schema " + targetNamespace);
                }
            } else {
                XmlSchemaTestHelper.checkSubsetSchema(schemaDocument, sourceNodes);
            }
        }
    }
 
Example 4
Source File: SampleWsApplicationClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String address = "http://localhost:8080/Service/Hello";
    String request = "<q0:sayHello xmlns:q0=\"http://service.ws.sample/\"><myname>Elan</myname></q0:sayHello>";

    StreamSource source = new StreamSource(new StringReader(request));
    Service service = Service.create(new URL(address + "?wsdl"), 
                                     new QName("http://service.ws.sample/" , "HelloService"));
    Dispatch<Source> disp = service.createDispatch(new QName("http://service.ws.sample/" , "HelloPort"),
                                                   Source.class, Mode.PAYLOAD);
    
    Source result = disp.invoke(source);
    String resultAsString = StaxUtils.toString(result);
    System.out.println(resultAsString);
   
}
 
Example 5
Source File: DispatchClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStAXSourcePAYLOAD() throws Exception {

    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    Service service = Service.create(wsdl, SERVICE_NAME);
    assertNotNull(service);

    Dispatch<StAXSource> disp = service.createDispatch(PORT_NAME, StAXSource.class, Service.Mode.PAYLOAD);
    disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                                 "http://localhost:"
                                 + greeterPort
                                 + "/SOAPDispatchService/SoapDispatchPort");
    QName opQName = new QName("http://apache.org/hello_world_soap_http", "greetMe");
    disp.getRequestContext().put(MessageContext.WSDL_OPERATION, opQName);

    // Test request-response
    InputStream is = getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq.xml");
    StAXSource staxSourceReq = new StAXSource(StaxUtils.createXMLStreamReader(is));
    assertNotNull(staxSourceReq);
    Source resp = disp.invoke(staxSourceReq);
    assertNotNull(resp);
    assertTrue(resp instanceof StAXSource);
    String expected = "Hello TestSOAPInputMessage";
    String actual = StaxUtils.toString(StaxUtils.read(resp));
    assertTrue("Expected: " + expected, actual.contains(expected));
}
 
Example 6
Source File: DispatchXMLClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamSourceMESSAGE() throws Exception {
    /*URL wsdl = getClass().getResource("/wsdl/hello_world_xml_wrapped.wsdl");
    assertNotNull(wsdl);

    XMLService service = new XMLService(wsdl, serviceName);
    assertNotNull(service);*/
    Service service = Service.create(SERVICE_NAME);
    assertNotNull(service);
    service.addPort(PORT_NAME, "http://cxf.apache.org/bindings/xformat",
                    "http://localhost:"
                    + port
                    + "/XMLService/XMLDispatchPort");

    InputStream is = getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq.xml");
    StreamSource reqMsg = new StreamSource(is);
    assertNotNull(reqMsg);

    Dispatch<Source> disp = service.createDispatch(PORT_NAME, Source.class, Service.Mode.MESSAGE);
    Source source = disp.invoke(reqMsg);
    assertNotNull(source);

    String streamString = StaxUtils.toString(source);
    Document doc = StaxUtils.read(new StringReader(streamString));
    assertEquals("greetMeResponse", doc.getFirstChild().getLocalName());
    assertEquals("Hello tli", doc.getFirstChild().getTextContent());
}
 
Example 7
Source File: Stax2DOMTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void assertDocumentContent(Document doc) {
    String content = StaxUtils.toString(doc);
    assertTrue(
            content,
            content.indexOf("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"") != -1);
    assertTrue(
            content,
            content.indexOf("xmlns:x1=\"http://cxf.apache.org/hello_world_jms/types\"") != -1);
}
 
Example 8
Source File: IDLToWSDLTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCXF3329() throws Exception {
    File input = new File(getClass().getResource("/idl/CXF3329.idl").toURI());
    String[] args = new String[] {
        "-o", output.toString(),
        input.toString()
    };
    IDLToWSDL.run(args);
    File fs = new File(output, "CXF3329.wsdl");
    assertTrue(fs.getName() + " was not created.", fs.exists());
    Document doc = StaxUtils.read(new FileInputStream(fs));
    String s = StaxUtils.toString(doc.getDocumentElement());
    assertTrue(s.contains("name=\"myStruct\""));
}
 
Example 9
Source File: CustomizedWSDLLocator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public InputSource getBaseInputSource() {
    if (elementMap.get(baseUri) != null) {
        Element ele = elementMap.get(baseUri);
        String content = StaxUtils.toString(ele);
        InputSource ins = new InputSource(new StringReader(content));
        ins.setSystemId(baseUri);
        return ins;

    }
    InputSource result = resolve(baseUri, null);
    baseUri = resolver.getURI();
    return result;
}
 
Example 10
Source File: CustomizedWSDLLocator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public InputSource getImportInputSource(String parent, String importLocation) {
    baseUri = parent;
    importedUri = importLocation;
    try {
        URI importURI = new URI(importLocation);
        if (!importURI.isAbsolute()) {
            URI parentURI = new URI(parent);
            importURI = parentURI.resolve(importURI);
        }

        if (elementMap.get(importURI.toString()) != null) {
            Element ele = elementMap.get(importURI.toString());
            String content = StaxUtils.toString(ele);

            InputSource ins = new InputSource(new StringReader(content));
            ins.setSystemId(importURI.toString());
            this.resolveFromMap = true;
            this.latestImportURI = importURI.toString();
            return ins;
        }

    } catch (URISyntaxException e) {
        throw new RuntimeException("Failed to Resolve " + importLocation, e);
    }
    resolveFromMap = false;
    return resolve(importedUri, baseUri);
}
 
Example 11
Source File: XMLSource.java    From cxf with Apache License 2.0 5 votes vote down vote up
private <T> Object readPrimitiveValue(Node node, Class<T> cls) {
    if (String.class == cls) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            return StaxUtils.toString((Element)node);
        }
        return cls.cast(node.getNodeValue());
    }

    return InjectionUtils.convertStringToPrimitive(node.getNodeValue(), cls);
}
 
Example 12
Source File: UndertowServerEngineFactoryParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Metadata parse(Element element, ParserContext context) {

        //Endpoint definition
        MutableBeanMetadata ef = context.createMetadata(MutableBeanMetadata.class);
        if (!StringUtils.isEmpty(getIdOrName(element))) {
            ef.setId(getIdOrName(element));
        } else {
            ef.setId("undertow.engine.factory-holder-" + UUID.randomUUID().toString());
        }
        ef.setRuntimeClass(UndertowHTTPServerEngineFactoryHolder.class);

        // setup the HandlersMap property for the UndertowHTTPServerEngineFactoryHolder

        try {
            // Print the DOM node
            String xmlString = StaxUtils.toString(element);
            ef.addProperty("parsedElement", createValue(context, xmlString));
            ef.setInitMethod("init");
            ef.setActivation(ComponentMetadata.ACTIVATION_EAGER);
            ef.setDestroyMethod("destroy");

            // setup the EngineConnector
            List<Element> engines = DOMUtils
                .getChildrenWithName(element, HTTPUndertowTransportNamespaceHandler.UNDERTOW_TRANSPORT, "engine");
            ef.addProperty("handlersMap", parseEngineHandlers(engines, ef, context));
            return ef;
        } catch (Exception e) {
            throw new RuntimeException("Could not process configuration.", e);
        }
    }
 
Example 13
Source File: JettyServerEngineFactoryParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Metadata parse(Element element, ParserContext context) {

        //Endpoint definition
        MutableBeanMetadata ef = context.createMetadata(MutableBeanMetadata.class);
        if (!StringUtils.isEmpty(getIdOrName(element))) {
            ef.setId(getIdOrName(element));
        } else {
            ef.setId("jetty.engine.factory-holder-" + UUID.randomUUID().toString());
        }
        ef.setRuntimeClass(JettyHTTPServerEngineFactoryHolder.class);

        // setup the ConnectorMap and HandlersMap property for the JettyHTTPServerEngineFactoryHolder

        try {
            // Print the DOM node
            String xmlString = StaxUtils.toString(element);
            ef.addProperty("parsedElement", createValue(context, xmlString));
            ef.setInitMethod("init");
            ef.setActivation(ComponentMetadata.ACTIVATION_EAGER);
            ef.setDestroyMethod("destroy");

            // setup the EngineConnector
            List<Element> engines = DOMUtils
                .getChildrenWithName(element, HTTPJettyTransportNamespaceHandler.JETTY_TRANSPORT, "engine");
            ef.addProperty("connectorMap", parseEngineConnector(engines, ef, context));
            ef.addProperty("handlersMap", parseEngineHandlers(engines, ef, context));
            return ef;
        } catch (Exception e) {
            throw new RuntimeException("Could not process configuration.", e);
        }
    }
 
Example 14
Source File: DOMLSInput.java    From cxf with Apache License 2.0 4 votes vote down vote up
DOMLSInput(Document doc, String systemId) throws TransformerException {
    this.systemId = systemId;
    data = StaxUtils.toString(doc);
    LOG.fine(systemId + ": " + data);

}
 
Example 15
Source File: BindingHelper.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private String getSpecificationString(XmlSchemaExtractor schemaExtractor) throws ParserException {
    try {
        // copy source elements and types to target schema
        schemaExtractor.copyObjects();
        final SchemaCollection targetSchemas = schemaExtractor.getTargetSchemas();

        // serialize schemas as AtlasMap schemaset
        // schemaset is described at https://docs.atlasmap.io/#importing-xml-files-into-atlasmap
        final Document schemaSet = this.documentBuilder.parse(new InputSource(new StringReader(SCHEMA_SET_XML)));
        final Node additionalSchemas = schemaSet.getElementsByTagName("d:AdditionalSchemas").item(0);

        // insert schemas into schemaset
        final XmlSchema[] xmlSchemas = targetSchemas.getXmlSchemaCollection().getXmlSchemas();
        for (XmlSchema schema : xmlSchemas) {
            final String targetNamespace = schema.getTargetNamespace();

            // no need to add XSD and XML schema
            if (!targetNamespace.equals(XMLConstants.XML_NS_URI) &&
                !targetNamespace.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {

                // get the schema DOM document
                final Document schemaDocument = schema.getSchemaDocument();
                // remove targetnamespace declaration for no namespace schema
                if (targetNamespace.isEmpty()) {
                    // remove invalid xmlns:tns="" attribute or it breaks StaxUtils.toString below
                    schemaDocument.getDocumentElement().removeAttribute("xmlns:tns");
                }

                // import the schema into schemaset
                final Node documentElement = schemaSet.importNode(schemaDocument.getDocumentElement(), true);

                if (targetNamespace.equals(soapVersion.getNamespace())) {
                    // add soap envelope under schemaset as first child
                    schemaSet.getDocumentElement().insertBefore(documentElement, additionalSchemas);
                } else {
                    // add the schema under 'AdditionalSchemas'
                    additionalSchemas.appendChild(documentElement);
                }
            }
        }

        // write schemaset as string
        return StaxUtils.toString(schemaSet);

    } catch (XmlSchemaSerializer.XmlSchemaSerializerException | ParserException | SAXException | IOException e) {
        throw new ParserException(String.format("Error parsing %s for operation %s: %s",
            bindingMessageInfo.getMessageInfo().getType(),
            bindingMessageInfo.getBindingOperation().getOperationInfo().getName(),
            e.getMessage())
            , e);
    }
}
 
Example 16
Source File: SamlTokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
static String serialize(Document doc) throws Exception {
    return StaxUtils.toString(doc);
}
 
Example 17
Source File: SecurityActionTokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
static String serialize(Document doc) {
    return StaxUtils.toString(doc);
}
 
Example 18
Source File: WSS4JInOutTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
static String serialize(Document doc) {
    return StaxUtils.toString(doc);
}
 
Example 19
Source File: XPathAssert.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static String writeNodeToString(Node node) {
    return StaxUtils.toString(node);
}
 
Example 20
Source File: AbstractEncodedTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
public Object readRef(Element element) throws XMLStreamException {
    String xml = StaxUtils.toString(element);
    ElementReader root = new ElementReader(new ByteArrayInputStream(xml.getBytes(UTF_8)));
    return readRef(root);
}