Search in sources :

Example 16 with IPentahoConnection

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

the class PentahoConnectionFactoryTest method testGetConnection.

@Test
public void testGetConnection() {
    // Test constructor.
    PentahoConnectionFactory factory = new PentahoConnectionFactory();
    assertNotNull(factory);
    String dsType = "connection-test";
    IPentahoSession session = mock(IPentahoSession.class);
    ILogger logger = mock(ILogger.class);
    IPentahoConnection connection = PentahoConnectionFactory.getConnection(dsType, session, logger);
    assertNull(connection);
    String connectStr = "connect-str";
    connection = PentahoConnectionFactory.getConnection(dsType, connectStr, session, logger);
    assertNull(connection);
    String driver = "ds-driver";
    String location = "location";
    String userName = "username";
    String password = "password";
    connection = PentahoConnectionFactory.getConnection(dsType, driver, location, userName, password, session, logger);
    assertNull(connection);
    connection = PentahoConnectionFactory.getConnection(dsType, null, null, null, null, session, logger);
    assertNull(connection);
}
Also used : IPentahoConnection(org.pentaho.commons.connection.IPentahoConnection) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ILogger(org.pentaho.platform.api.engine.ILogger) Test(org.junit.Test)

Example 17 with IPentahoConnection

use of org.pentaho.commons.connection.IPentahoConnection in project data-access by pentaho.

the class ConnectionServiceImpl method addConnection.

public boolean addConnection(IDatabaseConnection connection) throws ConnectionServiceException {
    ensureDataAccessPermission();
    try {
        if (connection.getAccessType() != null && connection.getAccessType().equals(DatabaseAccessType.JNDI)) {
            IPentahoConnection pentahoConnection = null;
            pentahoConnection = PentahoConnectionFactory.getConnection(IPentahoConnection.SQL_DATASOURCE, connection.getDatabaseName(), null, this);
            try {
                connection.setUsername((((SQLConnection) pentahoConnection).getNativeConnection().getMetaData().getUserName()));
            } catch (Exception e) {
                logger.warn("Unable to get username from datasource: " + connection.getName());
            }
        }
        datasourceMgmtSvc.createDatasource(connection);
        return true;
    } catch (DuplicateDatasourceException duplicateDatasourceException) {
        String message = Messages.getErrorString(// $NON-NLS-1$
        "ConnectionServiceImpl.ERROR_0004_UNABLE_TO_ADD_CONNECTION", connection.getName(), duplicateDatasourceException.getLocalizedMessage());
        logger.error(message);
        throw new ConnectionServiceException(Response.SC_CONFLICT, message, duplicateDatasourceException);
    } catch (Exception e) {
        String message = Messages.getErrorString(// $NON-NLS-1$
        "ConnectionServiceImpl.ERROR_0004_UNABLE_TO_ADD_CONNECTION", connection.getName(), e.getLocalizedMessage());
        logger.error(message);
        throw new ConnectionServiceException(message, e);
    }
}
Also used : IPentahoConnection(org.pentaho.commons.connection.IPentahoConnection) ConnectionServiceException(org.pentaho.platform.dataaccess.datasource.wizard.service.ConnectionServiceException) DuplicateDatasourceException(org.pentaho.platform.api.repository.datasource.DuplicateDatasourceException) SQLConnection(org.pentaho.platform.plugin.services.connections.sql.SQLConnection) DatabaseDialectException(org.pentaho.database.DatabaseDialectException) ConnectionServiceException(org.pentaho.platform.dataaccess.datasource.wizard.service.ConnectionServiceException) DuplicateDatasourceException(org.pentaho.platform.api.repository.datasource.DuplicateDatasourceException) DatasourceMgmtServiceException(org.pentaho.platform.api.repository.datasource.DatasourceMgmtServiceException) NonExistingDatasourceException(org.pentaho.platform.api.repository.datasource.NonExistingDatasourceException)

Example 18 with IPentahoConnection

use of org.pentaho.commons.connection.IPentahoConnection 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 19 with IPentahoConnection

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

the class PentahoConnectionFactory method getConnection.

/**
 * @param datasourceType
 * @param properties
 *          can be null
 * @param session
 *          can be null
 * @param logger
 * @return
 */
