Example usage for org.dom4j Node setText

List of usage examples for org.dom4j Node setText

Introduction

In this page you can find the example usage for org.dom4j Node setText.

Prototype

void setText(String text);

Source Link

Document

Sets the text data of this node or this method will throw an UnsupportedOperationException if it is read-only.

Usage

From source file:org.pentaho.platform.engine.services.ActionSequenceJCRHelper.java

License:Open Source License

public void localizeDoc(final Node document, final RepositoryFile file) {
    String fileName = file.getName();
    int dotIndex = fileName.indexOf('.');
    String baseName = fileName.substring(0, dotIndex);
    // TODO read in nodes from the locale file and use them to override the
    // ones in the main document
    try {//from  w  w w  .  java 2s.  c o  m
        List nodes = document.selectNodes("descendant::*"); //$NON-NLS-1$
        Iterator nodeIterator = nodes.iterator();
        while (nodeIterator.hasNext()) {
            Node node = (Node) nodeIterator.next();
            String name = node.getText();
            if (name.startsWith("%") && !node.getPath().endsWith("/text()")) { //$NON-NLS-1$ //$NON-NLS-2$
                try {
                    String localeText = getLocaleString(name, baseName, file, true);
                    if (localeText != null) {
                        node.setText(localeText);
                    }
                } catch (Exception e) {
                    logger.warn(Messages.getInstance().getString(
                            "ActionSequenceJCRHelper.WARN_MISSING_RESOURCE_PROPERTY", name.substring(1), //$NON-NLS-1$
                            baseName, getLocale().toString()));
                }
            }
        }
    } catch (Exception e) {
        logger.error(Messages.getInstance().getErrorString(
                "ActionSequenceJCRHelper.ERROR_0007_COULD_NOT_READ_PROPERTIES", file.getPath()), e); //$NON-NLS-1$
    }
}

From source file:org.pentaho.platform.engine.services.solution.ComponentBase.java

License:Open Source License

/**
 * Return the xml Node containing the component's definition. If <code>process</code> is true, visit every child
 * node in the tree, and if the child node's text is an action parameter convert it to it's value. (See doc for
 * applyInputsToFormat())//from  w  w w . j av  a  2s .  co  m
 * 
 * @param process
 *          if true, if the node's text represents a parameter, convert the parameter to it's value, and assign
 *          the value to the node's text.
 * 
 * @return Node containing this component's definition.
 */
@SuppressWarnings("unchecked")
public Node getComponentDefinition(final boolean process) {
    if (process) {
        List nodes = componentDefinition.selectNodes("//*"); //$NON-NLS-1$
        Iterator it = nodes.iterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            String txt = node.getText();
            if ((txt != null) && !node.isReadOnly()) {
                node.setText(applyInputsToFormat(txt));
            }
        }
    }
    return componentDefinition;
}

From source file:org.pentaho.platform.plugin.action.jfreechart.ChartComponent.java

License:Open Source License

