Search in sources :

Example 41 with IPentahoResultSet

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

the class PentahoFlashChartTest method getRelationData.

public static IPentahoResultSet getRelationData() {
    IPentahoResultSet ips = null;
    ArrayList<String> colHeaders = new ArrayList();
    colHeaders.add(0, "DEPARTMENT");
    colHeaders.add(1, "ACTUAL");
    colHeaders.add(2, "BUDGET");
    ArrayList r1 = new ArrayList();
    r1.add("Sales");
    r1.add(11);
    r1.add(12);
    ArrayList r2 = new ArrayList();
    r2.add("Finance");
    r2.add(14);
    r2.add(9);
    ArrayList r3 = new ArrayList();
    r3.add("Human Resource");
    r3.add(7);
    r3.add(100);
    ArrayList data = new ArrayList();
    data.add(r1);
    data.add(r2);
    data.add(r3);
    ips = MemoryResultSet.createFromLists(colHeaders, data);
    System.out.println(ips.getRowCount());
    return ips;
}
Also used : IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) ArrayList(java.util.ArrayList)

Example 42 with IPentahoResultSet

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

the class MetadataQueryComponent method execute.

public boolean execute() {
    // get the xml parser
    QueryXmlHelper helper = null;
    try {
        helper = createQueryXmlHelper();
    } catch (Exception e) {
        // $NON-NLS-1$
        logger.error("error", e);
        return false;
    }
    // parse the metadata query
    IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null);
    if (queryObject == null) {
        // there is no query model, so create one from the query string
        // apply templates to the query
        String templatedQuery = null;
        if (inputs != null) {
            Properties properties = new Properties();
            for (String name : inputs.keySet()) {
                if (!(inputs.get(name) == null)) {
                    properties.put(name, inputs.get(name).toString());
                }
            }
            templatedQuery = TemplateUtil.applyTemplate(query, properties, null);
        } else {
            templatedQuery = query;
        }
        try {
            queryObject = helper.fromXML(repo, templatedQuery);
        } catch (Exception e) {
            // $NON-NLS-1$
            logger.error("error", e);
            return false;
        }
    }
    if (queryObject == null) {
        // $NON-NLS-1$
        logger.error("error query object null");
        return false;
    }
    // Can still be overridden in the action sequence
    if (timeout == null) {
        // $NON-NLS-1$
        Object timeoutProperty = queryObject.getLogicalModel().getProperty("timeout");
        if (timeoutProperty != null && timeoutProperty instanceof Number) {
            int timeoutVal = ((Number) timeoutProperty).intValue();
            this.setTimeout(timeoutVal);
        }
    }
    if (maxRows == null) {
        // $NON-NLS-1$
        Object maxRowsProperty = queryObject.getLogicalModel().getProperty("max_rows");
        if (maxRowsProperty != null && maxRowsProperty instanceof Number) {
            int maxRowsVal = ((Number) maxRowsProperty).intValue();
            this.setMaxRows(maxRowsVal);
        }
    }
    String queryExecName = queryObject.getLogicalModel().getPhysicalModel().getQueryExecName();
    String queryExecDefault = queryObject.getLogicalModel().getPhysicalModel().getDefaultQueryClassname();
    // String modelType = (String) inputs.get("modeltype");
    IMetadataQueryExec executor = PentahoSystem.get(IMetadataQueryExec.class, queryExecName, session);
    if (executor == null) {
        // get the executor from a plugin possibly?
        Class clazz;
        try {
            clazz = Class.forName(queryExecDefault, true, queryObject.getLogicalModel().getPhysicalModel().getClass().getClassLoader());
            executor = (IMetadataQueryExec) clazz.getConstructor(new Class[] {}).newInstance(new Object[] {});
        } catch (Exception e) {
            logger.warn(Messages.getInstance().getErrorString("MetadataQueryComponent.ERROR_0002_NO_EXECUTOR", // $NON-NLS-1$
            queryExecName));
        }
    }
    if (executor == null) {
        // the query exec class is not defined thru configuration, go with the default
        Class clazz;
        try {
            clazz = Class.forName(queryExecDefault);
            executor = (IMetadataQueryExec) clazz.getConstructor(new Class[] {}).newInstance(new Object[] {});
        } catch (Exception e) {
            logger.error(Messages.getInstance().getErrorString("MetadataQueryComponent.ERROR_0002_NO_EXECUTOR", // $NON-NLS-1$
            queryExecName));
            return false;
        }
    }
    // determine parameter values
    if (queryObject.getParameters() != null) {
        for (Parameter param : queryObject.getParameters()) {
            Object value = null;
            if (inputs != null) {
                value = inputs.get(param.getName());
            }
            executor.setParameter(param, value);
        }
    }
    try {
        executor.setDoQueryLog(logSql);
        executor.setForwardOnly(this.useForwardOnlyResultSet);
        executor.setMaxRows(this.maxRows);
        executor.setMetadataDomainRepository(repo);
        executor.setReadOnly(this.readOnly);
        executor.setTimeout(this.timeout);
        if (this.inputs != null) {
            executor.setInputs(this.inputs);
        }
        resultSet = executor.executeQuery(queryObject);
        if (resultSet != null && !live && executor.isLive()) {
            // read the results and cache them
            IPentahoResultSet cachedResultSet = resultSet.memoryCopy();
            resultSet.close();
            resultSet.closeConnection();
            resultSet = cachedResultSet;
        }
        return resultSet != null;
    } catch (Exception e) {
        // $NON-NLS-1$
        logger.error("error", e);
        throw new RuntimeException(e.getLocalizedMessage(), e);
    }
}
Also used : QueryXmlHelper(org.pentaho.metadata.query.model.util.QueryXmlHelper) IMetadataDomainRepository(org.pentaho.metadata.repository.IMetadataDomainRepository) Properties(java.util.Properties) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) Parameter(org.pentaho.metadata.query.model.Parameter) IMetadataQueryExec(org.pentaho.metadata.model.IMetadataQueryExec)

