mondrian.olap.Util Java Examples

The following examples show how to use mondrian.olap.Util. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractQuerySpec.java    From youkefu with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a measure to a query.
 *
 * @param i Ordinal of measure
 * @param sqlQuery Query object
 */
protected void addMeasure(final int i, final SqlQuery sqlQuery) {
    RolapStar.Measure measure = getMeasure(i);
    if (!isPartOfSelect(measure)) {
        return;
    }
    Util.assertTrue(measure.getTable() == getStar().getFactTable());
    measure.getTable().addToFrom(sqlQuery, false, true);

    String exprInner =
        measure.getExpression() == null
            ? "*"
            : measure.generateExprString(sqlQuery);
    String exprOuter = measure.getAggregator().getExpression(exprInner);
    sqlQuery.addSelect(
        exprOuter,
        measure.getInternalType(),
        getMeasureAlias(i));
}
 
Example #2
Source File: AggregateTableOutputFactory.java    From pentaho-aggdesigner with GNU General Public License v2.0 6 votes vote down vote up
public AggregateTableOutput createOutput(Schema schema, Aggregate aggregate, List<String> uniqueTableNames) {
    AggregateTableOutput output = new AggregateTableOutput(aggregate);
    String tableName = schema.getDialect().removeInvalidIdentifierCharacters(aggregate.getCandidateTableName());
    tableName = Util.uniquify(tableName, schema.getDialect().getMaximumTableNameLength(), uniqueTableNames);
    output.setTableName(tableName);
    
    final List<String> columnNameList = new ArrayList<String>();
    int maximumColumnNameLength =
        schema.getDialect().getMaximumColumnNameLength();
    for (Attribute attribute :
        UnionIterator.over(
            aggregate.getAttributes(), 
            aggregate.getMeasures()))
    {
        String name = Util.uniquify(
            attribute.getCandidateColumnName(),
            maximumColumnNameLength,
            columnNameList);
        output.getColumnOutputs().add(new AggregateTableOutput.ColumnOutput(name, attribute));
    }
    
    return output;
}
 
Example #3
Source File: MondrianSchemaLoader.java    From pentaho-aggdesigner with GNU General Public License v2.0 6 votes vote down vote up
static double estimateSpaceForColumn( final RolapStar.Column column ) {
  switch ( column.getDatatype() ) {
    case Boolean:
      return 1;
    case Date:
      return 4;
    case Integer:
      return 4;
    case Numeric:
      return 4;
    case String:
      return 20;
    case Time:
      return 4;
    case Timestamp:
      return 8;
    default:
      throw Util.unexpected( column.getDatatype() );
  }
}
 
Example #4
Source File: AbstractMDXDataFactory.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected Member yuckyInternalMondrianLookup( final Query query, final Hierarchy hierarchy, final String parameter ) {
  final Member memberById = (Member) Util.lookup( query, Util.parseIdentifier( parameter ) );
  if ( memberById != null ) {
    final Hierarchy memberHierarchy = memberById.getHierarchy();
    if ( hierarchy != memberHierarchy ) {
      if ( ObjectUtilities.equal( hierarchy, memberHierarchy ) == false ) {
        logger
          .warn( "Cannot match hierarchy of member found with the hierarchy specfied in the parameter: " // NON-NLS
            + "Unabe to guarantee that the correct member has been queried, returning null" ); // NON-NLS
        return null;
      }
    }
    return memberById;
  }
  return null;
}
 
Example #5
Source File: MondrianUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static String getUniqueMemberName( Member member ) {
  String memberValue = Util.quoteMdxIdentifier( member.getName() );
  while ( member.getParentMember() != null ) {
    memberValue = Util.quoteMdxIdentifier( member.getParentMember().getName() ) + "." + memberValue;
    member = member.getParentMember();
  }
  final Hierarchy hierarchy = member.getHierarchy();
  final Dimension dimension = hierarchy.getDimension();
  if ( hierarchy.getName().equals( dimension.getName() ) ) {
    return Util.quoteMdxIdentifier( hierarchy.getName() ) + "." + memberValue;
  } else {
    return Util.quoteMdxIdentifier( dimension.getName() ) + "." + Util.quoteMdxIdentifier( hierarchy.getName() ) + "."
      +
      memberValue;
  }
}
 