@Override
protected boolean executeAction() {
    int height = -1;
    int width = -1;
    String title = ""; //$NON-NLS-1$
    Node chartDocument = null;//from   w  ww  .ja v a2s.c  o m
    IPentahoResultSet data = (IPentahoResultSet) getInputValue(ChartComponent.CHART_DATA_PROP);
    if (!data.isScrollable()) {
        getLogger().debug("ResultSet is not scrollable. Copying into memory"); //$NON-NLS-1$
        IPentahoResultSet memSet = data.memoryCopy();
        data.close();
        data = memSet;
    }

    String urlTemplate = (String) getInputValue(ChartComponent.URL_TEMPLATE);

    Node chartAttributes = null;
    String chartAttributeString = null;

    // Attempt to get chart attributes as an input string or as a resource file
    // If these don't trip, then we assume the chart attributes are defined in
    // the component-definition of the chart action.

    if (getInputNames().contains(ChartComponent.CHART_ATTRIBUTES_PROP)) {
        chartAttributeString = getInputStringValue(ChartComponent.CHART_ATTRIBUTES_PROP);
    } else if (isDefinedResource(ChartComponent.CHART_ATTRIBUTES_PROP)) {
        IActionSequenceResource resource = getResource(ChartComponent.CHART_ATTRIBUTES_PROP);
        chartAttributeString = getResourceAsString(resource);
    }

    // Realize chart attributes as an XML document
    if (chartAttributeString != null) {
        try {
            chartDocument = XmlDom4JHelper.getDocFromString(chartAttributeString, new PentahoEntityResolver());
        } catch (XmlParseException e) {
            getLogger().error(
                    Messages.getInstance().getString("ChartComponent.ERROR_0005_CANT_DOCUMENT_FROM_STRING"), e); //$NON-NLS-1$
            return false;
        }

        chartAttributes = chartDocument.selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP);

        // This line of code handles a discrepancy between the schema of a chart definition
        // handed to a dashboard versus a ChartComponent schema. The top level node for the dashboard charts
        // is <chart>, whereas the ChartComponent expects <chart-attributes>.

        // TODO:
        // This discrepancy should be resolved when we have ONE chart solution.

        if (chartAttributes == null) {
            chartAttributes = chartDocument.selectSingleNode(ChartComponent.ALTERNATIVE_CHART_ATTRIBUTES_PROP);
        }
    }

    // Default chart attributes are in the component-definition section of the action definition.
    if (chartAttributes == null) {
        chartAttributes = getComponentDefinition(true).selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP);
    }

    // URL click-through attributes (useBaseURL, target) are only processed IF we
    // have an urlTemplate attribute
    if ((urlTemplate == null) || (urlTemplate.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE) != null) {
            urlTemplate = chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE).getText();
        }
    }

    // These parameters are replacement variables parsed into the
    // urlTemplate specifically when we have a URL that is a drill-through
    // link in a chart intended to drill down into the chart data.
    String parameterName = (String) getInputValue(ChartComponent.PARAMETER_NAME);
    if ((parameterName == null) || (parameterName.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME) != null) {
            parameterName = chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME).getText();
        }
    }

    // These parameters are replacement variables parsed into the
    // urlTemplate specifically when we have a URL that is a drill-through
    // link in a chart intended to drill down into the chart data.
    String outerParameterName = (String) getInputValue(ChartComponent.OUTER_PARAMETER_NAME);
    if ((outerParameterName == null) || (outerParameterName.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME) != null) {
            outerParameterName = chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME)
                    .getText();
        }
    }

    String chartType = chartAttributes.selectSingleNode(ChartDefinition.TYPE_NODE_NAME).getText();

    // --------------- This code allows inputs to override the chartAttributes
    // of width, height, and title
    Object widthObj = getInputValue(ChartDefinition.WIDTH_NODE_NAME);
    if (widthObj != null) {
        width = Integer.parseInt(widthObj.toString());
        if (width != -1) {
            if (chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME) == null) {
                ((Element) chartAttributes).addElement(ChartDefinition.WIDTH_NODE_NAME);
            }
            chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME).setText(Integer.toString(width));
        }
    }
    Object heightObj = getInputValue(ChartDefinition.HEIGHT_NODE_NAME);
    if (heightObj != null) {
        height = Integer.parseInt(heightObj.toString());
        if (height != -1) {
            if (chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME) == null) {
                ((Element) chartAttributes).addElement(ChartDefinition.HEIGHT_NODE_NAME);
            }
            chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME)
                    .setText(Integer.toString(height));
        }
    }
    Object titleObj = getInputValue(ChartDefinition.TITLE_NODE_NAME);
    if (titleObj != null) {
        if (chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME) == null) {
            ((Element) chartAttributes).addElement(ChartDefinition.TITLE_NODE_NAME);
        }
        chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME).setText(titleObj.toString());
    }
    // ----------------End of Override

    // ---------------Feed the Title and Subtitle information through the input substitution
    Node titleNode = chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME);
    if (titleNode != null) {
        String titleStr = titleNode.getText();
        if (titleStr != null) {
            title = titleStr;
            String newTitle = applyInputsToFormat(titleStr);
            titleNode.setText(newTitle);
        }
    }

    List subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);

    if ((subtitles == null) || (subtitles.isEmpty())) {
        Node subTitlesNode = chartAttributes.selectSingleNode(ChartDefinition.SUBTITLES_NODE_NAME);
        if (subTitlesNode != null) {
            subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);
        }
    } else {
        // log a deprecation warning for this property...
        getLogger().warn(Messages.getInstance().getString("CHART.WARN_DEPRECATED_CHILD", //$NON-NLS-1$
                ChartDefinition.SUBTITLE_NODE_NAME, ChartDefinition.SUBTITLES_NODE_NAME));
        getLogger().warn(Messages.getInstance().getString("CHART.WARN_PROPERTY_WILL_NOT_VALIDATE", //$NON-NLS-1$
                ChartDefinition.SUBTITLE_NODE_NAME));
    }

    if (subtitles != null) {
        for (Iterator iter = subtitles.iterator(); iter.hasNext();) {
            Node subtitleNode = (Node) iter.next();
            if (subtitleNode != null) {
                String subtitleStr = subtitleNode.getText();
                if (subtitleStr != null) {
                    String newSubtitle = applyInputsToFormat(subtitleStr);
                    subtitleNode.setText(newSubtitle);
                }
            }
        }
    }

    // ----------------End of Format

    // Determine if we are going to read the chart data set by row or by column
    boolean byRow = false;
    if (getInputStringValue(ChartComponent.BY_ROW_PROP) != null) {
        byRow = Boolean.valueOf(getInputStringValue(ChartComponent.BY_ROW_PROP)).booleanValue();
    }

    // TODO Figure out why these overrides are called here. Seems like we are doing the same thing we just did above,
    // but
    // could possibly step on the height and width values set previously.

    if (height == -1) {
        height = (int) getInputLongValue(
                ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.HEIGHT_NODE_NAME, 50); //$NON-NLS-1$
    }
    if (width == -1) {
        width = (int) getInputLongValue(
                ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.WIDTH_NODE_NAME, 100); //$NON-NLS-1$      
    }

    if (title.length() <= 0) {
        title = getInputStringValue(
                ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.TITLE_NODE_NAME); //$NON-NLS-1$
    }

    // Select the right dataset to use based on the chart type
    // Default to category dataset
    String datasetType = ChartDefinition.CATEGORY_DATASET_STR;
    boolean isStacked = false;
    Node datasetTypeNode = chartAttributes.selectSingleNode(ChartDefinition.DATASET_TYPE_NODE_NAME);
    if (datasetTypeNode != null) {
        datasetType = datasetTypeNode.getText();
    }
    Dataset dataDefinition = null;
    if (ChartDefinition.XY_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {
        dataDefinition = new XYSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.TIME_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {

        Node stackedNode = chartAttributes.selectSingleNode(ChartDefinition.STACKED_NODE_NAME);
        if (stackedNode != null) {
            isStacked = Boolean.valueOf(stackedNode.getText()).booleanValue();
        }
        if ((isStacked) && (ChartDefinition.AREA_CHART_STR.equalsIgnoreCase(chartType))) {
            dataDefinition = new TimeTableXYDatasetChartDefinition(data, byRow, chartAttributes, getSession());
        } else {
            dataDefinition = new TimeSeriesCollectionChartDefinition(data, byRow, chartAttributes,
                    getSession());
        }
    } else if (ChartDefinition.PIE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new PieDatasetChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.DIAL_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new DialWidgetDefinition(data, byRow, chartAttributes, width, height, getSession());
    } else if (ChartDefinition.BAR_LINE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new BarLineChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.BUBBLE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new XYZSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
    } else {
        dataDefinition = new CategoryDatasetChartDefinition(data, byRow, chartAttributes, getSession());
    }

    // Determine what we are sending back - Default to OUTPUT_PNG output
    // OUTPUT_PNG = the chart gets written to a file in .png format
    // OUTPUT_SVG = the chart gets written to a file in .svg (XML) format
    // OUTPUT_CHART = the chart in a byte stream gets stored as as an IContentItem
    // OUTPUT_PNG_BYTES = the chart gets sent as a byte stream in .png format

    int outputType = JFreeChartEngine.OUTPUT_PNG;

    if (getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP) != null) {
        if (ChartComponent.SVG_TYPE.equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_SVG;
        } else if (ChartComponent.CHART_TYPE
                .equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_CHART;
        } else if (ChartComponent.PNG_BYTES_TYPE
                .equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_PNG_BYTES;
        }
    }

    boolean keepTempFile = false;
    if (isDefinedInput(KEEP_TEMP_FILE_PROP)) {
        keepTempFile = getInputBooleanValue(KEEP_TEMP_FILE_PROP, false);
    }

    JFreeChart chart = null;

    switch (outputType) {

    /**************************** OUTPUT_PNG_BYTES *********************************************/
    case JFreeChartEngine.OUTPUT_PNG_BYTES:

        chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this); //$NON-NLS-1$

        // TODO Shouldn't the mime types and other strings here be constant somewhere? Where do we
        // put this type of general info ?

        String mimeType = "image/png"; //$NON-NLS-1$
        IContentItem contentItem = getOutputItem("chartdata", mimeType, ".png"); //$NON-NLS-1$ //$NON-NLS-2$
        contentItem.setMimeType(mimeType);
        try {

            OutputStream output = contentItem.getOutputStream(getActionName());
            ChartUtilities.writeChartAsPNG(output, chart, width, height);

        } catch (Exception e) {
            error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0004_CANT_CREATE_IMAGE"), e); //$NON-NLS-1$
            return false;
        }

        break;

    /**************************** OUTPUT_SVG && OUTPUT_PNG *************************************/
    case JFreeChartEngine.OUTPUT_SVG:
        // intentionally fall through to PNG

    case JFreeChartEngine.OUTPUT_PNG:

        // Don't include the map in a file if HTML_MAPPING_HTML is specified, as that
        // param sends the map back on the outputstream as a string
        boolean createMapFile = !isDefinedOutput(ChartComponent.HTML_MAPPING_HTML);
        boolean hasTemplate = urlTemplate != null && urlTemplate.length() > 0;

        File[] fileResults = createTempFile(outputType, hasTemplate, !keepTempFile);

        if (fileResults == null) {
            error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0003_CANT_CREATE_TEMP_FILES")); //$NON-NLS-1$
            return false;
        }

        String chartId = fileResults[ChartComponent.FILE_NAME].getName().substring(0,
                fileResults[ChartComponent.FILE_NAME].getName().indexOf('.'));
        String filePathWithoutExtension = ChartComponent.TEMP_DIRECTORY + chartId;
        PrintWriter printWriter = new PrintWriter(new StringWriter());
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

        JFreeChartEngine.saveChart(dataDefinition, title, "", filePathWithoutExtension, width, height, //$NON-NLS-1$
                outputType, printWriter, info, this);

        // Creating the image map
        boolean useBaseUrl = true;
        String urlTarget = "pentaho_popup"; //$NON-NLS-1$

        // Prepend the base url to the front of every drill through link
        if (chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG) != null) {
            Boolean booleanValue = new Boolean(
                    chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG).getText());
            useBaseUrl = booleanValue.booleanValue();
        }

        // What target for link? _parent, _blank, etc.
        if (chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG) != null) {
            urlTarget = chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG).getText();
        }

        String mapString = null;
        if (hasTemplate) {
            try {
                String mapId = fileResults[ChartComponent.MAP_NAME].getName().substring(0,
                        fileResults[ChartComponent.MAP_NAME].getName().indexOf('.'));
                mapString = ImageMapUtilities.getImageMap(mapId, info,
                        new StandardToolTipTagFragmentGenerator(),
                        new PentahoChartURLTagFragmentGenerator(urlTemplate, urlTarget, useBaseUrl,
                                dataDefinition, parameterName, outerParameterName));

                if (createMapFile) {
                    BufferedWriter out = new BufferedWriter(
                            new FileWriter(fileResults[ChartComponent.MAP_NAME]));
                    out.write(mapString);
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0001_CANT_WRITE_MAP", //$NON-NLS-1$
                        fileResults[ChartComponent.MAP_NAME].getPath()));
                return false;
            } catch (Exception e) {
                error(e.getLocalizedMessage(), e);
                return false;
            }

        }

        /*******************************************************************************************************
         * Legitimate outputs for the ChartComponent in an action sequence:
         * 
         * CHART_OUTPUT (chart-output) Stores the chart in the content repository as an IContentItem.
         * 
         * CHART_FILE_NAME_OUTPUT (chart-filename) Returns the name of the chart file, including the file extension
         * (with no path information) as a String.
         * 
         * HTML_MAPPING_OUTPUT (chart-mapping) Returns the name of the file that the map has been saved to, including
         * the file extension (with no path information) as a String. Will be empty if url-template is undefined
         * 
         * HTML_MAPPING_HTML (chart-map-html) Returns the chart image map HTML as a String. Will be empty if
         * url-template is undefined
         * 
         * BASE_URL_OUTPUT (base-url) Returns the web app's base URL (ie., http://localhost:8080/pentaho) as a String.
         * 
         * HTML_IMG_TAG (image-tag) Returns the HTML snippet including the image map, image (<IMG />) tag for the chart
         * image with src, width, height and usemap attributes defined. Usemap will not be included if url-template is
         * undefined.
         * 
         *******************************************************************************************************/

        // Now set the outputs
        Set outputs = getOutputNames();

        if ((outputs != null) && (outputs.size() > 0)) {

            Iterator iter = outputs.iterator();
            while (iter.hasNext()) {

                String outputName = (String) iter.next();
                String outputValue = null;

                if (outputName.equals(ChartComponent.CHART_FILE_NAME_OUTPUT)) {

                    outputValue = fileResults[ChartComponent.FILE_NAME].getName();

                } else if (outputName.equals(ChartComponent.HTML_MAPPING_OUTPUT)) {
                    if (hasTemplate) {
                        outputValue = fileResults[ChartComponent.MAP_NAME].getName();
                    }
                } else if (outputName.equals(ChartComponent.HTML_MAPPING_HTML)) {

                    outputValue = mapString;

                } else if (outputName.equals(ChartComponent.BASE_URL_OUTPUT)) {
                    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                    outputValue = requestContext.getContextPath();

                } else if (outputName.equals(ChartComponent.CONTEXT_PATH_OUTPUT)) {
                    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                    outputValue = requestContext.getContextPath();
                } else if (outputName.equals(ChartComponent.FULLY_QUALIFIED_SERVER_URL_OUTPUT)) {

                    IApplicationContext applicationContext = PentahoSystem.getApplicationContext();
                    if (applicationContext != null) {
                        outputValue = applicationContext.getFullyQualifiedServerURL();
                    } else {
                        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                        outputValue = requestContext.getContextPath();
                    }
                } else if (outputName.equals(ChartComponent.HTML_IMG_TAG)) {

                    outputValue = hasTemplate ? mapString : ""; //$NON-NLS-1$

                    outputValue += "<img border=\"0\" "; //$NON-NLS-1$
                    outputValue += "width=\"" + width + "\" "; //$NON-NLS-1$//$NON-NLS-2$
                    outputValue += "height=\"" + height + "\" "; //$NON-NLS-1$//$NON-NLS-2$
                    if (hasTemplate) {
                        outputValue += "usemap=\"#" + fileResults[ChartComponent.MAP_NAME].getName().substring(
                                0, fileResults[ChartComponent.MAP_NAME].getName().indexOf('.')) + "\" "; //$NON-NLS-1$//$NON-NLS-2$
                    }
                    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                    String contextPath = requestContext.getContextPath();
                    outputValue += "src=\"" + contextPath + "getImage?image=" //$NON-NLS-1$//$NON-NLS-2$
                            + fileResults[ChartComponent.FILE_NAME].getName() + "\"/>"; //$NON-NLS-1$

                }

                if (outputValue != null) {
                    setOutputValue(outputName, outputValue);
                }
            }
        }

        break;

    /************************** OUTPUT_CHART && DEFAULT *************************************/
    case JFreeChartEngine.OUTPUT_CHART:
        // intentionally fall through to default

    default:

        String chartName = ChartComponent.CHART_OUTPUT;
        if (isDefinedInput(ChartComponent.CHART_NAME_PROP)) {
            chartName = getInputStringValue(ChartComponent.CHART_NAME_PROP);
        }
        chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this); //$NON-NLS-1$
        setOutputValue(chartName, chart);

        break;
    }

    return true;
}

