Search in sources :

Example 11 with OlapConnection

use of org.olap4j.OlapConnection in project mondrian by pentaho.

the class FileRepositoryTest method testDiscoverDatasourceLegacyNameMatch.

public void testDiscoverDatasourceLegacyNameMatch() throws Exception {
    final String contentStub = "<?xml version=\"1.0\"" + " encoding=\"UTF-8\"?>\n" + "<DataSources>\n" + "<DataSource>\n" + "<DataSourceName>Pentaho Mondrian</DataSourceName>\n" + "<DataSourceDescription>Pentaho BI Platform Datasources</DataSourceDescription>\n" + "<URL>/pentaho/Xmla</URL>\n" + "<DataSourceInfo>Provider=mondrian;Jdbc=SomethingAwfulWhichPeopleCantSee</DataSourceInfo>\n" + "<ProviderName>PentahoXMLA</ProviderName>\n" + "<ProviderType>MDP</ProviderType>\n" + "<AuthenticationMode>Unauthenticated</AuthenticationMode>\n" + "<Catalogs>\n" + "<Catalog name=\"SampleData\">\n" + "<DataSourceInfo>Jdbc=example.com;EnableXmla=false;Provider=mondrian;Datasource=\"SampleData\";overwrite=\"true\"</DataSourceInfo>\n" + "<Definition>mondrian:/SampleData</Definition>\n" + "</Catalog>\n" + "</Catalogs>\n" + "</DataSource>\n" + "</DataSources>\n";
    // Mocks.
    FileRepository fileRepositoryMock = mock(FileRepository.class);
    RepositoryContentFinder repositoryContentFinderMock = mock(RepositoryContentFinder.class);
    // Return the content we want from the RCF.
    doReturn(repositoryContentFinderMock).when(fileRepositoryMock).getRepositoryContentFinder();
    doReturn(contentStub).when(repositoryContentFinderMock).getContent();
    // Calling getServerInfo's actual implementation
    doCallRealMethod().when(fileRepositoryMock).getServerInfo();
    // Give it a try.
    final FileRepository.ServerInfo serverInfo = fileRepositoryMock.getServerInfo();
    // Some sanity checks.
    FileRepository.DatabaseInfo databaseInfo = serverInfo.getDatasourceMap().get("Pentaho Mondrian");
    assertNotNull("Database not found by name", databaseInfo);
    // Moar mocks.
    final Properties mockProps = mock(Properties.class);
    final MondrianServer mockServer = mock(MondrianServer.class);
    final String databaseName = "Pentaho Mondrian";
    final String dsInfo = "Provider=mondrian";
    final String catalogName = "SampleData";
    final String roleName = null;
    final CatalogInfo cInfo = databaseInfo.catalogMap.get("SampleData");
    final OlapConnection oc = mock(OlapConnection.class);
    // Make sure to short circuit the connection creation internal call...
    doReturn(oc).when(fileRepositoryMock).getConnection(cInfo, mockServer, roleName, mockProps);
    // We'll try to call into this method with the DS name.
    doCallRealMethod().when(fileRepositoryMock).getConnection(mockServer, databaseName, catalogName, roleName, mockProps);
    // OK make the call.
    OlapConnection ocPrime = fileRepositoryMock.getConnection(mockServer, databaseName, catalogName, roleName, mockProps);
    // Check we got a proper output.
    assertTrue(ocPrime == oc);
    // Make sure the protected call was made
    verify(fileRepositoryMock, times(1)).getConnection(cInfo, mockServer, roleName, mockProps);
    // *** Now do the same w/ the DS Info name instead. Legacy mode.
    // We'll try to call into this method with the DSInfo instead of the
    // name of the database.
    doCallRealMethod().when(fileRepositoryMock).getConnection(mockServer, dsInfo, catalogName, roleName, mockProps);
    // Make the call.
    ocPrime = fileRepositoryMock.getConnection(mockServer, dsInfo, catalogName, roleName, mockProps);
    // Check we got a proper output.
    assertTrue(ocPrime == oc);
    // Make sure the protected call was made. 2 calls by now.
    verify(fileRepositoryMock, times(2)).getConnection(cInfo, mockServer, roleName, mockProps);
}
Also used : MondrianServer(mondrian.olap.MondrianServer) OlapConnection(org.olap4j.OlapConnection) CatalogInfo(mondrian.server.FileRepository.CatalogInfo) Properties(java.util.Properties)