Example #6
Source File: MondrianUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static String parseSchemaName( final ResourceManager resourceManager,
                                      final ResourceKey contextKey,
                                      final String designTimeFile ) {
  try {
    final CubeFileProvider cubeFileProvider =
      ClassicEngineBoot.getInstance().getObjectFactory().get( CubeFileProvider.class );
    cubeFileProvider.setDesignTimeFile( designTimeFile );
    final InputStream inputStream =
      Util.readVirtualFile( cubeFileProvider.getCubeFile( resourceManager, contextKey ) );
    try {
      return parseXmlDocument( inputStream );
    } finally {
      inputStream.close();
    }
  } catch ( Exception e ) {
    logger.debug( "Failed to parse mondrian schema file at " + designTimeFile, e );
  }
  return null;
}
 
Example #7
Source File: MondrianDataAdapterService.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void contributeParameters(Map<String, Object> parameters)
		throws JRException {
	MondrianDataAdapter mda = getJdbcDataAdapter();
	if (mda != null) {
		Util.PropertyList props = new Util.PropertyList();
		props.put("Catalog", mda.getCatalogURI());
		props.put("Provider", "mondrian");
		props.put("Locale", Locale.getDefault().getLanguage());

		connection = DriverManager.getConnection(props, null,
				new SimpleSQLDataSource(this));

		parameters
				.put(JRMondrianQueryExecuterFactory.PARAMETER_MONDRIAN_CONNECTION,
						connection);
	}
}
 
Example #8
Source File: SpagoBIFilterDynamicSchemaProcessor.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Search for parameters to substitute in schema definition, identified by $P{attribute_name}
 * 
 * @param originalSchema
 * @param connectInfo
 * @return modifiedSchema
 * @throws Exception
 */
