public void testAbortMultiRecordFileRead() { Transformer spec = TransformerFactory.getTransformer(FixedColBean.class); spec.parseFlatFile( FixedColumnWithRecordListenerTestCase.class.getResourceAsStream( "abortread-multi-record-fixedcol-file.txt"), new AbortListener()); }
@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(); }
public void write(HttpServletResponse response) { StreamResult streamResult; SAXTransformerFactory tf; TransformerHandler hd; Transformer serializer; try { try { streamResult = new StreamResult(response.getWriter()); tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); hd = tf.newTransformerHandler(); serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, "http://labs.omniti.com/resmon/trunk/resources/resmon.dtd"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); hd.setResult(streamResult); hd.startDocument(); AttributesImpl atts = new AttributesImpl(); hd.startElement("", "", "ResmonResults", atts); for (ResmonResult r : s) { r.write(hd); } hd.endElement("", "", "ResmonResults"); hd.endDocument(); } catch (TransformerConfigurationException tce) { response.getWriter().println(tce.getMessage()); } catch (SAXException se) { response.getWriter().println(se.getMessage()); } } catch (IOException ioe) { } }
/** * Write the XML document to the file trace.xml from * http://java.developpez.com/faq/xml/?page=xslt#creerXmlDom */ public boolean close() { boolean status = true; try { // Create the DOM source Source source = new DOMSource(m_document); // Create the output file File file = new File(m_fileName); Result resultat = new StreamResult(m_fileName); // Create the transformer TransformerFactory fabrique = TransformerFactory.newInstance(); Transformer transformer = fabrique.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); // Transformation transformer.transform(source, resultat); } catch (Exception e) { System.out.println("Error creating the file trace.xml"); status = false; e.printStackTrace(); } return status; }
private String importXMI(File sourceFile) throws FileNotFoundException, TransformerConfigurationException, TransformerException { BufferedReader styledata; StreamSource sourcedata; Templates stylesheet; Transformer trans; // Get the stylesheet file stream styledata = new BufferedReader( new FileReader( new File( getClass().getClassLoader().getResource("verifier/xmi2lem.xsl").getFile()))); sourcedata = new StreamSource(new FileReader(sourceFile)); // Initialize Saxon TransformerFactory factory = TransformerFactoryImpl.newInstance(); stylesheet = factory.newTemplates(new StreamSource(styledata)); // Apply the transformation trans = stylesheet.newTransformer(); StringWriter sw = new StringWriter(); trans.transform(sourcedata, new StreamResult(sw)); // return sw.toString(); return sw.getBuffer().substring(sw.getBuffer().indexOf("model")); }
private void soapMessage(String path, String wsName, String wsPortName) { try { URL wsdlURL = new URL(APP_SERVER + path); final String NS = AbstractServiceImpl.WS_TARGET_NAMESPACE; Service service = Service.create(wsdlURL, new QName(NS, wsName)); Dispatch<Source> dispatcher = service.createDispatch(new QName(NS, wsPortName), Source.class, Service.Mode.PAYLOAD); Source request = new StreamSource(new StringReader("<hello/>")); Source response = dispatcher.invoke(request); assertNotNull(response); Transformer transformer = TransformerFactory.newInstance().newTransformer(); final StringWriter writer = new StringWriter(); Result output = new StreamResult(writer); transformer.transform(response, output); Message message = new Message("clientMessages"); message.dumpFormattedMessage( EchoServiceClient.class, Message.LevelEnum.INFO, "receivedAnswer", writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); fail(String.valueOf(e)); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
/** * Transforms the given XML string using the XSL string. * * @param xmlString The String containg the XML to transform * @param xslString The XML Stylesheet String containing the transform instructions * @return String representation of the transformation */ public static String transform(String xmlString, String xslString) { String shortString = new String(xmlString); if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "..."; try { TransformerFactory tFactory = TransformerFactory.newInstance(); logger.logComment("Transforming string: " + shortString); StreamSource xslFileSource = new StreamSource(new StringReader(xslString)); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform( new StreamSource(new StringReader(xmlString)), new StreamResult(writer)); String shortResult = writer.toString(); if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "..."; logger.logComment("Result: " + shortResult); return writer.toString(); } catch (TransformerException e) { GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null); return null; } }
public void saveToXml(String fileName) throws ParserConfigurationException, FileNotFoundException, TransformerException, TransformerConfigurationException { System.out.println("Saving network topology to file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.newDocument(); Element root = doc.createElement("neuralNetwork"); root.setAttribute("dateOfExport", new Date().toString()); Element layers = doc.createElement("structure"); layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers())); for (int il = 0; il < this.numberOfLayers(); il++) { Element layer = doc.createElement("layer"); layer.setAttribute("index", Integer.toString(il)); layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons())); for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) { Element neuron = doc.createElement("neuron"); neuron.setAttribute("index", Integer.toString(in)); neuron.setAttribute( "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs())); neuron.setAttribute( "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold)); for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) { Element input = doc.createElement("input"); input.setAttribute("index", Integer.toString(ii)); input.setAttribute( "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight)); neuron.appendChild(input); } layer.appendChild(neuron); } layers.appendChild(layer); } root.appendChild(layers); doc.appendChild(root); // save File xmlOutputFile = new File(fileName); FileOutputStream fos; Transformer transformer; fos = new FileOutputStream(xmlOutputFile); // Use a Transformer for output TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fos); // transform source into result will do save transformer.setOutputProperty("encoding", "iso-8859-2"); transformer.setOutputProperty("indent", "yes"); transformer.transform(source, result); }
/** Transform a SAX Source to a TinyTree. */ public static DocumentInfo readTinyTree( Configuration configuration, Source source, boolean handleXInclude) { final TinyBuilder treeBuilder = new TinyBuilder(); try { if (handleXInclude) { // Insert XIncludeContentHandler final TransformerXMLReceiver identityHandler = getIdentityTransformerHandler(configuration); identityHandler.setResult(treeBuilder); final XMLReceiver receiver = new XIncludeProcessor.XIncludeXMLReceiver( null, identityHandler, null, new TransformerURIResolver(XMLUtils.ParserConfiguration.PLAIN)); TransformerUtils.sourceToSAX(source, receiver); } else { final Transformer identity = getIdentityTransformer(configuration); identity.transform(source, treeBuilder); } } catch (TransformerException e) { throw new OXFException(e); } return (DocumentInfo) treeBuilder.getCurrentRoot(); }
/** * Transforms the given XML file using the specified XSL file. * * @param origXmlFile The file containg the XML to transform * @param xslString The XML Stylesheet conntaining the transform instructions * @return String representation of the transformation */ public static String transform(File origXmlFile, String xslString) { if (!origXmlFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null); return null; } try { TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource xslFileSource = new StreamSource(new StringReader(xslString)); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null); return null; } }
public static String format(String xmlStr) { // Instantiate transformer input Source xmlInput = new StreamSource(new StringReader(xmlStr)); StreamResult xmlOutput = new StreamResult(new StringWriter()); // Configure transformer Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e) { logger.error(e.getMessage(), e); return xmlStr; } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block logger.error(e.getMessage(), e); return xmlStr; } // An identity transformer try { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); } catch (TransformerException e) { logger.error(e.getMessage(), e); return xmlStr; } return xmlOutput.getWriter().toString(); }
private InputStream getInputStream(Source source) throws Exception { Transformer trans = TransformerFactory.newInstance().newTransformer(); ByteArrayBuffer bab = new ByteArrayBuffer(); StreamResult result = new StreamResult(bab); trans.transform(source, result); return bab.newInputStream(); }
/** * 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); } }
/** * 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); } }
/** * set a preset viewpager transformer by id. * * @param transformerId the recongized transformer ID */ public void setPresetTransformer(int transformerId) { for (Transformer t : Transformer.values()) { if (t.ordinal() == transformerId) { setPresetTransformer(t); break; } } }
/** * set preset PagerTransformer via the name of transforemer. * * @param transformerName the transformer name in string */ public void setPresetTransformer(String transformerName) { for (Transformer t : Transformer.values()) { if (t.equals(transformerName)) { setPresetTransformer(t); return; } } }
/** Transform a SAX source to SAX events. */ private static void sourceToSAX(Source source, ContentHandler contentHandler) { try { final Transformer identity = getIdentityTransformer(); final SAXResult saxResult = new SAXResult(contentHandler); identity.transform(source, saxResult); } catch (TransformerException e) { throw new OXFException(e); } }
private DOMSource toDOMSource(Source source) throws Exception { if (source instanceof DOMSource) { return (DOMSource) source; } Transformer trans = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); trans.transform(source, result); return new DOMSource(result.getNode()); }
/** * Transforms a DOM Document into a file on disk * * @param fromDocument the Document to use as the source * @param toPath the destination file path represented as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static void transform(Document fromDocument, File toPath) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(fromDocument); StreamResult result = new StreamResult(new BufferedWriter(new FileWriter(toPath))); transformer.transform(source, result); }
/** * return a random Transformer between [0, the length of enum -1) * * @return BaseTransformer */ public BaseTransformer getShuffleTransformer() { BaseTransformer t = null; int transformerNumber = Transformer.values().length; int random = new Random().nextInt(transformerNumber - 1); Transformer ts = Transformer.values()[random]; switch (ts) { case Default: t = new DefaultTransformer(); break; case Accordion: t = new AccordionTransformer(); break; case Background2Foreground: t = new BackgroundToForegroundTransformer(); break; case CubeIn: t = new CubeInTransformer(); break; case DepthPage: t = new DepthPageTransformer(); break; case Fade: t = new FadeTransformer(); break; case FlipHorizontal: t = new FlipHorizontalTransformer(); break; case FlipPage: t = new FlipPageViewTransformer(); break; case Foreground2Background: t = new ForegroundToBackgroundTransformer(); break; case RotateDown: t = new RotateDownTransformer(); break; case RotateUp: t = new RotateUpTransformer(); break; case Stack: t = new StackTransformer(); break; case Tablet: t = new TabletTransformer(); break; case ZoomIn: t = new ZoomInTransformer(); break; case ZoomOutSlide: t = new ZoomOutSlideTransformer(); break; case ZoomOut: t = new ZoomOutTransformer(); break; } return t; }
/** Transform a dom4j Document into a TinyTree. */ public static DocumentInfo dom4jToTinyTree(Configuration configuration, Document document) { final TinyBuilder treeBuilder = new TinyBuilder(); try { final Transformer identity = getIdentityTransformer(configuration); identity.transform(new LocationDocumentSource(document), treeBuilder); } catch (TransformerException e) { throw new OXFException(e); } return (DocumentInfo) treeBuilder.getCurrentRoot(); }
/** Transform a SAX source to SAX events. */ public static void sourceToSAX(Source source, XMLReceiver xmlReceiver) { try { final Transformer identity = getIdentityTransformer(); final SAXResult saxResult = new SAXResult(xmlReceiver); saxResult.setLexicalHandler(xmlReceiver); identity.transform(source, saxResult); } catch (TransformerException e) { throw new OXFException(e); } }
/** Transform a dom4j document to a String. */ public static String dom4jToString(Document document) { try { final Transformer identity = getXMLIdentityTransformer(); final StringBuilderWriter writer = new StringBuilderWriter(); identity.transform(new LocationDocumentSource(document), new StreamResult(writer)); return writer.toString(); } catch (TransformerException e) { throw new OXFException(e); } }
public static String transform(File fromPath) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); Reader reader = bomCheck(fromPath); StringWriter sw = new StringWriter(); transformer.transform(new StreamSource(reader), new StreamResult(sw)); return sw.toString(); }
/** * Transforms a DOM Document into a String * * @param fromDocument the Document to use as the source * @param omitXmlDeclaration will not write the XML header if true * @return the XML as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static String transform(Document fromDocument, boolean omitXmlDeclaration) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (omitXmlDeclaration) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(fromDocument), new StreamResult(sw)); return sw.toString(); }
/** * Transforms a DOM Document into a String * * @param fromDocument the Document to use as the source * @return the XML as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static String transform(Document fromDocument) throws TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(fromDocument); transformer.transform(source, result); return sw.toString(); }
/** Transform a TinyTree to a String. */ public static String tinyTreeToString(NodeInfo nodeInfo) { try { final Transformer identity = getXMLIdentityTransformer(); final StringBuilderWriter writer = new StringBuilderWriter(); identity.transform(nodeInfo, new StreamResult(writer)); return writer.toString(); } catch (TransformerException e) { throw new OXFException(e); } }
/** * Transform a dom4j document into a W3C DOM document * * @param document dom4j document * @return W3C DOM document * @throws TransformerException */ public static org.w3c.dom.Document dom4jToDomDocument(Document document) throws TransformerException { final Transformer identity = getIdentityTransformer(); final DOMResult domResult = new DOMResult(); identity.transform(new DocumentSource(document), domResult); final Node resultNode = domResult.getNode(); return (resultNode instanceof org.w3c.dom.Document) ? ((org.w3c.dom.Document) resultNode) : resultNode.getOwnerDocument(); }
/** * Apply output properties on a Transformer. * * @param transformer transformer to apply properties on * @param method output method * @param version HTML or XML version * @param publicDoctype public doctype * @param systemDoctype system doctype * @param encoding character encoding * @param omitXMLDeclaration whether XML declaration must be omitted * @param standalone wether a standalone declartion must be set and to what value * @param indent whether the HTML or XML must be indented * @param indentAmount amount of indenting for the markup */ public static void applyOutputProperties( Transformer transformer, String method, String version, String publicDoctype, String systemDoctype, String encoding, boolean omitXMLDeclaration, Boolean standalone, boolean indent, int indentAmount) { if (method != null && !"".equals(method)) transformer.setOutputProperty(OutputKeys.METHOD, method); if (version != null && !"".equals(version)) transformer.setOutputProperty(OutputKeys.VERSION, version); if (publicDoctype != null && !"".equals(publicDoctype)) transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, publicDoctype); if (systemDoctype != null && !"".equals(systemDoctype)) transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemDoctype); if (encoding != null && !"".equals(encoding)) transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); if (indent) transformer.setOutputProperty(INDENT_AMOUNT_PROPERTY, String.valueOf(indentAmount)); transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no"); if (standalone != null) transformer.setOutputProperty(OutputKeys.STANDALONE, standalone ? "yes" : "no"); }