Example usage for javax.xml.transform OutputKeys ENCODING

List of usage examples for javax.xml.transform OutputKeys ENCODING

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys ENCODING.

Prototype

String ENCODING

To view the source code for javax.xml.transform OutputKeys ENCODING.

Click Source Link

Document

encoding = string.

Usage

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createBusinessProcessforCRUD(String classname, String companyid) {
    try {/*from  w  ww  .ja v a  2 s  .  c o  m*/
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.parse(new ClassPathResource("logic/businesslogicEx.xml").getFile());
        //Document doc = docBuilder.newDocument();
        NodeList businessrules = doc.getElementsByTagName("businessrules");
        Node businessruleNode = businessrules.item(0);
        Element processEx = doc.getElementById(classname + "_addNew");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        processEx = doc.getElementById(classname + "_delete");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }
        processEx = doc.getElementById(classname + "_edit");
        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        Element process = createBasicProcessNode(doc, classname, "createNewRecord", "_addNew", "createNew");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "deleteRecord", "_delete", "deleteRec");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "editRecord", "_edit", "editRec");
        businessruleNode.appendChild(process);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/businesslogicEx.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/businesslogicEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);

    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }

}

From source file:tut.pori.javadocer.Javadocer.java

/**
 * //from ww w  . jav  a2  s. co  m
 * @throws IllegalArgumentException
 */
public Javadocer() throws IllegalArgumentException {
    _restUri = System.getProperty(PROPERTY_REST_URI);
    if (StringUtils.isBlank(_restUri)) {
        throw new IllegalArgumentException("Bad " + PROPERTY_REST_URI);
    }

    try {
        _documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        _transformer = TransformerFactory.newInstance().newTransformer();
        _transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        _transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // because of an issue with java's transformer indent, we need to add standalone attribute 
        _transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        _transformer.setOutputProperty(OutputKeys.ENCODING, CHARSET);
        _transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        _transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    } catch (ParserConfigurationException | TransformerConfigurationException
            | TransformerFactoryConfigurationError ex) {
        LOGGER.error(ex, ex);
        throw new IllegalArgumentException("Failed to create document builder/transformer instance.");
    }

    _xPath = XPathFactory.newInstance().newXPath();
    _client = HttpClients.createDefault();
}

From source file:io.fabric8.tooling.archetype.ArchetypeUtils.java

/**
 * Serializes the Document to a File./*from  w w w. j av a2s. c o m*/
 *
 * @param document
 * @param file
 * @throws IOException
 */