From source file:org.pentaho.platform.plugin.action.mondrian.AnalysisSaver.java

License:Open Source License

/**
 * @param document/*  w w  w. j  a  v  a2  s  . com*/
 * @param props
 * @return
 */
private static Document updateDocument(final Document document, final HashMap props) {
    try {
        Element componentDefinition = null;
        Element actionOutput = null;
        Element actionSequenceOutput = null;

        Node actionSequence = document.selectSingleNode("/action-sequence"); //$NON-NLS-1$
        if (actionSequence == null) {
            throw new InvalidDocumentException(
                    Messages.getErrorString("ANALYSISSAVER.ERROR_0004_INVALID_ORIGIN_DOCUMENT")); //$NON-NLS-1$
        }
        Element asElement = ((Element) actionSequence);
        Node title = null;
        String propertyTitle = (String) props.get(AnalysisSaver.TITLE_NODE_NAME);
        title = asElement.selectSingleNode(AnalysisSaver.TITLE_NODE_NAME);
        if ((title == null) && (propertyTitle != null)) {
            title = asElement.addElement(AnalysisSaver.TITLE_NODE_NAME);
        }

        if ((title != null) && (propertyTitle != null)) {
            // remove existing text if it's there
            title.setText(""); //$NON-NLS-1$ 
            ((Element) title).addCDATA(propertyTitle); // adds CDATA
        }

        // Next, we need to retrieve the PivotViewComponent action and
        // process/update it.. there could possibly be more than one
        // PivotViewComponent in an action sequence, however, we have no idea
        // how to figure out which one to process, so we default to picking the last one we found.

        componentDefinition = (Element) document.selectSingleNode(
                "//action-definition[component-name='PivotViewComponent']/component-definition"); //$NON-NLS-1$
        if (componentDefinition == null) {
            throw new InvalidDocumentException(
                    Messages.getErrorString("ANALYSISSAVER.ERROR_0005_INVALID_NO_PIVOT_ACTION")); //$NON-NLS-1$
        }

        AnalysisSaver.updateComponent(componentDefinition, props);

        // Get the action's root action-output node, in case we need to add the
        // appropriate outputs for the pivot view...
        actionOutput = (Element) document
                .selectSingleNode("//action-definition[component-name='PivotViewComponent']/action-outputs"); //$NON-NLS-1$
        AnalysisSaver.updateOutput(actionOutput, props);

        // Get the action's root action sequence output node, in case we need to add the
        // appropriate outputs for the pivot view...
        actionSequenceOutput = (Element) document.selectSingleNode("//action-sequence/outputs"); //$NON-NLS-1$
        AnalysisSaver.updateOutput(actionSequenceOutput, props);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return document;
}

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

License:Open Source License

/**
 * Create the JFreeReport file.//from   w w w  . j  a v a2 s.co m
 * 
 * NOTE on the merge precedence: this method should use properties set by the 
 * WAQR UI. If the waqr UI did not set the property, then the property 
 * should be set by the metadata. If the metadata did not set a property,
 * then the property should be set by the template. If the template
 * did not set the property, then use the default.
 * 
 * NOTE on the merge algorithm: 
 * For each of the attributes in the fields (aka columns) of the reportspec,
 * if the attribute is present in the reportspec that comes in from the client
 * (ie reportXML param), and the attribute has a non-default value, do not change it.
 * If the attribute is not present or has a default value, and if there is metadata
 * for that attribute, merge the metadata attribute. This take place inline in the 
 * main loop of this method. If after the metadata merge the attribute 
 * still does not have a value, merge the template value. This takes place
 * in the AdhocWebService.applyTemplate() method.
 * If the template does not have a value, do nothing (the default will be used).
 * 
 * @param reportDoc
 * @param reportXML
 * @param templatePath
 * @param mqlNode
 * @param repository
 * @param userSession
 * @return
 * @throws IOException
 * @throws AdhocWebServiceException
 * @throws PentahoMetadataException
 */
public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode,
        IPentahoSession userSession, OutputStream jfreeMergedOutputStream)
        throws IOException, AdhocWebServiceException, PentahoMetadataException {

    Map reportSpecTypeToElement = null;
    Document templateDoc = null;
    Element templateItems = null;
    boolean bUseTemplate = !StringUtils.isEmpty(templatePath);

    if (bUseTemplate) {
        templatePath = AdhocContentGenerator.WAQR_REPOSITORY_PATH + templatePath;
        try {
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            templateDoc = reader
                    .read(ActionSequenceResource.getInputStream(templatePath, LocaleHelper.getLocale()));
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }

        templateItems = (Element) templateDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List nodes = templateItems.elements();
        Iterator it = nodes.iterator();
        reportSpecTypeToElement = new HashMap();
        while (it.hasNext()) {
            Element element = (Element) it.next();
            reportSpecTypeToElement.put(element.getName(), element);
        }
    }

    // get the business model from the mql statement
    String xml = mqlNode.asXML();

    // first see if it's a thin model...
    QueryXmlHelper helper = new QueryXmlHelper();
    IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null);
    Query queryObject = null;
    try {
        queryObject = helper.fromXML(repo, xml);
    } catch (Exception e) {
        String msg = Messages.getInstance()
                .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    LogicalModel model = null;
    if (queryObject != null) {
        model = queryObject.getLogicalModel();
    }
    if (model == null) {
        throw new AdhocWebServiceException(
                Messages.getInstance().getErrorString("AdhocWebService.ERROR_0003_BUSINESS_VIEW_INVALID")); //$NON-NLS-1$
    }

    String locale = LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(),
            queryObject.getDomain().getLocaleCodes());

    String reportXMLEncoding = XmlHelper.getEncoding(reportXML);
    ByteArrayInputStream reportSpecInputStream = new ByteArrayInputStream(
            reportXML.getBytes(reportXMLEncoding));
    ReportSpec reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(reportSpecInputStream,
            ReportSpec.class, reportXMLEncoding);
    if (reportSpec == null) {
        throw new AdhocWebServiceException(
                Messages.getInstance().getErrorString("AdhocWebService.ERROR_0002_REPORT_INVALID")); //$NON-NLS-1$
    }

    // ========== begin column width stuff

    // make copies of the business columns; in the next step we're going to fill out any missing column widths
    LogicalColumn[] columns = new LogicalColumn[reportSpec.getField().length];
    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        String name = field.getName();
        LogicalColumn column = model.findLogicalColumn(name);
        columns[i] = (LogicalColumn) column.clone();
    }

    boolean columnWidthUnitsConsistent = AdhocContentGenerator.areMetadataColumnUnitsConsistent(reportSpec,
            model);

    if (!columnWidthUnitsConsistent) {
        logger.error(Messages.getInstance()
                .getErrorString("AdhocWebService.ERROR_0013_INCONSISTENT_COLUMN_WIDTH_UNITS")); //$NON-NLS-1$
    } else {
        double columnWidthScaleFactor = 1.0;
        int missingColumnWidthCount = 0;
        int columnWidthSumOfPercents;
        double defaultWidth;
        columnWidthSumOfPercents = AdhocContentGenerator.getSumOfMetadataColumnWidths(reportSpec, model);
        missingColumnWidthCount = AdhocContentGenerator.getMissingColumnWidthCount(reportSpec, model);

        // if there are columns with no column width specified, figure out what percent we should use for them
        if (missingColumnWidthCount > 0) {
            if (columnWidthSumOfPercents < 100) {
                int remainingPercent = 100 - columnWidthSumOfPercents;
                defaultWidth = remainingPercent / missingColumnWidthCount;
                columnWidthSumOfPercents = 100;
            } else {
                defaultWidth = 10;
                columnWidthSumOfPercents += (missingColumnWidthCount * 10);
            }

            // fill in columns without column widths
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                if (property == null) {
                    property = new ColumnWidth(WidthType.PERCENT, defaultWidth);
                    columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), property);
                }
            }
        }

        if (columnWidthSumOfPercents > 100) {
            columnWidthScaleFactor = 100.0 / (double) columnWidthSumOfPercents;
        }

        // now scale down if necessary
        if (columnWidthScaleFactor < 1.0) {
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                ColumnWidth newProperty = new ColumnWidth(property.getType(),
                        columnWidthScaleFactor * property.getWidth());
                columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), newProperty);
            }
        }

    }

    // ========== end column width stuff

    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        LogicalColumn column = columns[i];

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

        // Template properties have the lowest priority, merge them last
        if (bUseTemplate) {
            Element templateDefaults = null;
            if (column.getDataType() != null) {
                templateDefaults = (Element) reportSpecTypeToElement
                        .get(AdhocContentGenerator.METADATA_TYPE_TO_REPORT_SPEC_TYPE.get(column.getDataType())); // sorry, this is ugly as hell
            }
            /*
             * NOTE: this merge of the template with the node's properties only sets the following properties:
             * format, fontname, fontsize, color, alignment, vertical-alignment, 
             */
            AdhocContentGenerator.applyTemplate(field, templateDefaults);
        }
        AdhocContentGenerator.applyDefaults(field);
    } // end for

    /*
     * Create the xml document (generatedJFreeDoc) containing the jfreereport definition using
     * the reportSpec as input. generatedJFreeDoc will have the metadata merged with it,
     * and some of the template.
     */
    ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream();
    ReportGenerationUtility.createJFreeReportXMLAsStream(reportSpec, reportXMLEncoding,
            (OutputStream) jfreeOutputStream);
    String jfreeXml = jfreeOutputStream.toString(reportXMLEncoding);
    Document generatedJFreeDoc = null;
    try {
        generatedJFreeDoc = XmlDom4JHelper.getDocFromString(jfreeXml, 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);
    }

    /*
     * Merge template's /report/items element's attributes into the
     * generated document's /report/items element's attributes. There should not be any
     * conflict with the metadata, or the xreportspec in the reportXML param
     */
    if (bUseTemplate) {
        Element reportItems = (Element) generatedJFreeDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List templateAttrs = templateItems.attributes(); // from the template's /report/items element
        Iterator templateAttrsIt = templateAttrs.iterator();

        while (templateAttrsIt.hasNext()) {
            Attribute attr = (Attribute) templateAttrsIt.next();
            String name = attr.getName();
            String value = attr.getText();

            Node node = reportItems.selectSingleNode("@" + name); //$NON-NLS-1$
            if (node != null) {
                node.setText(value);
            } else {
                reportItems.addAttribute(name, value);
            }
        }
        List templateElements = templateItems.elements();
        Iterator templateElementsIt = templateElements.iterator();
        while (templateElementsIt.hasNext()) {
            Element element = (Element) templateElementsIt.next();
            element.detach();
            reportItems.add(element);
        }
        /*
         * NOTE: this merging of the template (ReportGenerationUtility.mergeTemplate())
         * with the generated document can wait until last because none of the 
         * properties involved in this merge are settable by the metadata or the WAQR UI
         */
        ReportGenerationUtility.mergeTemplateAsStream(templateDoc, generatedJFreeDoc, jfreeMergedOutputStream);
    } else {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(reportXMLEncoding);
        XMLWriter writer = new XMLWriter(jfreeMergedOutputStream, format);
        writer.write(generatedJFreeDoc);
        writer.close();
    }
}

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

