Search in sources :

Example 56 with IPentahoResultSet

use of org.pentaho.commons.connection.IPentahoResultSet in project pentaho-platform by pentaho.

the class ChartHelper method doChart.

/**
 * doChart generates the images and html necessary to render various charts within a web page.
 *
 * @param actionPath
 *          full path including the name of the action sequence or resource
 * @param parameterProvider
 *          the collection of parameters to customize the chart
 * @param outputStream
 *          the output string buffer for the content
 * @param userSession
 *          the user session object
 * @param messages
 *          a collection to store error and logging messages
 * @param logger
 *          logging object
 *
 * @return true if successful
 */
@Deprecated
public static boolean doChart(final String actionPath, final IParameterProvider parameterProvider, final StringBuffer outputStream, final IPentahoSession userSession, final ArrayList messages, ILogger logger) {
    deprecateWarning();
    boolean result = true;
    String content = null;
    StringBuffer messageBuffer = new StringBuffer();
    if (logger == null) {
        // No logger? The usersession extends ILogger, use it for logging
        logger = userSession;
    }
    // Retrieve all parameters from parameter provider
    // $NON-NLS-1$
    String outerParams = parameterProvider.getStringParameter("outer-params", null);
    // $NON-NLS-1$
    String innerParam = parameterProvider.getStringParameter("inner-param", null);
    // $NON-NLS-1$
    String urlDrillTemplate = parameterProvider.getStringParameter("drill-url", null);
    // $NON-NLS-1$
    String imageUrl = parameterProvider.getStringParameter("image-url", null);
    // Very likely null; allow API users to continue to pass the dial value via parameters
    // $NON-NLS-1$
    String dialValue = parameterProvider.getStringParameter("value", null);
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    if (imageUrl == null) {
        // $NON-NLS-1$
        imageUrl = requestContext.getContextPath();
    }
    if (urlDrillTemplate == null) {
        // $NON-NLS-1$
        urlDrillTemplate = "";
    }
    // $NON-NLS-1$
    int width = (int) parameterProvider.getLongParameter("image-width", 150);
    // $NON-NLS-1$
    int height = (int) parameterProvider.getLongParameter("image-height", 150);
    SimpleUrlFactory urlFactory = new SimpleUrlFactory(urlDrillTemplate);
    // Determine the type of chart we are building; these values can come from the chart xml definition, or
    // from the parameter provider. Try the parameter provider first, for performance reasons.
    String chartTypeStr = parameterProvider.getStringParameter(ChartDefinition.TYPE_NODE_NAME, null);
    String datasetType = ChartDefinition.CATEGORY_DATASET_STR;
    if ((chartTypeStr == null) || (chartTypeStr.length() == 0)) {
        try {
            // attempt to get the chart type and possibly data type from the xml doc
            ActionSequenceJCRHelper jcrHelper = new ActionSequenceJCRHelper(userSession);
            Document chartDefinition = jcrHelper.getSolutionDocument(actionPath, RepositoryFilePermission.READ);
            // $NON-NLS-1$
            Node chartAttributes = chartDefinition.selectSingleNode("//" + AbstractChartComponent.CHART_NODE_NAME);
            chartTypeStr = chartAttributes.selectSingleNode(ChartDefinition.TYPE_NODE_NAME).getText();
            Node datasetTypeNode = chartAttributes.selectSingleNode(ChartDefinition.DATASET_TYPE_NODE_NAME);
            if (datasetTypeNode != null) {
                datasetType = datasetTypeNode.getText();
            }
        } catch (Exception e) {
            logger.error(Messages.getInstance().getErrorString("ChartHelper.ERROR_0001_IO_PROBLEM_GETTING_CHART_TYPE"), // $NON-NLS-1$
            e);
            PentahoSystem.get(IMessageFormatter.class, userSession).formatErrorMessage("text/html", Messages.getInstance().getString("ChartHelper.ERROR_0001_IO_PROBLEM_GETTING_CHART_TYPE"), messages, // $NON-NLS-1$ //$NON-NLS-2$
            messageBuffer);
            content = messageBuffer.toString();
            result = false;
        }
    }
    // Check again - do we have a chart type now? If not, bail out, we have no idea what to try to generate
    if ((chartTypeStr == null) || (chartTypeStr.length() == 0)) {
        // $NON-NLS-1$
        logger.error(Messages.getInstance().getString("ChartHelper.ERROR_0002_COULD_NOT_DETERMINE_CHART_TYPE"));
        PentahoSystem.get(IMessageFormatter.class, userSession).formatErrorMessage("text/html", Messages.getInstance().getString("ChartHelper.ERROR_0002_COULD_NOT_DETERMINE_CHART_TYPE"), messages, // $NON-NLS-1$ //$NON-NLS-2$
        messageBuffer);
        content = messageBuffer.toString();
        result = false;
    }
    if (!result) {
        outputStream.append(content);
        return result;
    }
    int chartType = JFreeChartEngine.getChartType(chartTypeStr);
    AbstractJFreeChartComponent chartComponent = null;
    try {
        // Some charts are determined by the dataset that is passed in; check these first...
        if (datasetType.equalsIgnoreCase(ChartDefinition.TIME_SERIES_COLLECTION_STR)) {
            chartComponent = new TimeSeriesCollectionChartComponent(chartType, actionPath, width, height, urlFactory, messages);
        } else if (datasetType.equalsIgnoreCase(ChartDefinition.XY_SERIES_COLLECTION_STR)) {
            chartComponent = new XYSeriesCollectionChartComponent(chartType, actionPath, width, height, urlFactory, messages);
        } else if (datasetType.equalsIgnoreCase(ChartDefinition.XYZ_SERIES_COLLECTION_STR)) {
            chartComponent = new XYZSeriesCollectionChartComponent(chartType, actionPath, width, height, urlFactory, messages);
        }
        // Didn't find a dataset, so try to create the component based on chart type.
        if (chartComponent == null) {
            switch(chartType) {
                case JFreeChartEngine.BAR_CHART_TYPE:
                case JFreeChartEngine.AREA_CHART_TYPE:
                case JFreeChartEngine.BAR_LINE_CHART_TYPE:
                case JFreeChartEngine.LINE_CHART_TYPE:
                case JFreeChartEngine.DIFFERENCE_CHART_TYPE:
                case JFreeChartEngine.DOT_CHART_TYPE:
                case JFreeChartEngine.STEP_AREA_CHART_TYPE:
                case JFreeChartEngine.STEP_CHART_TYPE:
                case JFreeChartEngine.PIE_GRID_CHART_TYPE:
                    chartComponent = new CategoryDatasetChartComponent(chartType, actionPath, width, height, urlFactory, messages);
                    break;
                case JFreeChartEngine.PIE_CHART_TYPE:
                    chartComponent = new PieDatasetChartComponent(chartType, actionPath, width, height, urlFactory, messages);
                    break;
                case JFreeChartEngine.DIAL_CHART_TYPE:
                    chartComponent = new DialChartComponent(chartType, actionPath, width, height, urlFactory, messages);
                    if (dialValue != null) {
                        Number numericDialValue = DataUtilities.toNumber(dialValue, LocaleHelper.getCurrencyFormat(), LocaleHelper.getNumberFormat());
                        ((DialChartComponent) chartComponent).setValue(numericDialValue.doubleValue());
                    }
                    break;
                case JFreeChartEngine.BUBBLE_CHART_TYPE:
                    chartComponent = new XYZSeriesCollectionChartComponent(chartType, actionPath, width, height, urlFactory, messages);
                    break;
                case JFreeChartEngine.UNDEFINED_CHART_TYPE:
                default:
                    // Unsupported chart type, bail out
                    logger.error(Messages.getInstance().getString("ChartHelper.ERROR_0003_INVALID_CHART_TYPE", chartTypeStr, // $NON-NLS-1$
                    Integer.toString(chartType)));
                    PentahoSystem.get(IMessageFormatter.class, userSession).formatErrorMessage("text/html", // $NON-NLS-1$ //$NON-NLS-2$
                    Messages.getInstance().getString(// $NON-NLS-1$ //$NON-NLS-2$
                    "ChartHelper.ERROR_0003_INVALID_CHART_TYPE", chartTypeStr, Integer.toString(chartType)), messages, messageBuffer);
                    content = messageBuffer.toString();
                    result = false;
            }
        }
        if (result && (chartComponent != null)) {
            try {
                chartComponent.setLoggingLevel(logger.getLoggingLevel());
                chartComponent.validate(userSession, null);
                chartComponent.setDataAction(actionPath);
                chartComponent.setUrlTemplate(urlDrillTemplate);
                // $NON-NLS-1$
                String seriesName = parameterProvider.getStringParameter("series-name", null);
                if (chartComponent instanceof CategoryDatasetChartComponent) {
                    ((CategoryDatasetChartComponent) chartComponent).setSeriesName(seriesName);
                }
                // WARNING!!! This is an atypical way to access data for the chart... these parameters and their
                // usage are undocumented, and only left in here to support older solutions that may be using them.
                // *************** START QUESTIONABLE CODE ********************************************************
                // $NON-NLS-1$
                String connectionName = parameterProvider.getStringParameter("connection", null);
                // $NON-NLS-1$
                String query = parameterProvider.getStringParameter("query", null);
                // $NON-NLS-1$
                String dataAction = parameterProvider.getStringParameter("data-process", null);
                IPentahoConnection connection = null;
                try {
                    chartComponent.setParamName(innerParam);
                    chartComponent.setParameterProvider(IParameterProvider.SCOPE_REQUEST, parameterProvider);
                    if ((connectionName != null) && (query != null)) {
                        // connection = new SQLConnection(connectionName, logger)
                        // TODO support non-SQL data sources. Much easier now using the factory
                        connection = PentahoConnectionFactory.getConnection(IPentahoConnection.SQL_DATASOURCE, connectionName, userSession, logger);
                        try {
                            query = TemplateUtil.applyTemplate(query, TemplateUtil.parametersToProperties(parameterProvider), null);
                            IPentahoResultSet results = connection.executeQuery(query);
                            chartComponent.setValues(results);
                        } finally {
                            boolean ignored = true;
                        }
                        chartComponent.setUrlTemplate(urlDrillTemplate);
                        if (outerParams != null) {
                            // $NON-NLS-1$
                            StringTokenizer tokenizer = new StringTokenizer(outerParams, ";");
                            while (tokenizer.hasMoreTokens()) {
                                chartComponent.addOuterParamName(tokenizer.nextToken());
                            }
                        }
                    } else if (dataAction != null) {
                        chartComponent.setDataAction(dataAction);
                    }
                    // ***************** END QUESTIONABLE CODE ********************************************************
                    // $NON-NLS-1$
                    content = chartComponent.getContent("text/html");
                } finally {
                    if (connection != null) {
                        connection.close();
                    }
                }
            } catch (Throwable e) {
                // $NON-NLS-1$
                logger.error(Messages.getInstance().getErrorString("Widget.ERROR_0001_COULD_NOT_CREATE_WIDGET"), e);
            }
        }
        try {
            if (content == null) {
                PentahoSystem.get(IMessageFormatter.class, userSession).formatErrorMessage("text/html", Messages.getInstance().getErrorString("Widget.ERROR_0001_COULD_NOT_CREATE_WIDGET"), messages, // $NON-NLS-1$ //$NON-NLS-2$
                messageBuffer);
                content = messageBuffer.toString();
                result = false;
            }
            outputStream.append(content);
        } catch (Exception e) {
            // $NON-NLS-1$
            logger.error(Messages.getInstance().getErrorString("Widget.ERROR_0001_COULD_NOT_CREATE_WIDGET"), e);
        }
    } finally {
        if (chartComponent != null) {
            chartComponent.dispose();
        }
    }
    return result;
}
Also used : Node(org.dom4j.Node) Document(org.dom4j.Document) IPentahoConnection(org.pentaho.commons.connection.IPentahoConnection) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) StringTokenizer(java.util.StringTokenizer) IMessageFormatter(org.pentaho.platform.api.engine.IMessageFormatter) SimpleUrlFactory(org.pentaho.platform.util.web.SimpleUrlFactory) ActionSequenceJCRHelper(org.pentaho.platform.engine.services.ActionSequenceJCRHelper)