Example 43 with IPentahoResultSet

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

the class SQLBaseComponent method executePrepared.

/**
 * executes a prepared method that returns a result set executePrepared looks up any "PREPARELATER" params in the
 * preparedParams map.
 *
 * @param preparedParams
 *          a map of possible parameters.
 * @return result set
 */
public IPentahoResultSet executePrepared(final Map preparedParams) {
    try {
        if (connection == null) {
            // $NON-NLS-1$
            error(Messages.getInstance().getErrorString("SQLBaseComponent.ERROR_0007_NO_CONNECTION"));
            return null;
        }
        if (!connection.initialized()) {
            // $NON-NLS-1$
            error(Messages.getInstance().getErrorString("SQLBaseComponent.ERROR_0007_NO_CONNECTION"));
            return null;
        }
        if (preparedQuery == null) {
            error(Messages.getInstance().getErrorString("SQLBaseComponent.ERROR_0001_QUERY_NOT_SPECIFIED", // $NON-NLS-1$
            getActionName()));
            return null;
        }
        // copy the preparedParams list, so it can be used multiple times.
        ArrayList copyOfPreparedParameters = new ArrayList(preparedParameters);
        // parse preparedQuery, replacing any {PREPARELATER:NAME} with appropriate values
        String query = TemplateUtil.applyTemplate(preparedQuery, getRuntimeContext(), new ParamResolver(copyOfPreparedParameters, preparedParams));
        if (ComponentBase.debug) {
            dumpQuery(query);
        }
        // evaluate
        IPentahoResultSet resultSet = null;
        if (preparedParameters.size() > 0) {
            resultSet = connection.prepareAndExecuteQuery(query, copyOfPreparedParameters);
        } else {
            resultSet = connection.executeQuery(query);
        }
        if (connection instanceof SQLConnection) {
            if (((SQLConnection) connection).isForcedForwardOnly()) {
                // $NON-NLS-1$
                warn(Messages.getInstance().getString("SQLBaseComponent.WARN_FALL_BACK_TO_NONSCROLLABLE"));
            }
        }
        boolean live = true;
        IActionDefinition actionDefinition = getActionDefinition();
        if (actionDefinition instanceof AbstractRelationalDbAction) {
            AbstractRelationalDbAction relationalDbAction = (AbstractRelationalDbAction) actionDefinition;
            live = relationalDbAction.getLive().getBooleanValue(false);
        }
        IPentahoResultSet rs = resultSet;
        // BISERVER-5915, BISERVER-5875 - if the live setting is false, return an in memory resultset.
        if (!live) {
            rs = resultSet.memoryCopy();
        }
        rSet = rs;
        return rs;
    } catch (Exception e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("SQLBaseComponent.ERROR_0006_EXECUTE_FAILED", getActionName()), e);
    }
    return null;
}
Also used : IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) IActionDefinition(org.pentaho.actionsequence.dom.IActionDefinition) SQLConnection(org.pentaho.platform.plugin.services.connections.sql.SQLConnection) ArrayList(java.util.ArrayList) AbstractRelationalDbAction(org.pentaho.actionsequence.dom.actions.AbstractRelationalDbAction)

