javax.xml.transform.Transformer Java Examples

The following examples show how to use javax.xml.transform.Transformer. 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: DomLoader.java    From html5index with Apache License 2.0 9 votes vote down vote up
public static Document loadDom(String url) {
 Parser parser = new Parser();

 try {
   parser.setFeature(Parser.namespacesFeature, false);
   parser.setFeature(Parser.namespacePrefixesFeature, false);
   Reader reader = openReader(url);
   DOMResult result = new DOMResult();
   Transformer transformer = TransformerFactory.newInstance().newTransformer();
   transformer.transform(new SAXSource(parser, new InputSource(reader)), result);
   reader.close();
   return (Document) result.getNode();
 } catch (Exception e) {
   throw new RuntimeException(e);
 }
}
 
Example #2
Source File: EDLControllerChain.java    From rice with Educational Community License v2.0 7 votes vote down vote up
private void transform(EDLContext edlContext, Document dom, HttpServletResponse response) throws Exception {
	if (StringUtils.isNotBlank(edlContext.getRedirectUrl())) {
		response.sendRedirect(edlContext.getRedirectUrl());
		return;
	}
    response.setContentType("text/html; charset=UTF-8");
	Transformer transformer = edlContext.getTransformer();

       transformer.setOutputProperty("indent", "yes");
       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
       String user = null;
       String loggedInUser = null;
       if (edlContext.getUserSession() != null) {
           Person wu = edlContext.getUserSession().getPerson();
           if (wu != null) user = wu.getPrincipalId();
           wu = edlContext.getUserSession().getPerson();
           if (wu != null) loggedInUser = wu.getPrincipalId();
       }
       transformer.setParameter("user", user);
       transformer.setParameter("loggedInUser", loggedInUser);
       if (LOG.isDebugEnabled()) {
       	LOG.debug("Transforming dom " + XmlJotter.jotNode(dom, true));
       }
       transformer.transform(new DOMSource(dom), new StreamResult(response.getOutputStream()));
}
 
Example #3
Source File: EPRHeader.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = XmlUtil.newDocumentBuilderFactory(false);
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example #4
Source File: ClusteredOsgiTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
public static void testXmlClusteredCache(OsgiTestUtils.Cluster cluster) throws Exception {
  File config = cluster.getWorkingArea().resolve("ehcache.xml").toFile();

  Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(TestMethods.class.getResourceAsStream("ehcache-clustered-osgi.xml"));
  XPath xpath = XPathFactory.newInstance().newXPath();
  Node clusterUriAttribute = (Node) xpath.evaluate("//config/service/cluster/connection/@url", doc, XPathConstants.NODE);
  clusterUriAttribute.setTextContent(cluster.getConnectionUri().toString() + "/cache-manager");
  Transformer xformer = TransformerFactory.newInstance().newTransformer();
  xformer.transform(new DOMSource(doc), new StreamResult(config));


  try (PersistentCacheManager cacheManager = (PersistentCacheManager) CacheManagerBuilder.newCacheManager(
    new XmlConfiguration(config.toURI().toURL(), TestMethods.class.getClassLoader())
  )) {
    cacheManager.init();

    final Cache<Long, Person> cache = cacheManager.getCache("clustered-cache", Long.class, Person.class);

    cache.put(1L, new Person("Brian"));
    assertThat(cache.get(1L).name, is("Brian"));
  }
}
 
Example #5
Source File: MessageProviderWithAddressingPolicy.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Source invoke(Source request) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    try {
        transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        /*
        tfactory.setAttribute("indent-number", "2");
         */
        Transformer serializer = transformerFactory.newTransformer();
        // Setup indenting to "pretty print"
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StringWriter swriter = new StringWriter();
        serializer.transform(request, new StreamResult(swriter));
        swriter.flush();
        LOG.info("Provider received a request\n" + swriter.toString());

    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #6
Source File: XmlSupport.java    From java-scanner-access-twain with 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 #7
Source File: SubsystemParsingTestCase.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void buildSubsystemXml(final Element element, final String expression) throws IOException {
    if (element != null) {
        try {
            // locate the element and insert the node
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(this.document, XPathConstants.NODESET);
            nodeList.item(0).appendChild(element);
            // 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(this.document), new StreamResult(writer));
            this.subsystemXml = writer.getBuffer().toString();
        } catch(TransformerException | XPathExpressionException e) {
            throw new IOException(e);
        }
    } else {
        this.subsystemXml = this.subsystemTemplate;
    }
}
 
Example #8
Source File: SmartTransformerFactoryImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Transformer object that from the input stylesheet
 * Uses the com.sun.org.apache.xalan.internal.processor.TransformerFactory.
 * @param source the stylesheet.
 * @return A Transformer object.
 */
public Transformer newTransformer(Source source) throws
    TransformerConfigurationException
{
    if (_xalanFactory == null) {
        createXalanTransformerFactory();
    }
    if (_errorlistener != null) {
        _xalanFactory.setErrorListener(_errorlistener);
    }
    if (_uriresolver != null) {
        _xalanFactory.setURIResolver(_uriresolver);
    }
    _currFactory = _xalanFactory;
    return _currFactory.newTransformer(source);
}
 
Example #9
Source File: WadlGenerator.java    From cxf with 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 #10
Source File: XmlUtilities.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Pretty print XML Node
 * @param node
 * @return
 * @throws XmlUtilitiesException
 */
public String xmlNodeToString( Node node ) throws XmlUtilitiesException {

    StringWriter sw = new StringWriter();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
        transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException te) {
        throw new XmlUtilitiesException("Error transforming XML node to String", te);
    }
    return sw.toString().trim();
}
 