Example 57 with IPentahoResultSet

use of org.pentaho.commons.connection.IPentahoResultSet in project pentaho-platform by pentaho.

the class ActionFilterDefinition method getResultSet.

/**
 * If the <data-output> element is present in the xml file, its text specifies the name of the output parameter
 * in the runtime context containing the result set.
 *
 * However, the <data-output> element is not required. If this element is not in the xml file, then the first
 * parameter in the runtime context's output of type "resultset" contains the result set.
 */
@Override
protected IPentahoResultSet getResultSet(final Map parameterProviders) {
    // create an instance of the solution engine to execute the specified
    // action
    // TODO we need to ensure that this data is cached (not live) so that we
    // can validate selections
    // $NON-NLS-1$
    String solution = XmlDom4JHelper.getNodeText("data-solution", node);
    // $NON-NLS-1$
    String actionPath = XmlDom4JHelper.getNodeText("data-path", node);
    // $NON-NLS-1$
    String actionName = XmlDom4JHelper.getNodeText("data-action", node);
    // $NON-NLS-1$
    String listSource = XmlDom4JHelper.getNodeText("data-output", node);
    ISolutionEngine solutionEngine = PentahoSystem.get(ISolutionEngine.class, session);
    solutionEngine.setLoggingLevel(ILogger.DEBUG);
    solutionEngine.init(session);
    OutputStream outputStream = null;
    SimpleOutputHandler outputHandler = null;
    outputHandler = new SimpleOutputHandler(outputStream, false);
    ArrayList messages = new ArrayList();
    String processId = this.getClass().getName();
    String instanceId = null;
    IRuntimeContext context = null;
    try {
        String actionSeqPath = ActionInfo.buildSolutionPath(solution, actionPath, actionName);
        context = solutionEngine.execute(actionSeqPath, processId, false, true, instanceId, false, parameterProviders, outputHandler, null, null, messages);
        if (listSource != null) {
            if (context.getOutputNames().contains(listSource)) {
                IActionParameter output = context.getOutputParameter(listSource);
                IPentahoResultSet results = output.getValueAsResultSet();
                if (results != null) {
                    results = results.memoryCopy();
                }
                return results;
            } else {
                // this is an error
                return null;
            }
        } else {
            // return the first list that we find...
            Iterator it = context.getOutputNames().iterator();
            while (it.hasNext()) {
                IActionParameter output = (IActionParameter) it.next();
                if (output.getType().equalsIgnoreCase(IActionParameter.TYPE_RESULT_SET)) {
                    IPentahoResultSet results = output.getValueAsResultSet();
                    if (results != null) {
                        results = results.memoryCopy();
                    }
                    return results;
                }
            }
        }
        return null;
    } finally {
        if (context != null) {
            context.dispose();
        }
    }
}
Also used : IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) ISolutionEngine(org.pentaho.platform.api.engine.ISolutionEngine) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) SimpleOutputHandler(org.pentaho.platform.engine.core.output.SimpleOutputHandler) IRuntimeContext(org.pentaho.platform.api.engine.IRuntimeContext) IActionParameter(org.pentaho.platform.api.engine.IActionParameter)

