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.gbif.harvest.digir.DigirMetadataHandler.java

License:Open Source License

/**
 * Parse the response file and write the parsed values to their
 * appropriate file.//w  w w  .  j  ava2 s  .  c  o m
 *
 * @param inputStream representing harvested xml response
 *
 * @throws DocumentException thrown if parsing error occurred
 * @throws IOException       thrown
 */
private void parseResponseFile(ByteArrayInputStream inputStream) throws DocumentException, IOException {

    // create a DOM4J tree, reading a Document from the given File
    SAXReader reader = new SAXReader();
    reader.setEncoding("UTF-8");
    Document document = reader.read(inputStream);
    document.setXMLEncoding("UTF-8");

    // get all resource Elements
    List<Node> resourceEntities = (metadataRepeatingElementsXpath.get(resourceEntityRepeatingElementName))
            .selectNodes(document);
    // iterate over resource Elements
    for (Node resourceEntity : resourceEntities) {

        // Detatch resource Element and create new Document with it
        DefaultDocument doc1 = new DefaultDocument();
        doc1.setRootElement((Element) resourceEntity.detach());

        // get all resource contact Elements
        List<Node> resourceContacts = (metadataRepeatingElementsXpath.get(contactEntityRepeatingElementName))
                .selectNodes(doc1);
        // iterate over contact Elements
        for (Node resourceContact : resourceContacts) {

            // Detatch relatedEntity Element and create new Document with it
            DefaultDocument doc2 = new DefaultDocument();
            doc2.setRootElement((Element) resourceContact.detach());

            // write hasContact elements-of-interest to file
            fileUtils.writeValuesToFile(resourceContactsBW, metadataResourceContactElementsOfInterest.values(),
                    doc2, namespaceMap, String.valueOf(getLineNumber()));
        }
        // write relatedEntity elements-of-interest to file
        fileUtils.writeValuesToFile(resourcesBW, metadataElementsOfInterest.values(), doc1, namespaceMap,
                String.valueOf(getLineNumber()));

        setLineNumber(getLineNumber() + 1);
    }
}

From source file:org.gbif.harvest.tapir.TapirMetadataHandler.java

License:Open Source License

/**
 * Parse the response file and write the parsed values to their
 * appropriate file.//ww w. j a va 2  s. c  om
 *
 * @param stream file representing harvested xml response as ByteArrayInputStream
 *
 * @throws DocumentException thrown if parsing errors occur
 * @throws IOException       thrown
 */
private void parseResponseFile(ByteArrayInputStream stream) throws DocumentException, IOException {

    // create a DOM4J tree, reading a Document from the given File
    SAXReader reader = new SAXReader();
    reader.setEncoding("UTF-8");
    Document document = reader.read(stream);
    document.setXMLEncoding("UTF-8");

    // get all relatedEntity Elements
    List<Node> relatedEntities = (metadataRepeatingElementsXpath.get(RELATEDENTITY_REPEATING_ELEMENT_NAME))
            .selectNodes(document);
    // iterate over dataset Elements
    for (Node relatedEntity : relatedEntities) {

        // Detatch relatedEntity Element and create new Document with it
        DefaultDocument doc1 = new DefaultDocument();
        doc1.setRootElement((Element) relatedEntity.detach());

        // get all hasContact Elements
        List<Node> hasContacts = (metadataRepeatingElementsXpath.get(HASCONTACT_REPEATING_ELEMENT_NAME))
                .selectNodes(doc1);
        // iterate over hasContact Elements
        for (Node hasContact : hasContacts) {

            // Detatch relatedEntity Element and create new Document with it
            DefaultDocument doc2 = new DefaultDocument();
            doc2.setRootElement((Element) hasContact.detach());

            // write hasContact elements-of-interest to file
            fileUtils.writeValuesToFile(hasContactBW, harvestedHasContactElementsOfInterest.values(), doc2,
                    namespaceMap, String.valueOf(getLineNumber()));
        }
        // write relatedEntity elements-of-interest to file
        fileUtils.writeValuesToFile(relatedEntityBW, harvestedRelatedEntityElementsOfInterest.values(), doc1,
                namespaceMap, String.valueOf(getLineNumber()));

        setLineNumber(getLineNumber() + 1);
    }
}

From source file:org.openadaptor.auxil.convertor.xml.OrderedMapToXmlConvertor.java

License:Open Source License

/**
 * Performs the actual conversion. Will recursively add each element of the map as
 * //  www.  j a  v a  2 s  .c o  m
 * @param map
 *          the map to be converted
 * @param returnAsString
 *          if true then the Dom4j Document is returned
 * 
 * @return the xml (or Dom4j Document) corresponding to the supplied OrderedMap
 * 
 * @throws RecordException
 *           if the conversion fails
 */