private String substituteParameterValues(String originalSchema, Util.PropertyList connectInfo) throws Exception {
	String modifiedSchema = originalSchema;
	indexProgression = Integer.valueOf(0);
	String att = findParameterInSchema(originalSchema);
	while (att != null) {
		// if value is null I put null, if instead there is no the attribute
		// name in connectInfo I don't substitute
		if (connectInfo.get(att) != null) {
			String attrValueBase64 = connectInfo.get(att);
			logger.debug("Parameter value in Base64 encoding is " + attrValueBase64);
			String value = null;
			try {
				value = new String(DECODER.decodeBuffer(attrValueBase64), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("UTF-8 encoding not supported!!!!!", e);
				value = new String(DECODER.decodeBuffer(attrValueBase64));
			}
			logger.debug("change attribute " + att + " with  [" + value + "]");

			modifiedSchema = modifiedSchema.replaceAll("\\$P\\{" + att + "\\}", value);
		}
		att = findParameterInSchema(modifiedSchema);
	}
	return modifiedSchema;
}
 
Example #9
Source File: SpagoBIFilterDynamicSchemaProcessor.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Search for profile attributes to substitute in schema definition, identified by $P{attribute_name}
 * 
 * @param originalSchema
 * @param connectInfo
 * @return modifiedSchema
 * @throws Exception
 */
private String substituteProfileValues(String originalSchema, Util.PropertyList connectInfo) throws Exception {
	String modifiedSchema = originalSchema;
	indexProgression = Integer.valueOf(0);
	String att = findProfileAttributeInSchema(originalSchema);
	while (att != null) {
		// if value is null I put null, if instead there is no the attribute
		// name in connectInfo I don't substitute
		if (connectInfo.get(att) != null) {
			String attrValueBase64 = connectInfo.get(att);
			logger.debug("Attribute value in Base64 encoding is " + attrValueBase64);
			String value = null;
			try {
				value = new String(DECODER.decodeBuffer(attrValueBase64), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("UTF-8 encoding not supported!!!!!", e);
				value = new String(DECODER.decodeBuffer(attrValueBase64));
			}
			logger.debug("change attribute " + att + " with  [" + value + "]");

			modifiedSchema = modifiedSchema.replaceAll("\\$\\{" + att + "\\}", value);
		}
		att = findProfileAttributeInSchema(modifiedSchema);
	}
	return modifiedSchema;
}
 
Example #10
Source File: SpagoBIFilterDynamicSchemaProcessor.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String processSchema(String schemaUrl, Util.PropertyList connectInfo) throws Exception {
	logger.debug("IN: schemaUrl: " + schemaUrl);
	try {
		if (schemaUrl.startsWith("file:")) {
			schemaUrl = schemaUrl.substring("file:".length());
		}
		File schemaFile = new File(schemaUrl);
		schemaUrl = schemaFile.getAbsolutePath();
		logger.debug("Absolute file path: " + schemaUrl);
		return super.processSchema(schemaUrl, connectInfo);
	} finally {
		logger.debug("OUT");
	}
}
 
Example #11
Source File: SpagoBIFilterDynamicSchemaProcessor.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String filter(String schemaUrl, Util.PropertyList connectInfo, InputStream stream) throws Exception {
	logger.debug("IN");
	String originalSchema = super.filter(schemaUrl, connectInfo, stream);
	String modifiedSchema = originalSchema;
	// // search for profile attributes to substitute in schema definition,
	// // identified by $P{attribute_name}
	// indexProgression = Integer.valueOf(0);
	// String att = findProfileAttributeInSchema(originalSchema);
	// while (att != null) {
	// // if value is null I put null, if instead there is no the attribute
	// // name in connectInfo I don't substitute
	// if (connectInfo.get(att) != null) {
	// String attrValueBase64 = connectInfo.get(att);
	// logger.debug("Attribute value in Base64 encoding is " + attrValueBase64);
	// String value = null;
	// try {
	// value = new String(DECODER.decodeBuffer(attrValueBase64), "UTF-8");
	// } catch (UnsupportedEncodingException e) {
	// logger.error("UTF-8 encoding not supported!!!!!", e);
	// value = new String(DECODER.decodeBuffer(attrValueBase64));
	// }
	// logger.debug("change attribute " + att + " with  [" + value + "]");
	//
	// modifiedSchema = modifiedSchema.replaceAll("\\$\\{" + att + "\\}", value);
	// }
	// att = findProfileAttributeInSchema(modifiedSchema);
	// }
	// Substitutes profile attributes values
	modifiedSchema = substituteProfileValues(originalSchema, connectInfo);
	// Substitutes parameters values (pass modifiedSchema for don't loose profile attribute values)
	modifiedSchema = substituteParameterValues(modifiedSchema, connectInfo);
	logger.debug("OUT: modified schema is:\n" + modifiedSchema);
	return modifiedSchema;
}
 
Example #12
Source File: SpagoBICellWrapper.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getFormattedValue() {
	String formatString = (String) cell.getPropertyValue(Property.StandardCellProperty.FORMAT_STRING);
	SpagoBICellSetWrapper cellSet = (SpagoBICellSetWrapper) this.getCellSet();
	Locale locale = cellSet.getSpagoBIPivotModel().getLocale();
	Object value = this.getValue();
	if (value == Util.nullValue) {
		value = null;
	}
	if (value instanceof Throwable) {
		return "#ERR: " + value.toString();
	}
	Format format = Format.get(formatString, locale);
	return format.format(value);
}
 
Example #13
Source File: TestUtils.java    From pentaho-aggdesigner with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Converts a string constant into locale-specific line endings.
 */
public static String fold(String string) {
    if (!nl.equals("\n")) {
        string = Util.replace(string, "\n", nl);
    }
    return string;
}
 
Example #14
Source File: DrillThroughQuerySpec.java    From youkefu with Apache License 2.0 5 votes vote down vote up
protected void addMeasure(final int i, final SqlQuery sqlQuery) {
    RolapStar.Measure measure = getMeasure(i);

    if (!isPartOfSelect(measure)) {
        return;
    }

    Util.assertTrue(measure.getTable() == getStar().getFactTable());
    measure.getTable().addToFrom(sqlQuery, false, true);

    if (!countOnly) {
        String expr = measure.generateExprString(sqlQuery);
        sqlQuery.addSelect(expr, null, getMeasureAlias(i));
    }
}
 
Example #15
Source File: RuleBasedAggregateTableOutputFactory.java    From pentaho-aggdesigner with GNU General Public License v2.0 5 votes vote down vote up
public AggregateTableOutput createOutput(Schema schema, Aggregate aggregate, List<String> uniqueTableNames) {
    AggregateTableOutput output = new AggregateTableOutput(aggregate);
    String tableName = schema.getDialect().removeInvalidIdentifierCharacters(aggregate.getCandidateTableName());
    tableName = Util.uniquify(tableName, schema.getDialect().getMaximumTableNameLength(), uniqueTableNames);
    output.setTableName(tableName);
    
    final List<String> columnNameList = new ArrayList<String>();
    // TODO: throw an exception here if name is too large?
    //        int maximumColumnNameLength =
    //            schema.getDialect().getMaximumColumnNameLength();
    for (Attribute attribute :
        UnionIterator.over(
            aggregate.getAttributes(), 
            aggregate.getMeasures()))
    {
        if (attribute instanceof Measure) {
            String name = cleanse(((MondrianMeasure)attribute).getRolapStarMeasure().getName());
            
            output.getColumnOutputs().add(new AggregateTableOutput.ColumnOutput(name, attribute));
        } else {
            Level level = findLevel(schema, attribute);
            RolapCubeLevel rolapLevel = ((MondrianLevel)level).getRolapCubeLevel();
            output.getColumnOutputs().add(new AggregateTableOutput.ColumnOutput(
                    cleanse(rolapLevel.getHierarchy().getName()) + "_" + 
                    cleanse(rolapLevel.getName()), attribute));
                            
        }
    }
    
    return output;
}
 
Example #16
Source File: DataSourceService.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param cube
 * @throws Exception
 */
public Connection service(String xml) throws Exception {
	Connection dataSourceObject = null ;
	StringBuffer strb = new StringBuffer();
	Util.PropertyList properties = Util.parseConnectString(strb.append("Provider=mondrian;")
				.append(
			       "Catalog=").append(xml).append(";").toString());
	if(properties!=null){
		dataSourceObject = DriverManager.getConnection(properties,null , dataSource) ;
	}
	return dataSourceObject ;
}
 
Example #17
Source File: ValidationMondrianSchemaLoaderTest.java    From pentaho-aggdesigner with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testValidateConnectionWithIntegratedSecurity() {

  parameterValues.put(MondrianSchemaLoaderParameter.connectString,
    "Provider=Mondrian;JdbcDrivers=org.hsqldb.jdbcDriver;Jdbc=jdbc:hsqldb:mem:test;"
      + "databaseName=jackrabbit;integratedSecurity=true;JdbcUser=;JdbcPassword=;Catalog=file:"
      + tmpFile.getAbsolutePath());

  String connectionString = bean.getJdbcConnectionString( Util.parseConnectString(
    (String) parameterValues.get( MondrianSchemaLoaderParameter.connectString ) ), true);
  assertTrue(connectionString.contains( "integratedSecurity=true" ));
}
 
Example #18
Source File: ValidationMondrianSchemaLoaderTest.java    From pentaho-aggdesigner with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testValidateConnectionWithoutIntegratedSecurity() {

  parameterValues.put(MondrianSchemaLoaderParameter.connectString,
    "Provider=Mondrian;JdbcDrivers=org.hsqldb.jdbcDriver;Jdbc=jdbc:hsqldb:mem:test;"
      + "databaseName=jackrabbit;JdbcUser=user;JdbcPassword=password;Catalog=file:"
      + tmpFile.getAbsolutePath());

  String connectionString = bean.getJdbcConnectionString( Util.parseConnectString(
    (String) parameterValues.get( MondrianSchemaLoaderParameter.connectString ) ), false);
  assertFalse(connectionString.contains( "integratedSecurity=true" ));
}
 
Example #19
Source File: TestUtils.java    From pentaho-aggdesigner with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Converts a string constant into locale-specific line endings.
 */
public static String fold(String string) {
    if (!nl.equals("\n")) {
        string = Util.replace(string, "\n", nl);
    }
    return string;
}
 
Example #20
Source File: SchemaResolver.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String resolveSchema( final ResourceManager resourceManager,
                                    final ResourceKey contextKey,
                                    String catalogUrl )
  throws FileSystemException {
  final FileSystemManager fsManager = VFS.getManager();
  if ( fsManager == null ) {
    throw Util.newError( "Cannot get virtual file system manager" );
  }

  // Workaround VFS bug.
  if ( catalogUrl.startsWith( "file://localhost" ) ) {
    catalogUrl = catalogUrl.substring( "file://localhost".length() );
  }
  if ( catalogUrl.startsWith( "file:" ) ) {
    catalogUrl = catalogUrl.substring( "file:".length() );
  }

  try {
    final File catalogFile = new File( catalogUrl ).getCanonicalFile();
    final FileObject file = fsManager.toFileObject( catalogFile );
    if ( file.isReadable() ) {
      return catalogFile.getPath();
    }
  } catch ( FileSystemException fse ) {
    logger.info( "Failed to resolve schema file '" + catalogUrl + "' as local file. Treating file as non-readable.",
      fse );
  } catch ( IOException e ) {
    logger
      .info( "Failed to resolve schema file '" + catalogUrl + "' as local file. Treating file as non-readable.", e );
  }

  if ( contextKey == null ) {
    return catalogUrl;
  }

  final File contextAsFile = getContextAsFile( contextKey );
  if ( contextAsFile == null ) {
    return catalogUrl;
  }

  final File resolvedFile = new File( contextAsFile.getParentFile(), catalogUrl );
  if ( resolvedFile.isFile() && resolvedFile.canRead() ) {
    return resolvedFile.getAbsolutePath();
  }

  return catalogUrl;
}
 
Example #21
Source File: DefaultMondrianConnectionProvider.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
public Connection createConnection( final Properties properties, final DataSource dataSource )
  throws ReportDataFactoryException {
  logger.debug( "Creating Mondrian connection: " + Util.parseConnectString( computeConnectionString( properties ) ) );
  return DriverManager
    .getConnection( Util.parseConnectString( computeConnectionString( properties ) ), null, dataSource );
}
 
Example #22
Source File: DelegatingTupleList.java    From youkefu with Apache License 2.0 4 votes vote down vote up
public void addTuple(Member... members) {
    list.add(Util.flatList(members));
}
 
Example #23
Source File: MondrianSchemaLoader.java    From pentaho-aggdesigner with GNU General Public License v2.0 4 votes vote down vote up
public List<ValidationMessage> validateSchema( Map<Parameter, Object> parameterValues ) {
  String connectString =
    (String) parameterValues.get(
      MondrianSchemaLoaderParameter.connectString );
  String cubeName =
    (String) parameterValues.get(
      MondrianSchemaLoaderParameter.cube );

  PropertyList propertyList = Util.parseConnectString( connectString );

  String jdbcDrivers = propertyList.get( "JdbcDrivers" );
  if ( StringUtils.isBlank( jdbcDrivers ) ) {
    throw new RuntimeException( "missing 'JdbcDrivers' in connect string" );
  }

  Boolean integratedSecurity = Boolean.parseBoolean( propertyList.get( "integratedSecurity" ) );

  String jdbc = getJdbcConnectionString( propertyList, integratedSecurity );
  if ( StringUtils.isBlank( jdbcDrivers ) ) {
    throw new RuntimeException( "missing 'Jdbc' in connect string" );
  }

  String catalog = propertyList.get( "Catalog" );
  if ( StringUtils.isBlank( jdbcDrivers ) ) {
    throw new RuntimeException( "missing 'Catalog' in connect string" );
  }

  String jdbcUser = propertyList.get( "JdbcUser" );

  String jdbcPassword = propertyList.get( "JdbcPassword" );

  List<ValidationMessage> messages = new ArrayList<ValidationMessage>();

  try {
    List<MondrianSchemaValidator> validators = loadValidators( parameterValues );

    Class.forName( jdbcDrivers ); //$NON-NLS-1$

    java.sql.Connection conn;

    if ( integratedSecurity ) {
      conn = java.sql.DriverManager.getConnection( jdbc );
    } else {
      conn = java.sql.DriverManager.getConnection( jdbc, jdbcUser, jdbcPassword );
    }

    messages = ValidationHelper.validateCube( catalog, cubeName, conn, validators ); //$NON-NLS-1$

    conn.close();
  } catch ( Exception e ) {
    if ( logger.isErrorEnabled() ) {
      logger.error( "an exception occurred", e );
    }
    ValidationMessage msg =
      new ValidationMessage( ValidationMessage.Type.ERROR, e.getClass().getName() + ": " + e.getLocalizedMessage() );
    messages.add( msg );
  }
  return messages;
}