Example 58 with IPentahoResultSet

use of org.pentaho.commons.connection.IPentahoResultSet in project pentaho-platform by pentaho.

the class AbstractChartComponent method getActionData.

/**
 * Gets a IPentahoResultSet from the action output
 *
 * @return IPentahoResultSet
 */
public IPentahoResultSet getActionData() {
    // create an instance of the solution engine to execute the specified
    // action
    ISolutionEngine solutionEngine = PentahoSystem.get(ISolutionEngine.class, getSession());
    solutionEngine.setLoggingLevel(ILogger.DEBUG);
    solutionEngine.init(getSession());
    HashMap parameterProviders = getParameterProviders();
    OutputStream outputStream = null;
    SimpleOutputHandler outputHandler = null;
    outputHandler = new SimpleOutputHandler(outputStream, false);
    ArrayList messages = new ArrayList();
    String processId = this.getClass().getName();
    context = // $NON-NLS-1$ //$NON-NLS-2$
    solutionEngine.execute(// $NON-NLS-1$ //$NON-NLS-2$
    actionPath, // $NON-NLS-1$ //$NON-NLS-2$
    processId, // $NON-NLS-1$ //$NON-NLS-2$
    false, // $NON-NLS-1$ //$NON-NLS-2$
    true, // $NON-NLS-1$ //$NON-NLS-2$
    instanceId, // $NON-NLS-1$ //$NON-NLS-2$
    false, parameterProviders, outputHandler, null, urlFactory, messages);
    if (context == null) {
        // this went badly wrong
        return null;
    }
    if (actionOutput != null) {
        if (context.getOutputNames().contains(actionOutput)) {
            IActionParameter output = context.getOutputParameter(actionOutput);
            IPentahoResultSet results = output.getValueAsResultSet();
            if (results != null) {
                results = results.memoryCopy();
            }
            return results;
        } else {
            // this is an error
            return null;
        }
    } else {
        for (Object objAp : context.getOutputNames()) {
            IActionParameter output = (IActionParameter) objAp;
            if (output.getType().equalsIgnoreCase(IActionParameter.TYPE_RESULT_SET)) {
                IPentahoResultSet results = output.getValueAsResultSet();
                if (results != null) {
                    results = results.memoryCopy();
                }
                return results;
            }
        }
    }
    return null;
}
Also used : IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) ISolutionEngine(org.pentaho.platform.api.engine.ISolutionEngine) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) SimpleOutputHandler(org.pentaho.platform.engine.core.output.SimpleOutputHandler) IActionParameter(org.pentaho.platform.api.engine.IActionParameter)