Example 12 with OlapConnection

use of org.olap4j.OlapConnection in project mondrian by pentaho.

the class MondrianServerTest method testRepositoryWithBadCatalog.

/**
 * Tests a server that reads its repository from a file URL.
 */
public void testRepositoryWithBadCatalog() throws Exception {
    final XmlaTestContext xmlaTestContext = new XmlaTestContext() {

        Util.PropertyList connectProperties = Util.parseConnectString(getConnectString());

        String catalogUrl = connectProperties.get(RolapConnectionProperties.Catalog.name());

        public String getDataSourcesString() {
            return super.getDataSourcesString().replace("</Catalog>", "</Catalog>\n" + "<Catalog name='__1'>\n" + "<DataSourceInfo>Provider=mondrian;Jdbc='jdbc:derby:non-existing-db'</DataSourceInfo>\n" + "<Definition>" + catalogUrl + "</Definition>\n" + "</Catalog>\n");
        }
    };
    final MondrianServer server = MondrianServer.createWithRepository(new UrlRepositoryContentFinder("inline:" + xmlaTestContext.getDataSourcesString()), null);
    final int id = server.getId();
    assertNotNull(id);
    OlapConnection connection = server.getConnection("FoodMart", "FoodMart", null);
    final NamedList<Catalog> catalogs = connection.getOlapCatalogs();
    assertEquals(1, catalogs.size());
    assertEquals("FoodMart", catalogs.get(0).getName());
    server.shutdown();
}
Also used : MondrianServer(mondrian.olap.MondrianServer) OlapConnection(org.olap4j.OlapConnection) UrlRepositoryContentFinder(mondrian.server.UrlRepositoryContentFinder) Catalog(org.olap4j.metadata.Catalog) XmlaTestContext(mondrian.xmla.test.XmlaTestContext)

Example 13 with OlapConnection

use of org.olap4j.OlapConnection in project mondrian by pentaho.

the class CmdRunner method runQuery.

/**
 * Executes a query and processes the result using a callback.
 *
 * @param queryString MDX query text
 */
public <T> T runQuery(String queryString, Util.Functor1<T, CellSet> f) {
    long start = System.currentTimeMillis();
    OlapConnection connection = null;
    OlapStatement statement = null;
    CellSet cellSet = null;
    try {
        connection = getOlapConnection();
        statement = connection.createStatement();
        debug("CmdRunner.runQuery: AFTER createStatement");
        start = System.currentTimeMillis();
        cellSet = statement.executeOlapQuery(queryString);
        return f.apply(cellSet);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        queryTime = (System.currentTimeMillis() - start);
        totalQueryTime += queryTime;
        debug("CmdRunner.runQuery: BOTTOM");
        Util.close(cellSet, statement, connection);
    }
}
Also used : OlapStatement(org.olap4j.OlapStatement) OlapConnection(org.olap4j.OlapConnection) CellSet(org.olap4j.CellSet)

Example 14 with OlapConnection

use of org.olap4j.OlapConnection in project mondrian by pentaho.

the class XmlaUtil method getMetadataRowset.

/**
 * Returns a set of column headings and rows for a given metadata request.
 *
 * <p/>Leverages mondrian's implementation of the XML/A specification, and
 * is exposed here for use by mondrian's olap4j driver.
 *
 * @param connection Connection
 * @param methodName Metadata method name per XMLA (e.g. "MDSCHEMA_CUBES")
 * @param restrictionMap Restrictions
 * @return Set of rows and column headings
 */
