Java Code Examples for javax.xml.transform.dom.DOMSource

The following examples show how to use javax.xml.transform.dom.DOMSource. These examples are extracted from open source projects. 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 Project: jettison   Author: jettison-json   File: AbstractDOMDocumentSerializer.java    License: Apache License 2.0 6 votes vote down vote up
public void serialize(Element el) throws IOException {
	if (output == null)
		throw new IllegalStateException("OutputStream cannot be null");

	try {
		DOMSource source = new DOMSource(el);
		XMLInputFactory readerFactory = XMLInputFactory.newInstance();
		XMLStreamReader streamReader = readerFactory
				.createXMLStreamReader(source);
		XMLEventReader eventReader = readerFactory
				.createXMLEventReader(streamReader);

		XMLEventWriter eventWriter = writerFactory
				.createXMLEventWriter(output);
		eventWriter.add(eventReader);
		eventWriter.close();
	} catch (XMLStreamException ex) {
		IOException ioex = new IOException("Cannot serialize: " + el);
		ioex.initCause(ex);
		throw ioex;
	}
}
 
Example #2
Source Project: birt   Author: eclipse   File: SVGRendererImpl.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Writes the XML document to an output stream
 * 
 * @param svgDocument
 * @param outputStream
 * @throws Exception
 */
private void writeDocumentToOutputStream( Document svgDocument,
		OutputStream outputStream ) throws Exception
{
	if ( svgDocument != null && outputStream != null )
	{
		OutputStreamWriter writer = null;

		writer = SecurityUtil.newOutputStreamWriter( outputStream, "UTF-8" ); //$NON-NLS-1$

		DOMSource source = new DOMSource( svgDocument );
		StreamResult result = new StreamResult( writer );

		// need to check if we should use sun's implementation of the
		// transform factory. This is needed to work with jdk1.4 and jdk1.5
		// with tomcat
		checkForTransformFactoryImpl( );
		TransformerFactory transFactory = SecurityUtil.newTransformerFactory( );
		Transformer transformer = transFactory.newTransformer( );

		transformer.transform( source, result );
	}

}
 
Example #3
Source Project: teamengine   Author: opengeospatial   File: SoapUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
   * A method to create a SOAP message and retrieve it as byte.
   * 
   * @param version
   *            the SOAP version to be used (1.1 or 1.2).
   * @param headerBlocks
   *            the list of Header Blocks to be included in the SOAP Header .
   * @param body
   *            the XML message to be included in the SOAP BODY element.
   * @param encoding
   *            the encoding to be used for the message creation.
   * 
   * @return The created SOAP message as byte.
   * 
   * @author Simone Gianfranceschi
   */
  public static byte[] getSoapMessageAsByte(String version,
          List headerBlocks, Element body, String encoding) throws Exception {
      Document message = createSoapMessage(version, headerBlocks, body);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      TransformerFactory tf = TransformerFactory.newInstance();
        // Fortify Mod: prevent external entity injection
      tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      Transformer t = tf.newTransformer();
// End Fortify Mod
      t.setOutputProperty(OutputKeys.ENCODING, encoding);
      t.transform(new DOMSource(message), new StreamResult(baos));

      // System.out.println("SOAP MESSAGE : " + baos.toString());

      return baos.toByteArray();
  }
 
