Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

From source file:org.pentaho.platform.engine.services.actionsequence.SequenceDefinition.java

License:Open Source License

public static IActionSequence ActionSequenceFactory(final Document document, final String solutionPath,
        final ILogger logger, final IApplicationContext applicationContext, final int loggingLevel) {

    // Check for a sequence document
    Node sequenceDefinitionNode = document.selectSingleNode("//action-sequence"); //$NON-NLS-1$
    if (sequenceDefinitionNode == null) {
        logger.error(Messages.getInstance()
                .getErrorString("SequenceDefinition.ERROR_0002_NO_ACTION_SEQUENCE_NODE", "", solutionPath, "")); //$NON-NLS-1$
        return null;
    }/* www .  ja  va 2s  .co m*/

    ISequenceDefinition seqDef = new SequenceDefinition(sequenceDefinitionNode, solutionPath, logger,
            applicationContext);

    Node actionNode = sequenceDefinitionNode.selectSingleNode("actions"); //$NON-NLS-1$

    return (SequenceDefinition.getNextLoopGroup(seqDef, actionNode, solutionPath, logger, loggingLevel));
}

From source file:org.pentaho.platform.engine.services.actionsequence.SequenceDefinition.java

License:Open Source License

static IConditionalExecution parseConditionalExecution(final Node actionRootNode, final ILogger logger,
        final String nodePath) {
    try {/*  w  w w  . ja va2 s .c o  m*/
        Node condition = actionRootNode.selectSingleNode(nodePath);
        if (condition == null) {
            return null;
        }
        String script = condition.getText();
        IConditionalExecution ce = PentahoSystem.get(IConditionalExecution.class, null);
        ce.setScript(script);
        return ce;
    } catch (Exception ex) {
        logger.error(Messages.getInstance().getErrorString("SequenceDefinition.ERROR_0005_PARSING_PARAMETERS"), //$NON-NLS-1$
                ex);
    }
    return null;
}

From source file:org.pentaho.platform.engine.services.actionsequence.SequenceDefinition.java

License:Open Source License

private int parseResourceDefinitions(final Node actionRootNode, final ILogger logger) {

    resourceDefinitions = new ListOrderedMap();

    try {/*from   w  w  w  .j  a  va 2  s. c o m*/
        List resources = actionRootNode.selectNodes("resources/*"); //$NON-NLS-1$

        // TODO create objects to represent the types
        // TODO need source variable list
        Iterator resourcesIterator = resources.iterator();

        Node resourceNode;
        String resourceName;
        String resourceTypeName;
        String resourceMimeType;
        int resourceType;
        ActionSequenceResource resource;
        Node typeNode, mimeNode;
        while (resourcesIterator.hasNext()) {
            resourceNode = (Node) resourcesIterator.next();
            typeNode = resourceNode.selectSingleNode("./*"); //$NON-NLS-1$
            if (typeNode != null) {
                resourceName = resourceNode.getName();
                resourceTypeName = typeNode.getName();
                resourceType = ActionSequenceResource.getResourceType(resourceTypeName);
                String resourceLocation = XmlDom4JHelper.getNodeText("location", typeNode); //$NON-NLS-1$
                if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                        || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
                    if (resourceLocation == null) {
                        logger.error(Messages.getInstance().getErrorString(
                                "SequenceDefinition.ERROR_0008_RESOURCE_NO_LOCATION", resourceName)); //$NON-NLS-1$
                        continue;
                    }
                } else if (resourceType == IActionSequenceResource.STRING) {
                    resourceLocation = XmlDom4JHelper.getNodeText("string", resourceNode); //$NON-NLS-1$
                } else if (resourceType == IActionSequenceResource.XML) {
                    //resourceLocation = XmlHelper.getNodeText("xml", resourceNode); //$NON-NLS-1$
                    Node xmlNode = typeNode.selectSingleNode("./location/*"); //$NON-NLS-1$
                    // Danger, we have now lost the character encoding of the XML in this node
                    // see BISERVER-895
                    resourceLocation = (xmlNode == null) ? "" : xmlNode.asXML(); //$NON-NLS-1$
                }
                mimeNode = typeNode.selectSingleNode("mime-type"); //$NON-NLS-1$
                if (mimeNode != null) {
                    resourceMimeType = mimeNode.getText();
                    if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                            || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
                        resourceLocation = FilenameUtils.separatorsToUnix(resourceLocation);
                        if (!resourceLocation.startsWith("/")) { //$NON-NLS-1$
                            String parentDir = FilenameUtils.getFullPathNoEndSeparator(xactionPath);
                            if (parentDir.length() == 0) {
                                parentDir = RepositoryFile.SEPARATOR;
                            }
                            resourceLocation = FilenameUtils
                                    .separatorsToUnix(FilenameUtils.concat(parentDir, resourceLocation));
                        }
                    }
                    resource = new ActionSequenceResource(resourceName, resourceType, resourceMimeType,
                            resourceLocation);
                    resourceDefinitions.put(resourceName, resource);
                } else {
                    logger.error(Messages.getInstance().getErrorString(
                            "SequenceDefinition.ERROR_0007_RESOURCE_NO_MIME_TYPE", resourceName)); //$NON-NLS-1$
                }
            }
            // input = new ActionParameter( resourceName, resourceType, null
            // );
            // resourceDefinitions.put( inputName, input );
        }
        return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_OK;
    } catch (Exception e) {
        logger.error(Messages.getInstance().getErrorString("SequenceDefinition.ERROR_0006_PARSING_RESOURCE"), //$NON-NLS-1$
                e);
    }
    return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_INVALID_ACTION_DOC;

}