License:Open Source License

public void getWaqrReportSpecDoc(final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final boolean wrapWithSoap)
        throws AdhocWebServiceException, IOException {
    String responseEncoding = PentahoSystem.getSystemSetting("web-service-encoding", "utf-8"); //$NON-NLS-1$ //$NON-NLS-2$
    String solution = parameterProvider.getStringParameter("solution", null); //$NON-NLS-1$
    String path = parameterProvider.getStringParameter("path", null); //$NON-NLS-1$
    String filename = parameterProvider.getStringParameter("filename", null); //$NON-NLS-1$

    path = URLDecoder.decode(path);
    // replace the extension to get to the report spec
    int pos = filename.lastIndexOf("."); //$NON-NLS-1$
    filename = filename.substring(0, pos + 1) + "xreportspec"; //$NON-NLS-1$

    Document reportSpecDoc = null;
    if (!StringUtils.isEmpty(solution) && (null != path) && !StringUtils.isEmpty(filename)) {
        String filePath = ActionInfo.buildSolutionPath(solution, path, filename);
        try {/*ww w  . j  a  v a 2  s.  c  o  m*/
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            reportSpecDoc = reader
                    .read(ActionSequenceResource.getInputStream(filePath, LocaleHelper.getLocale()));
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }
    } else {
        String msg = Messages.getInstance().getString("AdhocWebService.ERROR_0005_MISSING_REPORTSPEC_NAME"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }
    /*
     * -------------------------------- BISERVER-5263
     * --------------------------------------- Pre-3.6 ReportSpecs generated by
     * waqr didn't have an xmi file specified in the domain_id node. Below we
     * detect this condition (ie. we're trying to edit a pre-3.6 report using a
     * 3.7 dist) and we specify the default metadata.xmi file for the solution
     * specified.
     */
    Node domainIdNode = reportSpecDoc.selectSingleNode("//report-spec/query/mql/domain_id"); //$NON-NLS-1$
    String domainId = domainIdNode.getText();
    if (!domainId.endsWith(".xmi")) { //$NON-NLS-1$
        domainId += "/metadata.xmi"; //$NON-NLS-1$
        domainIdNode.setText(domainId);
    }
    // ---------------------------------------------------------------------------------------
    XmlDom4JHelper.saveDom(reportSpecDoc, outputStream, responseEncoding, wrapWithSoap);
}

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

License:Open Source License

/**
 * Create the JFreeReport file./*from   ww  w  . ja  va  2 s.  c  om*/
 * 
 * NOTE on the merge precedence: this method should use properties set by the 
 * WAQR UI. If the waqr UI did not set the property, then the property 
 * should be set by the metadata. If the metadata did not set a property,
 * then the property should be set by the template. If the template
 * did not set the property, then use the default.
 * 
 * NOTE on the merge algorithm: 
 * For each of the attributes in the fields (aka columns) of the reportspec,
 * if the attribute is present in the reportspec that comes in from the client
 * (ie reportXML param), and the attribute has a non-default value, do not change it.
 * If the attribute is not present or has a default value, and if there is metadata
 * for that attribute, merge the metadata attribute. This take place inline in the 
 * main loop of this method. If after the metadata merge the attribute 
 * still does not have a value, merge the template value. This takes place
 * in the AdhocWebService.applyTemplate() method.
 * If the template does not have a value, do nothing (the default will be used).
 * 
 * @param reportDoc
 * @param reportXML
 * @param templatePath
 * @param mqlNode
 * @param userSession
 * @return
 * @throws IOException
 * @throws AdhocWebServiceException
 * @throws PentahoMetadataException
 */
public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode,
        IPentahoSession userSession, OutputStream jfreeMergedOutputStream)
        throws IOException, AdhocWebServiceException, PentahoMetadataException {

    Map reportSpecTypeToElement = null;
    Document templateDoc = null;
    Element templateItems = null;
    boolean bUseTemplate = !StringUtils.isEmpty(templatePath);

    if (bUseTemplate) {
        templatePath = AdhocWebService.WAQR_REPOSITORY_PATH + templatePath;
        try {
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            templateDoc = reader
                    .read(ActionSequenceResource.getInputStream(templatePath, LocaleHelper.getLocale()));
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }

        templateItems = (Element) templateDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List nodes = templateItems.elements();
        Iterator it = nodes.iterator();
        reportSpecTypeToElement = new HashMap();
        while (it.hasNext()) {
            Element element = (Element) it.next();
            reportSpecTypeToElement.put(element.getName(), element);
        }
    }

    // get the business model from the mql statement
    String xml = mqlNode.asXML();

    // first see if it's a thin model...
    QueryXmlHelper helper = new QueryXmlHelper();
    IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null);
    Query queryObject = null;
    try {
        queryObject = helper.fromXML(repo, xml);
    } catch (Exception e) {
        String msg = Messages.getInstance()
                .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    LogicalModel model = null;
    if (queryObject != null) {
        model = queryObject.getLogicalModel();
    }
    if (model == null) {
        throw new AdhocWebServiceException(
                Messages.getInstance().getErrorString("AdhocWebService.ERROR_0003_BUSINESS_VIEW_INVALID")); //$NON-NLS-1$
    }

    String locale = LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(),
            queryObject.getDomain().getLocaleCodes());

    String reportXMLEncoding = XmlHelper.getEncoding(reportXML);
    ByteArrayInputStream reportSpecInputStream = new ByteArrayInputStream(
            reportXML.getBytes(reportXMLEncoding));
    ReportSpec reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(reportSpecInputStream,
            ReportSpec.class, reportXMLEncoding);
    if (reportSpec == null) {
        throw new AdhocWebServiceException(
                Messages.getInstance().getErrorString("AdhocWebService.ERROR_0002_REPORT_INVALID")); //$NON-NLS-1$
    }

    // ========== begin column width stuff

    // make copies of the business columns; in the next step we're going to fill out any missing column widths
    LogicalColumn[] columns = new LogicalColumn[reportSpec.getField().length];
    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        String name = field.getName();
        LogicalColumn column = model.findLogicalColumn(name);
        columns[i] = (LogicalColumn) column.clone();
    }

    boolean columnWidthUnitsConsistent = AdhocWebService.areMetadataColumnUnitsConsistent(reportSpec, model);

    if (!columnWidthUnitsConsistent) {
        logger.error(Messages.getInstance()
                .getErrorString("AdhocWebService.ERROR_0013_INCONSISTENT_COLUMN_WIDTH_UNITS")); //$NON-NLS-1$
    } else {
        double columnWidthScaleFactor = 1.0;
        int missingColumnWidthCount = 0;
        int columnWidthSumOfPercents;
        double defaultWidth;
        columnWidthSumOfPercents = AdhocWebService.getSumOfMetadataColumnWidths(reportSpec, model);
        missingColumnWidthCount = AdhocWebService.getMissingColumnWidthCount(reportSpec, model);

        // if there are columns with no column width specified, figure out what percent we should use for them
        if (missingColumnWidthCount > 0) {
            if (columnWidthSumOfPercents < 100) {
                int remainingPercent = 100 - columnWidthSumOfPercents;
                defaultWidth = remainingPercent / missingColumnWidthCount;
                columnWidthSumOfPercents = 100;
            } else {
                defaultWidth = 10;
                columnWidthSumOfPercents += (missingColumnWidthCount * 10);
            }

            // fill in columns without column widths
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                if (property == null) {
                    property = new ColumnWidth(WidthType.PERCENT, defaultWidth);
                    columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), property);
                }
            }
        }

        if (columnWidthSumOfPercents > 100) {
            columnWidthScaleFactor = 100.0 / (double) columnWidthSumOfPercents;
        }

        // now scale down if necessary
        if (columnWidthScaleFactor < 1.0) {
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                ColumnWidth newProperty = new ColumnWidth(property.getType(),
                        columnWidthScaleFactor * property.getWidth());
                columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), newProperty);
            }
        }

    }

    // ========== end column width stuff

    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        LogicalColumn column = columns[i];

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

        // Template properties have the lowest priority, merge them last
        if (bUseTemplate) {
            Element templateDefaults = null;
            if (column.getDataType() != null) {
                templateDefaults = (Element) reportSpecTypeToElement
                        .get(AdhocWebService.METADATA_TYPE_TO_REPORT_SPEC_TYPE.get(column.getDataType())); // sorry, this is ugly as hell
            }
            /*
             * NOTE: this merge of the template with the node's properties only sets the following properties:
             * format, fontname, fontsize, color, alignment, vertical-alignment, 
             */
            AdhocWebService.applyTemplate(field, templateDefaults);
        }
        AdhocWebService.applyDefaults(field);
    } // end for

    /*
     * Create the xml document (generatedJFreeDoc) containing the jfreereport definition using
     * the reportSpec as input. generatedJFreeDoc will have the metadata merged with it,
     * and some of the template.
     */
    ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream();
    ReportGenerationUtility.createJFreeReportXMLAsStream(reportSpec, reportXMLEncoding,
            (OutputStream) jfreeOutputStream);
    String jfreeXml = jfreeOutputStream.toString(reportXMLEncoding);
    Document generatedJFreeDoc = null;
    try {
        generatedJFreeDoc = XmlDom4JHelper.getDocFromString(jfreeXml, 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);
    }

    /*
     * Merge template's /report/items element's attributes into the
     * generated document's /report/items element's attributes. There should not be any
     * conflict with the metadata, or the xreportspec in the reportXML param
     */
    if (bUseTemplate) {
        Element reportItems = (Element) generatedJFreeDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List templateAttrs = templateItems.attributes(); // from the template's /report/items element
        Iterator templateAttrsIt = templateAttrs.iterator();

        while (templateAttrsIt.hasNext()) {
            Attribute attr = (Attribute) templateAttrsIt.next();
            String name = attr.getName();
            String value = attr.getText();

            Node node = reportItems.selectSingleNode("@" + name); //$NON-NLS-1$
            if (node != null) {
                node.setText(value);
            } else {
                reportItems.addAttribute(name, value);
            }
        }
        List templateElements = templateItems.elements();
        Iterator templateElementsIt = templateElements.iterator();
        while (templateElementsIt.hasNext()) {
            Element element = (Element) templateElementsIt.next();
            element.detach();
            reportItems.add(element);
        }
        /*
         * NOTE: this merging of the template (ReportGenerationUtility.mergeTemplate())
         * with the generated document can wait until last because none of the 
         * properties involved in this merge are settable by the metadata or the WAQR UI
         */
        ReportGenerationUtility.mergeTemplateAsStream(templateDoc, generatedJFreeDoc, jfreeMergedOutputStream);
    } else {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(reportXMLEncoding);
        XMLWriter writer = new XMLWriter(jfreeMergedOutputStream, format);
        writer.write(generatedJFreeDoc);
        writer.close();
    }
}

