예제 #1
0
 public Cube getNativeCube(SaikuCube cube) throws SaikuOlapException {
   try {
     OlapConnection con = connections.getOlapConnection(cube.getConnectionName());
     if (con != null) {
       for (Database db : con.getOlapDatabases()) {
         Catalog cat = db.getCatalogs().get(cube.getCatalogName());
         if (cat != null) {
           for (Schema schema : cat.getSchemas()) {
             if (schema.getName().equals(cube.getSchemaName())) {
               for (Cube cub : schema.getCubes()) {
                 if (cub.getName().equals(cube.getName())
                     || cub.getUniqueName().equals(cube.getUniqueName())) {
                   return cub;
                 }
               }
             }
           }
         }
       }
     }
   } catch (Exception e) {
     throw new SaikuOlapException("Cannot get native cube for ( " + cube + " )", e);
   }
   throw new SaikuOlapException("Cannot get native cube for ( " + cube + " )");
 }
예제 #2
0
  public List<SaikuMember> getAllMembers(
      SaikuCube cube, String dimension, String hierarchy, String level) throws SaikuOlapException {
    try {
      Cube nativeCube = getNativeCube(cube);
      Dimension dim = nativeCube.getDimensions().get(dimension);
      if (dim != null) {
        Hierarchy h = dim.getHierarchies().get(hierarchy);
        if (h == null) {
          for (Hierarchy hlist : dim.getHierarchies()) {
            if (hlist.getUniqueName().equals(hierarchy) || hlist.getName().equals(hierarchy)) {
              h = hlist;
            }
          }
        }

        if (h != null) {
          Level l = h.getLevels().get(level);
          if (l == null) {
            for (Level lvl : h.getLevels()) {
              if (lvl.getUniqueName().equals(level) || lvl.getName().equals(level)) {
                return (ObjectUtil.convertMembers(lvl.getMembers()));
              }
            }
          } else {
            return (ObjectUtil.convertMembers(l.getMembers()));
          }
        }
      }
    } catch (OlapException e) {
      throw new SaikuOlapException("Cannot get all members", e);
    }

    return new ArrayList<SaikuMember>();
  }
