Search in sources :

Example 61 with Result

use of javax.xml.transform.Result in project adempiere by adempiere.

the class MAttachment method saveLOBDataToFileSystem.

//	saveLOBData
/**
	 * 	Save Entry Data to the file system.
	 *	@return true if saved
	 */
private boolean saveLOBDataToFileSystem() {
    if (m_attachmentPathRoot == null || "".equals(m_attachmentPathRoot)) {
        log.severe("no attachmentPath defined");
        return false;
    }
    if (m_items == null || m_items.size() == 0) {
        setBinaryData(null);
        return true;
    }
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.newDocument();
        final Element root = document.createElement("attachments");
        document.appendChild(root);
        document.setXmlStandalone(true);
        // create xml entries
        for (int i = 0; i < m_items.size(); i++) {
            log.fine(m_items.get(i).toString());
            File entryFile = m_items.get(i).getFile();
            final String path = entryFile.getAbsolutePath();
            // if local file - copy to central attachment folder
            log.fine(path + " - " + m_attachmentPathRoot);
            if (!path.startsWith(m_attachmentPathRoot)) {
                log.fine("move file: " + path);
                FileChannel in = null;
                FileChannel out = null;
                try {
                    //create destination folder
                    final File destFolder = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet());
                    if (!destFolder.exists()) {
                        if (!destFolder.mkdirs()) {
                            log.warning("unable to create folder: " + destFolder.getPath());
                        }
                    }
                    final File destFile = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName());
                    in = new FileInputStream(entryFile).getChannel();
                    out = new FileOutputStream(destFile).getChannel();
                    in.transferTo(0, in.size(), out);
                    in.close();
                    out.close();
                    if (entryFile.exists()) {
                        if (!entryFile.delete()) {
                            entryFile.deleteOnExit();
                        }
                    }
                    entryFile = destFile;
                } catch (IOException e) {
                    e.printStackTrace();
                    log.severe("unable to copy file " + entryFile.getAbsolutePath() + " to " + m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName());
                } finally {
                    if (in != null && in.isOpen()) {
                        in.close();
                    }
                    if (out != null && out.isOpen()) {
                        out.close();
                    }
                }
            }
            final Element entry = document.createElement("entry");
            //entry.setAttribute("name", m_items.get(i).getName());
            entry.setAttribute("name", getEntryName(i));
            String filePathToStore = entryFile.getAbsolutePath();
            filePathToStore = filePathToStore.replaceFirst(m_attachmentPathRoot.replaceAll("\\\\", "\\\\\\\\"), ATTACHMENT_FOLDER_PLACEHOLDER);
            log.fine(filePathToStore);
            entry.setAttribute("file", filePathToStore);
            root.appendChild(entry);
        }
        final Source source = new DOMSource(document);
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final Result result = new StreamResult(bos);
        final Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
        final byte[] xmlData = bos.toByteArray();
        log.fine(bos.toString());
        setBinaryData(xmlData);
        return true;
    } catch (Exception e) {
        log.log(Level.SEVERE, "saveLOBData", e);
    }
    setBinaryData(null);
    return false;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) FileChannel(java.nio.channels.FileChannel) Element(org.w3c.dom.Element) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) FileInputStream(java.io.FileInputStream) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 62 with Result

use of javax.xml.transform.Result in project adempiere by adempiere.

the class HDDExportProcessor method process.

public void process(Properties ctx, MEXPProcessor expProcessor, Document document, Trx trx) throws Exception {
    //String host 	= expProcessor.getHost();
    //int port 		= expProcessor.getPort();
    //String account 	= expProcessor.getAccount();
    //String password = expProcessor.getPasswordInfo();
    String fileName = "";
    String folder = "";
    // Read all processor parameters and set them!        
    X_EXP_ProcessorParameter[] processorParameters = expProcessor.getEXP_ProcessorParameters(trx.getTrxName());
    if (processorParameters != null && processorParameters.length > 0) {
        for (int i = 0; i < processorParameters.length; i++) {
            // One special parameter which will be used for remote folder name. 
            // Or could add flag to ProcessorParameters table which will distinguish between 
            // connection parameters and FTP Upload parameters.
            log.info("ProcesParameter          Value = " + processorParameters[i].getValue());
            log.info("ProcesParameter ParameterValue = " + processorParameters[i].getParameterValue());
            if (processorParameters[i].getValue().equals("fileName")) {
                fileName = processorParameters[i].getParameterValue();
            } else if (processorParameters[i].getValue().equals("folder")) {
                folder = processorParameters[i].getParameterValue();
            }
        }
    }
    if (fileName == null || fileName.length() == 0) {
        throw new Exception("Missing EXP_ProcessorParameter with key 'fileName'!");
    }
    // Save the document to the disk file
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    tranFactory.setAttribute("indent-number", Integer.valueOf(1));
    Transformer aTransformer = tranFactory.newTransformer();
    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
    Source src = new DOMSource(document);
    // =================================== Write to String
    Writer writer = new StringWriter();
    Result dest2 = new StreamResult(writer);
    aTransformer.transform(src, dest2);
    System.err.println(writer.toString());
    // =================================== Write to Disk
    try {
        Result dest = new StreamResult(new File(folder + fileName));
        aTransformer.transform(src, dest);
        writer.close();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        throw ex;
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) X_EXP_ProcessorParameter(org.compiere.model.X_EXP_ProcessorParameter) TransformerException(javax.xml.transform.TransformerException) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) StringWriter(java.io.StringWriter) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) TransformerException(javax.xml.transform.TransformerException)