private Object convertOrderedMapToXml(IOrderedMap map, boolean returnAsString) throws RecordException {
    Object result = null;

    // Create a Document to hold the data.
    Document doc = DocumentHelper.createDocument();
    if (encoding != null) {
        // Doesn't seem to have any effect here, so output formatter also sets it
        doc.setXMLEncoding(encoding);
        log.debug("Document encoding now " + doc.getXMLEncoding());
    }

    String rootTag = rootElementTag;

    if (rootTag != null) {
        log.debug("Using Supplied root tag - unset rootElementTag property to disable");
    } else { // Try and derive it. Must have a single entry, whose value is itself an OM.
        log.debug("rootElementTag property is not set. Deriving root tag from data.");
        if (map.size() == 1) { // Might be able to derive root tag.
            Object rootTagObject = map.keys().get(0);
            rootTag = rootTagObject == null ? null : rootTagObject.toString();
            Object value = map.get(rootTag);
            if (value instanceof IOrderedMap) { // Bingo we're in.
                log.debug(
                        "Deriving rootElementTag property from map (set rootElementTag property explicitly to prevent this");
                map = (IOrderedMap) value; // Move down a level as we're adding it here.
            } else {// No go -be safe and add our own root.
                log.warn("Failed to derive root tag. Using default of "
                        + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG);
                rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG;
            }
        } else {// More than one top level entry. Give up and default.
            log.warn("Top level has more than one entry. Using default of "
                    + OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG);
            rootTag = OrderedMapToXmlConvertor.DEFAULT_ROOT_ELEMENT_TAG;
        }
    }
    //Fix for #SC35: OrderedMapToXmlConvertor should, but does not map slashes in the root tag 
    rootTag = generateElementName(rootTag);
    log.debug("Document root tag will be: " + rootTag);

    // Prime the root tag.
    Element root = doc.addElement(rootTag);

    Iterator it = map.keys().iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        Object value = map.get(key);
        addElement(root, key, value);
    }
    // document done. Phew.
    if (returnAsString) { // Darn, need to output the Document as a String.
        StringWriter sw = new StringWriter();
        OutputFormat outputFormat = OutputFormat.createCompactFormat();
        if (encoding != null) {
            log.debug("Output Format encoding as " + encoding);
            outputFormat.setEncoding(encoding); // This definitely sets it in the header!
        }
        //    outputFormat.setOmitEncoding(true);
        //    outputFormat.setSuppressDeclaration(true);
        XMLWriter writer = new XMLWriter(sw, outputFormat);
        try {
            writer.write(doc);
        } catch (IOException ioe) {
            log.warn("Failed to write the XML as a String");
            throw new RecordFormatException("Failed to write the XML as a String. Reason: " + ioe.toString(),
                    ioe);
        }
        result = sw.toString();
    } else {
        result = doc;
    }
    return result;
}

From source file:org.pentaho.jfreereport.wizard.utility.report.ReportGenerationUtility.java

License:Open Source License

/**
 * From the report description in the <param>reportSpec</param> parameter, create 
 * a JFree Report report definition in XML format, and return the XML via
 * the <param>outputStream</param> parameter.
 * /* w w  w. j a  va2  s.  com*/
 * @param reportSpec
 * @param outputStream
 * @param encoding
 * @param pageWidth
 * @param pageHeight
 * @param createTotalColumn
 * @param totalColumnName
 * @param totalColumnWidth
 * @param spacerWidth
 */