From source file:org.pentaho.platform.repository.solution.SolutionRepositoryBase.java

License:Open Source License

public void localizeDoc(final Node document, final ISolutionFile file) {
    String fileName = file.getFileName();
    int dotIndex = fileName.indexOf('.');
    String baseName = fileName.substring(0, dotIndex);
    // TODO read in nodes from the locale file and use them to override the
    // ones in the main document
    try {/*from   w  ww.j  a v a  2s .c o  m*/
        List nodes = document.selectNodes("descendant::*"); //$NON-NLS-1$
        Iterator nodeIterator = nodes.iterator();
        while (nodeIterator.hasNext()) {
            Node node = (Node) nodeIterator.next();
            String name = node.getText();
            if (name.startsWith("%") && !node.getPath().endsWith("/text()")) { //$NON-NLS-1$ //$NON-NLS-2$
                try {
                    String localeText = getLocaleString(name, baseName, file, true);
                    if (localeText != null) {
                        node.setText(localeText);
                    }
                } catch (Exception e) {
                    warn(Messages.getString("SolutionRepository.WARN_MISSING_RESOURCE_PROPERTY", //$NON-NLS-1$
                            name.substring(1), baseName, getLocale().toString()));
                }
            }
        }
    } catch (Exception e) {
        error(Messages.getErrorString("SolutionRepository.ERROR_0007_COULD_NOT_READ_PROPERTIES", //$NON-NLS-1$
                file.getFullPath()), e);
    }
}

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