From source file:org.pentaho.platform.engine.services.actionsequence.SequenceDefinition.java

License:Open Source License

private static Object getDefaultValue(final Node parameterNode) {
    Node rootNode = parameterNode.selectSingleNode("default-value"); //$NON-NLS-1$
    if (rootNode == null) {
        return (null);
    }/*w w w.java2 s .co  m*/

    String dataType = XmlDom4JHelper.getNodeText("@type", rootNode); //$NON-NLS-1$
    if (dataType == null) {
        dataType = XmlDom4JHelper.getNodeText("@type", parameterNode); //$NON-NLS-1$
    }

    if ("string-list".equals(dataType)) { //$NON-NLS-1$
        List nodes = rootNode.selectNodes("list-item"); //$NON-NLS-1$
        if (nodes == null) {
            return (null);
        }

        ArrayList rtnList = new ArrayList();
        for (Iterator it = nodes.iterator(); it.hasNext();) {
            rtnList.add(((Node) it.next()).getText());
        }
        return (rtnList);
    } else if ("property-map-list".equals(dataType)) { //$NON-NLS-1$
        List nodes = rootNode.selectNodes("property-map"); //$NON-NLS-1$
        if (nodes == null) {
            return (null);
        }

        ArrayList rtnList = new ArrayList();
        for (Iterator it = nodes.iterator(); it.hasNext();) {
            Node mapNode = (Node) it.next();
            rtnList.add(SequenceDefinition.getMapFromNode(mapNode));
        }
        return (rtnList);
    } else if ("property-map".equals(dataType)) { //$NON-NLS-1$
        return (SequenceDefinition.getMapFromNode(rootNode.selectSingleNode("property-map"))); //$NON-NLS-1$
    } else if ("long".equals(dataType)) { //$NON-NLS-1$
        try {
            return (new Long(rootNode.getText()));
        } catch (Exception e) {
            //ignore
        }
        return (null);
    } else if ("result-set".equals(dataType)) { //$NON-NLS-1$

        return (MemoryResultSet.createFromActionSequenceInputsNode(parameterNode));
    } else { // Assume String
        return (rootNode.getText());
    }

}

From source file:org.pentaho.platform.plugin.action.builtin.SecureFilterComponent.java

License:Open Source License