Example #4
Source Project: hottub   Author: dsrg-uoft   File: AbstractUnmarshallerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal( Source source ) throws JAXBException {
    if( source == null ) {
        throw new IllegalArgumentException(
            Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
    }

    if(source instanceof SAXSource)
        return unmarshal( (SAXSource)source );
    if(source instanceof StreamSource)
        return unmarshal( streamSourceToInputSource((StreamSource)source));
    if(source instanceof DOMSource)
        return unmarshal( ((DOMSource)source).getNode() );

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #5
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: JaxpIssue43Test.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Source[] getSchemaSources() throws Exception {
    List<Source> list = new ArrayList<Source>();
    String file = getClass().getResource("hello_literal.wsdl").getFile();
    Source source = new StreamSource(new FileInputStream(file), file);

    Transformer trans = TransformerFactory.newInstance().newTransformer();
    DOMResult result = new DOMResult();
    trans.transform(source, result);

    // Look for <xsd:schema> element in wsdl
    Element e = ((Document) result.getNode()).getDocumentElement();
    NodeList typesList = e.getElementsByTagNameNS("http://schemas.xmlsoap.org/wsdl/", "types");
    NodeList schemaList = ((Element) typesList.item(0)).getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema");
    Element elem = (Element) schemaList.item(0);
    list.add(new DOMSource(elem, file + "#schema0"));

    // trans.transform(new DOMSource(elem), new StreamResult(System.out));

    return list.toArray(new Source[list.size()]);
}
 
Example #6
Source Project: nifi   Author: apache   File: StandardFlowSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(final Document flowConfiguration, final OutputStream os) throws FlowSerializationException {
    try {
        final DOMSource domSource = new DOMSource(flowConfiguration);
        final StreamResult streamResult = new StreamResult(new BufferedOutputStream(os));

        // configure the transformer and convert the DOM
        final TransformerFactory transformFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformFactory.newTransformer();
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // transform the document to byte stream
        transformer.transform(domSource, streamResult);

    } catch (final DOMException | TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
        throw new FlowSerializationException(e);
    }
}
 
Example #7
Source Project: proarc   Author: proarc   File: CrossrefBuilderTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testCreateCrossrefXml_SkippedVolume() throws Exception {
        File targetFolder = temp.getRoot();
        CrossrefBuilder builder = new CrossrefBuilder(targetFolder);
        builder.addPeriodicalTitle("1210-8510", "titleTest", "abbrevTest", "print");
        builder.addIssue("10", "2010", "uuid");
        Document article = builder.getDocumentBuilder().parse(
                CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
        builder.addArticle(article);
        Document articles = builder.mergeArticles();
        StringWriter dump = new StringWriter();
        TransformErrorListener errors = builder.createCrossrefXml(new DOMSource(articles), new StreamResult(dump));
//        System.out.println(dump);
        assertTrue(errors.getErrors().toString(), errors.getErrors().isEmpty());

        List<String> validateErrors = builder.validateCrossref(new StreamSource(new StringReader(dump.toString())));
        assertTrue(validateErrors.toString(), validateErrors.isEmpty());
    }
 
Example #8
Source Project: freehealth-connector   Author: taktik   File: DocumentResolver.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public XMLSignatureInput engineResolveURI(ResourceResolverContext context) throws ResourceResolverException {
   String id = context.attr.getNodeValue();
   if (id.startsWith("#")) {
      id = id.substring(1);
   }

   if (LOG.isDebugEnabled()) {
      try {
         LOG.debug("Selected document: " + ConnectorXmlUtils.flatten(ConnectorXmlUtils.toString((Source)(new DOMSource(this.doc)))));
      } catch (TechnicalConnectorException var5) {
         LOG.error(var5.getMessage());
      }
   }

   Node selectedElem = this.doc.getElementById(id);
   if (LOG.isDebugEnabled()) {
      LOG.debug("Try to catch an Element with ID " + id + " and Element was " + selectedElem);
   }

   this.processElement(context.attr, context.baseUri, selectedElem, id);
   XMLSignatureInput result = new XMLSignatureInput(selectedElem);
   result.setExcludeComments(true);
   result.setMIMEType("text/xml");
   result.setSourceURI(context.baseUri != null ? context.baseUri.concat(context.attr.getNodeValue()) : context.attr.getNodeValue());
   return result;
}
 
Example #9
Source Project: jolie   Author: jolie   File: WSDLConverter.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void parseSchemaElement( Element element )
	throws IOException {
	try {
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty( "indent", "yes" );
		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult( sw );
		DOMSource source = new DOMSource( element );
		transformer.transform( source, result );
		InputSource schemaSource = new InputSource( new StringReader( sw.toString() ) );
		schemaSource.setSystemId( definition.getDocumentBaseURI() );
		schemaParser.parse( schemaSource );
	} catch( SAXException | TransformerException e ) {
		throw new IOException( e );
	}
}
 
Example #10
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: CatalogSupport4.java    License: GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name = "data_ValidatorA")
public Object[][] getDataValidator() {
    DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
    StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);

    StreamSource source = new StreamSource(new File(xml_val_test));

    return new Object[][]{
        // use catalog
        {true, false, true, ds, null, null, xml_catalog, null},
        {false, true, true, ds, null, null, null, xml_catalog},
        {true, false, true, ss, null, null, xml_catalog, null},
        {false, true, true, ss, null, null, null, xml_catalog},
        {true, false, true, stax, null, null, xml_catalog, xml_catalog},
        {false, true, true, stax1, null, null, xml_catalog, xml_catalog},
        {true, false, true, source, null, null, xml_catalog, null},
        {false, true, true, source, null, null, null, xml_catalog},
    };
}
 
Example #11
Source Project: java-ocr-api   Author: Asprise   File: XmlSupport.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private static final void writeDoc(Document doc, OutputStream out)
    throws IOException
{
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            tf.setAttribute("indent-number", new Integer(2));
        } catch (IllegalArgumentException iae) {

        }
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
        t.setOutputProperty(OutputKeys.INDENT, "yes");

        t.transform(new DOMSource(doc),
                    new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
    } catch(TransformerException e) {
        throw new AssertionError(e);
    }
}
 
