List of usage examples for javax.xml.transform Transformer reset
public void reset()
Reset this Transformer
to its original configuration.
Transformer
is reset to the same state as when it was created with TransformerFactory#newTransformer() , TransformerFactory#newTransformer(Source source) or Templates#newTransformer() .
From source file:Main.java
public static String format(Document document) throws TransformerException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Transformer transformer = TRANSFORMER.get(); transformer.transform(new DOMSource(document), new StreamResult(out)); transformer.reset(); return new String(out.toByteArray(), StandardCharsets.UTF_8); }
From source file:Main.java
public static void transform(Source xmlSource, Result outputTarget) throws TransformerException { Transformer t = transformer(); try {//from w ww . java2 s. c o m t.transform(xmlSource, outputTarget); } finally { t.reset(); } }
From source file:Main.java
public static void transform(Source xsltSource, Source xmlSource, Result outputTarget) throws TransformerException { Transformer t = transformer(xsltSource); try {/*from w w w .jav a2 s. co m*/ t.transform(xmlSource, outputTarget); } finally { t.reset(); } }
From source file:Main.java
private static boolean updateXML(Document document, String path) throws TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // out put encoding. transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DocumentType type = document.getDoctype(); if (type != null) { System.out.println("doctype -->" + type.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, type.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, type.getSystemId()); }/*from ww w .j av a 2 s . c o m*/ DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(path)); transformer.transform(source, result); transformer.reset(); return true; }
From source file:com.honnix.jaxo.core.internal.pool.TransformerObjectFactory.java
@Override public void passivateObject(Transformer transformer) throws Exception { transformer.reset(); }
From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java
protected void processTempFile(final File df, final String fileEncoding, final String xmlVersion, final String header, final String footer, final TDocument persistenceConfig, final Pair collectivite, final Pair codeBudget, final File originalFile, final int docCount, final boolean shouldDelete, final int progress) { try {/*from w w w .jav a 2s . c o m*/ long startFile = System.currentTimeMillis(); String data = FileUtils.readTextFile(df, fileEncoding); StringBuilder fullText = new StringBuilder(); fullText.append("<?xml version=\"").append(xmlVersion).append("\" encoding=\"").append(fileEncoding) .append("\"?>"); fullText.append(header).append(data).append(footer); String sFullText = fullText.toString(); byte[] bData = sFullText.getBytes(fileEncoding); Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(bData)); // il faut retrouver de quel etat est ce document // on cherche si la balise root contient un // dm.getEtatxxx().getBalise() EtatModel currentEtat = null; for (EtatModel em : dm.getEtats()) { String balise = em.getBalise(); NodeList nl = doc.getElementsByTagName(balise); if (nl.getLength() > 0) { currentEtat = em; break; } else { nl = doc.getElementsByTagNameNS(em.getBaliseNamespace(), balise); if (nl.getLength() > 0) { currentEtat = em; break; } } } // traitement d'erreur, on n'arrive pas identifier l'etat if (currentEtat == null) { StringWriter sw = new StringWriter(); sw.append("Impossible de dterminer l'tat de ce document :\n"); TransformerFactory errorTransFactory = FactoryProvider.getTransformerFactory(); Transformer errorTransformer = errorTransFactory.newTransformer(); errorTransformer.transform(new DOMSource(doc), new StreamResult(sw)); sw.flush(); sw.close(); logger.error(sw.getBuffer().toString()); return; } // apply before-import xslt if (persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile() != null) { Transformer trans = importXsltCache .get(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile()); if (trans == null) { TransformerFactory tf = FactoryProvider.getTransformerFactory(); File directory = new File(currentEtat.getParent().getBaseDirectory()); File xslFile = new File(directory, persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile()); trans = tf.newTransformer(new StreamSource(xslFile)); importXsltCache.put(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile(), trans); } // important, maintenant que c'est mis en cache ! trans.reset(); if (codeBudget != null) { trans.setParameter("CodeBudget", codeBudget.key); trans.setParameter("LibelleBudget", codeBudget.libelle); } if (collectivite != null) { trans.setParameter("CodeCollectivite", collectivite.key); trans.setParameter("LibelleCollectivite", collectivite.libelle); } if (getManifeste() != null) { trans.setParameter("manifeste", new DOMSource(getManifeste())); } // on passe en parametre le nom du fichier trans.setParameter("file.name", originalFile.getName()); trans.setOutputProperty(OutputKeys.ENCODING, fileEncoding); ByteArrayOutputStream baos = new ByteArrayOutputStream(); trans.transform(new StreamSource(new ByteArrayInputStream(sFullText.getBytes(fileEncoding))), new StreamResult(baos)); bData = baos.toByteArray(); } importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm()) .append(";XSL;").append(Long.toString(startFile)).append(";") .append(Long.toString(startFile = System.currentTimeMillis())); importTimingOS.println(); String docName = StringUtilities.removeFileNameSuffix(originalFile.getName()) + "-" + docCount + "." + dm.getExtension(); if (!isCancelled()) { try { if (!DataLayerManager.getImplementation().importElement(dm, currentEtat, codeBudget, collectivite, originalFile.getName(), docName, bData, fileEncoding, getArchiveName(), user)) { logger.warn(DataLayerManager.getImplementation().getWarnings()); warningCount++; } } catch (DataAccessException daEx) { logger.error("importing element:", daEx); throw (Exception) daEx; } catch (DataConfigurationException dcEx) { logger.error("importing element:", dcEx); throw (Exception) dcEx.getCause(); } } if (shouldDelete) { df.delete(); } importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm()) .append(";IDX;").append(Long.toString(startFile)).append(";") .append(Long.toString(startFile = System.currentTimeMillis())); importTimingOS.println(); this.getImpSvcProvider().pushCurrentProgress(progress); } catch (Exception ex) { //TODO } }
From source file:ORG.oclc.os.SRW.SRUServerTester.java
public String sruRead(String initialURL) { out('\n');//w w w .j a va 2s .c o m out(" trying: "); out(initialURL); out('\n'); numTests++; URL url; try { url = new URL(initialURL); } catch (java.net.MalformedURLException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } HttpURLConnection huc; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentType = huc.getContentType(); if (contentType == null || (!contentType.contains("text/xml") && !contentType.contains("application/xml"))) { out(" ** Warning: Content-Type not set to text/xml or application/xml"); out('\n'); out(" Content-type: "); out(contentType); out('\n'); numWarns++; } InputStream urlStream; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: opening URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine; StringBuilder content = new StringBuilder(); Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading first line of response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine == null) { out("</pre><pre class='red'>"); out("test failed: No input read from URL"); out('\n'); out("</pre><pre>"); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { // normally, you'd expect to read the next line of input here // but some servers don't put a newline after the initial <?xml ?> int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); // I ran into a server that put an empty line before the stylesheet reference while (inputLine.length() == 0) inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine.startsWith("<?xml-stylesheet ")) { href = (inputLine.substring(inputLine.indexOf("href=") + 6)); href = href.substring(0, href.indexOf('"')); transformer = transformers.get(href); if (stylesheets.get(href) == null) try { // never seen this stylesheet before out(" reading stylesheet: "); out(href); out('\n'); out(" from source: "); out(url.toString()); out('\n'); StreamSource source = new StreamSource(url.toString()); TransformerFactory tFactory = TransformerFactory.newInstance(); Source stylesht = tFactory.getAssociatedStylesheet(source, null, null, null); transformer = tFactory.newTransformer(stylesht); transformers.put(href, transformer); } catch (TransformerConfigurationException e) { log.error(e, e); out("</pre><pre class='red'>"); out("unable to load stylesheet: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); } stylesheets.put(href, href); } else content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } // if(!xml) { // out("test failed: response was not an XML record");out('\n'); // out(content.toString());out('\n'); // return null; // } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); out(" successfully applied stylesheet '"); out(href); out("'"); out('\n'); } catch (javax.xml.transform.TransformerException e) { out("</pre><pre class='red'>"); out("unable to apply stylesheet '"); out(href); out("'to response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); log.error(e, e); transformer.reset(); } transformer.reset(); } return contentStr; }