public static MetadataRowset getMetadataRowset(final OlapConnection connection, String methodName, final Map<String, Object> restrictionMap) throws OlapException {
    RowsetDefinition rowsetDefinition = RowsetDefinition.valueOf(methodName);
    final XmlaHandler.ConnectionFactory connectionFactory = new XmlaHandler.ConnectionFactory() {

        public OlapConnection getConnection(String catalog, String schema, String roleName, Properties props) throws SQLException {
            return connection;
        }

        public Map<String, Object> getPreConfiguredDiscoverDatasourcesResponse() {
            // the "pre configured discover datasources" feature.
            return null;
        }
    };
    final XmlaRequest request = new XmlaRequest() {

        public Method getMethod() {
            return Method.DISCOVER;
        }

        public Map<String, String> getProperties() {
            return Collections.emptyMap();
        }

        public Map<String, Object> getRestrictions() {
            return restrictionMap;
        }

        public String getStatement() {
            return null;
        }

        public String getRoleName() {
            return null;
        }

        public String getRequestType() {
            throw new UnsupportedOperationException();
        }

        public boolean isDrillThrough() {
            throw new UnsupportedOperationException();
        }

        public Format getFormat() {
            throw new UnsupportedOperationException();
        }

        public String getUsername() {
            return null;
        }

        public String getPassword() {
            return null;
        }

        public String getSessionId() {
            return null;
        }
    };
    final Rowset rowset = rowsetDefinition.getRowset(request, new XmlaHandler(connectionFactory, "xmla") {

        @Override
        public OlapConnection getConnection(XmlaRequest request, Map<String, String> propMap) {
            return connection;
        }
    });
    List<Rowset.Row> rowList = new ArrayList<Rowset.Row>();
    rowset.populate(new DefaultXmlaResponse(new ByteArrayOutputStream(), Charset.defaultCharset().name(), Enumeration.ResponseMimeType.SOAP), connection, rowList);
    MetadataRowset result = new MetadataRowset();
    final List<RowsetDefinition.Column> colDefs = new ArrayList<RowsetDefinition.Column>();
    for (RowsetDefinition.Column columnDefinition : rowsetDefinition.columnDefinitions) {
        if (columnDefinition.type == RowsetDefinition.Type.Rowset) {
            // Cube.Dimensions
            continue;
        }
        colDefs.add(columnDefinition);
    }
    for (Rowset.Row row : rowList) {
        Object[] values = new Object[colDefs.size()];
        int k = -1;
        for (RowsetDefinition.Column colDef : colDefs) {
            Object o = row.get(colDef.name);
            if (o instanceof List) {
                o = toString((List<String>) o);
            } else if (o instanceof String[]) {
                o = toString(Arrays.asList((String[]) o));
            }
            values[++k] = o;
        }
        result.rowList.add(Arrays.asList(values));
    }
    for (RowsetDefinition.Column colDef : colDefs) {
        String columnName = colDef.name;
        if (LOWERCASE_PATTERN.matcher(columnName).matches()) {
            columnName = Util.camelToUpper(columnName);
        }
        // VALUE is a SQL reserved word
        if (columnName.equals("VALUE")) {
            columnName = "PROPERTY_VALUE";
        }
        result.headerList.add(columnName);
    }
    return result;
}
Also used : OlapConnection(org.olap4j.OlapConnection) DefaultXmlaResponse(mondrian.xmla.impl.DefaultXmlaResponse)

Example 15 with OlapConnection

use of org.olap4j.OlapConnection in project pentaho-platform by pentaho.

the class PentahoXmlaServlet method createConnectionFactory.