@Override
public boolean validateAction() {
    Node compDef = getComponentDefinition();
    List selNodes = compDef.selectNodes("selections/*"); //$NON-NLS-1$

    String inputName = null;/*  w  w  w .j av a 2s .  c  om*/
    boolean isOk = true;

    for (Iterator it = selNodes.iterator(); it.hasNext();) {
        Node node = (Node) it.next();
        try {
            inputName = node.getName(); // Get the Data Node
            IActionParameter inputParam = getInputParameter(inputName);
            String filterType = XmlDom4JHelper.getNodeText("@filter", node, null); //$NON-NLS-1$

            // BISERVER-149 Changed isOptional param to default to false in order to
            // enable prompting when no default value AND no selection list is given...
            // This is also the default that Design Studio presumes.

            String optionalParm = XmlDom4JHelper.getNodeText("@optional", node, "false"); //$NON-NLS-1$ //$NON-NLS-2$
            boolean isOptional = "true".equals(optionalParm); //$NON-NLS-1$

            if ("none".equalsIgnoreCase(filterType)) { //$NON-NLS-1$
                IActionParameter selectParam = getInputParameter(inputName);
                String title = XmlDom4JHelper.getNodeText("title", node, inputName); //$NON-NLS-1$
                String valueCol = ""; //$NON-NLS-1$
                String dispCol = ""; //$NON-NLS-1$
                String displayStyle = XmlDom4JHelper.getNodeText("@style", node, null); //$NON-NLS-1$
                boolean promptOne = "true" //$NON-NLS-1$
                        .equalsIgnoreCase(XmlDom4JHelper.getNodeText("@prompt-if-one-value", node, "false")); //$NON-NLS-1$ //$NON-NLS-2$
                if ("hidden".equals(displayStyle)) { //$NON-NLS-1$
                    hiddenList.add(new SelEntry(inputParam, selectParam, valueCol, dispCol, title, displayStyle,
                            promptOne, isOptional));
                } else {
                    selList.add(new SelEntry(inputParam, selectParam, valueCol, dispCol, title, displayStyle,
                            promptOne, isOptional));
                }
            } else {
                Node filterNode = node.selectSingleNode("filter"); //$NON-NLS-1$
                IActionParameter selectParam = getInputParameter(filterNode.getText().trim());

                String valueCol = XmlDom4JHelper.getNodeText("@value-col-name", filterNode, null); //$NON-NLS-1$
                String dispCol = XmlDom4JHelper.getNodeText("@display-col-name", filterNode, null); //$NON-NLS-1$

                String title = XmlDom4JHelper.getNodeText("title", node, null); //$NON-NLS-1$
                String displayStyle = XmlDom4JHelper.getNodeText("@style", node, null); //$NON-NLS-1$
                boolean promptOne = "true" //$NON-NLS-1$
                        .equalsIgnoreCase(XmlDom4JHelper.getNodeText("@prompt-if-one-value", node, "false")); //$NON-NLS-1$ //$NON-NLS-2$

                selList.add(new SelEntry(inputParam, selectParam, valueCol, dispCol, title, displayStyle,
                        promptOne, isOptional));
            }

        } catch (Exception e) { // Catch the exception to let us test all
            // the params
            isOk = false;
            error(Messages.getInstance().getErrorString("SecureFilterComponent.ERROR_0001_PARAM_MISSING", //$NON-NLS-1$
                    inputName));
        }
    }

    return (isOk);
}

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;
    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();/*www  .  j av a 2s . c  o  m*/
        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.kettle.KettleComponent.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   ww w  .j  a v  a 2  s  . c o  m*/
