Example usage for org.dom4j Document setXMLEncoding

List of usage examples for org.dom4j Document setXMLEncoding

Introduction

In this page you can find the example usage for org.dom4j Document setXMLEncoding.

Prototype

void setXMLEncoding(String encoding);

Source Link

Document

Sets the encoding of this document as it will appear in the XML declaration part of the document.

Usage

From source file:org.pentaho.platform.util.xml.dom4j.XmlDom4JHelper.java

License:Open Source License

public static void saveDom(final Document doc, final OutputStream outputStream, String encoding,
        boolean suppressDeclaration, boolean prettyPrint) throws IOException {
    OutputFormat format = prettyPrint ? OutputFormat.createPrettyPrint() : OutputFormat.createCompactFormat();
    format.setSuppressDeclaration(suppressDeclaration);
    if (encoding != null) {
        format.setEncoding(encoding.toLowerCase());
        if (!suppressDeclaration) {
            doc.setXMLEncoding(encoding.toUpperCase());
        }/*from   w w w.j  a  va2  s  .co m*/
    }
    XMLWriter writer = new XMLWriter(outputStream, format);
    writer.write(doc);
    writer.flush();
}

From source file:org.pentaho.platform.web.servlet.AdhocWebService.java

License:Open Source License

public ByteArrayOutputStream createMQLReportActionSequenceAsStream(final String reportName,
        final String reportDescription, final Element mqlNode, final String[] outputTypeList,
        final String xactionName, final String jfreeReportXML, final String jfreeReportFilename,
        final String loggingLevel, final IPentahoSession userSession)
        throws IOException, AdhocWebServiceException {

    boolean bIsMultipleOutputType = outputTypeList.length > 1;

    Document document = DOMDocumentFactory.getInstance().createDocument();
    document.setXMLEncoding(LocaleHelper.getSystemEncoding());
    Element actionSeqElement = document.addElement("action-sequence"); //$NON-NLS-1$
    Element actionSeqNameElement = actionSeqElement.addElement("name"); //$NON-NLS-1$
    actionSeqNameElement.setText(xactionName);
    Element actionSeqVersionElement = actionSeqElement.addElement("version"); //$NON-NLS-1$
    actionSeqVersionElement.setText("1"); //$NON-NLS-1$

    Element actionSeqTitleElement = actionSeqElement.addElement("title"); //$NON-NLS-1$
    String reportTitle = AdhocWebService.getBaseFilename(reportName); // remove ".waqr.xreportspec" if it is there
    actionSeqTitleElement.setText(reportTitle);

    Element loggingLevelElement = actionSeqElement.addElement("logging-level"); //$NON-NLS-1$
    loggingLevelElement.setText(loggingLevel);

    Element documentationElement = actionSeqElement.addElement("documentation"); //$NON-NLS-1$
    Element authorElement = documentationElement.addElement("author"); //$NON-NLS-1$
    if (userSession.getName() != null) {
        authorElement.setText(userSession.getName());
    } else {//  w  w  w.  j  av a  2 s  .  com
        authorElement.setText("Web Query & Reporting"); //$NON-NLS-1$
    }
    Element descElement = documentationElement.addElement("description"); //$NON-NLS-1$
    descElement.setText(reportDescription);
    Element iconElement = documentationElement.addElement("icon"); //$NON-NLS-1$
    iconElement.setText("PentahoReporting.png"); //$NON-NLS-1$
    Element helpElement = documentationElement.addElement("help"); //$NON-NLS-1$
    helpElement.setText("Auto-generated action-sequence for WAQR."); //$NON-NLS-1$
    Element resultTypeElement = documentationElement.addElement("result-type"); //$NON-NLS-1$
    resultTypeElement.setText("report"); //$NON-NLS-1$
    // inputs
    Element inputsElement = actionSeqElement.addElement("inputs"); //$NON-NLS-1$
    Element outputTypeElement = inputsElement.addElement("output-type"); //$NON-NLS-1$
    outputTypeElement.addAttribute("type", "string"); //$NON-NLS-1$ //$NON-NLS-2$
    Element defaultValueElement = outputTypeElement.addElement("default-value"); //$NON-NLS-1$
    defaultValueElement.setText(outputTypeList[0]);
    Element sourcesElement = outputTypeElement.addElement("sources"); //$NON-NLS-1$
    Element requestElement = sourcesElement.addElement(HttpRequestParameterProvider.SCOPE_REQUEST);
    requestElement.setText("type"); //$NON-NLS-1$

    if (bIsMultipleOutputType) {
        // define list of report output-file extensions (html, pdf, xls, csv)
        /*
         * <mimeTypes type="string-list"> <sources> <request>mimeTypes</request> </sources> <default-value type="string-list"> <list-item>html</list-item> <list-item>pdf</list-item> <list-item>xls</list-item> <list-item>csv</list-item>
         * </default-value> </mimeTypes>
         */
        Element mimeTypes = inputsElement.addElement("mimeTypes");//$NON-NLS-1$ 
        mimeTypes.addAttribute("type", "string-list"); //$NON-NLS-1$ //$NON-NLS-2$
        Element sources = mimeTypes.addElement("sources");//$NON-NLS-1$ 
        requestElement = sources.addElement("request"); //$NON-NLS-1$
        requestElement.setText("mimeTypes"); //$NON-NLS-1$
        Element defaultValue = mimeTypes.addElement("default-value"); //$NON-NLS-1$
        defaultValue.addAttribute("type", "string-list"); //$NON-NLS-1$ //$NON-NLS-2$
        //$NON-NLS-1$
        Element listItem = null;
        for (String outputType : outputTypeList) {
            listItem = defaultValue.addElement("list-item"); //$NON-NLS-1$
            listItem.setText(outputType);
        }
    }

    // outputs
    Element outputsElement = actionSeqElement.addElement("outputs"); //$NON-NLS-1$
    Element reportTypeElement = outputsElement.addElement("report"); //$NON-NLS-1$
    reportTypeElement.addAttribute("type", "content"); //$NON-NLS-1$ //$NON-NLS-2$
    Element destinationsElement = reportTypeElement.addElement("destinations"); //$NON-NLS-1$
    Element responseElement = destinationsElement.addElement("response"); //$NON-NLS-1$
    responseElement.setText("content"); //$NON-NLS-1$
    // resources
    Element resourcesElement = actionSeqElement.addElement("resources"); //$NON-NLS-1$
    Element reportDefinitionElement = resourcesElement.addElement("report-definition"); //$NON-NLS-1$

    Element solutionFileElement = null;
    if (null == jfreeReportFilename) {
        // likely they are running a preview
        solutionFileElement = reportDefinitionElement.addElement("xml"); //$NON-NLS-1$
        Element locationElement = solutionFileElement.addElement("location"); //$NON-NLS-1$ 
        Document jfreeReportDoc = null;
        try {
            jfreeReportDoc = XmlDom4JHelper.getDocFromString(jfreeReportXML, new PentahoEntityResolver());
        } catch (XmlParseException e) {
            String msg = Messages.getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
            error(msg, e);
            throw new AdhocWebServiceException(msg, e);
        }

        Node reportNode = jfreeReportDoc.selectSingleNode("/report"); //$NON-NLS-1$
        locationElement.add(reportNode);
    } else {
        // likely they are saving the report
        solutionFileElement = reportDefinitionElement.addElement("solution-file"); //$NON-NLS-1$
        Element locationElement = solutionFileElement.addElement("location"); //$NON-NLS-1$
        locationElement.setText(jfreeReportFilename);
    }

    Element mimeTypeElement = solutionFileElement.addElement("mime-type"); //$NON-NLS-1$
    mimeTypeElement.setText("text/xml"); //$NON-NLS-1$
    Element actionsElement = actionSeqElement.addElement("actions"); //$NON-NLS-1$
    Element actionDefinitionElement = null;
    if (bIsMultipleOutputType) // do secure filter
    {
        // begin action-definition for Secure Filter
        /*
         * <action-definition> <component-name>SecureFilterComponent</component-name> <action-type>Prompt/Secure Filter</action-type> <action-inputs> <output-type type="string"/> <mimeTypes type="string-list"/> </action-inputs>
         * <component-definition> <selections> <output-type prompt-if-one-value="true"> <title>Select output type:</title> <filter>mimeTypes</filter> </output-type> </selections> </component-definition> </action-definition>
         */
        actionDefinitionElement = actionsElement.addElement("action-definition"); //$NON-NLS-1$
        Element componentName = actionDefinitionElement.addElement("component-name"); //$NON-NLS-1$
        componentName.setText("SecureFilterComponent"); //$NON-NLS-1$
        Element actionType = actionDefinitionElement.addElement("action-type"); //$NON-NLS-1$
        actionType.setText("Prompt/Secure Filter"); //$NON-NLS-1$

        Element actionInputs = actionDefinitionElement.addElement("action-inputs"); //$NON-NLS-1$
        Element outputType = actionInputs.addElement("output-type"); //$NON-NLS-1$
        outputType.addAttribute("type", "string"); //$NON-NLS-1$ //$NON-NLS-2$
        Element mimeTypes = actionInputs.addElement("mimeTypes"); //$NON-NLS-1$
        mimeTypes.addAttribute("type", "string-list"); //$NON-NLS-1$ //$NON-NLS-2$

        Element componentDefinition = actionDefinitionElement.addElement("component-definition"); //$NON-NLS-1$
        Element selections = componentDefinition.addElement("selections"); //$NON-NLS-1$
        outputType = selections.addElement("output-type"); //$NON-NLS-1$
        outputType.addAttribute("prompt-if-one-value", "true"); //$NON-NLS-1$ //$NON-NLS-2$
        Element title = outputType.addElement("title"); //$NON-NLS-1$
        String prompt = Messages.getString("AdhocWebService.SELECT_OUTPUT_TYPE");//$NON-NLS-1$
        title.setText(prompt);
        Element filter = outputType.addElement("filter"); //$NON-NLS-1$
        filter.setText("mimeTypes"); //$NON-NLS-1$
    }

    // begin action-definition for SQLLookupRule
    actionDefinitionElement = actionsElement.addElement("action-definition"); //$NON-NLS-1$
    Element actionOutputsElement = actionDefinitionElement.addElement("action-outputs"); //$NON-NLS-1$
    Element ruleResultElement = actionOutputsElement.addElement("rule-result"); //$NON-NLS-1$
    ruleResultElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    Element componentNameElement = actionDefinitionElement.addElement("component-name"); //$NON-NLS-1$
    componentNameElement.setText("MQLRelationalDataComponent"); //$NON-NLS-1$
    Element actionTypeElement = actionDefinitionElement.addElement("action-type"); //$NON-NLS-1$
    actionTypeElement.setText("rule"); //$NON-NLS-1$
    Element componentDefinitionElement = actionDefinitionElement.addElement("component-definition"); //$NON-NLS-1$
    componentDefinitionElement.add(mqlNode);
    componentDefinitionElement.addElement("live").setText("true"); //$NON-NLS-1$ //$NON-NLS-2$
    componentDefinitionElement.addElement("display-names").setText("false"); //$NON-NLS-1$ //$NON-NLS-2$

    // log SQL flag
    if ("true".equals(PentahoSystem.getSystemSetting("adhoc-preview-log-sql", "false"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        componentDefinitionElement.addElement("logSql").addCDATA("true"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // end action-definition for SQLLookupRule
    // begin action-definition for JFreeReportComponent
    actionDefinitionElement = actionsElement.addElement("action-definition"); //$NON-NLS-1$
    actionOutputsElement = actionDefinitionElement.addElement("action-outputs"); //$NON-NLS-1$

    Element actionInputsElement = actionDefinitionElement.addElement("action-inputs"); //$NON-NLS-1$
    outputTypeElement = actionInputsElement.addElement("output-type"); //$NON-NLS-1$
    outputTypeElement.addAttribute("type", "string"); //$NON-NLS-1$ //$NON-NLS-2$
    Element dataElement = actionInputsElement.addElement("data"); //$NON-NLS-1$

    Element actionResourcesElement = actionDefinitionElement.addElement("action-resources"); //$NON-NLS-1$
    Element reportDefinition = actionResourcesElement.addElement("report-definition"); //$NON-NLS-1$
    reportDefinition.addAttribute("type", "resource"); //$NON-NLS-1$ //$NON-NLS-2$

    dataElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    dataElement.addAttribute("mapping", "rule-result"); //$NON-NLS-1$ //$NON-NLS-2$
    Element reportOutputElement = actionOutputsElement.addElement("report"); //$NON-NLS-1$
    reportOutputElement.addAttribute("type", "content"); //$NON-NLS-1$ //$NON-NLS-2$
    componentNameElement = actionDefinitionElement.addElement("component-name"); //$NON-NLS-1$
    componentNameElement.setText("JFreeReportComponent"); //$NON-NLS-1$
    actionTypeElement = actionDefinitionElement.addElement("action-type"); //$NON-NLS-1$
    actionTypeElement.setText("report"); //$NON-NLS-1$
    componentDefinitionElement = actionDefinitionElement.addElement("component-definition"); //$NON-NLS-1$
    componentDefinitionElement.addElement("output-type").setText(outputTypeList[0]); //$NON-NLS-1$

    Document tmp = customizeActionSequenceDocument(document);
    if (tmp != null) {
        document = tmp;
    }
    return exportDocumentAsByteArrayOutputStream(document);
}

From source file:org.pentaho.platform.web.servlet.AdhocWebService.java

License:Open Source License

public void searchTable(final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final boolean wrapWithSoap) throws IOException {
    String domainId = (String) parameterProvider.getParameter("modelId"); //$NON-NLS-1$
    String modelId = (String) parameterProvider.getParameter("viewId"); //$NON-NLS-1$
    String tableId = (String) parameterProvider.getParameter("tableId"); //$NON-NLS-1$
    String columnId = (String) parameterProvider.getParameter("columnId"); //$NON-NLS-1$
    String searchStr = (String) parameterProvider.getParameter("searchStr"); //$NON-NLS-1$

    ByteArrayOutputStream xactionOutputStream = new ByteArrayOutputStream();
    createMQLQueryActionSequence(domainId, modelId, tableId, columnId, searchStr, xactionOutputStream,
            userSession.getName());//from   w  w w .  j a  va  2s. c  o m
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding(LocaleHelper.getSystemEncoding());
    Element resultsElement = document.addElement("results"); //$NON-NLS-1$

    IRuntimeContext runtimeContext = AdhocWebService.executeActionSequence(
            xactionOutputStream.toString(LocaleHelper.getSystemEncoding()), "mqlQuery.xaction", //$NON-NLS-1$
            new SimpleParameterProvider(), userSession, new ByteArrayOutputStream());
    if (runtimeContext.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS) {
        IActionParameter actionParameter = runtimeContext.getOutputParameter("query_result"); //$NON-NLS-1$
        IPentahoResultSet pentahoResultSet = actionParameter.getValueAsResultSet();
        TreeSet treeSet = new TreeSet();
        for (int i = 0; i < pentahoResultSet.getRowCount(); i++) {
            Object[] rowValues = pentahoResultSet.getDataRow(i);
            if (rowValues[0] != null) {
                treeSet.add(rowValues[0]);
            }
        }
        for (Iterator iterator = treeSet.iterator(); iterator.hasNext();) {
            resultsElement.addElement("row").setText(iterator.next().toString()); //$NON-NLS-1$
        }
        runtimeContext.dispose();
    }
    WebServiceUtil.writeString(outputStream, document.asXML(), wrapWithSoap);
}

From source file:org.pentaho.platform.web.servlet.AdhocWebService.java

License:Open Source License

private Document getWaqrRepositoryDoc(final String folderPath, final IPentahoSession userSession)
        throws AdhocWebServiceException {

    if ((folderPath != null && StringUtil.doesPathContainParentPathSegment(folderPath))) {
        String msg = Messages.getString("AdhocWebService.ERROR_0011_FAILED_TO_LOCATE_PATH", folderPath); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }/* w  w w .jav a 2 s  . c  o m*/
    String solutionRepositoryName = AdhocWebService.getSolutionRepositoryName(userSession);

    String path = "/" + solutionRepositoryName + AdhocWebService.WAQR_REPOSITORY_PATH; //$NON-NLS-1$
    if ((folderPath != null) && (!folderPath.equals("/"))) { //$NON-NLS-1$
        path += folderPath;
    }

    Document fullDoc = getWaqrTemplates(userSession, path);

    Element folderElement = AdhocWebService.getFolderElement(fullDoc, path);
    Document systemDoc = null;
    if (folderElement != null) {
        Element clonedFolderElement = (Element) folderElement.clone();
        AdhocWebService.removeChildElements(clonedFolderElement);
        systemDoc = DocumentHelper.createDocument((Element) clonedFolderElement.detach());
        systemDoc.setXMLEncoding(LocaleHelper.getSystemEncoding());
    } else {
        String msg = Messages.getString("AdhocWebService.ERROR_0011_FAILED_TO_LOCATE_PATH", folderPath); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }
    return systemDoc;
}

From source file:org.rundeck.api.parser.ParserHelper.java

License:Apache License

/**
 * Load an XML {@link Document} from the given {@link InputStream}
 * /*  ww w  .  j a va  2 s .  c  o  m*/
 * @param inputStream from an API call to Rundeck
 * @return an XML {@link Document}
 * @throws RundeckApiException if we failed to read the response, or if the response is an error
 */
public static Document loadDocument(InputStream inputStream) throws RundeckApiException {
    SAXReader reader = new SAXReader();
    reader.setEncoding("UTF-8");

    Document document;
    try {
        document = reader.read(inputStream);
    } catch (DocumentException e) {
        throw new RundeckApiException("Failed to read Rundeck response", e);
    }
    document.setXMLEncoding("UTF-8");

    Node result = document.selectSingleNode("result");
    if (result != null) {
        Boolean failure = Boolean.valueOf(result.valueOf("@error"));
        if (failure) {
            throw new RundeckApiException(result.valueOf("error/message"));
        }
    }

    return document;
}

From source file:pt.webdetails.cda.exporter.HtmlExporter.java

License:Open Source License

@Override
public void export(OutputStream out, TableModel tableModel) throws ExporterException {
    final Document document = DocumentHelper.createDocument();
    Element table = null;/*  ww w .  j  av  a2 s . c o  m*/

    if (fullHtml) {
        final Element html = document.addElement("html");
        final Element head = html.addElement("head");
        head.addElement("title").addText(title);
        table = html.addElement("body").addElement("table");
    } else {
        table = document.addElement("table");
    }

    final int columnCount = tableModel.getColumnCount();

    //table headers
    final Element headerRow = table.addElement("tr");
    for (int i = 0; i < columnCount; i++) {
        String colName = tableModel.getColumnName(i);
        headerRow.addElement("th").addText(colName);
    }

    //table body
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        Element row = table.addElement("tr");

        for (int j = 0; j < columnCount; j++) {
            Element tableCell = row.addElement("td");
            Object value = tableModel.getValueAt(i, j);
            tableCell.setText(valueToText(value));

            if (value instanceof Date) {
                tableCell.setText(format.format(value));
            } else if (value != null) {
                // numbers can be safely converted via toString, as they use a well-defined format there
                tableCell.setText(value.toString());
            }

        }
    }

    try {
        document.setXMLEncoding("UTF-8");

        OutputFormat outFormat = new OutputFormat();
        outFormat.setOmitEncoding(true);
        outFormat.setSuppressDeclaration(true);//otherwise msexcel/oocalc may not recognize content
        outFormat.setNewlines(true);
        outFormat.setIndentSize(columnCount);
        final Writer writer = new BufferedWriter(new OutputStreamWriter(out));
        XMLWriter xmlWriter = new XMLWriter(writer, outFormat);
        xmlWriter.write(document);
        xmlWriter.flush();
    } catch (IOException e) {
        throw new ExporterException("IO Exception converting to utf-8", e);
    }
}

From source file:pt.webdetails.cda.exporter.XmlExporter.java

License:Open Source License

public void export(final OutputStream out, final TableModel tableModel) throws ExporterException {

    final Document document = DocumentHelper.createDocument();

    // Generate metadata

    final Element root = document.addElement("CdaExport");

    final Element metadata = root.addElement("MetaData");

    final int columnCount = tableModel.getColumnCount();
    final int rowCount = tableModel.getRowCount();

    for (int i = 0; i < columnCount; i++) {
        final Element columnInfo = metadata.addElement("ColumnMetaData");
        columnInfo.addAttribute("index", (String.valueOf(i)));
        columnInfo.addAttribute("type", getColType(tableModel.getColumnClass(i)));
        columnInfo.addAttribute("name", tableModel.getColumnName(i));

    }//  w  w w .  ja v a 2  s . com

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
    final Element resultSet = root.addElement("ResultSet");
    for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) {

        final Element row = resultSet.addElement("Row");

        for (int colIdx = 0; colIdx < columnCount; colIdx++) {
            final Element col = row.addElement("Col");

            final Object value = tableModel.getValueAt(rowIdx, colIdx);
            if (value instanceof Date) {
                col.setText(format.format(value));
            } else if (value != null) {
                // numbers can be safely converted via toString, as they use a well-defined format there
                col.setText(value.toString());
            } else {
                col.addAttribute("isNull", "true");
            }

        }
    }

    try {
        final Writer writer = new BufferedWriter(new OutputStreamWriter(out));

        document.setXMLEncoding("UTF-8");
        document.write(writer);
        writer.flush();
    } catch (IOException e) {
        throw new ExporterException("IO Exception converting to utf-8", e);
    }

}

From source file:routines.system.BigDataParserUtils.java

License:Open Source License

public static routines.system.Document parseTo_Document(String s, boolean ignoreDTD, String encoding)
        throws org.dom4j.DocumentException {
    if (isBlank(s)) {
        return null;
    }//from w  w  w  .  j  av  a 2s. c  o m
    routines.system.Document theDoc = new routines.system.Document();
    org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();

    if (ignoreDTD) {
        reader.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new org.xml.sax.InputSource(
                        new java.io.ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
            }
        });
    }

    org.dom4j.Document document = reader.read(new java.io.StringReader(s));
    if (encoding != null && !("".equals(encoding))) {
        document.setXMLEncoding(encoding);
    }
    theDoc.setDocument(document);
    return theDoc;
}