public static void createJFreeReportXML(ReportSpec reportSpec, OutputStream outputStream, String encoding,
        int pageWidth, int pageHeight, boolean createTotalColumn, String totalColumnName, int totalColumnWidth,
        int spacerWidth) {

    Field fields[] = reportSpec.getField();
    Field details[] = ReportSpecUtility.getDetails(fields);
    Field groups[] = ReportSpecUtility.getGroups(fields);
    List spaceFields = setupSpaceFields(fields);
    try {
        boolean expressionExists = ReportSpecUtility.doesExpressionExist(fields);
        setupDetailFieldWidths(reportSpec, details);
        int itemRowHeight = ReportSpecUtility.getRowHeight(reportSpec, details);
        // dom4j
        Document document = DOMDocumentFactory.getInstance().createDocument();

        document.addDocType("report", "-//JFreeReport//DTD report definition//EN//simple/version 0.8.5", //$NON-NLS-1$//$NON-NLS-2$
                "http://jfreereport.sourceforge.net/report-085.dtd"); //$NON-NLS-1$
        org.dom4j.Element reportNode = document.addElement("report"); //$NON-NLS-1$
        Element configuration = reportNode.addElement(CONFIGURATION_ELEMENT_NAME);

        if (null != encoding) {
            document.setXMLEncoding(encoding);
            addEncoding(configuration, encoding);
        }

        // reportNode.addAttribute("xmlns", "http://jfreereport.sourceforge.net/namespaces/reports/legacy/simple");
        // add parser-config to generated report
        addParserConfig(reportSpec, reportNode);
        // set report name
        reportNode.addAttribute(NAME_ATTRIBUTE_NAME, StringEscapeUtils.escapeXml(reportSpec.getReportName()));
        // set orientation
        reportNode.addAttribute("orientation", reportSpec.getOrientation()); //$NON-NLS-1$
        // set page-format or page width/height
        setPageFormat(reportSpec, reportNode, pageWidth, pageHeight);
        // set margins
        setMargins(reportSpec, reportNode);
        if (reportSpec.getIncludeSrc() != null && !"".equalsIgnoreCase(reportSpec.getIncludeSrc())) { //$NON-NLS-1$
            org.dom4j.Element includeElement = reportNode.addElement("include"); //$NON-NLS-1$
            includeElement.addAttribute("src", "file://" + reportSpec.getIncludeSrc().replace('\\', '/')); //$NON-NLS-1$ //$NON-NLS-2$
        }
        // set watermark
        setWatermark(reportSpec, reportNode);
        Element groupsNode = reportNode.addElement("groups"); //$NON-NLS-1$
        Element itemsNode = reportNode.addElement("items"); //$NON-NLS-1$
        Element functionNode = reportNode.addElement("functions"); //$NON-NLS-1$
        if (reportSpec.getChart() != null && reportSpec.getUseChart()) {
            Element reportHeaderElement = reportNode.addElement("reportheader"); //$NON-NLS-1$
            addChartElement(reportSpec, null, functionNode, reportHeaderElement, 0);
        }
        setItemsFont(reportSpec, itemsNode);
        // create banding rectangle if banding is turned on
        createRowBanding(reportSpec, details, itemsNode, functionNode, itemRowHeight);
        // programatically create details section
        processDetailsSection(reportSpec, details, groups, itemsNode, functionNode, itemRowHeight);
        // programatically create groups section
        processGroupsSection(reportSpec, details, groups, groupsNode, functionNode, itemRowHeight,
                expressionExists, spacerWidth);

        // spit out report xml definition
        OutputFormat format = OutputFormat.createPrettyPrint();
        if (null != encoding) {
            format.setEncoding(encoding); // TODO sbarkull, not sure this is necessary
        }
        XMLWriter writer = new XMLWriter(outputStream, format);
        writer.write(document);
        writer.close();
        // put _SPACE_ fields back in place as they were
        for (int i = 0; i < spaceFields.size(); i++) {
            Field f = (Field) spaceFields.get(i);
            f.setName("_SPACE_" + (i + 1)); //$NON-NLS-1$
            f.setDisplayName("_SPACE_" + (i + 1)); //$NON-NLS-1$
        }
    } catch (Exception e) {
        getLogger().error(e.getMessage(), e);
    }
}

From source file:org.pentaho.platform.plugin.adhoc.AdhocContentGenerator.java

License:Open Source License

