public static void writeXmlFile(Document doc, File saveFile, boolean systemOut) { try { Source source = new DOMSource(doc); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setParameter(OutputKeys.INDENT, "yes"); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); if (saveFile != null) { Result result = new StreamResult(saveFile); xformer.transform(source, result); } Writer outputWriter = new StringWriter(); Result stringOut = new StreamResult(outputWriter); xformer.transform(source, stringOut); // new SinglePanelPopup(new TextAreaPane(outputWriter.toString())); if (systemOut) { Result system = new StreamResult(System.out); xformer.transform(source, system); } } catch (TransformerConfigurationException e) { } catch (TransformerException e) { } }
private void _writeDocument(Document doc, HttpServletResponse response) { try { doc.getDocumentElement().normalize(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); if (_log.isDebugEnabled()) { StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } response.setContentType("text/xml; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.flush(); out.close(); } catch (Exception e) { throw new FCKException(e); } }
public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element root = document.createElement("Languages"); root.setAttribute("cat", "it"); Element lan1 = document.createElement("lan"); lan1.setAttribute("id", "1"); Element name1 = document.createElement("name"); name1.setTextContent("Java"); Element ide1 = document.createElement("ide"); ide1.setTextContent("Eclipse"); lan1.appendChild(name1); lan1.appendChild(ide1); Element lan2 = document.createElement("lan"); lan1.setAttribute("id", "2"); Element name2 = document.createElement("name"); name1.setTextContent("Swift"); Element ide2 = document.createElement("ide"); ide1.setTextContent("Xcode"); lan1.appendChild(name2); lan1.appendChild(ide2); Element lan3 = document.createElement("lan"); lan1.setAttribute("id", "1"); Element name3 = document.createElement("name"); name1.setTextContent("Java"); Element ide3 = document.createElement("ide"); ide1.setTextContent("Eclipse"); lan1.appendChild(name3); lan1.appendChild(ide3); root.appendChild(lan1); root.appendChild(lan2); root.appendChild(lan3); document.appendChild(root); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); System.out.println(writer.toString()); transformer.transform(new DOMSource(document), new StreamResult("newXML.xml")); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void writeAsAttachment(Object obj, OutputStream out) throws IOException { try { if (obj instanceof StreamSource) { StreamSource source = (StreamSource) obj; InputSource inputSource = null; InputStream is = source.getInputStream(); Reader reader = source.getReader(); String systemId = source.getSystemId(); if (is != null) inputSource = new InputSource(is); else if (reader != null) inputSource = new InputSource(reader); else if (systemId != null) inputSource = new InputSource(systemId); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(_entityResolver); SAXSource saxSource = new SAXSource(xmlReader, inputSource); _transformer.transform(saxSource, new StreamResult(out)); } else _transformer.transform((Source) obj, new StreamResult(out)); } catch (TransformerException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } catch (SAXException saxe) { IOException ioe = new IOException(); ioe.initCause(saxe); throw ioe; } }
/** * Writes visual structure to output XML * * @param visualStructure Given visual structure * @param pageViewport Page's viewport */ public void writeXML(VisualStructure visualStructure, Viewport pageViewport) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); Element vipsElement = doc.createElement("VIPSPage"); String pageTitle = pageViewport .getRootElement() .getOwnerDocument() .getElementsByTagName("title") .item(0) .getTextContent(); vipsElement.setAttribute("Url", pageViewport.getRootBox().getBase().toString()); vipsElement.setAttribute("PageTitle", pageTitle); vipsElement.setAttribute("WindowWidth", String.valueOf(pageViewport.getContentWidth())); vipsElement.setAttribute("WindowHeight", String.valueOf(pageViewport.getContentHeight())); vipsElement.setAttribute("PageRectTop", String.valueOf(pageViewport.getAbsoluteContentY())); vipsElement.setAttribute("PageRectLeft", String.valueOf(pageViewport.getAbsoluteContentX())); vipsElement.setAttribute("PageRectWidth", String.valueOf(pageViewport.getContentWidth())); vipsElement.setAttribute("PageRectHeight", String.valueOf(pageViewport.getContentHeight())); vipsElement.setAttribute("neworder", "0"); vipsElement.setAttribute("order", String.valueOf(pageViewport.getOrder())); doc.appendChild(vipsElement); writeVisualBlocks(vipsElement, visualStructure); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); if (_escapeOutput) { StreamResult result = new StreamResult(new File(_filename + ".xml")); transformer.transform(source, result); } else { StringWriter writer = new StringWriter(); transformer.transform(source, new StreamResult(writer)); String result = writer.toString(); result = result.replaceAll(">", ">"); result = result.replaceAll("<", "<"); result = result.replaceAll(""", "\""); FileWriter fstream = new FileWriter(_filename + ".xml"); fstream.write(result); fstream.close(); } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } }
public void saveCurrentRoute(View view) { if (GPS_captureStarted) { Log.w("Saving Route", "Can't Save, tracking not paused"); return; } Element metadata = gpx_document.createElement("metadata"); Element filename = gpx_document.createElement("name"); Element author = gpx_document.createElement("author"); Element trackName = gpx_document.createElement("name"); String fn = "TestFile"; String tn = "TestTrack"; String auth = "Username"; filename.appendChild(gpx_document.createTextNode(fn)); author.appendChild(gpx_document.createTextNode(auth)); trackName.appendChild(gpx_document.createTextNode(tn)); track.appendChild(trackName); metadata.appendChild(filename); metadata.appendChild(author); rootElement.appendChild(metadata); try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(gpx_document); StreamResult result; if (isConnected) { result = new StreamResult(new StringWriter()); transformer.transform(source, result); String gpx = result.getWriter().toString(); Request.send_GPX(gpx); } else { FileOutputStream stream = openFileOutput(fn + ".gpx", MODE_PRIVATE); result = new StreamResult(stream); transformer.transform(source, result); Log.i("writing file", "success"); filesToSync.put(fn + ".gpx", true); } } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private static void diffAll( String htmlOutputDir, String previousChangelist, String currentChangelist) throws Exception { ResultFileSetLoader loader = new ResultFileSetLoader(); Map currentTests = loader.loadResultFiles("."); FileTestImporter imp = new FileTestImporter(); Map previousTests = imp.getTestsForChangelist(previousChangelist); ArrayList diffs = new ArrayList(currentTests.keySet().size()); Object[] keys = currentTests.keySet().toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { String testFile = (String) keys[i]; XMLResult previous = (XMLResult) previousTests.get(testFile); if (null == previous) { System.out.println("Null Test file: " + testFile); previous = new EmptyXMLResult(testFile); previousTests.put(testFile, previous); } previous.setChangelist(previousChangelist); XMLResult current = (XMLResult) currentTests.get(testFile); current.setChangelist(currentChangelist); ResultDiff diff = new ResultDiff(previous, current); diffs.add(diff); } String databaseType = System.getProperty("database.key"); ReportIndex index = new ReportIndex(previousChangelist, currentChangelist, databaseType); XMLOutputter out = new XMLOutputter(" ", true); final String ACS_HOME = System.getProperty("ACS_HOME"); Transformer tran = TransformerFactory.newInstance() .newTransformer(new StreamSource(ACS_HOME + "/test/xsl/junit.xsl")); for (Iterator iterator = diffs.iterator(); iterator.hasNext(); ) { ResultDiff resultDiff = (ResultDiff) iterator.next(); index.addResult(resultDiff); String htmlFile = resultDiff.getAttributeValue("name") + ".html"; FileWriter file = new FileWriter(htmlOutputDir + "/" + htmlFile); JDOMResult html = new JDOMResult(); tran.transform(new JDOMSource(new Document(resultDiff)), html); out.output(html.getDocument(), file); } JDOMResult indexHtml = new JDOMResult(); tran = TransformerFactory.newInstance() .newTransformer(new StreamSource(ACS_HOME + "/test/xsl/index.xsl")); tran.transform(new JDOMSource(new Document(index)), indexHtml); FileWriter indexFile = new FileWriter(htmlOutputDir + "/index.html"); out.output(indexHtml.getDocument(), indexFile); out.output( new Document(index), new FileOutputStream("report_index_" + currentChangelist + ".xml")); }
private void createTestModel0(final I_EXP_Format exportFormat) throws Exception { final File directory = getTestModelDirectory(); final File file = new File(directory, getTestModelFileName(exportFormat)); final ExportHelper expHelper = new ExportHelper(getCtx(), getAD_Client_ID()); final IReplicationAccessContext racCtx = new ReplicationAccessContext(10, false); // TODO hardcoded final Document doc = expHelper.exportRecord( (MEXPFormat) LegacyAdapters.convertToPO(exportFormat), "", MReplicationStrategy.REPLICATION_TABLE, X_AD_ReplicationTable.REPLICATIONTYPE_Merge, ModelValidator.TYPE_AFTER_CHANGE, racCtx); if (doc == null) { addLog( "Not creating test XML for format '" + exportFormat.getName() + "', because with AD_Client_ID=" + getAD_Client_ID() + "the system can't access any '" + exportFormat.getAD_Table().getName() + "'-record"); return; } // Save the document to the disk file final TransformerFactory tranFactory = TransformerFactory.newInstance(); final Transformer aTransformer = tranFactory.newTransformer(); aTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); final Source src = new DOMSource(doc); // =================================== Write to String final Writer writer = new StringWriter(); final Result dest2 = new StreamResult(writer); aTransformer.transform(src, dest2); // =================================== Write to Disk try { final Result dest = new StreamResult(file); aTransformer.transform(src, dest); writer.flush(); writer.close(); } catch (TransformerException ex) { ex.printStackTrace(); throw ex; } addLog("Created test model: " + file); }
/** Save the modifications */ public static void writeDocument(String filename, Node written) { Transformer transformer = null; try { transformer = ScilabTransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e1) { System.err.println(ERROR_WRITE + filename); return; } catch (TransformerFactoryConfigurationError e1) { System.err.println(ERROR_WRITE + filename); return; } transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new File(filename)); DOMSource source = new DOMSource(written); try { transformer.transform(source, result); } catch (TransformerException e) { System.err.println(ERROR_WRITE + filename); return; } // Invalidate the current document if (filename.equals(USER_CONFIG_FILE)) { doc = null; } }
public String transform(String type, String input, Map<String, String> transformModel) throws TransformException { if (log.isDebugEnabled()) { log.debug("transform(input=" + input + ")"); } try { Templates template = templates.get(type); if (log.isDebugEnabled()) { log.debug("template=" + template); } if (template != null) { Transformer transformer = template.newTransformer(); StringWriter writer = new StringWriter(INITIAL_BUFFER_SIZE); transformer.setErrorListener(new DefaultErrorListener()); if (transformModel != null) { for (Map.Entry<String, String> entry : transformModel.entrySet()) { transformer.setParameter(entry.getKey(), entry.getValue()); } } transformer.transform(new StreamSource(new StringReader(input)), new StreamResult(writer)); String result = writer.toString().trim(); if (log.isDebugEnabled()) { log.debug("result=" + result); } return result; } else { String errMsg = "Transformation '" + type + "' not available"; log.error(errMsg); throw new RuntimeException(errMsg); } } catch (Exception e) { log.error("Error during transform", e); throw new TransformException(e); } }
@Override public boolean handleMessage(LogicalMessageContext logicalMessageContext) { try { boolean outboundMessage = (boolean) logicalMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (!outboundMessage) { return true; } LogicalMessage logicalMessage = logicalMessageContext.getMessage(); Transformer transformer = _transformerFactory.newTransformer(new StreamSource(_url.openStream())); DOMResult domResult = new DOMResult(); transformer.transform(logicalMessage.getPayload(), domResult); logicalMessage.setPayload(new DOMSource(domResult.getNode())); return true; } catch (Exception e) { throw new RuntimeException(e); } }
public void createDom() throws ParserConfigurationException, SAXException, IOException, TransformerException { String filePath = "maven_template.xml"; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(filePath); Node projectUrl = doc.getElementsByTagName("projectUrl").item(0); projectUrl.setTextContent("https://github.com/YuesongWang/TestJenkins/"); Node url = doc.getElementsByTagName("url").item(0); url.setTextContent("[email protected]:YuesongWang/TestJenkins.git"); Node credentialsId = doc.getElementsByTagName("credentialsId").item(0); credentialsId.setTextContent("c56c7063-12a8-4a0f-b772-83b16732f6bf"); Node targets = doc.getElementsByTagName("targets").item(0); targets.setTextContent("clean install"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("config.xml")); transformer.transform(source, result); }
public void write(Document doc, OutputStream outputStream) throws IOException { // OutputFormat format = new OutputFormat(doc); // format.setIndenting(true); // format.setEncoding("UTF-8"); // XMLSerializer serializer = new XMLSerializer(outputStream, format); // serializer.asDOMSerializer(); // serializer.serialize(doc); try { TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("indent-number", 4); } catch (Exception e) {; // guess we can't set it, that's ok } Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // need to nest outputStreamWriter to get around JDK 5 bug. See // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446 transformer.transform( new DOMSource(doc), new StreamResult(new OutputStreamWriter(outputStream, "utf-8"))); } catch (TransformerException e) { throw new IOException(e.getMessage()); } }
private String transformXml(final Document document) throws TransformerException { final Transformer transformer = XmlUtils.createIndentingTransformer(); final DOMSource source = new DOMSource(document); final StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); return result.getWriter().toString(); }
protected Document wbxmlStream2Doc(InputStream in, boolean event) throws Exception { XMLStreamReader xmlStreamReader = null; XMLEventReader xmlEventReader = null; try { if (event) { xmlEventReader = inFact.createXMLEventReader(in); } else { xmlStreamReader = inFact.createXMLStreamReader(in); } Transformer xformer = TransformerFactory.newInstance().newTransformer(); StAXSource staxSource = event ? new StAXSource(xmlEventReader) : new StAXSource(xmlStreamReader); DOMResult domResult = new DOMResult(); xformer.transform(staxSource, domResult); Document doc = (Document) domResult.getNode(); doc.normalize(); return doc; } finally { if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (Exception e) { } } if (xmlEventReader != null) { try { xmlEventReader.close(); } catch (Exception e) { } } } }
/** * Serialize this instance to a steam. * * <p>Default deserialization is pretty-printed but not schema-validated. * * @param out the stream for writing * @param validate whether to perform schema validation * @throws JAXBException if the steam can't be written to */ public void marshal(final OutputStream out, final Boolean validate) throws JAXBException { try { // Create an empty DOM DOMResult intermediateResult = new DOMResult(); // Marshal from JAXB to DOM Marshaller marshaller = /*BPMN_CONTEXT*/ newContext().createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); if (validate) { marshaller.setSchema(getBpmnSchema() /*BPMN_SCHEMA*/); } marshaller.marshal(new BpmnObjectFactory().createDefinitions(this), intermediateResult); // Apply the XSLT transformation, from DOM to the output stream TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer( new StreamSource( new java.io.StringBufferInputStream( fixNamespacesXslt[0] + getTargetNamespace() + fixNamespacesXslt[1]))); DOMSource finalSource = new DOMSource(intermediateResult.getNode()); StreamResult finalResult = new StreamResult(out); transformer.transform(finalSource, finalResult); } catch (TransformerException e) { throw new JAXBException("Dodgy wrapped exception", e); } // TODO - create transformer elsewhere }
@Override public void go(Source input) throws IOException, ServletException { // Set the content-type for the output assignContentType(this.getTransformCtx()); Transformer trans; try { trans = this.getCompiled().newTransformer(); } catch (TransformerConfigurationException ex) { throw new ServletException(ex); } // Populate any params which might have been set if (this.getTransformCtx().getTransformParams() != null) populateParams(trans, this.getTransformCtx().getTransformParams()); Result res; if (this.getNext().isLast()) res = new StreamResult(this.getNext().getResponse().getOutputStream()); else res = new SAXResult(this.getNext().getSAXHandler()); try { trans.transform(input, res); } catch (TransformerException ex) { throw new ServletException(ex); } this.getNext().done(); }
/** * @param monitor * @throws Exception */ private void addServletToGwtXml(IProgressMonitor monitor) throws Exception { monitor = Util.getNonNullMonitor(monitor); try { monitor.beginTask("", 1); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File moduleFile = getModuleFile(); Document document = builder.parse(moduleFile); Node module = document.getDocumentElement(); Element newServlet = document.createElement("servlet"); newServlet.setAttribute("path", "/" + serviceUri); // $NON-NLS-2$ newServlet.setAttribute( "class", getPackageFragment().getElementName() + '.' + getTypeName() + "Impl"); // $NON-NLS-2$ module.appendChild(newServlet); Transformer writer = TransformerFactory.newInstance().newTransformer(); writer.transform(new DOMSource(document), new StreamResult(moduleFile)); } finally { monitor.done(); } }
/** * Pomocnicza klasa wysyłająca dokument XML do writera * * @param doc dokument, który chcemy wysłać * @param out Writer, do którego chcemy pisać */ private void XML2Writer(Document doc, PrintWriter out) { Transformer transformer = null; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(doc); try { if (transformer != null) { transformer.transform(source, result); } } catch (TransformerException e) { e.printStackTrace(); } }
/** * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute * formatting with xsl transformation. * * @param jaxbElement * @return */ private String getXmlContent(Object jaxbElement) { StringResult jaxbContent = new StringResult(); springBeanMarshaller.marshal(jaxbElement, jaxbContent); Source xsltSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream()); Transformer transformer = transformerFactory.newTransformer(xsltSource); // transform StringResult result = new StringResult(); transformer.transform(new StringSource(jaxbContent.toString()), result); if (log.isDebugEnabled()) { log.debug("Created bean definition:\n" + result.toString()); } return result.toString(); } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * Method removes a Spring bean definition from the XML application context file. Bean definition * is identified by its id or bean name. * * @param project * @param id */ public void removeBeanDefinition(File configFile, Project project, String id) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_id", id); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * Method adds a new Spring bean definition to the XML application context file. * * @param project * @param jaxbElement */ public void addBeanDefinition(File configFile, Project project, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream()); xsltSource.setSystemId("add-bean"); xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), configFile); return; } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** Save the modifications */ public static String dumpNode(Node written) { Transformer transformer = null; try { transformer = ScilabTransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e1) { System.err.println("Cannot dump xml"); return ""; } catch (TransformerFactoryConfigurationError e1) { System.err.println("Cannot dump xml"); return ""; } transformer.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(new BufferedOutputStream(stream)); DOMSource source = new DOMSource(written); String str = ""; try { transformer.transform(source, result); str = stream.toString(); } catch (TransformerException e) { System.err.println("Cannot dump xml"); return str; } finally { try { stream.close(); } catch (Exception e) { } } return str; }
public void storeMappings(WorkspaceLanguageConfiguration config) throws CoreException { try { // Encode mappings as XML and serialize as a String. Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element rootElement = doc.createElement(WORKSPACE_MAPPINGS); doc.appendChild(rootElement); addContentTypeMappings(config.getWorkspaceMappings(), rootElement); Transformer serializer = createSerializer(); DOMSource source = new DOMSource(doc); StringWriter buffer = new StringWriter(); StreamResult result = new StreamResult(buffer); serializer.transform(source, result); String encodedMappings = buffer.getBuffer().toString(); IEclipsePreferences node = InstanceScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID); node.put(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, encodedMappings); node.flush(); } catch (ParserConfigurationException e) { throw new CoreException(Util.createStatus(e)); } catch (TransformerException e) { throw new CoreException(Util.createStatus(e)); } catch (BackingStoreException e) { throw new CoreException(Util.createStatus(e)); } }
protected void doTransform( MuleMessage message, String outputEncoding, Source sourceDoc, Result result) throws Exception { DefaultErrorListener errorListener = new DefaultErrorListener(this); javax.xml.transform.Transformer transformer = null; try { transformer = (javax.xml.transform.Transformer) transformerPool.borrowObject(); transformer.setErrorListener(errorListener); transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); // set transformation parameters if (contextProperties != null) { for (Entry<String, Object> parameter : contextProperties.entrySet()) { String key = parameter.getKey(); transformer.setParameter( key, evaluateTransformParameter(key, parameter.getValue(), message)); } } transformer.transform(sourceDoc, result); if (errorListener.isError()) { throw errorListener.getException(); } } finally { if (transformer != null) { transformerPool.returnObject(transformer); } } }
private void parseWebFragmentXml() throws XMLStreamException, IOException, TransformerException { final XMLInputFactory xif = XMLInputFactory.newInstance(); final XMLStreamReader xsr = xif.createXMLStreamReader(getInputStream()); xsr.nextTag(); // web-fragment tag skipped while (xsr.hasNext() && xsr.nextTag() == XMLStreamConstants.START_ELEMENT) { final String tagName = xsr.getLocalName(); // webFragmentName if ("name".equalsIgnoreCase(tagName)) { final String element = xsr.getElementText(); allWebFragmentNames.add(element); webFragmentXmlComponents.add("<name>" + element + "</name>"); } else { final TransformerFactory tf = TransformerFactory.newInstance(); final Transformer t = tf.newTransformer(); final StringWriter res = new StringWriter(); t.transform(new StAXSource(xsr), new StreamResult(res)); final String element = org.apache.commons.lang3.StringUtils.substringAfter(res.toString(), "?>"); if ("ordering".equalsIgnoreCase(tagName)) { // ordering parseOrdering(element); } else { // webFragmentXmlComponents webFragmentXmlComponents.add(element); } } } if (allWebFragmentNames.isEmpty()) { throw new IllegalStateException( "Name tag is missing. Please specify a name in the web-fragment.xml!"); } }
public static void main(String[] args) { String outputDir = "./"; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-o".equals(arg)) { outputDir = args[++i]; continue; } else { System.out.println("XMLSchemaGenerator -o <path to newly created xsd schema file>"); return; } } File f = new File(outputDir, "JGroups-" + Version.major + "." + Version.minor + ".xsd"); try { FileWriter fw = new FileWriter(f, false); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); Document xmldoc = impl.createDocument("http://www.w3.org/2001/XMLSchema", "xs:schema", null); xmldoc.getDocumentElement().setAttribute("targetNamespace", "urn:org:jgroups"); xmldoc.getDocumentElement().setAttribute("elementFormDefault", "qualified"); Element xsElement = xmldoc.createElement("xs:element"); xsElement.setAttribute("name", "config"); xmldoc.getDocumentElement().appendChild(xsElement); Element complexType = xmldoc.createElement("xs:complexType"); xsElement.appendChild(complexType); Element allType = xmldoc.createElement("xs:choice"); allType.setAttribute("maxOccurs", "unbounded"); complexType.appendChild(allType); Set<Class<?>> classes = getClasses("bboss.org.jgroups.protocols", Protocol.class); for (Class<?> clazz : classes) { classToXML(xmldoc, allType, clazz, ""); } classes = getClasses("bboss.org.jgroups.protocols.pbcast", Protocol.class); for (Class<?> clazz : classes) { classToXML(xmldoc, allType, clazz, "pbcast."); } DOMSource domSource = new DOMSource(xmldoc); StreamResult streamResult = new StreamResult(fw); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.METHOD, "xml"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1"); serializer.transform(domSource, streamResult); fw.flush(); fw.close(); } catch (Exception e) { e.printStackTrace(); } }
// write the content into xml file private void writeToXml(String fileName, Document doc) throws Exception { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(fileName)); transformer.transform(source, result); }
private void eatMemory(int callIndex, File foFile, int replicatorRepeats) throws Exception { Source src = new StreamSource(foFile); Transformer transformer = replicatorTemplates.newTransformer(); transformer.setParameter("repeats", new Integer(replicatorRepeats)); OutputStream out = new NullOutputStream(); // write to /dev/nul try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(foFile.getParentFile().toURL().toExternalForm()); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); stats.notifyPagesProduced(fop.getResults().getPageCount()); if (callIndex == 0) { System.out.println( foFile.getName() + " generates " + fop.getResults().getPageCount() + " pages."); } stats.checkStats(); } finally { IOUtils.closeQuietly(out); } }
// TODO - change the return type and the factory parameter to be Definitions and ObjectFactory, // and move to bpmn-schema public BpmnDefinitions correctFlowNodeRefs( final BpmnDefinitions definitions, final BpmnObjectFactory factory) throws JAXBException, TransformerException { JAXBContext context = JAXBContext.newInstance( factory.getClass(), com.processconfiguration.ObjectFactory.class, org.omg.spec.bpmn._20100524.di.ObjectFactory.class, org.omg.spec.bpmn._20100524.model.ObjectFactory.class, org.omg.spec.dd._20100524.dc.ObjectFactory.class, org.omg.spec.dd._20100524.di.ObjectFactory.class, com.signavio.ObjectFactory.class); // Marshal the BPMN into a DOM tree DOMResult intermediateResult = new DOMResult(); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(factory.createDefinitions(definitions), intermediateResult); // Apply the XSLT transformation, generating a new DOM tree TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer( new StreamSource( getClass().getClassLoader().getResourceAsStream("xsd/fix-flowNodeRef.xsl"))); DOMSource finalSource = new DOMSource(intermediateResult.getNode()); DOMResult finalResult = new DOMResult(); transformer.transform(finalSource, finalResult); // Unmarshal back to JAXB Object def2 = context.createUnmarshaller().unmarshal(finalResult.getNode()); return ((JAXBElement<BpmnDefinitions>) def2).getValue(); }