public boolean validateAction() {

    // If there are any mappings, validate their xml and values
    if (getComponentDefinition()
            .selectNodes(
                    PARAMETER_MAP_CMD_ARG + " | " + PARAMETER_MAP_VARIABLE + " | " + PARAMETER_MAP_PARAMETER) //$NON-NLS-1$//$NON-NLS-2$
            .size() > 0) {
        Map<String, String> argumentMap = null;

        Node name = null, mapping = null;

        // Extract all mapping elements from component-definition and verify
        // they have a 'name' and 'mapping' child element
        for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_CMD_ARG)) {
            name = n.selectSingleNode("name"); //$NON-NLS-1$
            mapping = n.selectSingleNode("mapping"); //$NON-NLS-1$
            if (checkMapping(name, mapping)) {
                if (argumentMap == null) {
                    argumentMap = new HashMap<String, String>();
                }
                argumentMap.put(name.getText(), applyInputsToFormat(getInputStringValue(mapping.getText())));
            } else {
                return false;
            }
        }

        for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_VARIABLE)) {
            name = n.selectSingleNode("name"); //$NON-NLS-1$
            mapping = n.selectSingleNode("mapping"); //$NON-NLS-1$
            if (!checkMapping(name, mapping)) {
                return false;
            }
        }

        for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_PARAMETER)) {
            name = n.selectSingleNode("name"); //$NON-NLS-1$
            mapping = n.selectSingleNode("mapping"); //$NON-NLS-1$
            if (!checkMapping(name, mapping)) {
                return false;
            }
        }

        // Make sure all of the arguments are present, correctly labeled and
        // that there are not more then 10 (currently supported by Kettle)
        if (argumentMap != null) {
            String val = null;
            for (int i = 1; i <= argumentMap.size(); i++) {
                val = argumentMap.get(Integer.toString(i));
                if (val == null) {
                    error(Messages.getInstance().getErrorString("Kettle.ERROR_0030_INVALID_ARGUMENT_MAPPING")); //$NON-NLS-1$
                    return false;
                }
            }
        }
    }

    if (isDefinedResource(KettleComponent.TRANSFORMFILE) || isDefinedResource(KettleComponent.JOBFILE)) {
        return true;
    }

    boolean useRepository = PentahoSystem.getSystemSetting("kettle/settings.xml", "repository.type", "files") //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            .equals("rdbms"); //$NON-NLS-1$

    if (!useRepository) {
        error(Messages.getInstance().getErrorString("Kettle.ERROR_0019_REPOSITORY_TYPE_FILES")); //$NON-NLS-1$
        return false;
    }

    if (isDefinedInput(KettleComponent.DIRECTORY)
            && (isDefinedInput(KettleComponent.TRANSFORMATION) || isDefinedInput(KettleComponent.JOB))) {
        return true;
    }

    if (!isDefinedInput(KettleComponent.DIRECTORY)) {
        error(Messages.getInstance().getErrorString("Kettle.ERROR_0002_DIR_OR_FILE__NOT_DEFINED", //$NON-NLS-1$
                getActionName()));
        return false;
    } else {
        if (!isDefinedInput(KettleComponent.TRANSFORMATION)) {
            error(Messages.getInstance().getErrorString("Kettle.ERROR_0003_TRANS_NOT_DEFINED", //$NON-NLS-1$
                    getActionName()));
            return false;
        }
    }

    return false;

}

From source file:org.pentaho.platform.plugin.action.kettle.KettleComponent.java

License:Open Source License

/**
 * Execute the specified transformation in the chosen repository.
 *//*  w w w  .  j  a v  a 2s . co m*/