Example 59 with IPentahoResultSet

use of org.pentaho.commons.connection.IPentahoResultSet in project pentaho-platform by pentaho.

the class StaticFilterDefinition method getResultSet.

@Override
protected IPentahoResultSet getResultSet(final Map parameterProviders) {
    // $NON-NLS-1$
    List headers = node.selectNodes("static-lov/headers/header");
    List colHeaders = new LinkedList();
    for (Iterator it = headers.iterator(); it.hasNext(); ) {
        Element header = (Element) it.next();
        String value = header.getStringValue();
        colHeaders.add(value);
    }
    // $NON-NLS-1$
    List rows = node.selectNodes("static-lov/rows/row");
    List data = new LinkedList();
    for (Iterator it = rows.iterator(); it.hasNext(); ) {
        Element rowItem = (Element) it.next();
        List items = rowItem.selectNodes("item");
        List row = new LinkedList();
        for (Iterator itt = items.iterator(); itt.hasNext(); ) {
            Element item = (Element) itt.next();
            String value = item.getStringValue();
            row.add(value);
        }
        data.add(row);
    }
    IPentahoResultSet resultSet = MemoryResultSet.createFromLists(colHeaders, data);
    return resultSet;
}
Also used : IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) Element(org.dom4j.Element) Iterator(java.util.Iterator) List(java.util.List) LinkedList(java.util.LinkedList) LinkedList(java.util.LinkedList)