Example #12
Source Project: cxf   Author: apache   File: EndpointReferenceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceGetPortUsingEndpointReference() throws Exception {
    BusFactory.setDefaultBus(getBus());
    GreeterImpl greeter1 = new GreeterImpl();
    try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter1, (String)null)) {
        endpoint.publish("http://localhost:8080/test");

        javax.xml.ws.Service s = javax.xml.ws.Service
            .create(new QName("http://apache.org/hello_world_soap_http", "SoapPort"));

        InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
        Document doc = StaxUtils.read(is);
        DOMSource erXML = new DOMSource(doc);
        EndpointReference endpointReference = EndpointReference.readFrom(erXML);

        WebServiceFeature[] wfs = new WebServiceFeature[] {};

        Greeter greeter = s.getPort(endpointReference, Greeter.class, wfs);

        String response = greeter.greetMe("John");

        assertEquals("Hello John", response);
    }
}
 
Example #13
Source Project: incubator-ratis   Author: apache   File: RaftProperties.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Write out the non-default properties in this configuration to the given
 * {@link Writer}.
 *
 * @param out the writer to write to.
 */
public void writeXml(Writer out) throws IOException {
  Document doc = asXmlDocument();

  try {
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();

    // Important to not hold Configuration log while writing result, since
    // 'out' may be an HDFS stream which needs to lock this configuration
    // from another thread.
    transformer.transform(source, result);
  } catch (TransformerException te) {
    throw new IOException(te);
  }
}
 
Example #14
Source Project: jdk8u60   Author: chenghanpeng   File: UnmarshallerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal0(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal0(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #15
Source Project: yangtools   Author: opendaylight   File: XmlParserStream.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
        final DOMSource source) {
    final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
    if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
        final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
        if (optName.isPresent()) {
            mount.setContainer(optName.get(), child);
            return;
        }

        LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
    } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
        mount.setSchemaMounts(child);
        return;
    }

    mount.addChild(child);
}
 
Example #16
Source Project: boost   Author: MicroShed   File: LibertyServerConfigGenerator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Write the server.xml and bootstrap.properties to the server config
 * directory
 *
 * @throws TransformerException
 * @throws IOException
 */
public void writeToServer() throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    // Replace auto-generated server.xml
    DOMSource server = new DOMSource(serverXml);
    StreamResult serverResult = new StreamResult(new File(serverPath + "/server.xml"));
    transformer.transform(server, serverResult);

    // Create configDropins/default path
    Path configDropins = Paths.get(serverPath + CONFIG_DROPINS_DIR);
    Files.createDirectories(configDropins);

    // Write variables.xml to configDropins
    DOMSource variables = new DOMSource(variablesXml);
    StreamResult variablesResult = new StreamResult(new File(serverPath + CONFIG_DROPINS_DIR + "/variables.xml"));
    transformer.transform(variables, variablesResult);

}
 
Example #17
Source Project: cxf   Author: apache   File: WadlGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private String copyDOMToString(Document wadlDoc) throws Exception {
    DOMSource domSource = new DOMSource(wadlDoc);
    // temporary workaround
    StringWriter stringWriter = new StringWriter();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
    try {
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
    } catch (IllegalArgumentException ex) {
        // ignore
    }

    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, new StreamResult(stringWriter));
    return stringWriter.toString();
}
 