@SuppressWarnings("unchecked")
@Override
public boolean executeAction() {

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Kettle.DEBUG_START")); //$NON-NLS-1$
    }

    TransMeta transMeta = null;
    JobMeta jobMeta = null;

    // Build lists of parameters, variables and command line arguments

    Map<String, String> argumentMap = new HashMap<String, String>();
    Map<String, String> variableMap = new HashMap<String, String>();
    Map<String, String> parameterMap = new HashMap<String, String>();

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_CMD_ARG)) {
        argumentMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_VARIABLE)) {
        variableMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    for (Node n : (List<Node>) getComponentDefinition().selectNodes(PARAMETER_MAP_PARAMETER)) {
        parameterMap.put(n.selectSingleNode("name").getText(),
                applyInputsToFormat(getInputStringValue(n.selectSingleNode("mapping").getText()))); //$NON-NLS-1$ //$NON-NLS-2$
    }

    String[] arguments = null;

    // If no mappings are provided, assume all inputs are command line
    // arguments (This supports the legacy method)
    if (argumentMap.size() <= 0 && variableMap.size() <= 0 && parameterMap.size() <= 0) {
        // this use is now considered obsolete, as we prefer the
        // action-sequence inputs since they
        // now maintain order
        boolean running = true;
        int index = 1;
        ArrayList<String> argumentList = new ArrayList<String>();
        while (running) {
            if (isDefinedInput("parameter" + index)) { //$NON-NLS-1$
                String value = null;
                String inputName = getInputStringValue("parameter" + index); //$NON-NLS-1$
                // see if we have an input with this name
                if (isDefinedInput(inputName)) {
                    value = getInputStringValue(inputName);
                }
                argumentList.add(value);
            } else {
                running = false;
            }
            index++;
        }

        // this is the preferred way to provide inputs to the
        // KetteComponent, the order of inputs is now preserved
        Iterator<?> inputNamesIter = getInputNames().iterator();
        while (inputNamesIter.hasNext()) {
            String name = (String) inputNamesIter.next();
            argumentList.add(getInputStringValue(name));
        }

        arguments = (String[]) argumentList.toArray(new String[argumentList.size()]);
    } else {
        // Extract arguments from argumentMap (Throw an error if the
        // sequential ordering is broken)
        arguments = new String[argumentMap.size()];
        for (int i = 0; i < argumentMap.size(); i++) {
            arguments[i] = argumentMap.get(Integer.toString(i + 1)); // Mapping
            // is
            // 1
            // based
            // to
            // match
            // Kettle
            // UI
            if (arguments[i] == null) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0030_INVALID_ARGUMENT_MAPPING")); //$NON-NLS-1$
            }
        }
    }

    // initialize environment variables
    try {
        KettleSystemListener.environmentInit(getSession());
    } catch (KettleException ke) {
        error(ke.getMessage(), ke);
    }

    String solutionPath = "solution:";

    Repository repository = connectToRepository();
    boolean result = false;

    try {
        if (isDefinedInput(KettleComponent.DIRECTORY)) {
            String directoryName = getInputStringValue(KettleComponent.DIRECTORY);

            if (repository == null) {
                return false;
            }

            if (isDefinedInput(KettleComponent.TRANSFORMATION)) {
                String transformationName = getInputStringValue(KettleComponent.TRANSFORMATION);
                transMeta = loadTransformFromRepository(directoryName, transformationName, repository);
                if (transMeta != null) {
                    try {
                        for (String key : parameterMap.keySet()) {
                            transMeta.setParameterValue(key, parameterMap.get(key));
                        }
                        for (String key : variableMap.keySet()) {
                            transMeta.setVariable(key, variableMap.get(key));
                        }

                    } catch (UnknownParamException e) {
                        error(e.getMessage());
                    }
                    transMeta.setArguments(arguments);
                } else {
                    return false;
                }
            } else if (isDefinedInput(KettleComponent.JOB)) {
                String jobName = getInputStringValue(KettleComponent.JOB);
                jobMeta = loadJobFromRepository(directoryName, jobName, repository);
                if (jobMeta != null) {
                    try {
                        for (String key : parameterMap.keySet()) {
                            jobMeta.setParameterValue(key, parameterMap.get(key));
                        }
                        for (String key : variableMap.keySet()) {
                            jobMeta.setVariable(key, variableMap.get(key));
                        }

                    } catch (UnknownParamException e) {
                        error(e.getMessage());
                    }
                    jobMeta.setArguments(arguments);
                } else {
                    return false;
                }
            }
        } else if (isDefinedResource(KettleComponent.TRANSFORMFILE)) {
            IActionSequenceResource transformResource = getResource(KettleComponent.TRANSFORMFILE);
            String fileAddress = getActualFileName(transformResource);

            try {
                if (fileAddress != null) { // We have an actual loadable
                    // filesystem and file
                    transMeta = new TransMeta(fileAddress, repository, true);
                    transMeta.setFilename(fileAddress);
                } else if (repository != null && repository.isConnected()) {

                    fileAddress = transformResource.getAddress();
                    // load transformation resource from kettle/settings.xml configured repository
                    transMeta = loadTransformFromRepository(FilenameUtils.getPathNoEndSeparator(fileAddress),
                            FilenameUtils.getBaseName(fileAddress), repository);
                } else {
                    String jobXmlStr = getResourceAsString(getResource(KettleComponent.TRANSFORMFILE));
                    jobXmlStr = jobXmlStr.replaceAll("\\$\\{pentaho.solutionpath\\}", solutionPath); //$NON-NLS-1$
                    jobXmlStr = jobXmlStr.replaceAll("\\%\\%pentaho.solutionpath\\%\\%", solutionPath); //$NON-NLS-1$
                    org.w3c.dom.Document doc = XmlW3CHelper.getDomFromString(jobXmlStr);
                    // create a tranformation from the document
                    transMeta = new TransMeta(doc.getFirstChild(), repository);
                }
            } catch (Exception e) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.TRANSFORMFILE, fileAddress), e);
                return false;
            }

            /*
             * Unreachable code below... if (transMeta == null) {
             * error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", KettleComponent.TRANSFORMFILE,
             * fileAddress)); //$NON-NLS-1$ debug(getKettleLog(true)); return false; }
             */

            // Don't forget to set the parameters here as well...
            try {
                for (String key : parameterMap.keySet()) {
                    transMeta.setParameterValue(key, parameterMap.get(key));
                }
                for (String key : variableMap.keySet()) {
                    transMeta.setVariable(key, variableMap.get(key));
                }

            } catch (UnknownParamException e) {
                error(e.getMessage());
            }
            transMeta.setArguments(arguments);
            /*
             * We do not need to concatenate the solutionPath info as the fileAddress has the complete location of the file
             * from start to end. This is to resolve BISERVER-502.
             */
            transMeta.setFilename(fileAddress);

        } else if (isDefinedResource(KettleComponent.JOBFILE)) {
            String fileAddress = ""; //$NON-NLS-1$
            try {
                fileAddress = getResource(KettleComponent.JOBFILE).getAddress();

                if (repository != null && repository.isConnected()) {

                    solutionPath = StringUtils.EMPTY;

                    // load job resource from kettle/settings.xml configured repository
                    jobMeta = loadJobFromRepository(FilenameUtils.getPathNoEndSeparator(fileAddress),
                            FilenameUtils.getBaseName(fileAddress), repository);

                } else {

                    String jobXmlStr = getResourceAsString(getResource(KettleComponent.JOBFILE));
                    // String jobXmlStr =
                    // XmlW3CHelper.getContentFromSolutionResource(fileAddress);
                    jobXmlStr = jobXmlStr.replaceAll("\\$\\{pentaho.solutionpath\\}", solutionPath); //$NON-NLS-1$
                    jobXmlStr = jobXmlStr.replaceAll("\\%\\%pentaho.solutionpath\\%\\%", solutionPath); //$NON-NLS-1$
                    org.w3c.dom.Document doc = XmlW3CHelper.getDomFromString(jobXmlStr);
                    if (doc == null) {
                        error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                                KettleComponent.JOBFILE, fileAddress));
                        debug(getKettleLog(true));
                        return false;
                    }
                    // create a job from the document
                    try {
                        repository = connectToRepository();
                        // if we get a valid repository its great, if not try it
                        // without

                        jobMeta = new JobMeta(solutionPath + fileAddress, repository);
                    } catch (Exception e) {
                        error(Messages.getInstance().getString("Kettle.ERROR_0023_NO_META"), e); //$NON-NLS-1$
                    } finally {
                        if (repository != null) {
                            if (ComponentBase.debug) {
                                debug(Messages.getInstance().getString("Kettle.DEBUG_DISCONNECTING")); //$NON-NLS-1$
                            }
                            repository.disconnect();
                        }
                    }
                }
            } catch (Exception e) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.JOBFILE, fileAddress), e);
                return false;
            }
            if (jobMeta == null) {
                error(Messages.getInstance().getErrorString("Kettle.ERROR_0015_BAD_RESOURCE", //$NON-NLS-1$
                        KettleComponent.JOBFILE, fileAddress));
                debug(getKettleLog(true));
                return false;
            } else {
                try {
                    for (String key : parameterMap.keySet()) {
                        jobMeta.setParameterValue(key, parameterMap.get(key));
                    }
                    for (String key : variableMap.keySet()) {
                        jobMeta.setVariable(key, variableMap.get(key));
                    }

                } catch (UnknownParamException e) {
                    error(e.getMessage());
                }
                jobMeta.setArguments(arguments);
                jobMeta.setFilename(solutionPath + fileAddress);
            }

        }

        // OK, we have the information, let's load and execute the
        // transformation or job

        if (transMeta != null) {
            result = executeTransformation(transMeta);
        }
        if (jobMeta != null) {
            result = executeJob(jobMeta, repository);
        }

    } finally {

        if (repository != null) {
            if (ComponentBase.debug) {
                debug(Messages.getInstance().getString("Kettle.DEBUG_DISCONNECTING")); //$NON-NLS-1$
            }
            try {
                repository.disconnect();
            } catch (Exception ignored) {
                //ignore
            }
        }

        if (transMeta != null) {
            try {
                cleanLogChannel(transMeta);
                transMeta.clear();
            } catch (Exception ignored) {
                //ignore
            }
            transMeta = null;
        }
        if (jobMeta != null) {
            try {
                cleanLogChannel(jobMeta);
                jobMeta.clear();
            } catch (Exception ignored) {
                //ignored
            }
            // Can't do anything about an exception here.
            jobMeta = null;
        }
    }

    if (isDefinedOutput(EXECUTION_LOG_OUTPUT)) {
        setOutputValue(EXECUTION_LOG_OUTPUT, executionLog);
    }

    if (isDefinedOutput(EXECUTION_STATUS_OUTPUT)) {
        setOutputValue(EXECUTION_STATUS_OUTPUT, executionStatus);
    }

    XMLHandlerCache.getInstance().clear();
    return result;

}

