Search in sources :

Example 61 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project oxCore by GluuFederation.

the class Response method printDocument.

public void printDocument(OutputStream out) throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.transform(new DOMSource(xmlDoc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) OutputStreamWriter(java.io.OutputStreamWriter)

Example 62 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project lucene-solr by apache.

the class XPathEntityProcessor method initXpathReader.

private void initXpathReader(VariableResolver resolver) {
    reinitXPathReader = false;
    useSolrAddXml = Boolean.parseBoolean(context.getEntityAttribute(USE_SOLR_ADD_SCHEMA));
    streamRows = Boolean.parseBoolean(context.getEntityAttribute(STREAM));
    if (context.getResolvedEntityAttribute("batchSize") != null) {
        blockingQueueSize = Integer.parseInt(context.getEntityAttribute("batchSize"));
    }
    if (context.getResolvedEntityAttribute("readTimeOut") != null) {
        blockingQueueTimeOut = Integer.parseInt(context.getEntityAttribute("readTimeOut"));
    }
    String xslt = context.getEntityAttribute(XSL);
    if (xslt != null) {
        xslt = context.replaceTokens(xslt);
        try {
            // create an instance of TransformerFactory
            TransformerFactory transFact = TransformerFactory.newInstance();
            final SolrCore core = context.getSolrCore();
            final StreamSource xsltSource;
            if (core != null) {
                final ResourceLoader loader = core.getResourceLoader();
                transFact.setURIResolver(new SystemIdResolver(loader).asURIResolver());
                xsltSource = new StreamSource(loader.openResource(xslt), SystemIdResolver.createSystemIdFromResourceName(xslt));
            } else {
                // fallback for tests
                xsltSource = new StreamSource(xslt);
            }
            transFact.setErrorListener(xmllog);
            try {
                xslTransformer = transFact.newTransformer(xsltSource);
            } finally {
                // some XML parsers are broken and don't close the byte stream (but they should according to spec)
                IOUtils.closeQuietly(xsltSource.getInputStream());
            }
            LOG.info("Using xslTransformer: " + xslTransformer.getClass().getName());
        } catch (Exception e) {
            throw new DataImportHandlerException(SEVERE, "Error initializing XSL ", e);
        }
    }
    if (useSolrAddXml) {
        // Support solr add documents
        xpathReader = new XPathRecordReader("/add/doc");
        xpathReader.addField("name", "/add/doc/field/@name", true);
        xpathReader.addField("value", "/add/doc/field", true);
    } else {
        String forEachXpath = context.getResolvedEntityAttribute(FOR_EACH);
        if (forEachXpath == null)
            throw new DataImportHandlerException(SEVERE, "Entity : " + context.getEntityAttribute("name") + " must have a 'forEach' attribute");
        if (forEachXpath.equals(context.getEntityAttribute(FOR_EACH)))
            reinitXPathReader = true;
        try {
            xpathReader = new XPathRecordReader(forEachXpath);
            for (Map<String, String> field : context.getAllEntityFields()) {
                if (field.get(XPATH) == null)
                    continue;
                int flags = 0;
                if ("true".equals(field.get("flatten"))) {
                    flags = XPathRecordReader.FLATTEN;
                }
                String xpath = field.get(XPATH);
                xpath = context.replaceTokens(xpath);
                //for each xml
                if (!xpath.equals(field.get(XPATH)) && !context.isRootEntity())
                    reinitXPathReader = true;
                xpathReader.addField(field.get(DataImporter.COLUMN), xpath, Boolean.parseBoolean(field.get(DataImporter.MULTI_VALUED)), flags);
            }
        } catch (RuntimeException e) {
            throw new DataImportHandlerException(SEVERE, "Exception while reading xpaths for fields", e);
        }
    }
    String url = context.getEntityAttribute(URL);
    List<String> l = url == null ? Collections.EMPTY_LIST : resolver.getVariables(url);
    for (String s : l) {
        if (s.startsWith(entityName + ".")) {
            if (placeHolderVariables == null)
                placeHolderVariables = new ArrayList<>();
            placeHolderVariables.add(s.substring(entityName.length() + 1));
        }
    }
    for (Map<String, String> fld : context.getAllEntityFields()) {
        if (fld.get(COMMON_FIELD) != null && "true".equals(fld.get(COMMON_FIELD))) {
            if (commonFields == null)
                commonFields = new ArrayList<>();
            commonFields.add(fld.get(DataImporter.COLUMN));
        }
    }
}
Also used : ResourceLoader(org.apache.lucene.analysis.util.ResourceLoader) TransformerFactory(javax.xml.transform.TransformerFactory) SolrCore(org.apache.solr.core.SolrCore) StreamSource(javax.xml.transform.stream.StreamSource) TransformerException(javax.xml.transform.TransformerException) SystemIdResolver(org.apache.solr.util.SystemIdResolver)

Example 63 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project GDSC-SMLM by aherbert.

the class BatchPeakFit method setParameters.

/**
	 * Modify the XML document using the specified values for the given parameter. For each value
	 * call the method recursively for the next parameter. If there are no more parameters
	 * then add the XML document to the xmlSettings.
	 * 
	 * @param parameters
	 *            The list of parameters
	 * @param i
	 *            Parameter to process
	 * @param doc
	 *            The XML document containing all the current parameters
	 * @param xmlSettings
	 *            A list of XML parameter settings
	 */
private void setParameters(ArrayList<ParameterSettings> parameters, int i, Document doc, ArrayList<String> xmlSettings) {
    if (i < parameters.size()) {
        ParameterSettings param = parameters.get(i);
        NodeList nodes = doc.getElementsByTagName(param.name);
        if (nodes.getLength() == 1) {
            // For each value, set the parameter and move to the next
            String[] values = param.value.split(",");
            for (String value : values) {
                Node node = nodes.item(0);
                node.setTextContent(value);
                setParameters(parameters, i + 1, doc, xmlSettings);
            }
        } else {
            // Just move to the next parameter
            setParameters(parameters, i + 1, doc, xmlSettings);
        }
    } else {
        // Add the final XML to the parameters to run
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            xmlSettings.add(writer.getBuffer().toString());
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ParameterSettings(gdsc.smlm.ij.settings.ParameterSettings) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) TransformerException(javax.xml.transform.TransformerException)

Example 64 with TransformerFactory

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

the class ModelExporter method doIt.

/**
	 * Process
	 * 
	 * @return info
	 */
protected String doIt() throws Exception {
    ExportHelper expHelper = new ExportHelper(getCtx(), p_AD_Client_ID);
    MEXPFormat exportFormat = new MEXPFormat(getCtx(), p_EXP_Format_ID, get_TrxName());
    File file = new File(p_FileName);
    Document doc = expHelper.exportRecord(exportFormat, "", MReplicationStrategy.REPLICATION_TABLE, X_AD_ReplicationTable.REPLICATIONTYPE_Merge, ModelValidator.TYPE_AFTER_CHANGE);
    // Save the document to the disk file
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    //   tranFactory.setAttribute("indent-number", 4); //Adempiere-65 change    
    Transformer aTransformer = tranFactory.newTransformer();
    aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
    Source src = new DOMSource(doc);
    // =================================== Write to String
    Writer writer = new StringWriter();
    Result dest2 = new StreamResult(writer);
    aTransformer.transform(src, dest2);
    // =================================== Write to Disk
    try {
        Result dest = new StreamResult(file);
        aTransformer.transform(src, dest);
        writer.flush();
        writer.close();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        throw ex;
    }
    return "Exported";
}
Also used : MEXPFormat(org.compiere.model.MEXPFormat) DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Document(org.w3c.dom.Document) 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 65 with TransformerFactory

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

the class TopicExportProcessor 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 protocol = null;
    String topicName = "";
    String clientID = null;
    String timeToLiveStr = null;
    int timeToLive = 10000;
    boolean isDeliveryModePersistent = true;
    // 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++) {
            log.info("ProcesParameter          Value = " + processorParameters[i].getValue());
            log.info("ProcesParameter ParameterValue = " + processorParameters[i].getParameterValue());
            if (processorParameters[i].getValue().equals("topicName")) {
                topicName = processorParameters[i].getParameterValue();
            } else if (processorParameters[i].getValue().equals("protocol")) {
                protocol = processorParameters[i].getParameterValue();
            } else if (processorParameters[i].getValue().equals("clientID")) {
                clientID = processorParameters[i].getParameterValue();
            } else if (processorParameters[i].getValue().equals("timeToLive")) {
                timeToLiveStr = processorParameters[i].getParameterValue();
                timeToLive = Integer.parseInt(timeToLiveStr);
            } else if (processorParameters[i].getValue().equals("isDeliveryModePersistent")) {
                isDeliveryModePersistent = Boolean.parseBoolean(processorParameters[i].getParameterValue());
            } else {
            // Some other mandatory parameter here
            }
        }
    }
    if (topicName == null || topicName.length() == 0) {
        throw new Exception("Missing " + X_EXP_ProcessorParameter.Table_Name + " with key 'topicName'!");
    }
    if (protocol == null || protocol.length() == 0) {
        throw new Exception("Missing " + X_EXP_ProcessorParameter.Table_Name + " with key 'protocol'!");
    }
    if (clientID == null || clientID.length() == 0) {
        throw new Exception("Missing " + X_EXP_ProcessorParameter.Table_Name + " with key 'clientID'!");
    }
    if (timeToLiveStr == null || timeToLiveStr.length() == 0) {
        throw new Exception("Missing " + X_EXP_ProcessorParameter.Table_Name + " with key 'timeToLive'!");
    }
    // Construct Transformer Factory and Transformer
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    String jVersion = System.getProperty("java.version");
    if (jVersion.startsWith("1.5.0"))
        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);
    sendJMSMessage(host, port, writer.toString(), protocol, topicName, clientID, account, password, timeToLive, isDeliveryModePersistent);
}
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) JMSException(javax.jms.JMSException) 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) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Aggregations

TransformerFactory (javax.xml.transform.TransformerFactory)257 Transformer (javax.xml.transform.Transformer)221 StreamResult (javax.xml.transform.stream.StreamResult)198 DOMSource (javax.xml.transform.dom.DOMSource)157 TransformerException (javax.xml.transform.TransformerException)86 StringWriter (java.io.StringWriter)77 StreamSource (javax.xml.transform.stream.StreamSource)77 Document (org.w3c.dom.Document)67 Source (javax.xml.transform.Source)56 IOException (java.io.IOException)55 File (java.io.File)47 DocumentBuilder (javax.xml.parsers.DocumentBuilder)43 ByteArrayOutputStream (java.io.ByteArrayOutputStream)37 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)37 Element (org.w3c.dom.Element)36 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)35 Result (javax.xml.transform.Result)32 ByteArrayInputStream (java.io.ByteArrayInputStream)29 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)29 StringReader (java.io.StringReader)28