예제 #3
0
 public List<SaikuCube> getCubes(String connectionName) {
   OlapConnection olapcon = connections.getOlapConnection(connectionName);
   List<SaikuCube> cubes = new ArrayList<SaikuCube>();
   if (olapcon != null) {
     try {
       for (Catalog cat : olapcon.getOlapCatalogs()) {
         for (Schema schem : cat.getSchemas()) {
           for (Cube cub : schem.getCubes()) {
             cubes.add(
                 new SaikuCube(
                     connectionName,
                     cub.getUniqueName(),
                     cub.getName(),
                     cub.getCaption(),
                     cat.getName(),
                     schem.getName(),
                     cub.isVisible()));
           }
         }
       }
     } catch (OlapException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
   Collections.sort(cubes, new SaikuCubeCaptionComparator());
   return cubes;
 }
예제 #4
0
 public SaikuHierarchy getHierarchy(SaikuCube cube, String hierarchyName)
     throws SaikuOlapException {
   Cube nativeCube = getNativeCube(cube);
   Hierarchy h = nativeCube.getHierarchies().get(hierarchyName);
   if (h != null) {
     return ObjectUtil.convert(h);
   }
   return null;
 }
예제 #5
0
 public SaikuDimension getDimension(SaikuCube cube, String dimensionName)
     throws SaikuOlapException {
   Cube nativeCube = getNativeCube(cube);
   Dimension dim = nativeCube.getDimensions().get(dimensionName);
   if (dim != null) {
     return ObjectUtil.convert(dim);
   }
   return null;
 }
예제 #6
0
 public List<SaikuDimension> getAllDimensions(SaikuCube cube) throws SaikuOlapException {
   Cube nativeCube = getNativeCube(cube);
   List<SaikuDimension> dimensions = ObjectUtil.convertDimensions(nativeCube.getDimensions());
   for (int i = 0; i < dimensions.size(); i++) {
     SaikuDimension dim = dimensions.get(i);
     if (dim.getName().equals("Measures") || dim.getUniqueName().equals("[Measures]")) {
       dimensions.remove(i);
       break;
     }
   }
   Collections.sort(dimensions, new SaikuDimensionCaptionComparator());
   return dimensions;
 }
예제 #7
0
 public SaikuMember getMember(SaikuCube cube, String uniqueMemberName) throws SaikuOlapException {
   try {
     Cube nativeCube = getNativeCube(cube);
     Member m =
         nativeCube.lookupMember(
             IdentifierNode.parseIdentifier(uniqueMemberName).getSegmentList());
     if (m != null) {
       return ObjectUtil.convert(m);
     }
     return null;
   } catch (Exception e) {
     throw new SaikuOlapException(
         "Cannot find member: " + uniqueMemberName + " in cube:" + cube.getName(), e);
   }
 }
예제 #8
0
  public static Hierarchy getHierarchy(Cube cube, ModelConfig modelConfig, String dimensionName) {
    List<Dimension> dimensions = cube.getDimensions();
    Dimension result = null;
    for (java.util.Iterator<Dimension> iterator = dimensions.iterator(); iterator.hasNext(); ) {
      Dimension dimension = iterator.next();
      if (dimension.getUniqueName().equals("[" + dimensionName + "]")) {
        result = dimension;
      }
    }
    if (result == null) {
      logger.error("Could not find dimension");
      throw new SpagoBIEngineRuntimeException("Could not find dimension");
    }
    logger.debug("Found dimension " + result.getUniqueName());

    // get Hierarchy Used by dimension
    NamedList<Hierarchy> hierarchies = result.getHierarchies();
    Hierarchy hierarchy = null;
    if (hierarchies == null || hierarchies.size() == 0) {
      logger.error("Could not find hierarchies for dimension");
      throw new SpagoBIEngineRuntimeException("Could not find hierarchies for dimension");
    } else if (hierarchies.size() == 1) {
      hierarchy = hierarchies.get(0);
    } else {
      String hierarchyUsed = modelConfig.getDimensionHierarchyMap().get(dimensionName);
      hierarchy = hierarchies.get(hierarchyUsed);
    }
    return hierarchy;
  }
  /**
   * Adds a catalog and its children to the cache. Do not use directly. This must be called with a
   * write lock on the cache.
   *
   * @param catalogName The name of the catalog to load in cache.
   */
  private void addCatalogToCache(IPentahoSession session, String catalogName) {

    final IOlapService.Catalog catalog =
        new Catalog(catalogName, new ArrayList<IOlapService.Schema>());

    OlapConnection connection = null;

    try {

      connection = getConnection(catalogName, session);

      for (org.olap4j.metadata.Schema schema4j : connection.getOlapSchemas()) {

        connection.setSchema(schema4j.getName());

        final IOlapService.Schema schema =
            new Schema(
                schema4j.getName(),
                catalog,
                new ArrayList<IOlapService.Cube>(),
                new ArrayList<String>(connection.getAvailableRoleNames()));

        for (org.olap4j.metadata.Cube cube4j : schema4j.getCubes()) {
          schema.cubes.add(new IOlapService.Cube(cube4j.getName(), cube4j.getCaption(), schema));
        }

        catalog.schemas.add(schema);
      }

      // We're done.
      getCache(session).add(catalog);

    } catch (OlapException e) {

      LOG.warn("Failed to initialize the olap connection cache for catalog " + catalogName, e);

    } finally {
      try {
        if (connection != null) {
          connection.close();
        }
      } catch (SQLException e) {
        LOG.warn("Failed to gracefully close an olap connection to catalog " + catalogName, e);
      }
    }
  }
  private void metadataTest(String dsUri, int numberOfDimensions, int numberOfMeasures) {
    try {

      // We have to use MDX encoded name
      String name = URLEncoder.encode(dsUri, "UTF-8");
      name = name.replace("%", "XXX");
      name = name.replace(".", "YYY");
      name = name.replace("-", "ZZZ");
      // xmla4js is attaching square brackets automatically
      // xmla-server is using a set of values for a restriction.
      Cube cube =
          olapConnection
              .getOlapDatabases()
              .get(0)
              .getCatalogs()
              .get(0)
              .getSchemas()
              .get(0)
              .getCubes()
              .get("[" + name + "]");

      // Currently, we have to first query for dimensions.
      List<Dimension> dimensions = cube.getDimensions();

      // Number of dimensions
      assertEquals(numberOfDimensions, dimensions.size());
      for (Dimension dimension : dimensions) {
        List<Member> members = dimension.getHierarchies().get(0).getLevels().get(0).getMembers();

        // Each dimension should have some members
        assertEquals(true, members.size() >= 1);
      }

      List<Measure> measures = cube.getMeasures();

      // Number of measures
      assertEquals(numberOfMeasures, measures.size());
    } catch (OlapException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
예제 #11
0
  public Map<String, SaikuFilter> getValidFilters(
      String queryName, Map<String, SaikuFilter> allFilters) {
    IQuery query = getIQuery(queryName);
    Cube c = query.getCube();
    Map<String, SaikuFilter> filteredMap = new HashMap<String, SaikuFilter>();
    for (SaikuFilter sf : allFilters.values()) {
      if (StringUtils.isBlank(sf.getName()) || sf.getDimension() == null) continue;

      String dimensionName = sf.getDimension().getName();
      String hierarchyName = sf.getHierarchy().getName();
      boolean hasDimension = c.getDimensions().indexOfName(dimensionName) >= 0;
      boolean hasHierarchy = c.getHierarchies().indexOfName(hierarchyName) >= 0;
      if (hasDimension || hasHierarchy) {
        filteredMap.put(sf.getName(), sf);
      }
    }
    return filteredMap;
  }
예제 #12
0
  public List<SaikuMember> getMemberChildren(SaikuCube cube, String uniqueMemberName)
      throws SaikuOlapException {
    List<SaikuMember> members = new ArrayList<SaikuMember>();
    try {
      Cube nativeCube = getNativeCube(cube);
      List<IdentifierSegment> memberList =
          IdentifierNode.parseIdentifier(uniqueMemberName).getSegmentList();
      Member m = nativeCube.lookupMember(memberList);
      if (m != null) {
        for (Member c : m.getChildMembers()) {
          SaikuMember sm = ObjectUtil.convert(c);
          members.add(sm);
        }
      }
    } catch (OlapException e) {
      throw new SaikuOlapException("Cannot get child members of member:" + uniqueMemberName, e);
    }

    return members;
  }
예제 #13
0
  public List<SaikuMember> getAllMeasures(SaikuCube cube) throws SaikuOlapException {
    List<SaikuMember> measures = new ArrayList<SaikuMember>();
    try {
      Cube nativeCube = getNativeCube(cube);
      for (Measure measure : nativeCube.getMeasures()) {
        if (measure.isVisible()) {
          measures.add(ObjectUtil.convertMeasure(measure));
        }
      }
      if (measures.size() == 0) {
        Hierarchy hierarchy = nativeCube.getDimensions().get("Measures").getDefaultHierarchy();
        measures = (ObjectUtil.convertMembers(hierarchy.getRootMembers()));
      }
    } catch (OlapException e) {
      throw new SaikuOlapException("Cannot get measures for cube:" + cube.getName(), e);
    }

    Collections.sort(measures, new SaikuMemberCaptionComparator());
    return measures;
  }
예제 #14
0
  /** @see org.pivot4j.analytics.datasource.DataSourceManager#getCubes(java.lang.String) */
  @Override
  public List<CubeInfo> getCubes(String catalogName) {
    if (catalogName == null) {
      throw new NullArgumentException("catalogName");
    }

    SimpleDataSourceInfo definition = getDefinition(catalogName);

    if (definition == null) {
      throw new IllegalArgumentException(
          "Data source with the given name does not exist : " + catalogName);
    }

    OlapDataSource dataSource = createDataSource(definition);

    List<CubeInfo> cubes = new LinkedList<CubeInfo>();

    OlapConnection connection = null;

    try {
      connection = dataSource.getConnection();

      for (Cube cube : connection.getOlapSchema().getCubes()) {
        if (cube.isVisible()) {
          cubes.add(new CubeInfo(cube.getName(), cube.getCaption(), cube.getDescription()));
        }
      }
    } catch (SQLException e) {
      throw new PivotException(e);
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e) {
          throw new PivotException(e);
        }
      }
    }

    return cubes;
  }
예제 #15
0
  public List<SaikuLevel> getAllLevels(SaikuCube cube, String dimension, String hierarchy)
      throws SaikuOlapException {
    Cube nativeCube = getNativeCube(cube);
    Dimension dim = nativeCube.getDimensions().get(dimension);
    if (dim != null) {
      Hierarchy h = dim.getHierarchies().get(hierarchy);
      if (h == null) {
        for (Hierarchy hlist : dim.getHierarchies()) {
          if (hlist.getUniqueName().equals(hierarchy) || hlist.getName().equals(hierarchy)) {
            h = hlist;
          }
        }
      }

      if (h != null) {
        List<SaikuLevel> levels = (ObjectUtil.convertLevels(h.getLevels()));
        return levels;
      }
    }
    return new ArrayList<SaikuLevel>();
  }
예제 #16
0
  public List<SaikuMember> getHierarchyRootMembers(SaikuCube cube, String hierarchyName)
      throws SaikuOlapException {
    Cube nativeCube = getNativeCube(cube);
    List<SaikuMember> members = new ArrayList<SaikuMember>();
    Hierarchy h = nativeCube.getHierarchies().get(hierarchyName);

    if (h == null) {
      for (Hierarchy hlist : nativeCube.getHierarchies()) {
        if (hlist.getUniqueName().equals(hierarchyName) || hlist.getName().equals(hierarchyName)) {
          h = hlist;
        }
      }
    }
    if (h != null) {
      try {
        members = (ObjectUtil.convertMembers(h.getRootMembers()));
      } catch (OlapException e) {
        throw new SaikuOlapException(
            "Cannot retrieve root members of hierarchy: " + hierarchyName, e);
      }
    }

    return members;
  }
예제 #17
0
  public SaikuConnection getConnection(String connectionName) throws SaikuOlapException {
    OlapConnection olapcon = connections.getOlapConnection(connectionName);
    SaikuConnection connection = null;
    if (olapcon != null) {
      List<SaikuCatalog> catalogs = new ArrayList<SaikuCatalog>();
      try {
        for (Catalog cat : olapcon.getOlapCatalogs()) {
          List<SaikuSchema> schemas = new ArrayList<SaikuSchema>();
          for (Schema schem : cat.getSchemas()) {
            List<SaikuCube> cubes = new ArrayList<SaikuCube>();
            for (Cube cub : schem.getCubes()) {
              cubes.add(
                  new SaikuCube(
                      connectionName,
                      cub.getUniqueName(),
                      cub.getName(),
                      cub.getCaption(),
                      cat.getName(),
                      schem.getName(),
                      cub.isVisible()));
            }
            Collections.sort(cubes, new SaikuCubeCaptionComparator());
            schemas.add(new SaikuSchema(schem.getName(), cubes));
          }
          if (schemas.size() == 0) {
            OlapDatabaseMetaData olapDbMeta = olapcon.getMetaData();
            ResultSet cubesResult = olapDbMeta.getCubes(cat.getName(), null, null);

            try {
              List<SaikuCube> cubes = new ArrayList<SaikuCube>();
              while (cubesResult.next()) {

                cubes.add(
                    new SaikuCube(
                        connectionName,
                        cubesResult.getString("CUBE_NAME"),
                        cubesResult.getString("CUBE_NAME"),
                        cubesResult.getString("CUBE_NAME"),
                        cubesResult.getString("CATALOG_NAME"),
                        cubesResult.getString("SCHEMA_NAME")));
              }
              Collections.sort(cubes, new SaikuCubeCaptionComparator());
              schemas.add(new SaikuSchema("", cubes));
            } catch (SQLException e) {
              throw new OlapException(e.getMessage(), e);
            } finally {
              try {
                cubesResult.close();
              } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
          }
          Collections.sort(schemas);
          catalogs.add(new SaikuCatalog(cat.getName(), schemas));
        }
      } catch (OlapException e) {
        throw new SaikuOlapException(
            "Error getting objects of connection (" + connectionName + ")", e);
      }
      Collections.sort(catalogs);
      connection = new SaikuConnection(connectionName, catalogs);
      return connection;
    }
    throw new SaikuOlapException("Cannot find connection: (" + connectionName + ")");
  }
예제 #18
0
 public int hashCode() {
   return cube == null ? 0 : cube.hashCode();
 }
예제 #19
0
  public TotalsListsBuilder(
      Measure[] selectedMeasures,
      TotalAggregator[] aggrTempl,
      CellSet cellSet,
      AxisInfo totalsAxisInfo,
      AxisInfo dataAxisInfo)
      throws Exception {
    Cube cube;
    try {
      cube = cellSet.getMetaData().getCube();
    } catch (OlapException e) {
      throw new RuntimeException(e);
    }
    uniqueToSelected = new HashMap<String, Integer>();
    if (selectedMeasures.length > 0) {
      valueFormats = new Format[selectedMeasures.length];
      measures = selectedMeasures;
      for (int i = 0; i < valueFormats.length; i++) {
        valueFormats[i] = getMeasureFormat(selectedMeasures[i]);
        uniqueToSelected.put(selectedMeasures[i].getUniqueName(), i);
      }
    } else {
      Measure defaultMeasure = cube.getMeasures().get(0);
      if (cube.getDimensions().get("Measures") != null) {
        Member ms = cube.getDimensions().get("Measures").getDefaultHierarchy().getDefaultMember();
        if (ms instanceof Measure) {
          defaultMeasure = (Measure) ms;
        }
      }
      measures = new Measure[] {defaultMeasure};
      valueFormats = new Format[] {getMeasureFormat(defaultMeasure)};
    }
    this.cellSet = cellSet;
    this.dataAxisInfo = dataAxisInfo;
    this.totalsAxisInfo = totalsAxisInfo;
    final int maxDepth = dataAxisInfo.maxDepth + 1;
    boolean hasMeasuresOnDataAxis = false;
    int measuresAt = 0;
    int measuresMember = 0;
    final List<Member> members =
        dataAxisInfo.axis.getPositionCount() > 0
            ? dataAxisInfo.axis.getPositions().get(0).getMembers()
            : Collections.<Member>emptyList();
    for (; measuresMember < members.size(); measuresMember++) {
      Member m = members.get(measuresMember);
      if ("Measures".equals(m.getDimension().getName())) {
        hasMeasuresOnDataAxis = true;
        break;
      }
      measuresAt += dataAxisInfo.levels[measuresMember].size();
    }
    if (hasMeasuresOnDataAxis) {
      this.measuresAt = measuresAt;
      measuresCaptions = new String[selectedMeasures.length];
      for (int i = 0; i < measuresCaptions.length; i++) {
        measuresCaptions[i] = selectedMeasures[i].getCaption();
      }
    } else {
      this.measuresAt = Integer.MIN_VALUE;
      measuresCaptions = null;
    }

    totalBranch = new TotalNode[maxDepth];
    TotalNode rootNode =
        new TotalNode(
            measuresCaptions, measures, aggrTempl[0], this, totalsAxisInfo.fullPositions.size());
    col = Axis.ROWS.equals(dataAxisInfo.axis.getAxisOrdinal()) ? 1 : 0;
    row = (col + 1) & 1;
    this.aggrTempl = aggrTempl;

    totalBranch[0] = rootNode;
    totalsLists = new List[maxDepth];
    for (int i = 0; i < totalsLists.length; i++) {
      totalsLists[i] = new ArrayList<TotalNode>();
    }
    totalsLists[0].add(rootNode);
    memberBranch = new Member[dataAxisInfo.maxDepth + 1];
  }
예제 #20
0
  public static void main(String[] args) throws Exception {

    // Load the driver
    Class.forName("mondrian.olap4j.MondrianOlap4jDriver");

    // Connect
    final Connection connection =
        DriverManager.getConnection(
            "jdbc:mondrian:" // Driver ident
                + "Jdbc=jdbc:hsqldb:file:foodmart/foodmart;" // Relational DB
                + "Catalog=file:foodmart/FoodMart.xml;"); // Catalog

    // We are dealing with an olap connection. we must unwrap it.
    final OlapConnection olapConnection = connection.unwrap(OlapConnection.class);

    // Get a cube object.
    Cube salesCube = olapConnection.getOlapSchema().getCubes().get("Sales");

    // Build a query object.
    Query myQuery = new Query("myQuery", salesCube);

    // Lookup some dimensions
    QueryDimension productDim = myQuery.getDimension("Product");
    QueryDimension storeDim = myQuery.getDimension("Store");
    QueryDimension timeDim = myQuery.getDimension("Time");

    // Place dimensions on some axis
    myQuery.getAxis(Axis.COLUMNS).addDimension(productDim);
    myQuery.getAxis(Axis.ROWS).addDimension(storeDim);
    myQuery.getAxis(Axis.FILTER).addDimension(timeDim);

    // Including a member by metadata
    Member year1997 =
        salesCube.lookupMember(IdentifierNode.ofNames("Time", "1997").getSegmentList());
    timeDim.include(year1997);

    // Including a member by name parts
    productDim.include(
        Selection.Operator.CHILDREN,
        IdentifierNode.ofNames("Product", "Drink", "Beverages").getSegmentList());

    // We can also exclude members
    productDim.exclude(
        IdentifierNode.ofNames("Product", "Drink", "Beverages", "Carbonated Beverages")
            .getSegmentList());

    // Validate this query
    myQuery.validate();

    // Print!
    System.out.println("/********************* QUERY ***********************/");

    System.out.println(myQuery.getSelect().toString());

    System.out.println("/********************* QUERY ***********************/");
    System.out.println(" ");
    System.out.println(" ");
    System.out.println(" ");
    System.out.println(" ");

    System.out.println("/********************* RESULTS ***********************/");

    RectangularCellSetFormatter formatter = new RectangularCellSetFormatter(false);

    PrintWriter writer = new PrintWriter(System.out);

    formatter.format(myQuery.execute(), writer);

    writer.flush();
    System.out.println("/********************* RESULTS ***********************/");
  }
예제 #21
0
 public List<SaikuHierarchy> getAllHierarchies(SaikuCube cube) throws SaikuOlapException {
   Cube nativeCube = getNativeCube(cube);
   return ObjectUtil.convertHierarchies(nativeCube.getHierarchies());
 }