Example 44 with IPentahoResultSet

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

the class ConditionalExecution method shouldExecute.

public boolean shouldExecute(final Map currentInputs, final Log logger) throws Exception {
    boolean shouldExecute = true;
    Context cx = ContextFactory.getGlobal().enterContext();
    try {
        ScriptableObject scriptable = new RhinoScriptable();
        // initialize the standard javascript objects
        Scriptable scope = cx.initStandardObjects(scriptable);
        ScriptableObject.defineClass(scope, JavaScriptResultSet.class);
        Object inputValue;
        IActionParameter inputParameter;
        String inputName;
        Iterator inputs = currentInputs.entrySet().iterator();
        Map.Entry mapEntry;
        while (inputs.hasNext()) {
            mapEntry = (Map.Entry) inputs.next();
            inputName = (String) mapEntry.getKey();
            if (inputName.indexOf('-') >= 0) {
                // $NON-NLS-1$
                logger.info("Ignoring Input: " + inputName);
                continue;
            }
            inputParameter = (IActionParameter) mapEntry.getValue();
            inputValue = inputParameter.getValue();
            Object wrapper;
            if (inputValue instanceof IPentahoResultSet) {
                JavaScriptResultSet results = new JavaScriptResultSet();
                // Required as of Rhino 1.7R1 to resolve caching, base object
                // inheritance and property tree
                results.setPrototype(scriptable);
                results.setResultSet((IPentahoResultSet) inputValue);
                wrapper = Context.javaToJS(inputValue, results);
            } else {
                wrapper = Context.javaToJS(inputValue, scope);
            }
            ScriptableObject.putProperty(scope, inputName, wrapper);
        }
        Object wrappedOut = Context.javaToJS(System.out, scope);
        Object wrappedThis = Context.javaToJS(this, scope);
        // $NON-NLS-1$
        ScriptableObject.putProperty(scope, "out", wrappedOut);
        // $NON-NLS-1$
        ScriptableObject.putProperty(scope, "rule", wrappedThis);
        // evaluate the script
        // $NON-NLS-1$
        Object resultObject = cx.evaluateString(scope, script, "<cmd>", 1, null);
        Object actualObject = null;
        if (resultObject instanceof org.mozilla.javascript.NativeJavaObject) {
            actualObject = ((org.mozilla.javascript.NativeJavaObject) resultObject).unwrap();
        } else {
            actualObject = resultObject;
        }
        if (actualObject instanceof Boolean) {
            return ((Boolean) actualObject).booleanValue();
        } else if (actualObject instanceof String) {
            return ("true".equalsIgnoreCase(actualObject.toString())) || ("yes".equalsIgnoreCase(// $NON-NLS-1$ //$NON-NLS-2$
            actualObject.toString()));
        } else if (actualObject instanceof Number) {
            return ((Number) actualObject).intValue() > 0;
        } else if (actualObject instanceof IPentahoResultSet) {
            return ((IPentahoResultSet) actualObject).getRowCount() > 0;
        }
    // } catch (Exception e) {
    // logger.error("Error executing conditional execution script.", e);
    } finally {
        Context.exit();
    }
    return shouldExecute;
}
Also used : Context(org.mozilla.javascript.Context) ScriptableObject(org.mozilla.javascript.ScriptableObject) Scriptable(org.mozilla.javascript.Scriptable) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) JavaScriptResultSet(org.pentaho.platform.plugin.services.connections.javascript.JavaScriptResultSet) Iterator(java.util.Iterator) ScriptableObject(org.mozilla.javascript.ScriptableObject) IActionParameter(org.pentaho.platform.api.engine.IActionParameter) Map(java.util.Map)