Example #18
Source Project: velocity-tools   Author: apache   File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * XML Node to string
 * @param node XML node
 * @return XML node string representation
 */
public static String nodeToString(Node node)
{
    StringWriter sw = new StringWriter();
    try
    {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "no");
        /* CB - Since everything is already stored as strings in memory why shoud an encoding be required here? */
        t.setOutputProperty(OutputKeys.ENCODING, RuntimeConstants.ENCODING_DEFAULT);
        t.transform(new DOMSource(node), new StreamResult(sw));
    }
    catch (TransformerException te)
    {
        LOGGER.error("could not convert XML node to string", te);
    }
    return sw.toString();
}
 
Example #19
Source Project: netbeans   Author: apache   File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String asString(Node node, boolean formatted) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (formatted) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
        }
        if (!(node instanceof Document)) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // NOI18N
        }
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(node);
        transformer.transform(source, result);

        return result.getWriter().toString();
    } catch (TransformerException ex) {
        LOGGER.log(Level.INFO, null, ex);
    }
    return null;
}
 
Example #20
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractMarshaller.java    License: MIT License 6 votes vote down vote up
/**
 * Unmarshals the given provided {@code javax.xml.transform.Source} into an object graph.
 * <p>This implementation inspects the given result, and calls {@code unmarshalDomSource},
 * {@code unmarshalSaxSource}, or {@code unmarshalStreamSource}.
 * @param source the source to marshal from
 * @return the object graph
 * @throws IOException if an I/O Exception occurs
 * @throws XmlMappingException if the given source cannot be mapped to an object
 * @throws IllegalArgumentException if {@code source} is neither a {@code DOMSource},
 * a {@code SAXSource}, nor a {@code StreamSource}
 * @see #unmarshalDomSource(javax.xml.transform.dom.DOMSource)
 * @see #unmarshalSaxSource(javax.xml.transform.sax.SAXSource)
 * @see #unmarshalStreamSource(javax.xml.transform.stream.StreamSource)
 */
@Override
public final Object unmarshal(Source source) throws IOException, XmlMappingException {
	if (source instanceof DOMSource) {
		return unmarshalDomSource((DOMSource) source);
	}
	else if (StaxUtils.isStaxSource(source)) {
		return unmarshalStaxSource(source);
	}
	else if (source instanceof SAXSource) {
		return unmarshalSaxSource((SAXSource) source);
	}
	else if (source instanceof StreamSource) {
		return unmarshalStreamSource((StreamSource) source);
	}
	else {
		throw new IllegalArgumentException("Unknown Source type: " + source.getClass());
	}
}
 
Example #21
Source Project: xml-avro   Author: elodina   File: Converter.java    License: Apache License 2.0 5 votes vote down vote up
private static void saveDocument(Document doc, File file) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(doc), new StreamResult(file));
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source Project: xmlunit   Author: xmlunit   File: Convert.java    License: Apache License 2.0 5 votes vote down vote up
private static Node tryExtractNodeFromDOMSource(Source s) {
    if (s instanceof DOMSource) {
        @SuppressWarnings("unchecked") DOMSource ds = (DOMSource) s;
        return ds.getNode();
    }
    return null;
}
 
Example #23
Source Project: jmeter-plugins   Author: undera   File: XMLFormatPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private String serialize2(String unformattedXml) throws Exception {
    final Document document = XmlUtil.stringToXml(unformattedXml);
    TransformerFactory tfactory = TransformerFactory.newInstance();
    StringWriter buffer = new StringWriter();
    Transformer serializer = tfactory.newTransformer();
    // Setup indenting to "pretty print"
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    serializer.transform(new DOMSource(document), new StreamResult(buffer));

    return buffer.toString();
}
 
Example #24
Source Project: carbon-commons   Author: wso2   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
public static DOMSource getSigStream(AxisService service, ByteArrayOutputStream wsdlOutStream, Map paramMap)
        throws TransformerFactoryConfigurationError, TransformerException,
               ParserConfigurationException {
    Source wsdlSource = new StreamSource(new ByteArrayInputStream(wsdlOutStream.toByteArray()));
    InputStream sigStream =
            Util.class.getClassLoader().getResourceAsStream(WSDL2SIG_XSL_LOCATION);
    Source wsdl2sigXSLTSource = new StreamSource(sigStream);
    DocumentBuilder docB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document docSig = docB.newDocument();
    Result resultSig = new DOMResult(docSig);
    Util.transform(wsdlSource, wsdl2sigXSLTSource, resultSig, paramMap, new SchemaURIResolver(service));
    return new DOMSource(docSig);
}
 
