Java Code Examples for javax.xml.transform.TransformerFactoryConfigurationError

The following examples show how to use javax.xml.transform.TransformerFactoryConfigurationError. 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: tutorials   Source File: JaxpTransformer.java    License: MIT License 6 votes vote down vote up
public String modifyAttribute(String attribute, String oldValue, String newValue) throws XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
    // 2- Locate the node(s) with xpath
    XPath xpath = XPathFactory.newInstance()
        .newXPath();
    NodeList nodes = (NodeList) xpath.evaluate(String.format("//*[contains(@%s, '%s')]", attribute, oldValue), this.input, XPathConstants.NODESET);
    // 3- Make the change on the selected nodes
    for (int i = 0; i < nodes.getLength(); i++) {
        Element value = (Element) nodes.item(i);
        value.setAttribute(attribute, newValue);
    }
    // Stream api syntax
    // IntStream
    // .range(0, nodes.getLength())
    // .mapToObj(i -> (Element) nodes.item(i))
    // .forEach(value -> value.setAttribute(attribute, newValue));
    // 4- Save the result to a new XML doc
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Transformer xformer = factory.newTransformer();
    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    Writer output = new StringWriter();
    xformer.transform(new DOMSource(this.input), new StreamResult(output));
    return output.toString();
}
 
Example 2
Source Project: spring-analysis-note   Source File: XsltView.java    License: MIT License 6 votes vote down vote up
/**
 * Instantiate a new TransformerFactory for this view.
 * <p>The default implementation simply calls
 * {@link javax.xml.transform.TransformerFactory#newInstance()}.
 * If a {@link #setTransformerFactoryClass "transformerFactoryClass"}
 * has been specified explicitly, the default constructor of the
 * specified class will be called instead.
 * <p>Can be overridden in subclasses.
 * @param transformerFactoryClass the specified factory class (if any)
 * @return the new TransactionFactory instance
 * @see #setTransformerFactoryClass
 * @see #getTransformerFactory()
 */
protected TransformerFactory newTransformerFactory(
		@Nullable Class<? extends TransformerFactory> transformerFactoryClass) {

	if (transformerFactoryClass != null) {
		try {
			return ReflectionUtils.accessibleConstructor(transformerFactoryClass).newInstance();
		}
		catch (Exception ex) {
			throw new TransformerFactoryConfigurationError(ex, "Could not instantiate TransformerFactory");
		}
	}
	else {
		return TransformerFactory.newInstance();
	}
}
 
Example 3
public void saveToFile(final @Nonnull File file) {
  try {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    final Element element = document.createElement(MAINFILE_ELEMENT);
    document.appendChild(element);

    this.saveValueToXML(element);

    // Create transformer.
    final Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    // Write to file and transform.
    transformer.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));

  } catch (ParserConfigurationException | TransformerFactoryConfigurationError
      | FileNotFoundException | TransformerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}
 