public void writeXmlDocument(Document document, File file) throws IOException {
    try {
        Transformer tr = transformerFactory.newTransformer();
        tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        tr.transform(new DOMSource(document), new StreamResult(fileOutputStream));
        fileOutputStream.close();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * <ul>//w ww  .  j a v  a  2 s .  c  o  m
 * <li>Strip &lt;script&gt; elements, because xml characters within these tags lead to invalid xhtml.</li>
 * <li>Xhtmlrenderer does not render form elements right (will probably support real PDF forms in the future), so we
 * need to replace select boxes with simple strings: Replace each select box with a bold string containing the
 * selected option.</li>
 * <li>Replace every input checkbox with [ ] for unchecked or [X] for checked inputs.</li>
 * </ul>
 *
 * @param xhtml
 *            xhtml as {@link Document}
 * @return
 */
private Document processDocument(final Document xhtml) {
    final String xslt = readFile(this.getClass().getResourceAsStream("adjustforpdfoutput.xslt"));
    final Source xsltSource = new StreamSource(new StringReader(xslt));
    try {
        final Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");

        final DOMResult result = new DOMResult();
        transformer.transform(new DOMSource(xhtml), result);
        return (Document) result.getNode();
    } catch (final TransformerConfigurationException e) {
        log.error("Internal: Wrong xslt configuration", e);
    } catch (final TransformerFactoryConfigurationError e) {
        log.error("Internal: Wrong xslt configuration", e);
    } catch (final TransformerException e) {
        log.error("Internal: Could not strip script tags from xhtml", e);
        e.printStackTrace();
    }
    // fall through in error case: return untransformed xhtml
    log.warn("Could not clean up html, using orginial instead. This might lead to missing content!");
    return xhtml;
}

From source file:io.fabric8.tooling.archetype.builder.ArchetypeHelper.java

/**
 * Serializes the Document to a File.//from   ww  w .  j  a  va  2  s  .co m
 *
 * @param document
 * @param file
 * @throws IOException
 */
protected void writeXmlDocument(Document document, File file) throws IOException {
    try {
        Transformer tr = transformerFactory.newTransformer();
        tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        tr.transform(new DOMSource(document), new StreamResult(fileOutputStream));
        fileOutputStream.close();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:com.action.ExportAction.java

public File exportXMLAction(File file) throws Exception {
    //document/*  w ww  .  ja  v a  2s .c o  m*/
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();
    Element reportsElement = document.createElement("reports");//
    reportsElement.setAttribute("date", (new Date()).toString());
    document.appendChild(reportsElement);
    System.out.println("exportXMLAction:" + tableCode);
    String[] ids = tableCode.split(",");
    for (String id : ids) {
        System.out.println("id:" + id);
        List<JQ_zhibiao_entity> list = Export.getDuizhaoByJqTbCode(id);
        document = Export.exportXML(reportsElement, document, list, id);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    PrintWriter pw = new PrintWriter(new FileOutputStream(file));
    StreamResult result = new StreamResult(pw);
    transformer.transform(source, result);
    pw.close();
    return file;
}

From source file:ca.uviccscu.lp.utils.Utils.java

public static String documentToString(Document d)
        throws TransformerConfigurationException, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(d);
    transformer.transform(source, result);
    String str = result.getWriter().toString();
    return str;/*from   w  ww. ja  va 2  s  .  com*/
}

From source file:com.seajas.search.attender.service.template.TemplateService.java

/**
 * Create a results template result.//from  w ww . j  a  v  a2 s  . c om
 * 
 * @param language
 * @param queryString
 * @param query
 * @param uuid
 * @param searchResults
 * @return TemplateResult
 */
public TemplateResult createResults(final String language, final String queryString, final String query,
        final String subscriberUUID, final String profileUUID, final List<SearchResult> searchResults)
        throws ScriptException {
    Template template = templateDAO.findTemplate(TemplateType.Results, language);

    if (template == null) {
        logger.warn("Could not retrieve results template for language " + language
                + " - falling back to default language " + attenderService.getDefaultApplicationLanguage());

        template = templateDAO.findTemplate(TemplateType.Confirmation,
                attenderService.getDefaultApplicationLanguage());

        if (template == null) {
            logger.error("Could not retrieve fall-back results template for language "
                    + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

            return null;
        }
    }

    // Create an input document

    Document document;

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        documentBuilderFactory.setCoalescing(true);
        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        document = documentBuilder.newDocument();

        Element results = document.createElement("results");

        results.setAttribute("templateLanguage", language);
        results.setAttribute("profileQuery", query);
        results.setAttribute("subscriberUUID", subscriberUUID);
        results.setAttribute("profileUUID", profileUUID);
        results.setAttribute("queryString", queryString);

        for (SearchResult searchResult : searchResults)
            results.appendChild(searchResult.toElement(document));

        document.appendChild(results);

        // Plain text

        Transformer textTransformer = getTransformer(template, true);
        StringWriter textWriter = new StringWriter();

        textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        textTransformer.transform(new DOMSource(document), new StreamResult(textWriter));

        // HTML

        Transformer htmlTransformer = getTransformer(template, false);
        StringWriter htmlWriter = new StringWriter();

        htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        htmlTransformer.transform(new DOMSource(document), new StreamResult(htmlWriter));

        return new TemplateResult(textWriter.toString(), htmlWriter.toString());
    } catch (ScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java

/**
 * execute DML//  w  w w.j  ava2  s  . c  o m
 * 
 * @param userDB
 * @param strQuery
 * @param listParam
 * @param resultType
 * @throws Exception
 */
public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam,
        final String resultType) throws Exception {
    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    Object effectObject = runSQLOther(userDB, strQuery, listParam);

    String strReturn = "";
    if (resultType.equals(RESULT_TYPE.CSV.name())) {
        final StringWriter stWriter = new StringWriter();
        CSVWriter csvWriter = new CSVWriter(stWriter, ',');

        String[] arryString = new String[2];
        arryString[0] = "effectrow";
        arryString[1] = String.valueOf(effectObject);
        csvWriter.writeNext(arryString);

        strReturn = stWriter.toString();
    } else if (resultType.equals(RESULT_TYPE.JSON.name())) {
        final JsonArray jsonArry = new JsonArray();
        JsonObject jsonObj = new JsonObject();
        jsonObj.addProperty("effectrow", String.valueOf(effectObject));
        jsonArry.add(jsonObj);

        strReturn = JSONUtil.getPretty(jsonArry.toString());
    } else {//if(resultType.equals(RESULT_TYPE.XML.name())) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.newDocument();
        final Element results = doc.createElement("Results");
        doc.appendChild(results);

        Element row = doc.createElement("Row");
        results.appendChild(row);
        Element node = doc.createElement("effectrow");
        node.appendChild(doc.createTextNode(String.valueOf(effectObject)));
        row.appendChild(node);

        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", 4);

        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        final StringWriter stWriter = new StringWriter();
        StreamResult sr = new StreamResult(stWriter);
        transformer.transform(domSource, sr);

        strReturn = stWriter.toString();
    }

    return strReturn;
}

From source file:dicoogle.ua.dim.DIMGeneric.java

public String getXML() {

    StringWriter writer = new StringWriter();

    StreamResult streamResult = new StreamResult(writer);
    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
    //      SAX2.0 ContentHandler.
    TransformerHandler hd = null;
    try {/* w  ww . ja va  2 s  . c om*/
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(DIMGeneric.class.getName()).log(Level.SEVERE, null, ex);
    }
    Transformer serializer = hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.METHOD, "xml");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    hd.setResult(streamResult);
    try {
        hd.startDocument();

        AttributesImpl atts = new AttributesImpl();
        hd.startElement("", "", "DIM", atts);

        for (Patient p : this.patients) {
            atts.clear();
            atts.addAttribute("", "", "name", "", p.getPatientName().trim());
            atts.addAttribute("", "", "id", "", p.getPatientID().trim());
            hd.startElement("", "", "Patient", atts);

            for (Study s : p.getStudies()) {
                atts.clear();
                atts.addAttribute("", "", "date", "", s.getStudyData().trim());
                atts.addAttribute("", "", "id", "", s.getStudyInstanceUID().trim());

                hd.startElement("", "", "Study", atts);

                for (Serie serie : s.getSeries()) {
                    atts.clear();
                    atts.addAttribute("", "", "modality", "", serie.getModality().trim());
                    atts.addAttribute("", "", "id", "", serie.getSerieInstanceUID().trim());

                    hd.startElement("", "", "Serie", atts);

                    ArrayList<URI> img = serie.getImageList();
                    ArrayList<String> uid = serie.getSOPInstanceUIDList();
                    int size = img.size();
                    for (int i = 0; i < size; i++) {
                        atts.clear();
                        atts.addAttribute("", "", "path", "", img.get(i).toString().trim());
                        atts.addAttribute("", "", "uid", "", uid.get(i).trim());

                        hd.startElement("", "", "Image", atts);
                        hd.endElement("", "", "Image");
                    }
                    hd.endElement("", "", "Serie");
                }
                hd.endElement("", "", "Study");
            }
            hd.endElement("", "", "Patient");
        }
        hd.endElement("", "", "DIM");

    } catch (SAXException ex) {
        Logger.getLogger(DIMGeneric.class.getName()).log(Level.SEVERE, null, ex);
    }

    return writer.toString();
}