From source file:org.pentaho.platform.plugin.action.openflashchart.factory.PentahoOFC4JChartHelper.java

License:Open Source License

@SuppressWarnings("unchecked")
public static String generateChartJson(Node chartNode, IPentahoResultSet data, boolean byRow, Log log) {
    String chartType = null;// w  ww.ja va  2s . com
    String factoryClassString = null;
    try {
        Node temp = chartNode.selectSingleNode(CHART_TYPE_NODE_LOC);
        if (AbstractChartFactory.getValue(temp) != null) {
            chartType = AbstractChartFactory.getValue(temp);
        } else {
            // This should NEVER happen.
            chartType = CHART_TYPE_DEFAULT;
        }

        factoryClassString = (String) getChartFactories().get(chartType);
        if (factoryClassString == null) {
            throw new RuntimeException(Messages.getInstance().getErrorString(
                    "PentahoOFC4JChartHelper.ERROR_0001_FACTORY_INIT", chartType, factoryClassString)); //$NON-NLS-1$
        } else {

            Class factoryClass = Class.forName(factoryClassString);

            // throw exception if factoryClass not found

            IChartFactory factory = (IChartFactory) factoryClass.getConstructor(new Class[0])
                    .newInstance(new Object[0]);
            factory.setChartNode(chartNode);
            factory.setLog(log);
            if (byRow) {
                factory.setData(PentahoDataTransmuter.pivot(data));
            } else {
                factory.setData(data);
            }
            return factory.convertToJson();
        }
    } catch (Exception e) {
        logger.error(Messages.getInstance().getErrorString("PentahoOFC4JChartHelper.ERROR_0001_FACTORY_INIT", //$NON-NLS-1$
                chartType, factoryClassString), e);
        throw new RuntimeException(e);
    }
}

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