Example 4
@Override
public void writeTo(StreamSource streamSource,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException {
    StreamResult streamResult = new StreamResult(entityStream);
    try {
        TransformerFactory factory = createFeaturedTransformerFactory();
        factory.newTransformer().transform(streamSource, streamResult);
    } catch (TransformerException | TransformerFactoryConfigurationError e) {
        throw new IOException(String.format("Can't write to output stream, %s", e));
    }
}
 
Example 5
Source Project: localization_nifi   Source File: EvaluateXQuery.java    License: Apache License 2.0 6 votes vote down vote up
void writeformattedItem(XdmItem item, ProcessContext context, OutputStream out)
        throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException {

    if (item.isAtomicValue()) {
        out.write(item.getStringValue().getBytes(UTF8));
    } else { // item is an XdmNode
        XdmNode node = (XdmNode) item;
        switch (node.getNodeKind()) {
            case DOCUMENT:
            case ELEMENT:
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                final Properties props = getTransformerProperties(context);
                transformer.setOutputProperties(props);
                transformer.transform(node.asSource(), new StreamResult(out));
                break;
            default:
                out.write(node.getStringValue().getBytes(UTF8));
        }
    }
}
 
Example 6
Source Project: nifi   Source File: EvaluateXQuery.java    License: Apache License 2.0 6 votes vote down vote up
void writeformattedItem(XdmItem item, ProcessContext context, OutputStream out)
        throws TransformerFactoryConfigurationError, TransformerException, IOException {

    if (item.isAtomicValue()) {
        out.write(item.getStringValue().getBytes(UTF8));
    } else { // item is an XdmNode
        XdmNode node = (XdmNode) item;
        switch (node.getNodeKind()) {
            case DOCUMENT:
            case ELEMENT:
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                final Properties props = getTransformerProperties(context);
                transformer.setOutputProperties(props);
                transformer.transform(node.asSource(), new StreamResult(out));
                break;
            default:
                out.write(node.getStringValue().getBytes(UTF8));
        }
    }
}
 
Example 7
Source Project: neoscada   Source File: XMLBase.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected void storeXmlDocument ( final Document doc, final File file ) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException
{
    // create output directory

    file.getParentFile ().mkdirs ();

    // write out xml

    final TransformerFactory transformerFactory = TransformerFactory.newInstance ();

    final Transformer transformer = transformerFactory.newTransformer ();
    transformer.setOutputProperty ( OutputKeys.INDENT, "yes" ); //$NON-NLS-1$

    final DOMSource source = new DOMSource ( doc );
    final StreamResult result = new StreamResult ( file );
    transformer.transform ( source, result );
}
 
Example 8
Source Project: tutorials   Source File: Dom4jProcessorUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, TransformerException, URISyntaxException, DocumentException, SAXException {
    String path = getClass().getResource("/xml/attribute.xml")
        .toString();
    Dom4jTransformer transformer = new Dom4jTransformer(path);
    String attribute = "customer";
    String oldValue = "true";
    String newValue = "false";
    String expectedXml = new String(Files.readAllBytes((Paths.get(getClass().getResource("/xml/attribute_expected.xml")
        .toURI()))));

    String result = transformer
      .modifyAttribute(attribute, oldValue, newValue)
      .replaceAll("(?m)^[ \t]*\r?\n", "");//Delete extra spaces added by Java 11

    assertThat(result).and(expectedXml)
        .areSimilar();
}
 
Example 9
Source Project: teiid-spring-boot   Source File: TeiidServer.java    License: Apache License 2.0 6 votes vote down vote up
private static String prettyFormat(String xml) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        StreamResult result = new StreamResult(new StringWriter());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        DOMSource source = new DOMSource(db.parse(is));
        transformer.transform(source, result);
        return result.getWriter().toString();
    } catch (IllegalArgumentException | TransformerFactoryConfigurationError | ParserConfigurationException
            | SAXException | IOException | TransformerException e) {
        return xml;
    }
}
 
Example 10
/**
 * Creates an instance of the currently specified JAXP {@link TransformerFactory}, ensuring
 * that the result supports the {@link DOMSource#FEATURE} and {@link DOMResult#FEATURE}
 * features.
 */
public static TransformerFactory createJAXPTransformerFactory() {
    TransformerFactory transformerFactory = null;
    try {
        transformerFactory = TransformerFactory.newInstance();
    }
    catch (TransformerFactoryConfigurationError e) {
        throw new SnuggleRuntimeException(e);
    }
    /* Make sure we have DOM-based features */
    requireFeature(transformerFactory, DOMSource.FEATURE);
    requireFeature(transformerFactory, DOMResult.FEATURE);
    
    /* Must have been OK! */
    return transformerFactory;
}
 
Example 11
@POST
@Path("/getKpiTemplate")
public String loadTemplate(@Context HttpServletRequest req)
		throws EMFUserError, EMFInternalError, JSONException, TransformerFactoryConfigurationError, TransformerException {
	ObjTemplate template;
	try {
		JSONObject request = RestUtilities.readBodyAsJSONObject(req);

		template = DAOFactory.getObjTemplateDAO().getBIObjectActiveTemplate(request.getInt("id"));
		if (template == null) {
			return new JSONObject().toString();
		}

	} catch (Exception e) {
		logger.error("Error converting JSON Template to XML...", e);
		throw new SpagoBIServiceException(this.request.getPathInfo(), "An unexpected error occured while executing service", e);

	}
	return new JSONObject(Xml.xml2json(new String(template.getContent()))).toString();

}
 