Example #11
Source File: DependencyServiceImpl.java    From score with Apache License 2.0 6 votes vote down vote up
private void removeByXpathExpression(String pomFilePath, String expression) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException {
    File xmlFile = new File(pomFilePath);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nl = (NodeList) xpath.compile(expression).
            evaluate(doc, XPathConstants.NODESET);

    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            node.getParentNode().removeChild(node);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        // need to convert to file and then to path to override a problem with spaces
        Result output = new StreamResult(new File(pomFilePath).getPath());
        Source input = new DOMSource(doc);
        transformer.transform(input, output);
    }
}
 
Example #12
Source File: I18nXmlUtility.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Adds the specified element to the XML document and returns the document's contents as a String
 */
public static String addElementAndGetDocumentAsString(Document doc, Element el)
{
	doc.appendChild(el);

	try {
		TransformerFactory tranFactory = TransformerFactory.newInstance();
		Transformer aTransformer = tranFactory.newTransformer();
		Source src = new DOMSource(doc);
		StringWriter writer = new StringWriter();
		Result dest = new StreamResult(writer);
		aTransformer.transform(src, dest);
		String result = writer.getBuffer().toString();
		return result;
	}
	catch (Exception e) {
		throw new ContentReviewProviderException("Failed to transform the XML Document into a String");
	}
}
 
Example #13
Source File: XSLTFunctionsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @bug 8165116
 * Verifies that redirect works properly when extension function is enabled
 *
 * @param xml the XML source
 * @param xsl the stylesheet that redirect output to a file
 * @param output the output file
 * @param redirect the redirect file
 * @throws Exception if the test fails
 **/
@Test(dataProvider = "redirect")
public void testRedirect(String xml, String xsl, String output, String redirect) throws Exception {

    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
    Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));

    //Transform the xml
    tryRunWithTmpPermission(
            () -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
            new FilePermission(output, "write"), new FilePermission(redirect, "write"));

    // Verifies that the output is redirected successfully
    String userDir = getSystemProperty("user.dir");
    Path pathOutput = Paths.get(userDir, output);
    Path pathRedirect = Paths.get(userDir, redirect);
    Assert.assertTrue(Files.exists(pathOutput));
    Assert.assertTrue(Files.exists(pathRedirect));
    System.out.println("Output to " + pathOutput + " successful.");
    System.out.println("Redirect to " + pathRedirect + " successful.");
    Files.deleteIfExists(pathOutput);
    Files.deleteIfExists(pathRedirect);
}
 
Example #14
Source File: AbstractXsltFileUpgradeOperation.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
protected void executeTemplate(String site, String path, OutputStream os) throws UpgradeException {
    if(contentRepository.contentExists(site, path)) {
        try(InputStream templateIs = template.getInputStream()) {
            // Saxon is used to support XSLT 2.0
            Transformer transformer =
                TransformerFactory.newInstance(SAXON_CLASS, null)
                    .newTransformer(new StreamSource(templateIs));
            logger.info("Applying XSLT template {0} to file {1} for site {2}", template, path, site);
            try(InputStream sourceIs = contentRepository.getContent(site, path)) {
                transformer.setParameter(PARAM_KEY_SITE, site);
                transformer.setParameter(PARAM_KEY_VERSION, nextVersion);
                transformer.setURIResolver(getURIResolver(site));
                transformer.transform(new StreamSource(sourceIs), new StreamResult(os));
            }
        } catch (Exception e) {
            throw new UpgradeException("Error processing file", e);
        }
    } else {
        logger.warn("Source file {0} does not exist in site {1}", path, site);
    }
}
 
Example #15
Source File: HQMFProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
private String writeDocument(Document d) {
    try {
        DOMSource source = new DOMSource(d);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);

        transformer.transform(source, result);

        return writer.toString();
    }
    catch (Exception e) {
        return null;
    }
}
 