Example 45 with IPentahoResultSet

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

the class MDXBaseComponent method runQuery.

protected boolean runQuery(final IPentahoConnection localConnection, final String rawQuery) {
    try {
        if (localConnection == null) {
            // $NON-NLS-1$
            error(Messages.getInstance().getErrorString("MDXBaseComponent.ERROR_0008_NO_CONNECTION"));
            return false;
        }
        if (!localConnection.initialized()) {
            // $NON-NLS-1$
            error(Messages.getInstance().getErrorString("MDXBaseComponent.ERROR_0008_NO_CONNECTION"));
            return false;
        }
        if (rawQuery == null) {
            error(Messages.getInstance().getErrorString("MDXBaseComponent.ERROR_0001_QUERY_NOT_SPECIFIED", // $NON-NLS-1$
            getActionName()));
            return false;
        }
        if (ComponentBase.debug) {
            // $NON-NLS-1$
            debug(Messages.getInstance().getString("MDXBaseComponent.DEBUG_RUNNING_QUERY", rawQuery));
        }
        // execute the query, read the results and cache them
        IPentahoResultSet resultSet = localConnection.executeQuery(rawQuery);
        if (resultSet != null && resultSet instanceof MDXResultSet) {
            // BISERVER-3543 - set the result set to return formatted cell values
            boolean formattedCellValues = false;
            if (isDefinedInput(FORMATTED_CELL_VALUES)) {
                formattedCellValues = getInputBooleanValue(FORMATTED_CELL_VALUES, false);
            }
            ((MDXResultSet) resultSet).setFormattedCellValues(formattedCellValues);
        }
        rSet = resultSet;
        if (resultSet != null) {
            MdxQueryAction mdxQueryAction = (MdxQueryAction) getActionDefinition();
            IActionOutput actionOutput = mdxQueryAction.getOutputResultSet();
            if (actionOutput != null) {
                actionOutput.setValue(resultSet);
            }
            return true;
        } else {
            // close the connection
            error(Messages.getInstance().getErrorString("MDXBaseComponent.ERROR_0006_EXECUTE_FAILED", // $NON-NLS-1$
            getActionName()));
            localConnection.close();
            return false;
        }
    } catch (Exception e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getErrorString("MDXBaseComponent.ERROR_0006_EXECUTE_FAILED", getActionName()), e);
    }
    return false;
}
Also used : IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) IActionOutput(org.pentaho.actionsequence.dom.IActionOutput) MDXResultSet(org.pentaho.platform.plugin.services.connections.mondrian.MDXResultSet) MdxQueryAction(org.pentaho.actionsequence.dom.actions.MdxQueryAction) UnifiedRepositoryException(org.pentaho.platform.api.repository2.unified.UnifiedRepositoryException)

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