Example 12
Source Project: birt   Source File: SecurityUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Instantiate a new TransformerFactory.
 * 
 * @return
 * @throws Exception
 */
public static TransformerFactory newTransformerFactory( ) throws Exception
{
	return AccessController.doPrivileged( new PrivilegedExceptionAction<TransformerFactory>( ) {

		public TransformerFactory run( ) throws Exception
		{
			try
			{
				return TransformerFactory.newInstance( );
			}
			catch ( TransformerFactoryConfigurationError error )
			{
				throw error.getException( );
			}
		}
	} );
}
 
Example 13
Source Project: mycore   Source File: MCRIncludeHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void preloadFromURI(String uri, String sStatic)
    throws TransformerException, TransformerFactoryConfigurationError {
    if (uri.trim().isEmpty()) {
        return;
    }

    LOGGER.debug("preloading " + uri);

    Element xml;
    try {
        xml = resolve(uri.trim(), sStatic);
    } catch (Exception ex) {
        LOGGER.warn("Exception preloading " + uri, ex);
        return;
    }

    Map<String, Element> cache = chooseCacheLevel(uri, sStatic);
    handlePreloadedComponents(xml, cache);
}
 
Example 14
Source Project: cxf   Source File: JsXMLHttpRequest.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] domToUtf8(JsSimpleDomNode xml) {
    Node node = xml.getWrappedNode();
    // entire document.
    // if that's an issue, we could code something more complex.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(baos);
    DOMSource source = new DOMSource(node);
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        transformerFactory.newTransformer().transform(source, result);
    } catch (TransformerException | TransformerFactoryConfigurationError e) {
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}
 
Example 15
Source Project: mycore   Source File: MCRDerivateCommands.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param style
 * @return
 * @throws TransformerFactoryConfigurationError
 */
private static Transformer getTransformer(String style) throws TransformerFactoryConfigurationError {
    String xslfile = DEFAULT_TRANSFORMER;
    if (style != null && style.trim().length() != 0) {
        xslfile = style + "-derivate.xsl";
    }
    Transformer trans = null;

    try {
        URL xslURL = MCRDerivateCommands.class.getResource("/" + xslfile);

        if (xslURL != null) {
            StreamSource source = new StreamSource(xslURL.toURI().toASCIIString());
            TransformerFactory transfakt = TransformerFactory.newInstance();
            transfakt.setURIResolver(MCRURIResolver.instance());
            trans = transfakt.newTransformer(source);
        }
    } catch (Exception e) {
        LOGGER.debug("Cannot build Transformer.", e);
    }
    return trans;
}
 
Example 16
/**
 * Tests saving a configuration if an invalid transformer factory is
 * specified. In this case an error is thrown by the transformer factory.
 * XMLConfiguration should not catch this error.
 */
@Test
public void testSaveWithInvalidTransformerFactory() throws ConfigurationException {
    System.setProperty(PROP_FACTORY, "an.invalid.Class");
    try
    {
        saveTestConfig();
        fail("Could save with invalid TransformerFactory!");
    }
    catch (final TransformerFactoryConfigurationError cex)
    {
        // ok
    }
    finally
    {
        System.getProperties().remove(PROP_FACTORY);
    }
}
 
Example 17
Source Project: NLIWOD   Source File: StoreQALDXML.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void close() throws IOException, TransformerFactoryConfigurationError, TransformerException {
	Element root = doc.createElement("dataset");
	root.setAttribute("id", dataset);
	doc.appendChild(root);
	for (Element question : questions) {
		root.appendChild(question);
	}

	Transformer transformer = TransformerFactory.newInstance().newTransformer();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	DOMSource source = new DOMSource(doc);
	StreamResult file = new StreamResult(new File("answer_" + dataset + ".xml"));
	transformer.transform(source, file);

	System.out.println("\nXML DOM Created Successfully..");
}
 