Example #16
Source File: VisualizeXML.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param xmlName
 *            the name of XML file
 * @param stylesheetName
 *            the name of style sheet
 * @param outputFile
 *            the name of log file
 * @return boolean
 * @see
 * @since 1.0
 */
public boolean toStyledDocument(final String xmlName,
		final String stylesheetName, final String outputFile) {
	TransformerFactory factory = TransformerFactory.newInstance();
	StreamSource xslStream = new StreamSource(stylesheetName);
	Transformer transformer;
	try {
		transformer = factory.newTransformer(xslStream);
		StreamSource in = new StreamSource(xmlName);
		StreamResult out = new StreamResult(outputFile);
		transformer.transform(in, out);
	} catch (TransformerException e) {
		logger.debug(MessageCatalog._00101_TRANSFORMATION_EXCEPTION);
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example #17
Source File: ApacheFopWorker.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/** Transform an xsl-fo StreamSource to the specified output format.
 * @param src The xsl-fo StreamSource instance
 * @param stylesheet Optional stylesheet StreamSource instance
 * @param fop
 */
public static void transform(StreamSource src, StreamSource stylesheet, Fop fop) throws FOPException {
    Result res = new SAXResult(fop.getDefaultHandler());
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        if (stylesheet == null) {
            transformer = factory.newTransformer();
        } else {
            transformer = factory.newTransformer(stylesheet);
        }
        transformer.setURIResolver(new LocalResolver(transformer.getURIResolver()));
        transformer.transform(src, res);
    } catch (Exception e) {
        throw new FOPException(e);
    }
}
 
Example #18
Source File: ReplaySearch.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Saves the search filters to the specified search filters file.
 * @param filtersFile filters file to save to
 */
private void saveSearchFiltersFile( final File filtersFile ) {
	try {
		final Document document    = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		final Element  rootElement = document.createElement( "filters" );
		rootElement.setAttribute( "version", "1.0" ); // To keep the possibility for future changes
		
		for ( final SearchFieldGroup searchFieldGroup : searchFieldGroups )
			searchFieldGroup.saveValues( document, rootElement );
		
		document.appendChild( rootElement );
		
		final Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
		transformer.transform( new DOMSource( document ), new StreamResult( filtersFile ) );
		
		GuiUtils.showInfoDialog( Language.getText( "module.repSearch.tab.filters.filtersSaved" ) );
	} catch ( final Exception e ) {
		e.printStackTrace();
		GuiUtils.showErrorDialog( Language.getText( "module.repSearch.tab.filters.failedToSaveFilters" ) );
	}
}
 
Example #19
Source File: STSHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Element convert(Source stsResponse) throws IntegrationModuleException {
   try {
      StringWriter stringWriter = new StringWriter();
      Result result = new StreamResult(stringWriter);
      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer();
      transformer.transform(stsResponse, result);
      String xmlResponse = stringWriter.getBuffer().toString();
      return SAML10Converter.toElement(xmlResponse);
   } catch (TransformerException var6) {
      throw new IntegrationModuleException(var6);
   }
}
 
Example #20
Source File: IbmMisc.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static String getJmsDestinations(String confResString)
		throws IOException, DomBuilderException, TransformerException, SAXException {
	URL url = ClassUtils.getResourceURL(IbmMisc.class, GETJMSDEST_XSLT);
	if (url == null) {
		throw new IOException(
				"cannot find resource [" + GETJMSDEST_XSLT + "]");
	}
	Transformer t = XmlUtils.createTransformer(url, 2);
	String jmsDestinations = XmlUtils.transformXml(t, confResString);
	if (LOG.isDebugEnabled()) {
		LOG.debug("jmsDestinations [" + chomp(jmsDestinations, 100, true)
				+ "]");
	}
	return jmsDestinations;
}
 
Example #21
Source File: ConfigXMLFileWriter.java    From ApprovalTests.Java with Apache License 2.0 5 votes vote down vote up
public static void writeToIndentedXMLFile(String configFile, Document domDocument) throws Exception
{
  DataOutputStream out = new DataOutputStream(new FileOutputStream(configFile));
  TransformerFactory tFactory = TransformerFactory.newInstance();
  Transformer transformer = tFactory.newTransformer();
  DOMSource source = new DOMSource(domDocument);
  StreamResult result = new StreamResult(out);
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
  transformer.transform(source, result);
  out.close();
}
 
Example #22
Source File: BootableJar.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void updateConfig(Path configFile, String name, boolean isExploded) throws Exception {
    FileInputStream fileInputStream = new FileInputStream(configFile.toFile());
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(fileInputStream);
    Element root = document.getDocumentElement();

    NodeList lst = root.getChildNodes();
    for (int i = 0; i < lst.getLength(); i++) {
        Node n = lst.item(i);
        if (n instanceof Element) {
            if (DEPLOYMENTS.equals(n.getNodeName())) {
                throw BootableJarLogger.ROOT_LOGGER.deploymentAlreadyExist();
            }
        }
    }
    Element deployments = document.createElement(DEPLOYMENTS);
    Element deployment = document.createElement(DEPLOYMENT);
    Element content = document.createElement(CONTENT);
    content.setAttribute(SHA1, DEP_1 + DEP_2);
    if (isExploded) {
        content.setAttribute(ARCHIVE, "false");
    }
    deployment.appendChild(content);
    deployment.setAttribute(NAME, name);
    deployment.setAttribute(RUNTIME_NAME, name);
    deployments.appendChild(deployment);

    root.appendChild(deployments);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StreamResult output = new StreamResult(configFile.toFile());
    DOMSource input = new DOMSource(document);

    transformer.transform(input, output);

}
 
Example #23
Source File: XMLUtil.java    From EasyML with Apache License 2.0 5 votes vote down vote up
/** Transform a XML Document to String */
public static String toString(Document doc) {
	try {
		DOMSource domSource = new DOMSource(doc);
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.transform(domSource, result);
		return writer.toString();
	} catch (Exception e) {
		e.printStackTrace();
		return "";
	}
}
 
Example #24
Source File: XmlUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Create a transformer from a stylesheet
 *
 * @param stylesheet Document
 *
 * @return the Transformer
 */
public static Transformer createTransformer(Document stylesheet)
{

  if(log.isDebugEnabled())
  {
    log.debug("createTransformer(Document " + stylesheet + ")");
  }

  Transformer transformer = null;
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  URIResolver resolver = new URIResolver();
  transformerFactory.setURIResolver(resolver);


  try
  {
    DOMSource source = new DOMSource(stylesheet);
    String systemId = "/xml/xsl/report";
    source.setSystemId(systemId);
    transformer = transformerFactory.newTransformer(source);
  }
  catch(TransformerConfigurationException e)
  {
    log.error(e.getMessage(), e);
  }

  return transformer;
}
 
Example #25
Source File: ApplyXslTransformationService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
public final Map<String, String> execute(final ApplyXslTransformationInputs applyXslTransformationInputs)
        throws Exception {
    final Templates template = getTemplate(applyXslTransformationInputs);
    final Transformer xmlTransformer = template.newTransformer();

    final Source source = getSourceStream(applyXslTransformationInputs);
    final Result result = getResultStream(applyXslTransformationInputs);

    xmlTransformer.transform(source, result);
    if (StringUtilities.isEmpty(applyXslTransformationInputs.getOutputFile())) {
        return OutputUtilities.getSuccessResultsMap(((StreamResult) result).getWriter().toString());
    }
    return OutputUtilities.getSuccessResultsMap("Result was written in the output file: " + applyXslTransformationInputs.getOutputFile());
}
 
Example #26
Source File: TFDv1.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes() throws Exception {
    JAXBSource in = new JAXBSource(CONTEXT, tfd);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Result out = new StreamResult(baos);
    TransformerFactory factory = tf;
    if (factory == null) {
        factory = TransformerFactory.newInstance();
    }
    Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
    transformer.transform(in, out);
    return baos.toByteArray();
}
 
Example #27
Source File: TransformerFactoryImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * javax.xml.transform.sax.TransformerFactory implementation.
 * Process the Source into a Templates object, which is a a compiled
 * representation of the source. Note that this method should not be
 * used with XSLTC, as the time-consuming compilation is done for each
 * and every transformation.
 *
 * @return A Templates object that can be used to create Transformers.
 * @throws TransformerConfigurationException
 */
@Override
public Transformer newTransformer(Source source) throws
    TransformerConfigurationException
{
    final Templates templates = newTemplates(source);
    final Transformer transformer = templates.newTransformer();
    if (_uriResolver != null) {
        transformer.setURIResolver(_uriResolver);
    }
    return(transformer);
}
 
Example #28
Source File: SOAPEncoder.java    From feign with 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 #29
Source File: JaxpIssue49.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
DOMSource toDOMSource(Source source) throws Exception {
    if (source instanceof DOMSource) {
        return (DOMSource) source;
    }
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    DOMResult result = new DOMResult();
    trans.transform(source, result);
    trans.transform(new DOMSource(result.getNode()), new StreamResult(System.out));
    return new DOMSource(result.getNode());
}
 
Example #30
Source File: XmlFullSignature.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
protected byte[] perform(byte[] input) throws Exception {
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     dbf.setNamespaceAware(true);
     Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(input));

     this.createSignature(doc);

     DOMSource source = new DOMSource(doc);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     StreamResult result = new StreamResult(bos);
     TransformerFactory transformerFactory = TransformerFactory.newInstance();
     Transformer transformer = transformerFactory.newTransformer();
     transformer.transform(source, result);
     return bos.toByteArray();
}