License:Open Source License

/**
 * Create the JFreeReport file.//  w  ww  .  ja va2 s.co m
 * 
 * NOTE on the merge precedence: this method should use properties set by the 
 * WAQR UI. If the waqr UI did not set the property, then the property 
 * should be set by the metadata. If the metadata did not set a property,
 * then the property should be set by the template. If the template
 * did not set the property, then use the default.
 * 
 * NOTE on the merge algorithm: 
 * For each of the attributes in the fields (aka columns) of the reportspec,
 * if the attribute is present in the reportspec that comes in from the client
 * (ie reportXML param), and the attribute has a non-default value, do not change it.
 * If the attribute is not present or has a default value, and if there is metadata
 * for that attribute, merge the metadata attribute. This take place inline in the 
 * main loop of this method. If after the metadata merge the attribute 
 * still does not have a value, merge the template value. This takes place
 * in the AdhocWebService.applyTemplate() method.
 * If the template does not have a value, do nothing (the default will be used).
 * 
 * @param reportDoc
 * @param reportXML
 * @param templatePath
 * @param mqlNode
 * @param repository
 * @param userSession
 * @return
 * @throws IOException
 * @throws AdhocWebServiceException
 * @throws PentahoMetadataException
 */
public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode,
        ISolutionRepository repository, IPentahoSession userSession, OutputStream jfreeMergedOutputStream)
        throws IOException, AdhocWebServiceException, PentahoMetadataException {

    Map reportSpecTypeToElement = null;
    Document templateDoc = null;
    Element templateItems = null;
    boolean bUseTemplate = !StringUtils.isEmpty(templatePath);

    if (bUseTemplate) {
        templatePath = AdhocWebService.WAQR_REPOSITORY_PATH + templatePath;
        templateDoc = repository.getResourceAsDocument(templatePath, ISolutionRepository.ACTION_EXECUTE);

        templateItems = (Element) templateDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List nodes = templateItems.elements();
        Iterator it = nodes.iterator();
        reportSpecTypeToElement = new HashMap();
        while (it.hasNext()) {
            Element element = (Element) it.next();
            reportSpecTypeToElement.put(element.getName(), element);
        }
    }

    // get the business model from the mql statement
    String xml = mqlNode.asXML();

    // first see if it's a thin model...
    QueryXmlHelper helper = new QueryXmlHelper();
    IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null);
    Query queryObject = null;
    try {
        queryObject = helper.fromXML(repo, xml);
    } catch (Exception e) {
        String msg = Messages.getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    LogicalModel model = null;
    if (queryObject != null) {
        model = queryObject.getLogicalModel();
    }
    if (model == null) {
        throw new AdhocWebServiceException(
                Messages.getErrorString("AdhocWebService.ERROR_0003_BUSINESS_VIEW_INVALID")); //$NON-NLS-1$
    }

    String locale = LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(),
            queryObject.getDomain().getLocaleCodes());

    String reportXMLEncoding = XmlHelper.getEncoding(reportXML);
    ByteArrayInputStream reportSpecInputStream = new ByteArrayInputStream(
            reportXML.getBytes(reportXMLEncoding));
    ReportSpec reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(reportSpecInputStream,
            ReportSpec.class, reportXMLEncoding);
    if (reportSpec == null) {
        throw new AdhocWebServiceException(
                Messages.getErrorString("AdhocWebService.ERROR_0002_REPORT_INVALID")); //$NON-NLS-1$
    }

    // ========== begin column width stuff

    // make copies of the business columns; in the next step we're going to fill out any missing column widths
    LogicalColumn[] columns = new LogicalColumn[reportSpec.getField().length];
    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        String name = field.getName();
        LogicalColumn column = model.findLogicalColumn(name);
        columns[i] = (LogicalColumn) column.clone();
    }

    boolean columnWidthUnitsConsistent = AdhocWebService.areMetadataColumnUnitsConsistent(reportSpec, model);

    if (!columnWidthUnitsConsistent) {
        logger.error(Messages.getErrorString("AdhocWebService.ERROR_0013_INCONSISTENT_COLUMN_WIDTH_UNITS")); //$NON-NLS-1$
    } else {
        double columnWidthScaleFactor = 1.0;
        int missingColumnWidthCount = 0;
        int columnWidthSumOfPercents;
        double defaultWidth;
        columnWidthSumOfPercents = AdhocWebService.getSumOfMetadataColumnWidths(reportSpec, model);
        missingColumnWidthCount = AdhocWebService.getMissingColumnWidthCount(reportSpec, model);

        // if there are columns with no column width specified, figure out what percent we should use for them
        if (missingColumnWidthCount > 0) {
            if (columnWidthSumOfPercents < 100) {
                int remainingPercent = 100 - columnWidthSumOfPercents;
                defaultWidth = remainingPercent / missingColumnWidthCount;
                columnWidthSumOfPercents = 100;
            } else {
                defaultWidth = 10;
                columnWidthSumOfPercents += (missingColumnWidthCount * 10);
            }

            // fill in columns without column widths
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                if (property == null) {
                    property = new ColumnWidth(WidthType.PERCENT, defaultWidth);
                    columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), property);
                }
            }
        }

        if (columnWidthSumOfPercents > 100) {
            columnWidthScaleFactor = 100.0 / (double) columnWidthSumOfPercents;
        }

        // now scale down if necessary
        if (columnWidthScaleFactor < 1.0) {
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                ColumnWidth newProperty = new ColumnWidth(property.getType(),
                        columnWidthScaleFactor * property.getWidth());
                columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), newProperty);
            }
        }

    }

    // ========== end column width stuff

    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        LogicalColumn column = columns[i];

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

        // Template properties have the lowest priority, merge them last
        if (bUseTemplate) {
            Element templateDefaults = null;
            if (column.getDataType() != null) {
                templateDefaults = (Element) reportSpecTypeToElement
                        .get(AdhocWebService.METADATA_TYPE_TO_REPORT_SPEC_TYPE.get(column.getDataType())); // sorry, this is ugly as hell
            }
            /*
             * NOTE: this merge of the template with the node's properties only sets the following properties:
             * format, fontname, fontsize, color, alignment, vertical-alignment, 
             */
            AdhocWebService.applyTemplate(field, templateDefaults);
        }
        AdhocWebService.applyDefaults(field);
    } // end for

    /*
     * Create the xml document (generatedJFreeDoc) containing the jfreereport definition using
     * the reportSpec as input. generatedJFreeDoc will have the metadata merged with it,
     * and some of the template.
     */
    ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream();
    ReportGenerationUtility.createJFreeReportXMLAsStream(reportSpec, reportXMLEncoding,
            (OutputStream) jfreeOutputStream);
    String jfreeXml = jfreeOutputStream.toString(reportXMLEncoding);
    Document generatedJFreeDoc = null;
    try {
        generatedJFreeDoc = XmlDom4JHelper.getDocFromString(jfreeXml, 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);
    }

    /*
     * Merge template's /report/items element's attributes into the
     * generated document's /report/items element's attributes. There should not be any
     * conflict with the metadata, or the xreportspec in the reportXML param
     */
    if (bUseTemplate) {
        Element reportItems = (Element) generatedJFreeDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List templateAttrs = templateItems.attributes(); // from the template's /report/items element
        Iterator templateAttrsIt = templateAttrs.iterator();

        while (templateAttrsIt.hasNext()) {
            Attribute attr = (Attribute) templateAttrsIt.next();
            String name = attr.getName();
            String value = attr.getText();

            Node node = reportItems.selectSingleNode("@" + name); //$NON-NLS-1$
            if (node != null) {
                node.setText(value);
            } else {
                reportItems.addAttribute(name, value);
            }
        }
        List templateElements = templateItems.elements();
        Iterator templateElementsIt = templateElements.iterator();
        while (templateElementsIt.hasNext()) {
            Element element = (Element) templateElementsIt.next();
            element.detach();
            reportItems.add(element);
        }
        /*
         * NOTE: this merging of the template (ReportGenerationUtility.mergeTemplate())
         * with the generated document can wait until last because none of the 
         * properties involved in this merge are settable by the metadata or the WAQR UI
         */
        ReportGenerationUtility.mergeTemplateAsStream(templateDoc, generatedJFreeDoc, jfreeMergedOutputStream);
    } else {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(reportXMLEncoding);
        XMLWriter writer = new XMLWriter(jfreeMergedOutputStream, format);
        writer.write(generatedJFreeDoc);
        writer.close();
    }
}

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