Example 18
public static void simplifyPointsOfTextLines(String pageXmlIn, String pageXmlOut, boolean doIndent) throws XPathFactoryConfigurationException, ParserConfigurationException, MalformedURLException, IllegalArgumentException, SAXException, IOException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
		PageXmlFileProcessor fp = new PageXmlFileProcessor(pageXmlIn);
		Document doc = fp.getDocument();
		NodeList nl = fp.getTextLineCoordsPoints(doc);
		
		logger.debug("got "+nl.getLength()+" lines");
		for (int i=0; i<nl.getLength(); ++i) {
			Node n = nl.item(i);
//			Node pts = n.getAttributes().getNamedItem("points");
//			String oldPoints = pts.getNodeValue();
			String oldPoints = n.getNodeValue();
			logger.trace("old points = "+oldPoints);
			String simplified = simplifyPointsStr(oldPoints, RamerDouglasPeuckerFilter.DEFAULT_PERC_OF_POLYGON_LENGTH);
			logger.trace("simplified = "+simplified);
			n.setNodeValue(simplified);
		}
		
		if (!StringUtils.isEmpty(pageXmlOut)) {
			logger.debug("writing PAGE-XML to: "+pageXmlOut+", doIndent: "+doIndent);
			fp.writeToFile(doc, new File(pageXmlOut), doIndent);	
		}
	}
 
Example 19
Source Project: nifi   Source 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 20
Source Project: everrest   Source File: SAXSourceEntityProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void writeTo(SAXSource saxSource,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException {
    StreamResult streamResult = new StreamResult(entityStream);
    try {
        TransformerFactory factory = createFeaturedTransformerFactory();
        factory.newTransformer().transform(saxSource, streamResult);
    } catch (TransformerException | TransformerFactoryConfigurationError e) {
        throw new IOException(String.format("Can't write to output stream, %s", e));
    }
}
 
Example 21
Source Project: ph-commons   Source File: XMLTransformerFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public static TransformerFactory createTransformerFactory (@Nullable final ErrorListener aErrorListener,
                                                           @Nullable final URIResolver aURIResolver)
{
  try
  {
    final TransformerFactory aFactory = TransformerFactory.newInstance ();
    if (aErrorListener != null)
      aFactory.setErrorListener (aErrorListener);
    if (aURIResolver != null)
      aFactory.setURIResolver (aURIResolver);
    return aFactory;
  }
  catch (final TransformerFactoryConfigurationError ex)
  {
    throw new InitializationException ("Failed to create XML TransformerFactory", ex);
  }
}
 
Example 22
Source Project: OkapiBarcode   Source File: SvgRenderer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Cleans / sanitizes the specified string for inclusion in XML. A bit convoluted, but we're
 * trying to do it without adding an external dependency just for this...
 *
 * @param s the string to be cleaned / sanitized
 * @return the cleaned / sanitized string
 */
protected String clean(String s) {

    // remove control characters
    s = s.replaceAll("[\u0000-\u001f]", "");

    // escape XML characters
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Text text = document.createTextNode(s);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(text);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(source, result);
        return writer.toString();
    } catch (ParserConfigurationException | TransformerException | TransformerFactoryConfigurationError e) {
        return s;
    }
}
 
Example 23
Source Project: container   Source File: DocumentConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a given node to a String
 *
 * @return String - String representation of the given Node
 */
private static String getString(final Node node) {
    String result = null;
    if (node != null) {
        try {
            // prepare
            final Source source = new DOMSource(node);
            final StringWriter stringWriter = new StringWriter();
            final Result streamResult = new StreamResult(stringWriter);
            final TransformerFactory factory = TransformerFactory.newInstance();
            final Transformer transformer = factory.newTransformer();
            // serialize
            transformer.transform(source, streamResult);
            result = stringWriter.getBuffer().toString();
        } catch (final TransformerFactoryConfigurationError | TransformerException e) {
            e.printStackTrace();
        }
    }
    return result;
}
 
