/** * Saves the xml, contained by the specified input with the custom indentation. * If the input is the result of jaxb marshalling, make sure to set * Marshaller.JAXB_FORMATTED_OUTPUT to false in order for this method to work * properly. * * @param input * @param fos * @param indentation */ public static void saveWithCustomIndetation(ByteArrayInputStream input, FileOutputStream fos, int indentation) { try { Transformer transformer = SAXTransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentation)); Source xmlSource = new SAXSource(new org.xml.sax.InputSource(input)); StreamResult res = new StreamResult(fos); transformer.transform(xmlSource, res); fos.flush(); fos.close(); } catch (TransformerFactoryConfigurationError | TransformerException | IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } }
public static void write(Document doc, OutputStream out) throws IOException { // XXX note that this may fail to write out namespaces correctly if the document // is created with namespaces and no explicit prefixes; however no code in // this package is likely to be doing so try { Transformer t = TransformerFactory.newInstance().newTransformer( new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); DocumentType dt = doc.getDoctype(); if (dt != null) { String pub = dt.getPublicId(); if (pub != null) { t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub); } t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId()); } t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N Source source = new DOMSource(doc); Result result = new StreamResult(out); t.transform(source, result); } catch (Exception | TransformerFactoryConfigurationError e) { throw new IOException(e); } }
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 ); }
private static void generateConverterDoc(ModelContext ctx, ConverterModel converter) throws TransformerFactoryConfigurationError, IOException { String bundleName = converter.getBundleName(); int dot = bundleName.lastIndexOf('.'); String packageName = bundleName.substring(0, dot); String fileName = bundleName.substring(dot + 1) + ".xml"; FileObject fo; try { fo = ctx.getFiler().getResource(StandardLocation.SOURCE_PATH, packageName, fileName); } catch (IOException ioe) { fo = ctx.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, packageName, fileName); ctx.note("generating " + fo.getName()); PrintWriter out = new PrintWriter(fo.openOutputStream()); XMLUtils.writeDOMToFile(converter.generateDoc(), null, out); out.close(); } }
private void generateDocuments(Logger logger, EvaluationContext evalCtx, Corpus corpus, Set<String> classes, Document docList) throws XPathExpressionException, IOException, SAXException, TransformerFactoryConfigurationError { logger.info("generating HTML documents"); Element docListUL = XMLUtils.evaluateElement(XPATH_DOCUMENT_LIST, docList); Document docSkel = createDocumentSkeleton(); Iterator<fr.inra.maiage.bibliome.alvisnlp.core.corpus.Document> docIt = documentIterator(evalCtx, corpus); fr.inra.maiage.bibliome.alvisnlp.core.corpus.Document prev = null; fr.inra.maiage.bibliome.alvisnlp.core.corpus.Document next = docIt.hasNext() ? docIt.next() : null; while (next != null) { fr.inra.maiage.bibliome.alvisnlp.core.corpus.Document doc = next; addDocumentListItem(docList, docListUL, doc); next = docIt.hasNext() ? docIt.next() : null; Document xmlDoc = createDocument(docSkel, doc, prev, next); HTMLBuilderFragmentTagIterator frit = new HTMLBuilderFragmentTagIterator(this, classes); for (Section sec : Iterators.loop(sectionIterator(evalCtx, doc))) { createSection(xmlDoc, sec, frit); } writeXHTMLDocument(xmlDoc, doc.getId()); prev = doc; } }
protected void backupWsdlTypes(Element element) throws TransformerFactoryConfigurationError, Exception { if (wsdlType.equals("")) return; StringEx sx = new StringEx(wsdlType); sx.replaceAll("<cdata>","<![CDATA["); sx.replaceAll("</cdata>","]]>"); String sDom = "<"+fake_root+">\n" + sx.toString() + "</"+fake_root+">"; DocumentBuilder documentBuilder = XMLUtils.getDefaultDocumentBuilder(); Document document = documentBuilder.parse(new InputSource(new StringReader(sDom))); String wsdlBackupDir = getWsdlBackupDir(element); File dir = new File(wsdlBackupDir); if (!dir.exists()) dir.mkdirs(); File file = new File(wsdlBackupDir + "/" + getName() + ".xml"); XMLUtils.saveXml(document, file); }
protected void backupWsdlTypes(Element element) throws TransformerFactoryConfigurationError, Exception { if (wsdlType.equals("")) return; StringEx sx = new StringEx(wsdlType); sx.replaceAll("<cdata>","<![CDATA["); sx.replaceAll("</cdata>","]]>"); sx.replaceAll("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>", ""); String sDom = sx.toString(); DocumentBuilder documentBuilder = XMLUtils.getDefaultDocumentBuilder(); Document document = documentBuilder.parse(new InputSource(new StringReader(sDom))); String wsdlBackupDir = getWsdlBackupDir(element); File dir = new File(wsdlBackupDir); if (!dir.exists()) dir.mkdirs(); File file = new File(wsdlBackupDir + "/step-" + priority + ".xml"); XMLUtils.saveXml(document, file); }
/** * Used supplied XML {@link Document} to extract the XML for the defined {@link XmlEntity}. * * @param document to extract XML from. * @return XML for {@link XmlEntity} if found, otherwise <code>null</code>. * @throws XPathExpressionException * @throws TransformerException * @throws TransformerFactoryConfigurationError * @since GemFire 8.1 */ private final String loadXmlDefinition(final Document document) throws XPathExpressionException, TransformerFactoryConfigurationError, TransformerException { final Cache cache = CacheFactory.getAnyInstance(); this.searchString = createQueryString(prefix, type, attributes); logger.info("XmlEntity:searchString: {}", this.searchString); if (document != null) { XPathContext xpathContext = new XPathContext(); xpathContext.addNamespace(prefix, namespace); // Create an XPathContext here Node element = XmlUtils.querySingleElement(document, this.searchString, xpathContext); // Must copy to preserve namespaces. if (null != element) { return XmlUtils.elementToString(element); } } logger.warn("No XML definition could be found with name={} and attributes={}", type, attributes); return null; }
/** * Reads the configuration information from the shared configuration directory and returns a * {@link Configuration} object * * @return {@link Configuration} */ private Configuration readConfiguration(File groupConfigDir) throws SAXException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException { Configuration configuration = new Configuration(groupConfigDir.getName()); File cacheXmlFull = new File(groupConfigDir, configuration.getCacheXmlFileName()); File propertiesFull = new File(groupConfigDir, configuration.getPropertiesFileName()); configuration.setCacheXmlFile(cacheXmlFull); configuration.setPropertiesFile(propertiesFull); Set<String> jarFileNames = Arrays.stream(groupConfigDir.list()) .filter((String filename) -> filename.endsWith(".jar")).collect(Collectors.toSet()); configuration.addJarNames(jarFileNames); return configuration; }
/** * Writes given xmlDocument to xml file. * * @param xmlDocument */ @SuppressWarnings("unused") private void writeXml(final Document xmlDocument) { Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); final DOMSource source = new DOMSource(xmlDocument); // final StreamResult console = // new StreamResult(new File("C:/Users/emre.kirmizi/Desktop/out.xml")); final StreamResult console = new StreamResult(new File("C:/Users/anil.ozturk/Desktop/out.xml")); transformer.transform(source, console); } catch (TransformerFactoryConfigurationError | TransformerException e) { e.printStackTrace(); } }
/** * getSoapBodyXMLFromMessage * * @param response * SOAPMessage response * @return String representation of the SOAPBody */ public String getSoapBodyXMLFromMessage(SOAPMessage response) { String message = null; try { DOMSource source = new DOMSource(response.getSOAPBody()); StringWriter stringResult = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(stringResult)); message = stringResult.toString(); } catch (TransformerException | TransformerFactoryConfigurationError | SOAPException e) { log.error("Unable to parse body from response.", e); } return message; }
/** * @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; }
/** * The method search for a stylesheet mcr_<em>style</em>_object.xsl and * build the transformer. Default is <em>mcr_save-object.xsl</em>. * * @param style * the style attribute for the transformer stylesheet * @return the transformer * @throws TransformerFactoryConfigurationError * @throws TransformerConfigurationException */ private static Transformer getTransformer(String style) throws TransformerFactoryConfigurationError, TransformerConfigurationException { String xslfile = DEFAULT_TRANSFORMER; if (style != null && style.trim().length() != 0) { xslfile = style + "-classification.xsl"; } Transformer trans = null; URL styleURL = MCRClassification2Commands.class.getResource("/" + xslfile); if (styleURL == null) { styleURL = MCRClassification2Commands.class.getResource(DEFAULT_TRANSFORMER); } if (styleURL != null) { StreamSource source; try { source = new StreamSource(styleURL.toURI().toASCIIString()); } catch (URISyntaxException e) { throw new TransformerConfigurationException(e); } TransformerFactory transfakt = TransformerFactory.newInstance(); transfakt.setURIResolver(MCRURIResolver.instance()); trans = transfakt.newTransformer(source); } return trans; }
@Test public void singleTransform() throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException { String testFilePath = "/" + getClass().getSimpleName() + "/oneObj.xml"; InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath); JDOMResult jdomResult = xslTransformation(testXMLAsStream); Document resultXML = jdomResult.getDocument(); // XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); // xmlOutputter.output(resultXML, System.out); List<Element> mycoreojectTags = XPathFactory.instance() .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML); assertEquals(1, mycoreojectTags.size()); List<Element> userFieldTags = XPathFactory.instance() .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML); assertEquals(1, userFieldTags.size()); }
@Test public void multiTransform() throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException { String testFilePath = "/" + getClass().getSimpleName() + "/multiplObj.xml"; InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath); JDOMResult jdomResult = xslTransformation(testXMLAsStream); Document resultXML = jdomResult.getDocument(); // XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); // xmlOutputter.output(resultXML, System.out); List<Element> mycoreojectTags = XPathFactory.instance() .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML); assertEquals(3, mycoreojectTags.size()); List<Element> userFieldTags = XPathFactory.instance() .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML); assertEquals(3, userFieldTags.size()); }
@Test public void derivates() throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException { String testFilePath = "/" + getClass().getSimpleName() + "/xml/derivateObj.xml"; InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath); // JDOMResult jdomResult = xslTransformation(testXMLAsStream, "/" + getClass().getSimpleName() + "/xsl/mcr2solrOld.xsl"); JDOMResult jdomResult = xslTransformation(testXMLAsStream); Document resultXML = jdomResult.getDocument(); XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); xmlOutputter.output(resultXML, System.out); List<Element> mycoreojectTags = XPathFactory.instance() .compile("/solr-document-container/source/mycorederivate", Filters.element()).evaluate(resultXML); assertEquals(1, mycoreojectTags.size()); }
@RobotKeyword("Exports the data from the given table into a file that is stored at the " + "given location. The where-clause can (and should) be used to narrow the " + "amount of rows that is exported this way. The file is stored in some " + "simple XML-format and can be imported again to the database using the " + "\"Import Data From File\" keyword. This way it is possible to store a set " + "of testdata permanently retrieving it for example from some Live- or " + "Demosystem. This keyword will probably have some issues if millions of " + "rows are exported/imported using it. " + "\n\n" + "*NOTE*: If using keyword remotely, file need to be trasfered to server some " + "other way; this library is not doing the transfer.\n\n" + "The keyword returns the amount of rows written to the XML-file. " + "\n\n" + "Example: | ${ROWSEXPORTED}= | MySampleTable | /tmp/mysampletable.xml | Timestamp > sysdate-50 |") @ArgumentNames({ "Table name", "Export file path (including name)", "Where clause=''" }) public int exportDataFromTable(String tableName, String filePath, String... whereClause) throws SQLException, DatabaseLibraryException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException { new Assert().tableMustExist(tableName); String query = "Select * from " + tableName; if (whereClause.length > 0) { query += " where " + whereClause[0]; } List<HashMap<String, Object>> data = queryRunner.executeSql(query); return writeQueryResultsToFile(tableName, filePath, data); }
/** * Parses the source and sends SAX events to a content handler. * * @param contentHandler * The SAX content handler to use for parsing. */ public void parse(ContentHandler contentHandler) throws IOException { if (contentHandler != null) { try { Result result = new SAXResult(contentHandler); TransformerFactory.newInstance().newTransformer() .transform(getSaxSource(), result); } catch (TransformerConfigurationException tce) { throw new IOException( "Couldn't parse the source representation: " + tce.getMessage(), tce); } catch (TransformerException te) { throw new IOException( "Couldn't parse the source representation: " + te.getMessage(), te); } catch (TransformerFactoryConfigurationError tfce) { throw new IOException( "Couldn't parse the source representation: " + tfce.getMessage(), tfce); } } else { throw new IOException( "Couldn't parse the source representation: no content restlet defined."); } }
@Override public void write(OutputStream sysOut, Schema schema) throws ModelPersistenceException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); // Create from whole cloth Element root = doc.createElement("Model"); doc.appendChild(root); SchemaWriter writer = (SchemaWriter) NamedElementWriterBuilder.build(schema); writer.write(root, schema); TransformerFactory tf = TransformerFactory.newInstance(); Transformer tr = tf.newTransformer(); DOMSource src = new DOMSource(doc); StreamResult result = new StreamResult(sysOut); tr.transform(src, result); } catch (ParserConfigurationException | DOMException | TransformerFactoryConfigurationError | TransformerException ex) { throw new ModelPersistenceException(ex); } }
@Deprecated public void writeXML(String outPath) throws ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException, DOMException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = doc.createElement("properties"); doc.appendChild(root); for (Property prop : properties) { if (prop != null) { Element elem; elem = prop.getClass() == ArrayProperty.class ? doc.createElement(prop.getPluralName()) : doc.createElement(prop.getSingularName()); root.appendChild(elem); elem.setAttribute("name", prop.nameStr); prop.writeXML(doc, elem); } } Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(outPath).getAbsolutePath()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); }
/** * To transform XML with Stream. * * @param fis {@link InputStream} * @param pathToTargetXML {@link String} * @param xslStream {@link InputStream} * @throws TransformerFactoryConfigurationError * @throws TransformerConfigurationException * @throws FileNotFoundException * @throws TransformerException * @throws IOException */ public static void transformXMLWithStream(final InputStream fis, final String pathToTargetXML, final InputStream xslStream) throws TransformerFactoryConfigurationError, TransformerConfigurationException, FileNotFoundException, TransformerException, IOException { FileOutputStream fileOutputStream = null; try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(xslStream)); fileOutputStream = new FileOutputStream(pathToTargetXML); transformer.transform(new javax.xml.transform.stream.StreamSource(fis), new javax.xml.transform.stream.StreamResult( fileOutputStream)); } finally { if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } if (fis != null) { fis.close(); } } }
public static void getTextInFileOutPut(String search, int nbResult, int longueur) throws ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException, FileNotFoundException, IOException, BadLocationException { ArrayList<String> list = getURLs(search, nbResult); ArrayList<Document> listDoc = new ArrayList<Document>(); Iterator<String> it = list.iterator(); // Create an AlchemyAPI object. AlchemyAPI alchemyObj = AlchemyAPI.GetInstanceFromFile(API_KEY); while (it.hasNext()) // Extract page text from a web URL. (ignoring ads, navigation links, // and other content). try { listDoc.add(alchemyObj.URLGetText(it.next())); } catch (Exception e) {} // G�n�rer le fichier xml SerialiseurXML.getInstance().saveFile(listDoc,search,longueur); }
public static void main(String[] args) throws TransformerFactoryConfigurationError, Exception { try { if (args.length < 4) throw new Exception("Erreur! Il faut 4 param�tres.."); ExtractURL.setAPIKey(args[0]); ExtractURL.getTextInFileOutPut(args[1],Integer.parseInt(args[2]),Integer.parseInt(args[3])); System.exit(EXIT_SUCCESS); } catch (Exception e) { System.err.print(e.getMessage()); System.exit(EXIT_FAILED); } }
/** * Ouvre un fichier xml et ecrit dans ce fichier une description xml de plan * @param plan * @throws ParserConfigurationException * @throws TransformerFactoryConfigurationError * @throws TransformerException * @throws ExceptionXML */ public void saveFile(ArrayList<Document> list, String search, int longeur) throws ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException { File xml = new File("Texts.xml"); StreamResult result = new StreamResult(xml); document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); this.search = search.replaceAll("\\+", " "); this.longueur = longeur; document.appendChild(createElements(list)); DOMSource source = new DOMSource(document); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.transform(source, result); }
/** * Save a file trying to auto-guess the file type. * * @param file File name * @param width Width (for pixel formats) * @param height Height (for pixel formats) * @param quality Quality (for lossy compression) * @throws IOException on file write errors or unrecognized file extensions * @throws TranscoderException on transcoding errors * @throws TransformerFactoryConfigurationError on transcoding errors * @throws TransformerException on transcoding errors * @throws ClassNotFoundException when the transcoder was not installed */ public void saveAsANY(File file, int width, int height, double quality) throws IOException, TranscoderException, TransformerFactoryConfigurationError, TransformerException, ClassNotFoundException { String extension = FileUtil.getFilenameExtension(file); if("svg".equals(extension)) { saveAsSVG(file); } else if("pdf".equals(extension)) { saveAsPDF(file); } else if("ps".equals(extension)) { saveAsPS(file); } else if("eps".equals(extension)) { saveAsEPS(file); } else if("png".equals(extension)) { saveAsPNG(file, width, height); } else if("jpg".equals(extension) || "jpeg".equals(extension)) { saveAsJPEG(file, width, height, quality); } else { throw new IOException("Unknown file extension: " + extension); } }
@Override public ByteArrayOutputStream decompress(final InputStream inputStream) { StreamResult streamResult = streamResultFactory.createStreamResult(); InputStream fiDocument = inputStream; ByteArrayOutputStream baos = outputStreamFactory.createByteArrayOutputStream(); try { Transformer tx = fastInfosetTransformerFactory.createTransformer(); tx.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); tx.setOutputProperty(OutputKeys.INDENT, "yes"); FastInfosetSource fastInfosetSource = fastInfosetSourceFactory.createFastInfosetSource(fiDocument); tx.transform(fastInfosetSource, streamResult); fiDocument.close(); baos.write(streamResult.getWriter().toString().getBytes()); } catch (TransformerFactoryConfigurationError | Exception e) { throw new SystemException("Could not perform fastinfoset decompression!", e); } return baos; }
public void writeSvgFile(File svgFile) throws IOException, TransformerFactoryConfigurationError, TransformerException { if (!svgFile.isDirectory()) throw new FileNotFoundException(svgFile.getPath() + " was not found!"); for (String objectEntity : dStruct.getDiagrams()) { File f = new File(svgFile.getAbsolutePath() + File.separator + objectEntity + ".svg"); f.createNewFile(); System.out.println("Writing outputfile: " + f.getAbsolutePath()); FileOutputStream fstream = new FileOutputStream(f); DOMSource src = new DOMSource(dStruct.getObjectDiagramDocument(objectEntity)); Result res = new StreamResult(fstream); // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(src, res); fstream.close(); } }
/** * Writes and org.w3c.dom.Document to a file in a colored syntax HTML file * * @param doc * @param filename * @throws TransformerFactoryConfigurationError * @throws TransformerException */ public static void writeXmlFileAsHtml(Document doc, String filename) throws TransformerFactoryConfigurationError, TransformerException { // Prepare the DOM document for writing Source source = new DOMSource(doc); // Prepare the output file File file = new File(filename); Result result = new StreamResult(file); // Get transform Source xsltSource = new StreamSource( Utils.class.getResourceAsStream("xml2html.xslt")); // use this.getClass() instead for non static methods // Write the DOM document to the file Transformer xformer = TransformerFactory.newInstance().newTransformer(xsltSource); xformer.transform(source, result); }
/** * Get a {@link Transformer} instance that pretty prints the output. * * @return Transformer The indenting {@link Transformer} instance. */ private static Transformer getTransformer() { Transformer transformer; Properties outputProps = new Properties(); outputProps.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); outputProps.put(OutputKeys.STANDALONE, "no"); outputProps.put(OutputKeys.INDENT, "yes"); try { TransformerFactory tfFactory = TransformerFactory.newInstance(); transformer = tfFactory.newTransformer(); transformer.setOutputProperties(outputProps); } catch (TransformerFactoryConfigurationError | TransformerConfigurationException t) { org.apache.commons.logging.Log log = LogFactory.getLog(SCXMLWriter.class); log.error(t.getMessage(), t); return null; } return transformer; }
public void testAttributeOrderIsSame() throws ParserConfigurationException, IOException, TransformerFactoryConfigurationError, TransformerException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); String document = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rootElement><tag a=\"valuea\" b=\"valueb\"/></rootElement>"; Document first = builder.parse(new ByteArrayInputStream(document.getBytes())); String document2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rootElement><tag b=\"valueb\" a=\"valuea\"/></rootElement>"; Document second = builder.parse(new ByteArrayInputStream(document2.getBytes())); assertTrue(DifferenceHelper.getDifferences(first, NO_DOCS, second).isEmpty()); }
/** * If we end up using the JDK's own TraX factory on Java 9+, then * set the features and attributes necessary to allow redirect * extensions to be used. * @since Ant 1.9.8 */ protected void configureForRedirectExtension() { XSLTProcess.Factory factory = createFactory(); String factoryName = factory.getName(); if (factoryName == null) { try { factoryName = TransformerFactory.newInstance().getClass().getName(); } catch (TransformerFactoryConfigurationError exc) { throw new BuildException(exc); } } if (JDK_INTERNAL_FACTORY.equals(factoryName) && JavaEnvUtils.isAtLeastJavaVersion(JavaEnvUtils.JAVA_9)) { factory.addFeature(new XSLTProcess.Factory.Feature( "http://www.oracle.com/xml/jaxp/properties/enableExtensionFunctions", true)); } }
@Test public void testWithSecurityManagerAndXalanFactory() throws Exception { try { String factoryName = TransformerFactory.newInstance().getClass().getName(); Assume.assumeTrue("TraxFactory is " + factoryName + " and not Xalan", "org.apache.xalan.processor.TransformerFactoryImpl" .equals(factoryName)); } catch (TransformerFactoryConfigurationError exc) { throw new RuntimeException(exc); } try { System.setSecurityManager(new SecurityManager() { public void checkPermission(Permission perm) { } }); buildRule.executeTarget("testWithStyleFromClasspath"); commonIndexFileAssertions(); } finally { System.setSecurityManager(null); } }
@GET @Path("ctsaSearchCoauthors") @Produces(MediaType.APPLICATION_XML) public String ctsaSearchCoauthors(@QueryParam("PMID") String pmid) throws IOException, DOMException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException { Document doc = Jsoup.connect("http://research.icts.uiowa.edu/polyglot/service/person_by_pub.jsp") .data("mode", "PMID") .data("sort", "rank") .data("value", pmid) .post(); //System.out.println(doc.select("th").first().parent().parent()); // root elements org.w3c.dom.Document document = docBuilder.newDocument(); org.w3c.dom.Element rootElement = document.createElement("coauthors"); document.appendChild(rootElement); for (Element tr : doc.select("th").first().parent().parent().select("tr")) { //System.out.println(tr); rootElement.appendChild(getAuthor(document, tr)); } StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.getBuffer().toString().replaceAll("\n|\r", ""); }
@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); } }
/** * Revalida um objeto Document * @param documento * @return Document * @throws ParserConfigurationException * @throws IOException * @throws SAXException * @throws TransformerFactoryConfigurationError * @throws TransformerException * @throws TransformerConfigurationException */ public static Document revalidaDocument(Document documento) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = null; DocumentBuilder db; db = dbf.newDocumentBuilder(); InputSource is = converterDoc(documento); if (is != null){ doc = db.parse(is); } return doc; }
/** A bit convoluted, but we're trying to do it without adding an external dependency just for this... */ 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; } }
/** * Reads a JSON response from an ArcGIS server Rest end-point and converts it to an * XML string. * @param url the rest URL to the ArcGIS service * @return the rest response as an XML String * @throws MalformedURLException if the URL is invalid * @throws IOException if the communication fails * @throws JSONException if a non-empty response could not be * loaded as a JSON onject or conversion to XML fails * @throws TransformerFactoryConfigurationError configuration related exception * @throws TransformerException transformation related exception */ private String readAgsXml(String url) throws MalformedURLException, IOException, JSONException, TransformerFactoryConfigurationError, TransformerException { String xml = ""; JSONObject jso = readAgsJson(url); if (jso != null) { try { JSONObject jsoError = jso.getJSONObject("error"); if (jsoError != null) { throw new IOException(jsoError.toString()); } } catch (JSONException e) {} if (autoRecurse) { parseAgsTree(jso); for (String service: this.agsServiceUrls) System.err.println(service); } xml = toAgsXml(jso); LOGGER.finer("ArcGIS Rest/JSON to XML\n"+xml); } return xml; }
/** * Create an XML string from an ArcGIS Rest response. * <br/>The XML string is wrappoed in a parent tag <ags-rest>. * @param jso the JSON object representing the response * @return the XML String * @throws JSONException if the JDON object cannot be converted to an XML * @throws TransformerFactoryConfigurationError configuration related exception * @throws TransformerException transformation related exception */ private String toAgsXml(JSONObject jso) throws JSONException, TransformerFactoryConfigurationError, TransformerException { String xml = XML.toString(jso,"ags-rest"); StreamSource source = new StreamSource(new StringReader(xml)); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.transform(source,result); return Val.chkStr(writer.toString()); }
public static void main(String[] args) throws InvalidMessage, ConfigError, TransformerFactoryConfigurationError, TransformerException { String line = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader( PrintXML.class.getResourceAsStream("fixmsg.txt")))) { line = reader.readLine(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } DataDictionary dd = new DataDictionary("FIX44.xml"); DefaultMessageFactory messageFactory = new DefaultMessageFactory(); Message message = messageFactory.create("FIX.4.4", MessageUtils.getMessageType(line)); message.fromString(line, dd, false); String xmlString = message.toXML(dd); System.out.println(prettyFormat(xmlString)); }