public void createMQLQueryActionSequence(final String domainId, final String modelId, final String tableId,
        final String columnId, final String searchStr, final OutputStream outputStream,
        final String userSessionName) throws IOException {

    Document document = DOMDocumentFactory.getInstance().createDocument();
    document.setXMLEncoding(LocaleHelper.getSystemEncoding());
    Element actionSeqElement = document.addElement("action-sequence"); //$NON-NLS-1$
    actionSeqElement.addElement("version").setText("1"); //$NON-NLS-1$ //$NON-NLS-2$
    actionSeqElement.addElement("title").setText("MQL Query"); //$NON-NLS-1$ //$NON-NLS-2$
    actionSeqElement.addElement("logging-level").setText("ERROR"); //$NON-NLS-1$ //$NON-NLS-2$
    Element documentationElement = actionSeqElement.addElement("documentation"); //$NON-NLS-1$
    Element authorElement = documentationElement.addElement("author"); //$NON-NLS-1$
    if (userSessionName != null) {
        authorElement.setText(userSessionName);
    } else {/*www.  ja v  a 2s.  c  om*/
        authorElement.setText("Web Query & Reporting"); //$NON-NLS-1$
    }
    documentationElement.addElement("description") //$NON-NLS-1$
            .setText("Temporary action sequence used by Web Query & Reporting"); //$NON-NLS-1$
    documentationElement.addElement("result-type").setText("result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    Element outputsElement = actionSeqElement.addElement("outputs"); //$NON-NLS-1$
    Element reportTypeElement = outputsElement.addElement("query_result"); //$NON-NLS-1$
    reportTypeElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    Element destinationsElement = reportTypeElement.addElement("destinations"); //$NON-NLS-1$
    destinationsElement.addElement("response").setText("query_result"); //$NON-NLS-1$ //$NON-NLS-2$

    Element actionsElement = actionSeqElement.addElement("actions"); //$NON-NLS-1$
    Element actionDefinitionElement = actionsElement.addElement("action-definition"); //$NON-NLS-1$
    Element actionOutputsElement = actionDefinitionElement.addElement("action-outputs"); //$NON-NLS-1$
    Element ruleResultElement = actionOutputsElement.addElement("query-result"); //$NON-NLS-1$
    ruleResultElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    ruleResultElement.addAttribute("mapping", "query_result"); //$NON-NLS-1$ //$NON-NLS-2$
    actionDefinitionElement.addElement("component-name").setText("MQLRelationalDataComponent"); //$NON-NLS-1$ //$NON-NLS-2$
    actionDefinitionElement.addElement("action-type").setText("MQL Query"); //$NON-NLS-1$ //$NON-NLS-2$
    Element componentDefinitionElement = actionDefinitionElement.addElement("component-definition"); //$NON-NLS-1$

    // 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$
    }
    // componentDefinitionElement.addElement("query").addCDATA(createMQLQueryXml(domainId, modelId, tableId, columnId, searchStr)); //$NON-NLS-1$
    addMQLQueryXml(componentDefinitionElement, domainId, modelId, tableId, columnId, searchStr);

    // end action-definition for JFreeReportComponent
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(LocaleHelper.getSystemEncoding());
    XMLWriter writer = new XMLWriter(outputStream, format);
    writer.write(document);
    writer.close();
}

From source file:org.pentaho.platform.plugin.adhoc.AdhocContentGenerator.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 = AdhocContentGenerator.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. ja va  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.getInstance()
                    .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.getInstance().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.plugin.adhoc.AdhocContentGenerator.java

License:Open Source License

public void searchTable(final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final boolean wrapWithSoap) throws IOException {
    String responseEncoding = PentahoSystem.getSystemSetting("web-service-encoding", "utf-8"); //$NON-NLS-1$ //$NON-NLS-2$     
    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  ww w.  j  av  a 2s .com*/
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding(LocaleHelper.getSystemEncoding());
    Element resultsElement = document.addElement("results"); //$NON-NLS-1$

    IRuntimeContext runtimeContext = AdhocContentGenerator.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();
    }
    XmlDom4JHelper.saveDom(document, outputStream, responseEncoding, wrapWithSoap);
}

From source file:org.pentaho.platform.plugin.adhoc.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$
    actionSeqTitleElement.setText(reportName);

    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 {/* ww  w . jav  a2 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.getInstance()
                    .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.getInstance().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.plugin.adhoc.AdhocWebService.java

License:Open Source License

public static void main(String args[]) throws Exception {
    XMLWriter writer = new XMLWriter(System.out, OutputFormat.createPrettyPrint());
    Document doc = new AdhocWebService().createSolutionTree(new File("package-res/resources/templates"));

    Element folderElement = AdhocWebService.getFolderElement(doc, "/system/waqr/resources");
    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 {/*from w ww.  j  a  v  a2s .c  o m*/
        String msg = Messages.getInstance().getString("AdhocWebService.ERROR_0011_FAILED_TO_LOCATE_PATH", "/"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }

    writer.write(systemDoc);
    writer.flush();
    //    System.out.println(XmlDom4JHelper.docToString();
}

From source file:org.pentaho.platform.plugin.adhoc.AdhocWebService.java

License:Open Source License

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

    // //branch[@id='" + parentPath + "']/branch
    // @isDir/*  w w w  .  j a  v  a2 s  . c  om*/
    // branchText element is the name
    // leaf
    // leafText
    // path

    if ((folderPath != null && StringUtil.doesPathContainParentPathSegment(folderPath))) {
        String msg = Messages.getInstance().getString("AdhocWebService.ERROR_0011_FAILED_TO_LOCATE_PATH", //$NON-NLS-1$
                folderPath);
        throw new AdhocWebServiceException(msg);
    }

    String path = "/" + AdhocWebService.WAQR_REPOSITORY_PATH; //$NON-NLS-1$ //$NON-NLS-2$
    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.getInstance().getString("AdhocWebService.ERROR_0011_FAILED_TO_LOCATE_PATH", //$NON-NLS-1$
                folderPath);
        throw new AdhocWebServiceException(msg);
    }
    return systemDoc;
}