Example #25
Source Project: constellation   Author: constellation-app   File: ProjectUpdater.java    License: Apache License 2.0 5 votes vote down vote up
private static void saveXMLFile(final Document document, final File xmlFile) throws IOException, TransformerException {
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        // Ant's build.xml can not use this
//        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); 
        final Transformer transformer = transformerFactory.newTransformer();

        try ( FileOutputStream out = new FileOutputStream(xmlFile)) {
            final Source saveSource = new DOMSource(document);
            final Result saveResult = new StreamResult(out);
            transformer.transform(saveSource, saveResult);
        }
    }
 
Example #26
Source Project: uima-uimaj   Author: apache   File: XMLSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public void serialize(Node node) {
  try {
    mTransformer.transform(new DOMSource(node), createSaxResultObject());
  } catch (TransformerException e) {
    throw new UIMARuntimeException(e);
  }
}
 
Example #27
Source Project: keycloak   Author: keycloak   File: SubsystemParsingAllowedClockSkewTestCase.java    License: Apache License 2.0 5 votes vote down vote up
private void setSubsystemXml(String value, String unit) throws IOException {
    try {
        String template = readResource("keycloak-saml-1.3.xml");
        if (value != null) {
            // assign the AllowedClockSkew element using DOM
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = db.parse(new InputSource(new StringReader(template)));
            // create the skew element
            Element allowedClockSkew = doc.createElement(Constants.XML.ALLOWED_CLOCK_SKEW);
            if (unit != null) {
                allowedClockSkew.setAttribute(Constants.XML.ALLOWED_CLOCK_SKEW_UNIT, unit);
            }
            allowedClockSkew.setTextContent(value);
            // locate the IDP and insert the node
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeList = (NodeList) xPath.compile("/subsystem/secure-deployment[1]/SP/IDP").evaluate(doc, XPathConstants.NODESET);
            nodeList.item(0).appendChild(allowedClockSkew);
            // transform again to XML
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            subsystemXml = writer.getBuffer().toString();
        } else {
            subsystemXml = template;
        }
    } catch (DOMException | ParserConfigurationException | SAXException | TransformerException | XPathExpressionException e) {
        throw new IOException(e);
    }
}
 
Example #28
Source Project: SEAL   Author: TeamCohen   File: XMLUtil.java    License: Apache License 2.0 5 votes vote down vote up
static public Document cloneDocument(Document document) {
  if (document == null) return null;
  Document result = newDocument();
  try {
    identityTransformer.transform(new DOMSource( document), new DOMResult( result));
  } catch (TransformerException e) {
    e.printStackTrace();
  }
  return result;
}
 
Example #29
Source Project: freehealth-connector   Author: taktik   File: CacheFeederHandler.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean handleOutbound(SOAPMessageContext context) {
   this.endpoint = (String)context.get("javax.xml.ws.service.endpoint.address");
   if (distributor.mustCache(this.endpoint)) {
      try {
         Node body = context.getMessage().getSOAPBody().cloneNode(true);
         this.request = new DOMSource(ConnectorXmlUtils.getFirstChildElement(body));
      } catch (SOAPException var3) {
         LOG.trace("Unable to determine endpoint and payload", var3);
      }
   }

   return true;
}
 
Example #30
Source Project: pipeline-maven-plugin   Author: jenkinsci   File: XmlUtils.java    License: MIT License 5 votes vote down vote up
@Nonnull
public static String toString(@Nullable Node node) {
    try {
        StringWriter out = new StringWriter();
        Transformer identityTransformer = TransformerFactory.newInstance().newTransformer();
        identityTransformer.transform(new DOMSource(node), new StreamResult(out));
        return out.toString();
    } catch (TransformerException e) {
        LOGGER.log(Level.WARNING, "Exception dumping node " + node, e);
        return e.toString();
    }
}