License:Open Source License

public static Document convertXml(final Document reportXml) {

    // get the list of headers
    List<String> headerList = new ArrayList<String>();
    List<?> nodes = reportXml.selectNodes("/report/groupheader/@name"); //$NON-NLS-1$
    // find all the unique group header names

    Iterator<?> it = nodes.iterator();
    Attribute attr;/*from   www. j ava  2 s .  c om*/
    String name;
    while (it.hasNext()) {
        // we only need to go until we get the first duplicate
        attr = (Attribute) it.next();
        name = attr.getText();
        if (!"dummy".equals(name)) { //$NON-NLS-1$
            if (!headerList.contains(name)) {
                headerList.add(name);
                System.out.println(name);
            } else {
                break;
            }
        }
    }

    String headerNames[] = new String[headerList.size()];
    String headerValues[] = new String[headerList.size()];
    Element headerNodes[] = new Element[headerList.size()];
    String columnHeaders[] = new String[0];
    Element columnHeaderNodes[] = new Element[0];
    headerList.toArray(headerNames);
    for (int idx = 0; idx < headerValues.length; idx++) {
        headerValues[idx] = ""; //$NON-NLS-1$
    }

    Document reportDoc = DocumentHelper.createDocument();
    Element reportNode = DocumentHelper.createElement("report"); //$NON-NLS-1$
    reportDoc.setRootElement(reportNode);

    // process the top-level nodes
    nodes = reportXml.selectNodes("/report/*"); //$NON-NLS-1$

    Node node;
    // go thru all the nodes
    it = nodes.iterator();
    while (it.hasNext()) {
        node = (Node) it.next();
        name = node.getName();
        if ("groupheader".equals(name)) { //$NON-NLS-1$
            // process the group headers
            // get the group header name
            String headerName = node.selectSingleNode("@name").getText(); //$NON-NLS-1$
            if (!"dummy".equals(headerName)) { //$NON-NLS-1$
                // find the header index
                String headerValue = node.selectSingleNode("element[1]").getText();//$NON-NLS-1$
                int headerIdx = -1;
                for (int idx = 0; idx < headerNames.length; idx++) {
                    if (headerNames[idx].equals(headerName)) {
                        headerIdx = idx;
                        break;
                    }
                }
                if (!headerValues[headerIdx].equals(headerValue)) {
                    // this is a new header value
                    headerValues[headerIdx] = headerValue;
                    // find the parent node
                    Element parentNode;
                    if (headerIdx == 0) {
                        parentNode = reportNode;
                    } else {
                        parentNode = headerNodes[headerIdx - 1];
                    }

                    // create a group header node for this
                    Element headerNode = DocumentHelper.createElement("groupheader");//$NON-NLS-1$
                    parentNode.add(headerNode);
                    headerNodes[headerIdx] = headerNode;

                    // create the name attribute
                    attr = DocumentHelper.createAttribute(headerNode, "name", headerName);//$NON-NLS-1$
                    headerNode.add(attr);

                    // create the value node
                    Element elementNode = DocumentHelper.createElement("element");//$NON-NLS-1$
                    headerNode.add(elementNode);
                    attr = DocumentHelper.createAttribute(elementNode, "name", headerName);//$NON-NLS-1$
                    elementNode.add(attr);
                    elementNode.setText(headerValue);

                }
            }

            // see if there are any column headers
            List<?> elements = node.selectNodes("element");//$NON-NLS-1$
            if (elements.size() == 0) {
                elements = node.selectNodes("band/element");//$NON-NLS-1$
            }
            if (elements.size() > 1) {
                // there are column headers here, get them and store them for the next set of rows
                columnHeaders = new String[elements.size() - 1];
                columnHeaderNodes = new Element[elements.size() - 1];
                for (int idx = 1; idx < elements.size(); idx++) {
                    columnHeaders[idx - 1] = ((Element) elements.get(idx)).getText();
                }
            }
        } else if ("items".equals(name)) {//$NON-NLS-1$
            // process items (rows)
            // get the parent node, this should always be the last one on the list
            Element parentNode;
            if (headerNodes.length == 0) {
                parentNode = reportNode;
            } else {
                parentNode = headerNodes[headerNodes.length - 1];
            }
            // create the items node
            Element itemsNode = DocumentHelper.createElement("items");//$NON-NLS-1$
            parentNode.add(itemsNode);
            // create the headers node
            Element headersNode = DocumentHelper.createElement("headers");//$NON-NLS-1$
            itemsNode.add(headersNode);
            // create the rows node
            Element itemBandsNode = DocumentHelper.createElement("itembands");//$NON-NLS-1$
            itemsNode.add(itemBandsNode);
            for (int idx = 0; idx < columnHeaders.length; idx++) {
                Element headerNode = DocumentHelper.createElement("header");//$NON-NLS-1$
                headerNode.setText(columnHeaders[idx]);
                headersNode.add(headerNode);
                columnHeaderNodes[idx] = headerNode;

            }
            // now copy the item bands over
            List<?> itembands = node.selectNodes("itemband");//$NON-NLS-1$
            Iterator<?> bands = itembands.iterator();
            boolean first = true;
            while (bands.hasNext()) {
                Element itemband = (Element) bands.next();
                Element itemBandNode = DocumentHelper.createElement("itemband");//$NON-NLS-1$
                itemBandsNode.add(itemBandNode);
                List<?> elementList = itemband.selectNodes("element");//$NON-NLS-1$
                Iterator<?> elements = elementList.iterator();
                int idx = 0;
                while (elements.hasNext()) {
                    Element element = (Element) elements.next();
                    Element elementNode = DocumentHelper.createElement("element");//$NON-NLS-1$
                    itemBandNode.add(elementNode);
                    elementNode.setText(element.getText());
                    name = element.selectSingleNode("@name").getText();//$NON-NLS-1$
                    if (name.endsWith("Element")) {//$NON-NLS-1$
                        name = name.substring(0, name.length() - "Element".length());//$NON-NLS-1$
                    }
                    attr = DocumentHelper.createAttribute(elementNode, "name", name);//$NON-NLS-1$
                    elementNode.add(attr);
                    if (first) {
                        // copy the item name over to the column header
                        attr = DocumentHelper.createAttribute(columnHeaderNodes[idx], "name", name);//$NON-NLS-1$
                        columnHeaderNodes[idx].add(attr);
                    }
                    idx++;
                }
                first = false;

            }

        }

    }

    return reportDoc;

}