Example 60 with IPentahoResultSet

use of org.pentaho.commons.connection.IPentahoResultSet in project pentaho-platform by pentaho.

the class HQLConnection method executeQuery.

/*
   * (non-Javadoc)
   * 
   * @see org.pentaho.connection.IPentahoConnection#executeQuery(java.lang.String)
   */
public IPentahoResultSet executeQuery(final String query) {
    lastQuery = query;
    Session sess = null;
    IPentahoResultSet localResultSet = null;
    try {
        SessionFactory sf = hibernateConfig.buildSessionFactory();
        // open session
        sess = sf.openSession();
        Query q = sess.createQuery(query);
        if (timeOut >= 0) {
            q.setTimeout(timeOut);
        }
        if (maxRows >= 0) {
            q.setMaxResults(maxRows);
        }
        List list = q.list();
        localResultSet = generateResultSet(list, q.getReturnAliases(), q.getReturnTypes());
    } finally {
        try {
            if (sess != null) {
                sess.close();
            }
        } catch (Exception e) {
            // Doesn't seem like we would get any exception from sess.close()
            // $NON-NLS-1$
            logger.error(Messages.getInstance().getErrorString("HQLConnection.ERROR_0001_UNABLE_TO_CLOSE"), e);
        }
    }
    return localResultSet;
}
Also used : SessionFactory(org.hibernate.SessionFactory) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) Query(org.hibernate.Query) List(java.util.List) Session(org.hibernate.Session)

Aggregations

IPentahoResultSet (org.pentaho.commons.connection.IPentahoResultSet)113 Test (org.junit.Test)26 Node (org.dom4j.Node)18 ArrayList (java.util.ArrayList)17 IPentahoMetaData (org.pentaho.commons.connection.IPentahoMetaData)12 Iterator (java.util.Iterator)10 List (java.util.List)10 IPentahoConnection (org.pentaho.commons.connection.IPentahoConnection)10 IActionParameter (org.pentaho.platform.api.engine.IActionParameter)10 IPentahoSession (org.pentaho.platform.api.engine.IPentahoSession)10 OutputStream (java.io.OutputStream)9 ResultSetCompareAction (org.pentaho.actionsequence.dom.actions.ResultSetCompareAction)8 IRuntimeContext (org.pentaho.platform.api.engine.IRuntimeContext)8 XQConnection (org.pentaho.platform.plugin.services.connections.xquery.XQConnection)8 SQLException (java.sql.SQLException)7 HashMap (java.util.HashMap)6 StandaloneSession (org.pentaho.platform.engine.core.system.StandaloneSession)6 Map (java.util.Map)5 Set (java.util.Set)5 IPreparedComponent (org.pentaho.platform.api.data.IPreparedComponent)5