@Override
protected ConnectionFactory createConnectionFactory(final ServletConfig servletConfig) throws ServletException {
    final ConnectionFactory delegate = super.createConnectionFactory(servletConfig);
    /*
     * This wrapper for the connection factory allows us to
     * override the list of roles with the ones defined in
     * the IPentahoSession and filter it through the
     * IConnectionUserRoleMapper.
     */
    return new ConnectionFactory() {

        public Map<String, Object> getPreConfiguredDiscoverDatasourcesResponse() {
            return delegate.getPreConfiguredDiscoverDatasourcesResponse();
        }

        public OlapConnection getConnection(String databaseName, String catalogName, String roleName, Properties props) throws SQLException {
            // What we do here is to filter the role names with the mapper.
            // First, get a user role mapper, if one is configured.
            final IPentahoSession session = PentahoSessionHolder.getSession();
            final IConnectionUserRoleMapper mondrianUserRoleMapper = PentahoSystem.get(IConnectionUserRoleMapper.class, MDXConnection.MDX_CONNECTION_MAPPER_KEY, // Don't use the user session here yet.
            null);
            String[] effectiveRoles = new String[0];
            /*
         * If Catalog/Schema are null (this happens with high level metadata requests,
         * like DISCOVER_DATASOURCES) we can't use the role mapper, even if it
         * is present and configured.
         */
            if (mondrianUserRoleMapper != null && catalogName != null) {
                // Use the role mapper.
                try {
                    effectiveRoles = mondrianUserRoleMapper.mapConnectionRoles(session, catalogName);
                    if (effectiveRoles == null) {
                        effectiveRoles = new String[0];
                    }
                } catch (PentahoAccessControlException e) {
                    throw new SQLException(e);
                }
            }
            // Now we tokenize that list.
            boolean addComma = false;
            // $NON-NLS-1$
            roleName = "";
            for (String role : effectiveRoles) {
                if (addComma) {
                    // $NON-NLS-1$
                    roleName = roleName.concat(",");
                }
                roleName = roleName.concat(role);
                addComma = true;
            }
            // Now let the delegate connection factory do its magic.
            if (catalogName == null) {
                return delegate.getConnection(databaseName, catalogName, roleName.equals("") ? null : roleName, props);
            } else {
                // We create a connection differently so we can ensure that
                // the XMLA servlet shares the same MondrianServer instance as the rest
                // of the platform
                IMondrianCatalogService mcs = PentahoSystem.get(IMondrianCatalogService.class);
                MondrianCatalog mc = mcs.getCatalog(catalogName, PentahoSessionHolder.getSession());
                if (mc == null) {
                    throw new XmlaException(CLIENT_FAULT_FC, HSB_BAD_RESTRICTION_LIST_CODE, HSB_BAD_RESTRICTION_LIST_FAULT_FS, new MondrianException("No such catalog: " + catalogName));
                }
                Connection con = DriverManager.getConnection(mc.getDataSourceInfo() + ";Catalog=" + mc.getDefinition(), catalogLocator);
                try {
                    final MondrianServer server = MondrianServer.forConnection(con);
                    FileRepository fr = new FileRepository(makeContentFinder(makeDataSourcesUrl(servletConfig)), catalogLocator);
                    OlapConnection connection = fr.getConnection(server, databaseName, catalogName, roleName, props);
                    fr.shutdown();
                    return connection;
                } finally {
                    con.close();
                }
            }
        }
    };
}
Also used : FileRepository(mondrian.server.FileRepository) MondrianServer(mondrian.olap.MondrianServer) MondrianCatalog(org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalog) SQLException(java.sql.SQLException) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) IConnectionUserRoleMapper(org.pentaho.platform.api.engine.IConnectionUserRoleMapper) OlapConnection(org.olap4j.OlapConnection) OlapConnection(org.olap4j.OlapConnection) MDXConnection(org.pentaho.platform.plugin.services.connections.mondrian.MDXConnection) Connection(mondrian.olap.Connection) Properties(java.util.Properties) IMondrianCatalogService(org.pentaho.platform.plugin.action.mondrian.catalog.IMondrianCatalogService) PentahoAccessControlException(org.pentaho.platform.api.engine.PentahoAccessControlException) ConnectionFactory(mondrian.xmla.XmlaHandler.ConnectionFactory) SolutionRepositoryVfsFileObject(org.pentaho.platform.repository.solution.filebased.SolutionRepositoryVfsFileObject) XmlaException(mondrian.xmla.XmlaException) MondrianException(mondrian.olap.MondrianException)

Aggregations

OlapConnection (org.olap4j.OlapConnection)22 SQLException (java.sql.SQLException)8 RolapConnection (mondrian.rolap.RolapConnection)5 OlapException (org.olap4j.OlapException)5 Properties (java.util.Properties)4 MondrianServer (mondrian.olap.MondrianServer)4 IOlapServiceException (org.pentaho.platform.plugin.action.olap.IOlapServiceException)4 PrintWriter (java.io.PrintWriter)3 Connection (java.sql.Connection)3 Test (org.junit.Test)3 OlapWrapper (org.olap4j.OlapWrapper)3 PentahoAccessControlException (org.pentaho.platform.api.engine.PentahoAccessControlException)3 IOException (java.io.IOException)2 Connection (mondrian.olap.Connection)2 RolapConnectionProperties (mondrian.rolap.RolapConnectionProperties)2 UrlRepositoryContentFinder (mondrian.server.UrlRepositoryContentFinder)2 XmlaHandler (mondrian.xmla.XmlaHandler)2 XmlaTestContext (mondrian.xmla.test.XmlaTestContext)2 FileSystemException (org.apache.commons.vfs2.FileSystemException)2 OlapDataSource (org.olap4j.OlapDataSource)2