public static IPentahoConnection getConnection(final String datasourceType, Properties properties, final IPentahoSession session, final ILogger logger) {
    /*
     * TODO - This is where the "connection factory" action occurs. Based on if the datasourceType, location,
     * username, or password have changed then we create a new one.
     */
    String key = CONNECTION_PREFIX + datasourceType;
    IPentahoConnection connection = null;
    try {
        connection = PentahoSystem.getObjectFactory().get(IPentahoConnection.class, key, session);
        if (connection instanceof IPentahoLoggingConnection) {
            ((IPentahoLoggingConnection) connection).setLogger(logger);
        }
        connection.setProperties(properties);
    } catch (ObjectFactoryException e) {
        Logger.error(PentahoSystem.class.getName(), Messages.getInstance().getErrorString("PentahoConnectionFactory.ERROR_0001_COULD_NOT_CREATE_CONNECTION", key), // $NON-NLS-1$
        e);
    }
    return connection;
}
Also used : IPentahoConnection(org.pentaho.commons.connection.IPentahoConnection) ObjectFactoryException(org.pentaho.platform.api.engine.ObjectFactoryException) IPentahoLoggingConnection(org.pentaho.platform.engine.core.system.IPentahoLoggingConnection)

Example 20 with IPentahoConnection

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

the class MDXBaseComponentTest method testGetConnection.

@Test
public void testGetConnection() throws Exception {
    doReturn(connAction).when(mdxBaseComponent).getActionDefinition();
    when(connAction.getCatalog()).thenReturn(catalog);
    when(catalog.getStringValue()).thenReturn("my catalog");
    PentahoSystem.registerObject(mondrianCatalogService);
    PentahoSystem.registerObject(mdxConnection);
    PentahoSystem.registerPrimaryObjectFactory(objFactory);
    PentahoSessionHolder.setSession(session);
    when(objFactory.get(any(Class.class), eq("connection-MDX"), any(IPentahoSession.class))).thenReturn(mdxConnection);
    when(mondrianCatalogService.getCatalog(anyString(), any(IPentahoSession.class))).thenReturn(mondrianCatalog);
    when(mondrianCatalog.getDataSourceInfo()).thenReturn("connection info");
    when(mondrianCatalog.getDefinition()).thenReturn("<catalog></catalog>");
    when(connAction.getExtendedColumnNames()).thenReturn(ActionInputConstant.NULL_INPUT);
    IPentahoConnection connection = mdxBaseComponent.getConnection();
    assertNotNull(connection);
    assertEquals(mdxConnection, connection);
}
Also used : IPentahoConnection(org.pentaho.commons.connection.IPentahoConnection) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) Test(org.junit.Test)

Aggregations

IPentahoConnection (org.pentaho.commons.connection.IPentahoConnection)29 IPentahoSession (org.pentaho.platform.api.engine.IPentahoSession)11 Test (org.junit.Test)9 IPentahoResultSet (org.pentaho.commons.connection.IPentahoResultSet)9 Properties (java.util.Properties)6 OutputStream (java.io.OutputStream)5 StandaloneSession (org.pentaho.platform.engine.core.system.StandaloneSession)5 File (java.io.File)4 IDBDatasourceService (org.pentaho.platform.api.data.IDBDatasourceService)3 IPreparedComponent (org.pentaho.platform.api.data.IPreparedComponent)3 UnifiedRepositoryException (org.pentaho.platform.api.repository2.unified.UnifiedRepositoryException)3 IActionOutput (org.pentaho.actionsequence.dom.IActionOutput)2 AbstractRelationalDbAction (org.pentaho.actionsequence.dom.actions.AbstractRelationalDbAction)2 MdxConnectionAction (org.pentaho.actionsequence.dom.actions.MdxConnectionAction)2 SqlConnectionAction (org.pentaho.actionsequence.dom.actions.SqlConnectionAction)2 DatabaseDialectException (org.pentaho.database.DatabaseDialectException)2 ConnectionServiceException (org.pentaho.platform.dataaccess.datasource.wizard.service.ConnectionServiceException)2 FileInputStream (java.io.FileInputStream)1 Format (java.text.Format)1 ArrayList (java.util.ArrayList)1