License:Open Source License

public void getWaqrReportSpecDoc(final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final boolean wrapWithSoap)
        throws AdhocWebServiceException, IOException {

    ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);
    String solution = parameterProvider.getStringParameter("solution", null); //$NON-NLS-1$
    String path = parameterProvider.getStringParameter("path", null); //$NON-NLS-1$
    String filename = parameterProvider.getStringParameter("filename", null); //$NON-NLS-1$

    Document reportSpecDoc = null;
    if (!StringUtils.isEmpty(solution) && (null != path) && !StringUtils.isEmpty(filename)) {
        try {/*  w w w . ja  v  a  2s  .  c o  m*/
            String filePath = ActionInfo.buildSolutionPath(solution, path, filename);
            reportSpecDoc = repository.getResourceAsDocument(filePath, ISolutionRepository.ACTION_EXECUTE);
        } catch (IOException ex) {
            String msg = Messages.getString("AdhocWebService.ERROR_0004_FAILED_TO_LOAD_REPORTSPEC", //$NON-NLS-1$
                    filename);
            throw new AdhocWebServiceException(msg, ex);
        }
    } else {
        String msg = Messages.getString("AdhocWebService.ERROR_0005_MISSING_REPORTSPEC_NAME"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }
    /* -------------------------------- BISERVER-5263 ---------------------------------------
     * Pre-3.6 ReportSpecs generated by waqr didn't have an xmi file specified in the domain_id
     * node.  Below we detect this condition (ie. we're trying to edit a pre-3.6 report using a
     * 3.7 dist) and we specify the default metadata.xmi file for the solution specified.
     */
    Node domainIdNode = reportSpecDoc.selectSingleNode("//report-spec/query/mql/domain_id"); //$NON-NLS-1$
    String domainId = domainIdNode.getText();
    if (!domainId.endsWith(".xmi")) { //$NON-NLS-1$
        domainId += "/metadata.xmi"; //$NON-NLS-1$
        domainIdNode.setText(domainId);
    }
    // ---------------------------------------------------------------------------------------
    WebServiceUtil.writeDocument(outputStream, reportSpecDoc, wrapWithSoap);
}