Example 24
private static String prettyFormatXML(String input) {
    int indent = 5;
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
        logger.log(Level.SEVERE, "Pretty print error", e);
        return input;
    }
}
 
Example 25
private static String prettyFormatXML(String input) {
    int indent = 5;
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (TransformerFactoryConfigurationError | IllegalArgumentException | TransformerException e) {
        logger.log(Level.SEVERE, "Pretty print error", e);
        return input;
    }
}
 
Example 26
public void saveToFile(final @Nonnull File file) {
  try {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    final Element element = document.createElement("DataPointProcessing");
    document.appendChild(element);

    // Serialize batch queue.
    this.saveToXML(element);

    // Create transformer.
    final Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    // Write to file and transform.
    transformer.transform(new DOMSource(document), new StreamResult(new FileOutputStream(file)));

    logger.finest("Saved " + this.size() + " processing step(s) to " + file.getName());

  } catch (ParserConfigurationException | TransformerFactoryConfigurationError
      | FileNotFoundException | TransformerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return;
  }

}
 
Example 27
Source Project: feign   Source File: SOAPEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void encode(Object object, Type bodyType, RequestTemplate template) {
  if (!(bodyType instanceof Class)) {
    throw new UnsupportedOperationException(
        "SOAP only supports encoding raw types. Found " + bodyType);
  }
  try {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Marshaller marshaller = jaxbContextFactory.createMarshaller((Class<?>) bodyType);
    marshaller.marshal(object, document);
    SOAPMessage soapMessage = MessageFactory.newInstance(soapProtocol).createMessage();
    soapMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION,
        Boolean.toString(writeXmlDeclaration));
    soapMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, charsetEncoding.displayName());
    soapMessage.getSOAPBody().addDocument(document);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    if (formattedOutput) {
      Transformer t = TransformerFactory.newInstance().newTransformer();
      t.setOutputProperty(OutputKeys.INDENT, "yes");
      t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
      t.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(bos));
    } else {
      soapMessage.writeTo(bos);
    }
    template.body(new String(bos.toByteArray()));
  } catch (SOAPException | JAXBException | ParserConfigurationException | IOException
      | TransformerFactoryConfigurationError | TransformerException e) {
    throw new EncodeException(e.toString(), e);
  }
}
 
Example 28
Source Project: quarkus   Source File: PomTransformerTest.java    License: Apache License 2.0 5 votes vote down vote up
static void assertFormat(String xml, String expectedIndent, String expectedEol)
        throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new StringReader(xml)), result);
    final Node document = result.getNode();
    Assertions.assertEquals(expectedIndent, PomTransformer.detectIndentation(document, xPath));
    Assertions.assertEquals(expectedEol, PomTransformer.detectEol(xml));
}
 
Example 29
Source Project: netbeans   Source File: XMLUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void write(Element el, OutputStream out) throws IOException {
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer(
                new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source source = new DOMSource(el);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception | TransformerFactoryConfigurationError e) {
        throw new IOException(e);
    }
}
 
Example 30
Source Project: syndesis   Source File: RequestPayloadConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
void convertAsXml(final Message in) {
    final String body = bodyAsString(in);
    if (body == null) {
        return;
    }

    try {
        final XMLStreamReader bodyReader = XML_INPUT_FACTORY.createXMLStreamReader(new StringReader(body));

        final XMLStreamReader eventReader = XML_INPUT_FACTORY.createFilteredReader(bodyReader, new XmlPayloadProcessor(in.getHeaders()));

        final Source source = new StAXSource(eventReader);
        final ByteArrayOutputStream out = new ByteArrayOutputStream(body.length());
        final Result result = new StreamResult(out);

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(source, result);

        in.setBody(new String(out.toByteArray(), StandardCharsets.UTF_8));
    } catch (XMLStreamException | TransformerFactoryConfigurationError | TransformerException e) {
        LOG.warn("Unable to parse payload, continuing without conversion", e);

        return;
    }

}