Example 63 with Result

use of javax.xml.transform.Result in project geode by apache.

the class CacheXmlGenerator method generate.

/**
   * Writes the generator's state to pw
   */
private void generate(PrintWriter pw) {
    // XML text
    try {
        Source src = new SAXSource(this, new InputSource());
        Result res = new StreamResult(pw);
        TransformerFactory xFactory = TransformerFactory.newInstance();
        Transformer xform = xFactory.newTransformer();
        xform.setOutputProperty(OutputKeys.METHOD, "xml");
        xform.setOutputProperty(OutputKeys.INDENT, "yes");
        if (!useSchema) {
            // set the doctype system and public ids from version for older DTDs.
            xform.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, version.getSystemId());
            xform.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, version.getPublicId());
        }
        xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        xform.transform(src, res);
        pw.flush();
    } catch (Exception ex) {
        RuntimeException ex2 = new RuntimeException(LocalizedStrings.CacheXmlGenerator_AN_EXCEPTION_WAS_THROWN_WHILE_GENERATING_XML.toLocalizedString());
        ex2.initCause(ex);
        throw ex2;
    }
}
Also used : InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) InternalGemFireException(org.apache.geode.InternalGemFireException) IOException(java.io.IOException) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) SAXException(org.xml.sax.SAXException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result)

Example 64 with Result

use of javax.xml.transform.Result in project JMRI by JMRI.

the class XMLUtil method write.

/**
     * Writes a DOM document to a stream. The precise output format is not
     * guaranteed but this method will attempt to indent it sensibly.
     *
     * <p class="nonnormative"><b>Important</b>: There might be some problems
     * with <code>&lt;![CDATA[ ]]&gt;</code> sections in the DOM tree you pass
     * into this method. Specifically, some CDATA sections my not be written as
     * CDATA section or may be merged with other CDATA section at the same
     * level. Also if plain text nodes are mixed with CDATA sections at the same
     * level all text is likely to end up in one big CDATA section.
     * <br>
     * For nodes that only have one CDATA section this method should work fine.
     * </p>
     *
     * @param doc DOM document to be written
     * @param out data sink
     * @param enc XML-defined encoding name (for example, "UTF-8")
     * @throws IOException if JAXP fails or the stream cannot be written to
     */
public static void write(Document doc, OutputStream out, String enc) throws IOException {
    if (enc == null) {
        // NOI18N
        throw new NullPointerException("You must set an encoding; use \"UTF-8\" unless you have a good reason not to!");
    }
    Document doc2 = normalize(doc);
    ClassLoader orig = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(AccessController.doPrivileged(new // #195921
    PrivilegedAction<ClassLoader>() {

        @Override
        public ClassLoader run() {
            return new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) {

                @Override
                public InputStream getResourceAsStream(String name) {
                    if (name.startsWith("META-INF/services/")) {
                        // JAXP #6723276
                        return new ByteArrayInputStream(new byte[0]);
                    }
                    return super.getResourceAsStream(name);
                }
            };
        }
    }));
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        DocumentType dt = doc2.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            String sys = dt.getSystemId();
            if (sys != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, sys);
            }
        }
        t.setOutputProperty(OutputKeys.ENCODING, enc);
        try {
            t.setOutputProperty(ORACLE_IS_STANDALONE, "yes");
        } catch (IllegalArgumentException x) {
        // fine, introduced in JDK 7u4
        }
        // See #123816
        Set<String> cdataQNames = new HashSet<String>();
        collectCDATASections(doc2, cdataQNames);
        if (cdataQNames.size() > 0) {
            StringBuilder cdataSections = new StringBuilder();
            for (String s : cdataQNames) {
                //NOI18N
                cdataSections.append(s).append(' ');
            }
            t.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSections.toString());
        }
        Source source = new DOMSource(doc2);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (javax.xml.transform.TransformerException | RuntimeException e) {
        // catch anything that happens
        throw new IOException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(orig);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) DocumentType(org.w3c.dom.DocumentType) IOException(java.io.IOException) Document(org.w3c.dom.Document) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) PrivilegedAction(java.security.PrivilegedAction) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) HashSet(java.util.HashSet)

Example 65 with Result

use of javax.xml.transform.Result in project midpoint by Evolveum.

the class DOMUtil method serializeDOMToFile.

public static void serializeDOMToFile(org.w3c.dom.Node node, File file) throws TransformerFactoryConfigurationError, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    Result output = new StreamResult(file);
    Source input = new DOMSource(node);
    transformer.transform(input, output);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result)

Aggregations

Result (javax.xml.transform.Result)80 StreamResult (javax.xml.transform.stream.StreamResult)72 Source (javax.xml.transform.Source)52 Transformer (javax.xml.transform.Transformer)52 DOMSource (javax.xml.transform.dom.DOMSource)42 TransformerFactory (javax.xml.transform.TransformerFactory)33 StringWriter (java.io.StringWriter)24 TransformerException (javax.xml.transform.TransformerException)21 IOException (java.io.IOException)20 StreamSource (javax.xml.transform.stream.StreamSource)20 SAXResult (javax.xml.transform.sax.SAXResult)16 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 File (java.io.File)15 Document (org.w3c.dom.Document)14 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)11 DOMResult (javax.xml.transform.dom.DOMResult)11 InputSource (org.xml.sax.InputSource)11 SAXException (org.xml.sax.SAXException)10 ByteArrayInputStream (java.io.ByteArrayInputStream)9 DocumentBuilder (javax.xml.parsers.DocumentBuilder)9