List of usage examples for javax.xml.transform TransformerException TransformerException
public TransformerException(String message, SourceLocator locator)
From source file:Main.java
/** * Convert the document to an array of bytes. * * @param doc The XML document./*www .j a v a 2 s . co m*/ * @param encoding The encoding of the output data. * * @return The XML document as an array of bytes. * * @throws TransformerException If there is an error transforming to text. */ public static byte[] asByteArray(Document doc, String encoding) throws TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); DOMSource source = new DOMSource(doc); transformer.transform(source, result); try { return writer.getBuffer().toString().getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new TransformerException("Unsupported Encoding", e); } }
From source file:IOUtils.java
public static ContentHandler getSerializer(File file) throws IOException, TransformerException { final FileWriter writer = new FileWriter(file); final TransformerHandler transformerHandler = FACTORY.newTransformerHandler(); final Transformer transformer = transformerHandler.getTransformer(); final Properties format = new Properties(); format.put(OutputKeys.METHOD, "xml"); format.put(OutputKeys.OMIT_XML_DECLARATION, "no"); format.put(OutputKeys.ENCODING, "UTF-8"); format.put(OutputKeys.INDENT, "yes"); transformer.setOutputProperties(format); transformerHandler.setResult(new StreamResult(writer)); try {//from w w w .ja va2s. com if (needsNamespacesAsAttributes(format)) { return new NamespaceAsAttributes(transformerHandler); } } catch (SAXException se) { throw new TransformerException("Unable to detect of namespace support for sax works properly.", se); } return transformerHandler; }
From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java
@PostConstruct protected void init() { transformerFactory.setURIResolver(new URIResolver() { @Override//from w w w .ja va 2 s . c o m public Source resolve(String href, String base) throws TransformerException { try { return new StreamSource(new ClassPathResource("transform/" + href).getInputStream()); } catch (IOException e) { throw new TransformerException("Failed to resolve uri: " + href, e); } } }); }
From source file:dk.defxws.fedoragsearch.server.URIResolverImpl.java
public Source resolve(String href, String base) throws TransformerException { Source source = null;/*from w ww . ja v a 2 s . com*/ URL url; try { url = new URL(href); } catch (MalformedURLException e) { // the XSLT processor should try to resolve the URI itself, // here it may be a location path, which it can resolve if (logger.isDebugEnabled()) logger.debug("resolve back to XSLT processor MalformedURLException href=" + href + " base=" + base + " exception=" + e); return null; } String reposName = config.getRepositoryNameFromUrl(url); if (reposName == null || reposName.length() == 0) { // here other resolve mechanism may be coded, or // the XSLT processor should try to resolve the URI itself, // e.g. it can resolve the file protocol if (logger.isDebugEnabled()) logger.debug("resolve back to XSLT processor no reposName href=" + href + " base=" + base + " url=" + url.toString()); return null; } if (logger.isDebugEnabled()) logger.debug("resolve get from repository href=" + href + " base=" + base + " url=" + url.toString() + " reposName=" + reposName); System.setProperty("javax.net.ssl.trustStore", config.getTrustStorePath(reposName)); System.setProperty("javax.net.ssl.trustStorePassword", config.getTrustStorePass(reposName)); WebClient client = new WebClient(); try { if (logger.isDebugEnabled()) logger.debug("resolve get from reposName=" + reposName + " source=\n" + client.getResponseAsString(href, false, new UsernamePasswordCredentials( config.getFedoraUser(reposName), config.getFedoraPass(reposName)))); source = new StreamSource( client.get(href, false, config.getFedoraUser(reposName), config.getFedoraPass(reposName))); } catch (Exception e) { throw new TransformerException( "resolve get from reposName=" + reposName + " href=" + href + " base=" + base + " exception=\n", e); } return source; }
From source file:ddf.util.XSLTUtil.java
/** * Performs an xsl transformation against an XML document * * @param template/* w w w.ja v a 2 s . c o m*/ * The compiled XSL template to be run * @param xmlDoc * xml document to be transformed * @param xslProperties * default classification * @return the transformed document. * @throws TransformerException */ public static Document transform(Templates template, Document xmlDoc, Map<String, Object> parameters) throws TransformerException { ByteArrayOutputStream baos; ByteArrayInputStream bais = null; Document resultDoc; try { Transformer transformer = template.newTransformer(); DBF.setNamespaceAware(true); DocumentBuilder builder = DBF.newDocumentBuilder(); StreamResult resultOutput = null; Source source = new DOMSource(xmlDoc); baos = new ByteArrayOutputStream(); try { resultOutput = new StreamResult(baos); if (parameters != null && !parameters.isEmpty()) { for (Map.Entry<String, Object> entry : parameters.entrySet()) { LOGGER.debug("Adding parameter key: {} value: {}", entry.getKey(), entry.getValue()); String key = entry.getKey(); Object value = entry.getValue(); if (key != null && !key.isEmpty() && value != null) { transformer.setParameter(key, value); } else { LOGGER.debug("Null or empty value for parameter: {}", entry.getKey()); } } } else { LOGGER.warn("All properties were null. Using \"last-resort\" defaults: U, USA, MTS"); } transformer.transform(source, resultOutput); bais = new ByteArrayInputStream(baos.toByteArray()); resultDoc = builder.parse(bais); } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(baos); } return resultDoc; } catch (TransformerException e) { LOGGER.warn(e.getMessage(), e); throw e; } catch (Exception e) { LOGGER.warn(e.getMessage(), e); throw new TransformerException("Error while transforming document: " + e.getMessage(), e); } }
From source file:org.obm.sync.push.client.XMLOPClient.java
private ByteArrayEntity getRequestEntity(Document doc) throws UnsupportedEncodingException, TransformerException { try {//from w ww.j a va 2s. c o m String xmlData = DOMUtils.serialize(doc); return new ByteArrayEntity(xmlData.getBytes("UTF8"), ContentType.TEXT_XML); } catch (TransformerException e) { throw new TransformerException("Cannot serialize data to xml", e); } }
From source file:de.mpg.mpdl.inge.transformation.transformations.LocalUriResolver.java
/** * {@inheritDoc}/*from w ww. j av a 2 s .c o m*/ */ public final Source resolve(String href, String altBase) throws TransformerException { String path = null; if (altBase == null) { altBase = ""; } try { if ("ves-mapping.xml".equals(href) || "vocabulary-mappings.xsl".equals(href)) { path = TRANS_PATH + href; } else if (href != null && href.matches("^https?://.*")) { HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(href); ProxyHelper.executeMethod(client, getMethod); return new StreamSource(getMethod.getResponseBodyAsStream()); } else { path = this.base + altBase + "/" + href; } return new StreamSource( ResourceUtil.getResourceAsStream(path, LocalUriResolver.class.getClassLoader())); } catch (FileNotFoundException e) { // throw new TransformerException("Cannot resolve URI: " + href); throw new TransformerException("Cannot resolve URI: " + path, e); } catch (HttpException e) { throw new TransformerException("Cannot connect to URI: " + path, e); } catch (IOException e) { throw new TransformerException("Cannot get content from URI: " + path, e); } }
From source file:de.mpg.escidoc.services.transformation.transformations.LocalUriResolver.java
/** * {@inheritDoc}/* w w w .j a va2 s .c o m*/ */ public final Source resolve(String href, String altBase) throws TransformerException { String path = null; if (altBase == null) { altBase = ""; } try { if ("ves-mapping.xml".equals(href) || "vocabulary-mappings.xsl".equals(href)) { path = TRANS_PATH + href; } else if (href != null && href.matches("^https?://.*")) { HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(href); ProxyHelper.executeMethod(client, getMethod); return new StreamSource(getMethod.getResponseBodyAsStream()); } else { path = this.base + altBase + "/" + href; } return new StreamSource( ResourceUtil.getResourceAsStream(path, LocalUriResolver.class.getClassLoader())); } catch (FileNotFoundException e) { //throw new TransformerException("Cannot resolve URI: " + href); throw new TransformerException("Cannot resolve URI: " + path, e); } catch (HttpException e) { throw new TransformerException("Cannot connect to URI: " + path, e); } catch (IOException e) { throw new TransformerException("Cannot get content from URI: " + path, e); } }
From source file:dk.statsbiblioteket.util.xml.XSLT.java
/** * Creates a new transformer based on the given XSLTLocation. * Useful for e.g. using Saxon instead of the default Xalan. * * @param factory the factory to use for creating the transformer. * @param xslt the location of the XSLT. * @return a Transformer based on the given XSLT. * @throws javax.xml.transform.TransformerException thrown if for some * reason a Transformer could not be instantiated. * This is normally due to problems with the {@code xslt} URL * @see #getLocalTransformer for reusing Transformers. *//*w w w .j a va 2s . c o m*/ public static Transformer createTransformer(TransformerFactory factory, URL xslt) throws TransformerException { log.trace("createTransformer: Requesting and compiling XSLT from '" + xslt + "'"); final long startTime = System.nanoTime(); InputStream in = null; Transformer transformer; try { if (xslt == null) { throw new NullPointerException("xslt URL is null"); } in = xslt.openStream(); transformer = factory.newTransformer(new StreamSource(in, xslt.toString())); transformer.setErrorListener(getErrorListener()); } catch (TransformerException e) { throw new TransformerException(String.format( "Unable to instantiate Transformer, a system configuration error for XSLT at '%s'", xslt), e); } catch (MalformedURLException e) { throw new TransformerException(String.format("The URL to the XSLT is not a valid URL: '%s'", xslt), e); } catch (IOException e) { throw new TransformerException( String.format("Unable to open the XSLT resource due to IOException '%s'", xslt), e); } catch (Exception e) { throw new TransformerException(String.format("Unable to open the XSLT resource '%s'", xslt), e); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { log.warn("Non-fatal IOException while closing stream to '" + xslt + "'"); } } log.debug("createTransformer: Requested and compiled XSLT from '" + xslt + "' in " + (System.nanoTime() - startTime) / 1000000 + "ms"); return transformer; }
From source file:edu.unc.lib.dl.schematron.SchematronValidator.java
/** * Use this to initialize the configured schemas. Generate stylesheet * implementations of ISO Schematron files and preload them into Transformer * Templates for quick use./*from w w w.j av a2 s . c o m*/ */ public void loadSchemas() { templates = new HashMap<String, Templates>(); // Load up a transformer and the ISO Schematron to XSL templates. Templates isoSVRLTemplates = null; ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl", SchematronValidator.class); Source svrlrc; try { svrlrc = new StreamSource(svrlRes.getInputStream()); } catch (IOException e1) { throw new Error("Cannot load iso_svrl.xsl", e1); } TransformerFactory factory = null; try { factory = new TransformerFactoryImpl(); // enable relative classpath-based URIs factory.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class); Source result; try { result = new StreamSource(svrlRes.getInputStream()); } catch (IOException e1) { throw new TransformerException("Cannot resolve " + href, e1); } return result; } }); isoSVRLTemplates = factory.newTemplates(svrlrc); } catch (TransformerFactoryConfigurationError e) { log.error("Error setting up transformer factory.", e); throw new Error("Error setting up transformer factory", e); } catch (TransformerConfigurationException e) { log.error("Error setting up transformer.", e); throw new Error("Error setting up transformer", e); } // Get a transformer Transformer t = null; try { t = isoSVRLTemplates.newTransformer(); } catch (TransformerConfigurationException e) { throw new Error("There was a problem configuring the transformer.", e); } for (String schema : schemas.keySet()) { // make XSLT out of Schematron for each schema Resource resource = schemas.get(schema); Source schematron = null; try { schematron = new StreamSource(resource.getInputStream()); } catch (IOException e) { throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription() + resource.toString()); } JDOMResult res = new JDOMResult(); try { t.transform(schematron, res); } catch (TransformerException e) { throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e); } // compile templates object for each profile try { Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument())); templates.put(schema, schemaTemplates); } catch (TransformerConfigurationException e) { throw new Error("There was a problem configuring the transformer.", e); } } }