blob: c87fb67dc5ec39008f0b2b7bade928cbbd5f3448 [file] [log] [blame]
/*
*
* Copyright (c) 2013, 2016 - Loetz GmbH&Co.KG, 69115 Heidelberg, Germany
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christophe Loetz (Loetz GmbH&Co.KG) - initial implementation
*
*/
package org.eclipse.osbp.xtext.datamartdsl.jvmmodel
import java.beans.PropertyChangeSupport
import java.io.Serializable
import java.sql.Connection
import java.sql.ResultSet
import java.sql.SQLException
import java.util.ArrayList
import java.util.HashMap
import java.util.HashSet
import java.util.LinkedHashMap
import java.util.List
import java.util.Map
import java.util.Set
import java.util.stream.Collectors
import javax.inject.Inject
import mondrian.rolap.RolapConnection
import org.apache.commons.lang3.StringUtils
import org.eclipse.emf.common.util.EList
import org.eclipse.osbp.bpm.api.IBPMEngine
import org.eclipse.osbp.bpm.api.IBPMTaskClient
import org.eclipse.osbp.core.api.persistence.IPersistenceService
import org.eclipse.osbp.dsl.common.datatypes.IDto
import org.eclipse.osbp.dsl.common.xtext.extensions.AnnotationExtension
import org.eclipse.osbp.dsl.entity.xtext.extensions.ModelExtensions
import org.eclipse.osbp.dsl.entity.xtext.extensions.NamingExtensions
import org.eclipse.osbp.dsl.semantic.common.types.LAttribute
import org.eclipse.osbp.dsl.semantic.common.types.LDataType
import org.eclipse.osbp.dsl.semantic.common.types.LScalarType
import org.eclipse.osbp.dsl.semantic.entity.LBean
import org.eclipse.osbp.dsl.semantic.entity.LEntity
import org.eclipse.osbp.dsl.semantic.entity.LEntityAttribute
import org.eclipse.osbp.dsl.semantic.entity.LEntityFeature
import org.eclipse.osbp.preferences.EnumDatabaseVendor
import org.eclipse.osbp.runtime.common.annotations.Datamart
import org.eclipse.osbp.runtime.common.annotations.Dispose
import org.eclipse.osbp.runtime.common.filter.IDatamartService
import org.eclipse.osbp.ui.api.datamart.DatamartFilter
import org.eclipse.osbp.ui.api.datamart.DatamartPrimary
import org.eclipse.osbp.ui.api.datamart.IDataMart
import org.eclipse.osbp.ui.api.datamart.IDataMart.EType
import org.eclipse.osbp.ui.api.datamart.IDatamartContainer
import org.eclipse.osbp.ui.api.metadata.IDSLMetadataService
import org.eclipse.osbp.ui.api.user.IUser
import org.eclipse.osbp.ui.api.useraccess.IUserAccessService
import org.eclipse.osbp.utils.common.EntityUtils
import org.eclipse.osbp.utils.entityhelper.DataType
import org.eclipse.osbp.xtext.authorizationdsl.RoleEntity
import org.eclipse.osbp.xtext.authorizationdsl.RoleEntityAttribute
import org.eclipse.osbp.xtext.authorizationdsl.RoleEntityReference
import org.eclipse.osbp.xtext.cubedsl.CubeDimension
import org.eclipse.osbp.xtext.cubedsl.CubePackage
import org.eclipse.osbp.xtext.datamart.common.ACubeDatamart
import org.eclipse.osbp.xtext.datamart.common.AEntityDatamart
import org.eclipse.osbp.xtext.datamart.common.ATaskDatamart
import org.eclipse.osbp.xtext.datamart.common.DatamartDefinitionUtil
import org.eclipse.osbp.xtext.datamart.common.DatamartDtoMapper
import org.eclipse.osbp.xtext.datamart.common.olap.DerivedCellSet
import org.eclipse.osbp.xtext.datamart.common.sql.FillerTextResultSet
import org.eclipse.osbp.xtext.datamartdsl.Addition
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerDateFuture
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerDatePast
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerDateRange
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerDateType
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerDoubleType
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerIntegerType
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerSignedDoubleRandom
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerSignedDoubleRange
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerSignedIntegerRandom
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerSignedIntegerRange
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerTextParagraphs
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerTextRandom
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerTextSentences
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerTextType
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerTextWords
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerUnsignedDoubleRandom
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerUnsignedDoubleRange
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerUnsignedIntegerRandom
import org.eclipse.osbp.xtext.datamartdsl.AttributeFillerUnsignedIntegerRange
import org.eclipse.osbp.xtext.datamartdsl.AxisEnum
import org.eclipse.osbp.xtext.datamartdsl.ConditionalExpression
import org.eclipse.osbp.xtext.datamartdsl.Conjunction
import org.eclipse.osbp.xtext.datamartdsl.DatamartAggregation
import org.eclipse.osbp.xtext.datamartdsl.DatamartAggregationFunction
import org.eclipse.osbp.xtext.datamartdsl.DatamartAttribute
import org.eclipse.osbp.xtext.datamartdsl.DatamartAttributeBase
import org.eclipse.osbp.xtext.datamartdsl.DatamartCondition
import org.eclipse.osbp.xtext.datamartdsl.DatamartCube
import org.eclipse.osbp.xtext.datamartdsl.DatamartCubeAxis
import org.eclipse.osbp.xtext.datamartdsl.DatamartDSLFactory
import org.eclipse.osbp.xtext.datamartdsl.DatamartDefineDerivedMeasure
import org.eclipse.osbp.xtext.datamartdsl.DatamartDefinition
import org.eclipse.osbp.xtext.datamartdsl.DatamartDerivedMeasure
import org.eclipse.osbp.xtext.datamartdsl.DatamartEntity
import org.eclipse.osbp.xtext.datamartdsl.DatamartFunction
import org.eclipse.osbp.xtext.datamartdsl.DatamartFunctionIntParameter
import org.eclipse.osbp.xtext.datamartdsl.DatamartHierarchy
import org.eclipse.osbp.xtext.datamartdsl.DatamartMeasure
import org.eclipse.osbp.xtext.datamartdsl.DatamartMember
import org.eclipse.osbp.xtext.datamartdsl.DatamartMemberTuple
import org.eclipse.osbp.xtext.datamartdsl.DatamartNavigation
import org.eclipse.osbp.xtext.datamartdsl.DatamartOrder
import org.eclipse.osbp.xtext.datamartdsl.DatamartOwner
import org.eclipse.osbp.xtext.datamartdsl.DatamartPackage
import org.eclipse.osbp.xtext.datamartdsl.DatamartParameterFunction
import org.eclipse.osbp.xtext.datamartdsl.DatamartReference
import org.eclipse.osbp.xtext.datamartdsl.DatamartRole
import org.eclipse.osbp.xtext.datamartdsl.DatamartSetAggregation
import org.eclipse.osbp.xtext.datamartdsl.DatamartSetAggregationFunction
import org.eclipse.osbp.xtext.datamartdsl.DatamartSetFunction
import org.eclipse.osbp.xtext.datamartdsl.DatamartSetParameterFunction
import org.eclipse.osbp.xtext.datamartdsl.DatamartSetTuple
import org.eclipse.osbp.xtext.datamartdsl.DatamartSlicer
import org.eclipse.osbp.xtext.datamartdsl.DatamartSource
import org.eclipse.osbp.xtext.datamartdsl.DatamartTask
import org.eclipse.osbp.xtext.datamartdsl.DatamartTaskFilter
import org.eclipse.osbp.xtext.datamartdsl.Disjunction
import org.eclipse.osbp.xtext.datamartdsl.Division
import org.eclipse.osbp.xtext.datamartdsl.Expression
import org.eclipse.osbp.xtext.datamartdsl.Multiplication
import org.eclipse.osbp.xtext.datamartdsl.Subtraction
import org.eclipse.osbp.xtext.datamartdsl.util.DatamartAttributeUtil
import org.eclipse.osbp.xtext.entitymock.common.filler.FillerTextProvider
import org.eclipse.xtext.common.types.JvmAnnotationReference
import org.eclipse.xtext.common.types.JvmDeclaredType
import org.eclipse.xtext.common.types.JvmField
import org.eclipse.xtext.common.types.JvmGenericType
import org.eclipse.xtext.common.types.JvmMember
import org.eclipse.xtext.common.types.JvmOperation
import org.eclipse.xtext.common.types.JvmTypeReference
import org.eclipse.xtext.common.types.JvmVisibility
import org.eclipse.xtext.common.types.TypesFactory
import org.eclipse.xtext.common.types.util.TypeReferences
import org.eclipse.xtext.naming.IQualifiedNameProvider
import org.eclipse.xtext.xbase.jvmmodel.AbstractModelInferrer
import org.eclipse.xtext.xbase.jvmmodel.IJvmDeclaredTypeAcceptor
import org.eclipse.xtext.xbase.jvmmodel.JvmTypesBuilder
import org.junit.Test
import org.osgi.service.component.annotations.Component
import org.osgi.service.component.annotations.Reference
import org.osgi.service.component.annotations.ReferenceCardinality
import org.osgi.service.component.annotations.ReferencePolicy
import org.slf4j.Logger
import org.eclipse.osbp.xtext.datamart.lib.AbstractDatamartService
import org.eclipse.osbp.xtext.datamartdsl.OperatorEnum
/**
* <p>
* This inferrer infers models of extension .datamart and generates code to be used by other dsl. It encapsulates difficult syntax construction
* and provides a reflective call interface as well as a data transfer object olap cellSet.
* There are two different approaches: the traditional SQL thru entities and their attributes and MDX thru cubes and their measures and stuff.
* For SQL the olap cellSet is emulated by appropriate classes and implements NOT ALL features of a MDX filled olap cellSet.
* </p>
*
* @author Joerg Riegel
*/
/**
* <p>Infers a JVM model from the source model.</p>
*
* <p>The JVM model should contain all elements that would appear in the Java code
* which is generated from the source model. Other models link against the JVM model rather than the source model.</p>
*/
class DatamartDSLJvmModelInferrer extends AbstractModelInferrer {
/**
* convenience API to build and initialize JVM types and their members.
*/
@Inject extension JvmTypesBuilder
@Inject extension IQualifiedNameProvider
@Inject extension NamingExtensions
@Inject extension TypeReferences
@Inject extension AnnotationExtension
@Inject extension ModelExtensions
@Inject
@Extension
private DataType dtType;
var sqlAliasCounter = <String, Integer>newHashMap
var sqlFilterMap = <String, DatamartAttributeBase>newHashMap
var sqlGrouping = <String>newArrayList
var idMap = <String, LEntity>newHashMap
var datamartDtoMapper = null as String
var entityGrouping = new HashMap<String, LEntity>()
var ignoreEntityGrouping = false
var sqlHasAggregate = false
var sqlHasOrder = false
var public static String pckgName = null
var String binderClassName = ""
var defaultColumnWeight = 500
def void generatePckgName(DatamartPackage pckg, IJvmDeclaredTypeAcceptor acceptor) {
pckgName = pckg.name
}
/**
* <p>infer method dispatches the neccessary routines to build fields, setter, getter, constructors and methods of the generated code.</p>
*
*/
def dispatch void infer(DatamartPackage datamart, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
datamart.generatePckgName(acceptor)
// the test main class
var cls = datamart.toClass(datamart.name.toString.concat("TestClass"))
cls.simpleName = cls.simpleName.toFirstUpper
acceptor.accept(cls, [
annotations += _annotationTypesBuilder.annotationRef(SuppressWarnings, "serial")
packageName = datamart.fullyQualifiedName.toString
it.toTestCalls(datamart)
it.fileHeader = datamart.documentation
])
// the service binder class
binderClassName = datamart.fullyQualifiedName.toString + "." +
datamart.fullyQualifiedName.lastSegment.toFirstUpper + "ServiceBinder"
cls = datamart.toClass(datamart.name.toString.concat("ServiceBinder"))
cls.simpleName = cls.simpleName.toFirstUpper
acceptor.accept(cls, [
annotations += _annotationTypesBuilder.annotationRef(SuppressWarnings, "serial")
annotations += _annotationTypesBuilder.annotationRef(typeof(Component))
packageName = datamart.fullyQualifiedName.toString
it.fileHeader = datamart.documentation
it.toBinderFields(datamart)
it.toBinderOperations(datamart)
])
for (definition : datamart.definitions) {
acceptor.accept(definition.toClass(definition.fullyQualifiedName + IDataMart.DATAMART_CLASS_POSTFIX), [
annotations += _annotationTypesBuilder.annotationRef(SuppressWarnings, "serial")
packageName = datamart.fullyQualifiedName.toString
if (definition.source instanceof DatamartEntity) {
superTypes += _typeReferenceBuilder.typeRef(AEntityDatamart)
}
if (definition.source instanceof DatamartCube) {
superTypes += _typeReferenceBuilder.typeRef(ACubeDatamart)
}
if (definition.source instanceof DatamartTask) {
superTypes += _typeReferenceBuilder.typeRef(ATaskDatamart)
}
it.toFields(definition)
it.toGetterSetter(definition)
it.toOperations(definition, datamart)
])
// create DatamartContainer
val containerClassName = definition.fullyQualifiedName + IDataMart.DATAMART_CONTAINER_POSTFIX
val containerClass = definition.toClass(containerClassName)
acceptor.accept(containerClass, [
annotations += _annotationTypesBuilder.annotationRef(Datamart)
packageName = datamart.fullyQualifiedName.toString
if (definition.source instanceof DatamartEntity) {
superTypes += _typeReferenceBuilder.typeRef(IDatamartContainer)
superTypes += _typeReferenceBuilder.typeRef(Serializable)
it.members +=
definition.toField("propertyChangeSupport",
_typeReferenceBuilder.typeRef(PropertyChangeSupport)) [
setInitializer('''new PropertyChangeSupport(this)''')
]
it.members += definition.toField("disposed", _typeReferenceBuilder.typeRef(Boolean::TYPE)) [
annotations += _annotationTypesBuilder.annotationRef(Dispose)
]
it.members += definition.toMethod(
"isDisposed",
_typeReferenceBuilder.typeRef(Boolean::TYPE),
[
body = [append('''return this.disposed;''')]
]
)
it.members += definition.toMethod(
"checkDisposed",
_typeReferenceBuilder.typeRef(Void::TYPE),
[
body = [
append(
'''
if (isDisposed()) {
throw new RuntimeException("Object already disposed: " + this);
}''')
]
]
)
it.members += definition.toMethod(
"dispose",
_typeReferenceBuilder.typeRef(Void::TYPE),
[
body = [
append(
'''
if (isDisposed()) {
return;
}
propertyChangeSupport.firePropertyChange("disposed", this.disposed, this.disposed = true);''')
]
]
)
it.members += definition.toMethod(
'''getIdValue''',
_typeReferenceBuilder.typeRef(Object),
[
annotations += _annotationTypesBuilder.annotationRef(Override)
body = [
append('''return «(definition.source as DatamartEntity).entityRef.primaryKeyAttribute.name.toFirstLower»;''')
]
]
)
it.toContainerFields(definition)
}
])
// extend AbstractDatamartService
val serviceClassName = definition.fullyQualifiedName + IDataMart.DATAMART_SERVICE_POSTFIX
acceptor.accept(definition.toClass(serviceClassName), [
packageName = datamart.fullyQualifiedName.toString
if (definition.source instanceof DatamartEntity) {
var serviceAnnotation = _annotationTypesBuilder.annotationRef(typeof(Component))
serviceAnnotation.addAnnAttr(definition, "service",
_typeReferenceBuilder.typeRef(IDatamartService) as JvmTypeReference)
val properties = <String>newArrayList
properties += '''datamart:String=«containerClassName»'''.toString
properties += '''service.pid:String=«serviceClassName»'''.toString
serviceAnnotation.addAnnAttr(definition, "property", properties)
annotations += serviceAnnotation
superTypes +=
_typeReferenceBuilder.typeRef(AbstractDatamartService,
_typeReferenceBuilder.typeRef(containerClass))
it.toServiceConstructor(definition)
it.members +=
definition.toMethod("getDatamartClass",
_typeReferenceBuilder.typeRef(Class, _typeReferenceBuilder.typeRef(containerClass)), [
body = [append('''return «containerClassName».class;''')]
])
}
])
}
}
def void toContainerFields(JvmGenericType type, DatamartDefinition definition) {
var attributes = definition.allEntityAttributes
attributes.forEach [
type.members +=
definition.toField(DatamartAttributeUtil.getAliasedAttributeName(it),
it.attributeRef.type.toTypeReference)
]
attributes.forEach [
val attributeName = DatamartAttributeUtil.getAliasedAttributeName(it)
type.members += definition.toMethod(
'''get«attributeName.toFirstUpper»''',
it.attributeRef.type.toTypeReference,
[
body = [append('''return «attributeName»;''')]
]
)
val attributeType = it.attributeRef.type.toTypeReference
type.members += definition.toMethod(
'''set«attributeName.toFirstUpper»''',
_typeReferenceBuilder.typeRef(Void::TYPE),
[
parameters += definition.toParameter(attributeName, attributeType)
body = [
append('''propertyChangeSupport.firePropertyChange("«attributeName»", this.«attributeName», this.«attributeName» = «attributeName»);''')
]
]
)
]
}
def void toServiceConstructor(JvmGenericType type, DatamartDefinition definition) {
type.members += definition.toConstructor([
body = [
append('''
setPersistenceId("«(definition.source as DatamartEntity).entityRef.persistenceUnit»");''')
]
])
}
def toTestCalls(JvmGenericType type, DatamartPackage datamart) {
var JvmOperation operation
for (definition : datamart.definitions) {
operation = definition.toMethod("test".concat(definition.name), _typeReferenceBuilder.typeRef(Void::TYPE), [
annotations += _annotationTypesBuilder.annotationRef(Test)
body = [append('''«definition.getAllTestcalls»''')]
])
type.members += operation
}
}
def getAllTestcalls(DatamartDefinition definition) {
var body = ""
body = '''
«body»
«definition.name»Datamart «definition.name.toFirstLower»Datamart = new «definition.name»Datamart();
«definition.name.toFirstLower»Datamart.setUser(new User("«IUserAccessService.ADMINISTRATOR»"));
«body»«definition.name.toFirstLower»Datamart.Test«definition.name»();
'''
return body
}
def void toBinderFields(JvmDeclaredType type, DatamartPackage datamart) {
var JvmField field = null
// create logger
field = datamart.toField("log", _typeReferenceBuilder.typeRef(Logger)) [
setInitializer([append('''org.slf4j.LoggerFactory.getLogger("servicebinder")''')])
]
field.static = true
field.visibility = JvmVisibility::PRIVATE
type.members += field
// create persistence service field
field = datamart.toField("persistenceService", _typeReferenceBuilder.typeRef(IPersistenceService))
field.static = true
field.visibility = JvmVisibility::PRIVATE
type.members += field
field = datamart.toField("bpmEngine", _typeReferenceBuilder.typeRef(IBPMEngine))
field.static = true
field.visibility = JvmVisibility::PRIVATE
type.members += field
field = datamart.toField("userAccessService", _typeReferenceBuilder.typeRef(IUserAccessService))
field.static = true
field.visibility = JvmVisibility::PRIVATE
type.members += field
field = datamart.toField("dslMetadataService", _typeReferenceBuilder.typeRef(IDSLMetadataService))
field.static = true
field.visibility = JvmVisibility::PRIVATE
type.members += field
field = datamart.toField("taskClient", _typeReferenceBuilder.typeRef(IBPMTaskClient))
field.static = true
field.visibility = JvmVisibility::PRIVATE
type.members += field
}
def void toBinderOperations(JvmDeclaredType type, DatamartPackage datamart) {
type.members += datamart.toMethod("getPersistenceService", _typeReferenceBuilder.typeRef(IPersistenceService), [
visibility = JvmVisibility.PUBLIC
static = true
body = [
append(
'''return persistenceService;''')
]
])
type.members += datamart.toMethod("getBpmEngine", _typeReferenceBuilder.typeRef(IBPMEngine), [
visibility = JvmVisibility.PUBLIC
static = true
body = [
append(
'''return bpmEngine;''')
]
])
type.members += datamart.toMethod("getUserAccessService", _typeReferenceBuilder.typeRef(IUserAccessService), [
visibility = JvmVisibility.PUBLIC
static = true
body = [
append(
'''return userAccessService;''')
]
])
type.members += datamart.toMethod("getDSLMetadataService", _typeReferenceBuilder.typeRef(IDSLMetadataService), [
visibility = JvmVisibility.PUBLIC
static = true
body = [
append(
'''return dslMetadataService;''')
]
])
type.members += datamart.toMethod("getTaskClient", _typeReferenceBuilder.typeRef(IBPMTaskClient), [
visibility = JvmVisibility.PUBLIC
static = true
body = [
append(
'''return taskClient;''')
]
])
type.members += datamart.toMethod("bindPersistenceMethod", _typeReferenceBuilder.typeRef(Void::TYPE), [
var annotationRef = _annotationTypesBuilder.annotationRef(typeof(Reference))
annotationRef.addAnnAttr(datamart, "cardinality", ReferenceCardinality.MANDATORY)
annotationRef.addAnnAttr(datamart, "policy", ReferencePolicy.STATIC)
annotations += annotationRef
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("persistenceService", _typeReferenceBuilder.typeRef(IPersistenceService))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».persistenceService = persistenceService;
log.debug("Datamart PersistenceService bound");''')
]
])
// unbind persistence service
type.members += datamart.toMethod("unbindPersistenceMethod", _typeReferenceBuilder.typeRef(Void::TYPE), [
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("persistenceService", _typeReferenceBuilder.typeRef(IPersistenceService))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».persistenceService = null;
log.debug("Datamart PersistenceService unbound");''')
]
])
// bind bpm service
type.members += datamart.toMethod("bindBPMMethod", _typeReferenceBuilder.typeRef(Void::TYPE), [
var annotationRef = _annotationTypesBuilder.annotationRef(typeof(Reference))
annotationRef.addAnnAttr(datamart, "cardinality", ReferenceCardinality.OPTIONAL)
annotationRef.addAnnAttr(datamart, "policy", ReferencePolicy.DYNAMIC)
annotations += annotationRef
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("bpmEngine", _typeReferenceBuilder.typeRef(IBPMEngine))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».bpmEngine = bpmEngine;
log.debug("Datamart BPMEngine bound");''')
]
])
// unbind bpm service
type.members += datamart.toMethod("unbindBPMMethod", _typeReferenceBuilder.typeRef(Void::TYPE), [
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("bpmEngine", _typeReferenceBuilder.typeRef(IBPMEngine))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».bpmEngine = null;
log.debug("Datamart BPMEngine unbound");''')
]
])
// bind userAccessService
type.members += datamart.toMethod("bindUserAccessMethod", _typeReferenceBuilder.typeRef(Void::TYPE), [
var annotationRef = _annotationTypesBuilder.annotationRef(typeof(Reference))
annotationRef.addAnnAttr(datamart, "cardinality", ReferenceCardinality.MANDATORY)
annotationRef.addAnnAttr(datamart, "policy", ReferencePolicy.STATIC)
annotations += annotationRef
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("userAccessService", _typeReferenceBuilder.typeRef(IUserAccessService))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».userAccessService = userAccessService;
log.debug("Datamart UserAccessService bound");''')
]
])
// unbind userAccessService
type.members += datamart.toMethod("unbindUserAccessMethod", _typeReferenceBuilder.typeRef(Void::TYPE), [
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("userAccessService", _typeReferenceBuilder.typeRef(IUserAccessService))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».userAccessService = null;
log.debug("Datamart UserAccessService unbound");''')
]
])
// bind dslMetadataService
type.members += datamart.toMethod("bindDSLMetadataService", _typeReferenceBuilder.typeRef(Void::TYPE), [
var annotationRef = _annotationTypesBuilder.annotationRef(typeof(Reference))
annotationRef.addAnnAttr(datamart, "cardinality", ReferenceCardinality.MANDATORY)
annotationRef.addAnnAttr(datamart, "policy", ReferencePolicy.STATIC)
annotations += annotationRef
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("dslMetadataService", _typeReferenceBuilder.typeRef(IDSLMetadataService))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».dslMetadataService = dslMetadataService;
log.debug("Datamart DSLMetadataService bound");''')
]
])
// unbind dslMetadataService
type.members += datamart.toMethod("unbindDSLMetadataService", _typeReferenceBuilder.typeRef(Void::TYPE), [
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("dslMetadataService", _typeReferenceBuilder.typeRef(IDSLMetadataService))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».dslMetadataService = null;
log.debug("Datamart DSLMetadataService unbound");''')
]
])
// bind taskClient
type.members += datamart.toMethod("bindTaskClient", _typeReferenceBuilder.typeRef(Void::TYPE), [
var annotationRef = _annotationTypesBuilder.annotationRef(typeof(Reference))
annotationRef.addAnnAttr(datamart, "cardinality", ReferenceCardinality.MANDATORY)
annotationRef.addAnnAttr(datamart, "policy", ReferencePolicy.STATIC)
annotations += annotationRef
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("taskClient", _typeReferenceBuilder.typeRef(IBPMTaskClient))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».taskClient = taskClient;
log.debug("Datamart BPMTaskClient bound");''')
]
])
// unbind taskClient
type.members += datamart.toMethod("unbindTaskClient", _typeReferenceBuilder.typeRef(Void::TYPE), [
visibility = JvmVisibility.PUBLIC
synchronized = true
parameters += datamart.toParameter("taskClient", _typeReferenceBuilder.typeRef(IBPMTaskClient))
body = [
append(
'''
«datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».taskClient = null;
log.debug("Datamart BPMTaskClient unbound");''')
]
])
}
/**
* <p>build the class variables for each datamart definition.</p>
*
*/
def void toFields(JvmDeclaredType type, DatamartDefinition definition) {
val typesMap = <String, LEntityAttribute>newHashMap
var JvmField field = null
// create logger
field = definition.toField("log", _typeReferenceBuilder.typeRef(Logger)) [
setInitializer([append('''org.slf4j.LoggerFactory.getLogger("datamarts")''')])
]
field.static = true
field.visibility = JvmVisibility::PRIVATE
type.members += field
field = definition.toField("user", _typeReferenceBuilder.typeRef(IUser))
field.visibility = JvmVisibility::PRIVATE
type.members += field
if (definition.source instanceof DatamartCube) {
field = definition.toField("statement", _typeReferenceBuilder.typeRef(String)) [
setInitializer([append('''"«definition.createMDXStatement»"''')])
]
type.members += field
field = definition.toField("connection", _typeReferenceBuilder.typeRef(RolapConnection)) [
setInitializer([append('''null''')])
]
type.members += field
field = definition.toField("datamartDtoMapper", _typeReferenceBuilder.typeRef(DatamartDtoMapper)) [
setInitializer([append('''new DatamartDtoMapper()''')])
]
type.members += field
}
if (definition.source instanceof DatamartEntity) {
field = definition.toField("dateFilterAttributeProperties",
_typeReferenceBuilder.typeRef(Map, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(Map, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(String)))) [
setInitializer = [
append('''new HashMap<String, Map<String, String>>()«(definition.source as DatamartEntity).createFilterAttributeProperties»''')
]
]
field.visibility = JvmVisibility::PRIVATE
type.members += field
field = definition.toField("statements",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(String))) [
setInitializer([
append('''new HashMap<String,String>() «definition.createSQLStatements((definition.source as DatamartEntity), typesMap)»''')
])
]
type.members += field
field = definition.toField("datamartDtoMapper", _typeReferenceBuilder.typeRef(DatamartDtoMapper)) [
setInitializer([append('''«datamartDtoMapper»''')])
]
type.members += field
field = definition.toField("connection", _typeReferenceBuilder.typeRef(Connection)) [
setInitializer([append('''null''')])
]
type.members += field
field = definition.toField("axisMap",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(Integer),
_typeReferenceBuilder.typeRef(ArrayList, _typeReferenceBuilder.typeRef(String)))) [
setInitializer([append('''new HashMap<Integer,ArrayList<String>>() «definition.createAxisMap»''')])
]
type.members += field
}
if (definition.source instanceof DatamartTask) {
field = definition.toField("axisMap",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(Integer),
_typeReferenceBuilder.typeRef(ArrayList, _typeReferenceBuilder.typeRef(String)))) [
setInitializer([append('''new HashMap<Integer,ArrayList<String>>() «definition.createAxisMap»''')])
]
type.members += field
field = definition.toField("datamartDtoMapper", _typeReferenceBuilder.typeRef(DatamartDtoMapper)) [
setInitializer([append('''new DatamartDtoMapper()''')])
]
type.members += field
}
// must be made after createSQLStatement
field = definition.toField("idMap",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(EType))) [
setInitializer([append('''new HashMap<String,EType>() «definition.createIdMap»''')])
]
type.members += field
field = definition.toField("primaryList",
_typeReferenceBuilder.typeRef(ArrayList,
getTypeForName(DatamartPrimary, definition, _typeReferenceBuilder.wildcard()))) [
setInitializer([append('''new ArrayList<DatamartPrimary<?>>() «definition.createPrimaryList»''')])
]
type.members += field
field = definition.toField("typesMap",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(EType)))) [
setInitializer([
append('''new HashMap<String,HashMap<String,EType>>() «definition.createTypesMaps(typesMap)»''')
])
]
type.members += field
field = definition.toField("resultAttributes",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(String)))[setInitializer([append('''new HashMap<String,String>()''')])]
type.members += field
}
/**
* <p>build the getters and setters from class variables of datamart definition.</p>
*
*/
def void toGetterSetter(JvmDeclaredType type, DatamartDefinition definition) {
var JvmOperation operation = null
operation = definition.toGetter("idMap",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(EType)))
operation.visibility = JvmVisibility::PUBLIC
type.members += operation
operation = definition.toGetter("primaryList",
_typeReferenceBuilder.typeRef(ArrayList,
getTypeForName(DatamartPrimary, definition, _typeReferenceBuilder.wildcard())))
operation.visibility = JvmVisibility::PUBLIC
type.members += operation
if (definition.source instanceof DatamartEntity || definition.source instanceof DatamartTask) {
operation = definition.toGetter("axisMap",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(Integer),
_typeReferenceBuilder.typeRef(ArrayList, _typeReferenceBuilder.typeRef(String))))
operation.visibility = JvmVisibility::PUBLIC
type.members += operation
}
operation = definition.toGetter("user", _typeReferenceBuilder.typeRef(IUser))
operation.visibility = JvmVisibility::PUBLIC
type.members += operation
operation = definition.toSetter("user", _typeReferenceBuilder.typeRef(IUser))
operation.visibility = JvmVisibility::PUBLIC
type.members += operation
}
/**
* <p>build the methods separately for cube, entity and task or SQL and MDX respective.</p>
*
*/
def void toOperations(JvmDeclaredType type, DatamartDefinition definition, DatamartPackage datamart) {
var JvmOperation operation
operation = definition.toMethod("initializeFilterMap",
_typeReferenceBuilder.typeRef(ArrayList, _typeReferenceBuilder.typeRef(DatamartFilter))) [
body = [
append('''
return new ArrayList<DatamartFilter>() «definition.createFilterMap»;
''')
]
]
operation.visibility = JvmVisibility::PROTECTED
type.members += operation
operation = definition.toMethod("clearCache", _typeReferenceBuilder.typeRef(Void::TYPE), [
annotations += _annotationTypesBuilder.annotationRef(Override)
body = [
append('''
«IF definition.source instanceof DatamartCube»
try {
«binderClassName».getPersistenceService().clearCubeCache(«binderClassName».getPersistenceService().getMondrianConnection(getPersistenceUnit(), "«((definition.source as DatamartCube).cubeRef.eContainer as CubePackage).fullyQualifiedName»"), "«(definition.source as DatamartCube).cubeRef.name»");
} catch (SQLException e) {
log.error("{}", e);
};
«ENDIF»''')
]
])
type.members += operation
operation = definition.toMethod("getResultAttribute", _typeReferenceBuilder.typeRef(String), [
annotations += _annotationTypesBuilder.annotationRef(Override)
parameters += definition.toParameter("attributeName", _typeReferenceBuilder.typeRef(String))
body = [
append('''
return resultAttributes.get(attributeName);''')
]
])
type.members += operation
operation = definition.toMethod("getTypesMap",
_typeReferenceBuilder.typeRef(HashMap, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(EType)), [
body = [
append('''
«IF definition.roles.size > 0»
if («binderClassName».getUserAccessService().getRoles() == null)
{
return typesMap.get("«IUserAccessService.ADMINISTRATOR»");
} else {
// find the role with the most authorized items
String bestRole = null;
int bestSize = -1;
for(String role:«binderClassName».getUserAccessService().getRoles()) {
if (typesMap.containsKey(role)) {
if (bestSize < typesMap.get(role).size()) {
bestSize = typesMap.get(role).size();
bestRole = role;
}
}
}
if (bestRole != null) {
return typesMap.get(bestRole);
}
return null;
}
«ELSE»
return typesMap.get("«IUserAccessService.ADMINISTRATOR»");
«ENDIF»
''')
]
])
operation.visibility = JvmVisibility::PUBLIC
type.members += operation
/* the task stuff */
if (definition.source instanceof DatamartTask) {
// get persistence unit
type.members += definition.toMethod("getPersistenceUnit", _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
return null;
'''
)
]
])
// client connect method
type.members += definition.toMethod("connect", _typeReferenceBuilder.typeRef(Connection), [
body = [
append(
'''
return null;''')
]
])
// disconnect method
type.members += definition.toMethod("disconnect", _typeReferenceBuilder.typeRef(Void::TYPE), [
body = [
append(
'''''')
]
])
// renderFilters method
operation = definition.toMethod("renderFilters", _typeReferenceBuilder.typeRef(Void::TYPE), [
body = [
append(
'''
for (DatamartFilter filter : getFilters()) {
filter.clearData();
if (filter.getName().equals("Groups")) {
for(String grp : «binderClassName».getBpmEngine().getGroups()) {
filter.addItem(grp, true);
}
}
if (filter.getName().equals("Users")) {
for(String usr : «binderClassName».getBpmEngine().getUsers()) {
filter.addItem(usr, true);
}
}
}''')
]
])
type.members += operation
// getResults method
type.members += definition.toMethod("getResults", _typeReferenceBuilder.typeRef(DerivedCellSet), [
body = [
append(
'''
if(user != null) {
List<BPMTaskSummary> tasks = «datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».getTaskClient().getUserTaskList(user, false);
if (tasks == null || tasks.size() == 0) {
tasks = «datamart.fullyQualifiedName.lastSegment.toFirstUpper+"ServiceBinder"».getTaskClient().getUserTaskList(user, true);
}
return (new DerivedCellSet(new SqlCellSet(tasks, getAxisMap()), null,
«binderClassName».getDSLMetadataService(),
user));
}
return null;
''')
]
])
// getResults by taskid method
type.members += definition.toMethod("getResultsByTaskId", _typeReferenceBuilder.typeRef(DerivedCellSet), [
parameters += definition.toParameter("client", _typeReferenceBuilder.typeRef(IBPMTaskClient))
parameters += definition.toParameter("taskId", _typeReferenceBuilder.typeRef(Long))
body = [
append(
'''
List<BPMTaskSummary> myTasks = new ArrayList<>();
myTasks.add(client.getUserTask(taskId, user));
return (new DerivedCellSet(new SqlCellSet(myTasks, getAxisMap()), null,
«binderClassName».getDSLMetadataService(), user));''')
]
])
// test method
operation = definition.toMethod('''Test«definition.name»''', _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
renderFilters();
org.junit.Assert.assertNotNull(getResults());''')
]
])
operation.returnType = _typeReferenceBuilder.typeRef(Void::TYPE)
var JvmAnnotationReference annRef = _annotationTypesBuilder.annotationRef(Test)
operation.annotations.add(annRef)
type.members += operation
}
/* the cube stuff */
if (definition.source instanceof DatamartCube) {
if ((definition.source as DatamartCube).cubeRef.cubeTypeEntity !== null) {
val entity = (definition.source as DatamartCube).cubeRef.cubeTypeEntity.entityRef.entityValue
// get persistence unit
type.members += definition.toMethod("getPersistenceUnit", _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
return "«(entity as LEntity).persistenceUnit»";
'''
)
]
])
// connect method
type.members += definition.toMethod("connect", _typeReferenceBuilder.typeRef(RolapConnection), [
body = [
append(
'''
if (connection == null) {
try {
connection = «binderClassName».getPersistenceService().getMondrianConnection(getPersistenceUnit(), "«((definition.source as DatamartCube).cubeRef.eContainer as CubePackage).fullyQualifiedName»");
«binderClassName».getPersistenceService().registerPersistenceUnit(getPersistenceUnit(), «(entity as LEntity).fullyQualifiedName».class);
} catch (SQLException e) {
log.error("{}", e);
return (connection);
}
}
return (connection);''')
]
])
// disconnect method
type.members += definition.toMethod("disconnect", _typeReferenceBuilder.typeRef(Void::TYPE), [
body = [
append(
'''
if (connection != null) {
connection.close();
connection = null;
}''')
]
])
// renderFilters method
operation = definition.toMethod("renderFilters", _typeReferenceBuilder.typeRef(Void::TYPE), [
body = [
append(
'''
connect();
if (connection != null) {
for (DatamartFilter filter : getFilters()) {
filter.clearData();
DerivedCellSet cellSet = new DerivedCellSet(«binderClassName».getPersistenceService().sendQuery(connection,getVendorSql(filter)),
«binderClassName».getDSLMetadataService(),
user);
List<DerivedAxis> axes = cellSet.getAxes();
DerivedAxis columnsAxis = axes.get(Axis.COLUMNS.ordinal());
for (DerivedPosition position : columnsAxis.getPositions()) {
DerivedMember measure = position.getMembers().get(0);
filter.addOlapItem(measure.getHierarchy().getName(), measure.getUniqueName());
}
}
}
disconnect();''')
]
])
type.members += operation
// applyFilters method
operation = definition.toMethod("applyFilters", _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
String filteredStatement = statement;
computeConditions();
for (DatamartFilter filter : getFilters()) {
if(filter.getCondition() != null) {
filteredStatement = filteredStatement.replace(filter.getDecoratedName(), filter.getCondition().replace("'",""));
}
}
filteredStatement = filteredStatement.replace("<empty>,","").replace(",<empty>","").replace("<empty>","");
log.debug("«definition.name»:"+filteredStatement);
return filteredStatement;''')
]
])
type.members += operation
// execute method
type.members += definition.toMethod("getResults", _typeReferenceBuilder.typeRef(DerivedCellSet), [
parameters += definition.toParameter("operativeDtoClass", _typeReferenceBuilder.typeRef(Class))
parameters += definition.toParameter("operativeDtos",
_typeReferenceBuilder.typeRef(List, _typeReferenceBuilder.typeRef(IDto)))
body = [
append(
'''
DerivedCellSet derivedCellSet = null;
connect();
if (connection != null) {
derivedCellSet = new DerivedCellSet(«binderClassName».getPersistenceService().sendQuery(connection, applyFilters()),
«binderClassName».getDSLMetadataService(),
user);
}
disconnect();
return derivedCellSet;''')
]
])
// test method
operation = definition.toMethod('''Test«definition.name»''', _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
renderFilters();
org.junit.Assert.assertNotNull(getResults(null, null));'''
)
]
])
operation.returnType = _typeReferenceBuilder.typeRef(Void::TYPE)
var JvmAnnotationReference annRef = _annotationTypesBuilder.annotationRef(Test)
operation.annotations.add(annRef)
type.members += operation
}
}
/* the entity stuff */
if (definition.source instanceof DatamartEntity) {
// get persistence unit
type.members += definition.toMethod("getPersistenceUnit", _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
return "«(definition.source as DatamartEntity)?.entityRef?.persistenceUnit»";
'''
)
]
])
// connect method
type.members += definition.toMethod("connect", _typeReferenceBuilder.typeRef(Connection), [
body = [
append(
'''
if (connection == null) {
try {
connection = «binderClassName».getPersistenceService().getPersistenceUnitConnection(getPersistenceUnit());
«binderClassName».getPersistenceService().registerPersistenceUnit(getPersistenceUnit(), «(definition.source as DatamartEntity)?.entityRef?.fullyQualifiedName».class);
} catch (SQLException e) {
log.error("{}", e);
return (connection);
}
}
return (connection);'''
)
]
])
// disconnect method
type.members += definition.toMethod("disconnect", _typeReferenceBuilder.typeRef(Void::TYPE), [
body = [
append(
'''
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
log.error("{}", e);
}
}'''
)
]
])
// renderFilters method
type.members += definition.toMethod("insertCondition", _typeReferenceBuilder.typeRef(String), [
parameters += definition.toParameter("filteredStatement", _typeReferenceBuilder.typeRef(String))
parameters += definition.toParameter("condition", _typeReferenceBuilder.typeRef(String))
body = [
append(
'''
int index = filteredStatement.indexOf("order by");
if(index > -1) {
return filteredStatement.substring(0, index-1) + condition + filteredStatement.substring(index-1);
} else {
return filteredStatement + condition;
}'''
)
]
])
// renderFilters method
operation = definition.toMethod("renderFilters", _typeReferenceBuilder.typeRef(Void::TYPE), [
body = [
append(
'''
connect();
if (connection != null) {
for (DatamartFilter filter : getFilters()) {
if((DatamartFilter.FilterType.BY_ID != filter.getType()) && (DatamartFilter.FilterType.BETWEEN != filter.getType()) && (DatamartFilter.FilterType.BETWEEN_DATE != filter.getType())) {
ResultSet rs = null;
try {
rs = connection.createStatement().executeQuery(getVendorSql(filter));
if (rs != null) {
while (rs.next()) {
int type = rs.getMetaData().getColumnType(1);
switch (type) {
case java.sql.Types.DATE:
Date date = rs.getDate(1);
if (date != null) {
if (user == null) {
filter.addItem(date.toString(), getVendorToDateSQLMethod()+"('"+date.toString().replace(".0","")+"','YYYY-MM-DD HH24:MI:SS')", false);
} else {
filter.addItem(SimpleDateFormatter.getFormat("LONGDATE", user.getLocale()).format(date), getVendorToDateSQLMethod()+"('"+date.toString().replace(".0","")+"','YYYY-MM-DD HH24:MI:SS')", false);
}
}
break;
case java.sql.Types.TIMESTAMP:
Timestamp timestamp = rs.getTimestamp(1);
if (timestamp != null) {
if (user == null) {
filter.addItem(timestamp.toString(), getVendorToTimestampSQLMethod()+"('"+timestamp.toString().replace(".0","")+"','YYYY-MM-DD HH24:MI:SS')", false);
} else {
filter.addItem(SimpleDateFormatter.getFormat("LONGDATE", user.getLocale()).format(timestamp), getVendorToTimestampSQLMethod()+"('"+timestamp.toString().replace(".0","")+"','YYYY-MM-DD HH24:MI:SS')", false);
}
}
break;
case java.sql.Types.DECIMAL:
BigDecimal bigDecimal = rs.getBigDecimal(1);
if (bigDecimal != null) {
filter.addItem(bigDecimal.toPlainString(), bigDecimal.toPlainString(), false);
}
break;
case java.sql.Types.NUMERIC:
case java.sql.Types.DOUBLE:
filter.addItem(Double.toString(rs.getDouble(1)), Double.toString(rs.getDouble(1)), false);
break;
case java.sql.Types.FLOAT:
filter.addItem(Float.toString(rs.getFloat(1)), Float.toString(rs.getFloat(1)), false);
break;
case java.sql.Types.CHAR:
case java.sql.Types.NCHAR:
case java.sql.Types.NVARCHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
filter.addItem(rs.getString(1), rs.getString(1), true);
break;
}
}
}
} catch (SQLException e) {
log.error("{}", e);
} finally {
try {
rs.close();
} catch (java.sql.SQLException e) {}
}
}
}
}
disconnect();'''
)
]
])
type.members += operation
// applyFilters method
operation = definition.toMethod("applyFilters", _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
String filteredStatement = "";
«IF definition.roles.size > 0»
if (user == null ||
user.getUserName().equals("«IUserAccessService.ADMINISTRATOR»") ||
«binderClassName».getUserAccessService().getRoles() == null)
{
filteredStatement = statements.get("«IUserAccessService.ADMINISTRATOR»");
}
else {
// find the role with the biggest statement of authorized items
String bestRole = null;
int bestSize = -1;
for(String role:«binderClassName».getUserAccessService().getRoles()) {
if (statements.containsKey(role)) {
if (bestSize < statements.get(role).length()) {
bestSize = statements.get(role).length();
bestRole = role;
}
}
}
if (bestRole != null) {
filteredStatement = statements.get(bestRole);
}
}
«ELSE»
filteredStatement = statements.get("«IUserAccessService.ADMINISTRATOR»");
«ENDIF»
computeConditions();
for (DatamartFilter filter : getFilters()) {
if (DatamartFilter.FilterType.BY_ID == filter.getType()) {
if(filter.getCondition() != null) {
if (!filteredStatement.toLowerCase().contains(" where ")) {
if ((" "+filter.getCondition()).toLowerCase().contains("where ")) {
filteredStatement = insertCondition(filteredStatement, " "+filter.getCondition());
}
else {
filteredStatement = insertCondition(filteredStatement, " where "+filter.getCondition());
}
}
else {
if (filter.getCondition().trim().toLowerCase().startsWith("and ") ||
filter.getCondition().trim().toLowerCase().startsWith("or ") ) {
filteredStatement = insertCondition(filteredStatement, filter.getCondition());
}
else {
filteredStatement = insertCondition(filteredStatement, " and "+filter.getCondition());
}
}
}
}
else {
filteredStatement = filteredStatement.replace(filter.getDecoratedName(), filter.getCondition());
}
}
log.debug("«definition.name»:"+filteredStatement);
return filteredStatement;''')
]
])
type.members += operation
// execute method
type.members += definition.toMethod("getResults", _typeReferenceBuilder.typeRef(DerivedCellSet), [
parameters += definition.toParameter("operativeDtoClass", _typeReferenceBuilder.typeRef(Class))
parameters += definition.toParameter("operativeDtos",
_typeReferenceBuilder.typeRef(List, _typeReferenceBuilder.typeRef(IDto)))
body = [
append(
'''
ResultSet rs = null;
SqlCellSet cellSet = null;
java.sql.ResultSetMetaData metaData = null;
// --- if filler text is enabled ---
if (fFillerTextEnabled) {
// --- try to generate filler text ---
rs = generateFillerTextResultSet();
}
// --- if no result set is generated by now ---
connect();
if (rs == null) {
if (connection != null) {
String query = applyFilters();
if (query.length()>0) {
try {
rs = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY).executeQuery(query);
} catch (SQLException e) {
log.error("Query: "+query);
log.error("{}", e);
}
}
}
}
if (rs != null) {
try {
cellSet = new SqlCellSet(rs, getAxisMap(), getIdMap(), datamartDtoMapper, operativeDtoClass, operativeDtos, getPrimaryList());
registerFirstLine(rs, user);
metaData = rs.getMetaData();
rs.close();
}
catch (java.sql.SQLException e) {
try {
log.error("Statement: "+rs.getStatement().toString());
} catch (SQLException e1) {}
log.error("{}", e);
}
return (new DerivedCellSet(cellSet,
metaData,
«binderClassName».getDSLMetadataService(), user));
}
disconnect();
return null;''')
]
])
// registerFirstLine method
type.members += definition.toMethod("registerFirstLine", _typeReferenceBuilder.typeRef(Void::TYPE), [
parameters += definition.toParameter("rs", _typeReferenceBuilder.typeRef(ResultSet))
parameters += definition.toParameter("user", _typeReferenceBuilder.typeRef(IUser))
exceptions += _typeReferenceBuilder.typeRef(SQLException)
body = [
append(
'''
if (rs != null && rs.first()) {
for (int column = 1; column <= rs.getMetaData().getColumnCount(); column++) {
int type = rs.getMetaData().getColumnType(column);
switch (type) {
case java.sql.Types.DATE:
if(rs.getDate(column) != null) {
if (user == null) {
resultAttributes.put(rs.getMetaData().getColumnName(column), rs.getDate(column).toString());
} else {
resultAttributes.put(rs.getMetaData().getColumnName(column),
SimpleDateFormatter.getFormat("LONGDATE", user.getLocale()).format(rs.getDate(column)));
}
}
break;
case java.sql.Types.TIMESTAMP:
if(rs.getTimestamp(column) != null) {
if (user == null) {
resultAttributes.put(rs.getMetaData().getColumnName(column), rs.getTimestamp(column).toString());
} else {
resultAttributes.put(rs.getMetaData().getColumnName(column), SimpleDateFormatter
.getFormat("LONGDATE", user.getLocale()).format(rs.getTimestamp(column)));
}
}
break;
case java.sql.Types.DECIMAL:
if(rs.getBigDecimal(column) != null) {
resultAttributes.put(rs.getMetaData().getColumnName(column),
rs.getBigDecimal(column).toPlainString());
}
break;
case java.sql.Types.NUMERIC:
case java.sql.Types.DOUBLE:
resultAttributes.put(rs.getMetaData().getColumnName(column), Double.toString(rs.getDouble(column)));
break;
case java.sql.Types.FLOAT:
resultAttributes.put(rs.getMetaData().getColumnName(column), Float.toString(rs.getFloat(column)));
break;
case java.sql.Types.CHAR:
case java.sql.Types.NCHAR:
case java.sql.Types.NVARCHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
resultAttributes.put(rs.getMetaData().getColumnName(column), rs.getString(column));
break;
}
}
}
'''
)
]
])
addFillerTextMethods(type.members, definition, definition.source as DatamartEntity)
// test method
operation = definition.toMethod('''Test«definition.name»''', _typeReferenceBuilder.typeRef(String), [
body = [
append(
'''
renderFilters();
org.junit.Assert.assertNotNull(getResults(null, null));''')
]
])
operation.returnType = _typeReferenceBuilder.typeRef(Void::TYPE)
var JvmAnnotationReference annRef = _annotationTypesBuilder.annotationRef(Test)
operation.annotations.add(annRef)
type.members += operation
}
}
def String createFilterAttributeProperties(DatamartEntity entity) {
var text = ""
for (condition : entity.conditions) {
if (condition.condition !== null) {
if (condition.condition instanceof ConditionalExpression) {
var element = (condition.condition as ConditionalExpression).right
var attribute = (condition.condition as ConditionalExpression).left as DatamartAttributeBase
if (element.ranged) {
if (attribute.attributeRef.datatype.isDate) {
if (attribute.attributeRef.properties !== null && !attribute.attributeRef.properties.empty) {
text = '''
{{
put("«attribute.getAttributeName(entity)»", new HashMap<String, String>() {{'''
for (property : attribute.attributeRef.properties) {
text = '''
«text»
put("«property.key»", "«property.value»");'''
}
text = '''
«text»
}});
}}'''
}
}
}
}
}
}
for (navigation : entity.navigations) {
if (navigation instanceof DatamartMember) {
text = '''
«text»
«(navigation as DatamartMember).datamartEntity.createFilterAttributeProperties»'''
}
if (navigation instanceof DatamartOwner) {
text = '''
«text»
«(navigation as DatamartOwner).datamartEntity.createFilterAttributeProperties»'''
}
}
return text
}
def addFillerTextMethods(EList<JvmMember> list, DatamartDefinition definition, DatamartEntity entity) {
if (entity.fillerMinCountRows > 0 && entity.fillerMaxCountRows > 0 && !entity.fillerDatas.empty) {
list +=
definition.toMethod("generateFillerTextResultSet", _typeReferenceBuilder.typeRef(FillerTextResultSet), [
body = [
append(
'''
FillerTextResultSet rs = new FillerTextResultSet(this, «entity.fillerMinCountRows», «entity.fillerMaxCountRows»);
''')
// @see {@link org.eclipse.osbp.xtext.reportdsl.common.DataTapyes}
for (data : entity.fillerDatas) {
var className = "String.class"
var typeName = "java.sql.Types.CHAR"
var type = data.fillerType
switch type {
AttributeFillerDateType: {
className = "Timestamp.class"
typeName = "java.sql.Types.TIMESTAMP"
}
AttributeFillerDoubleType: {
className = "BigDecimal.class"
typeName = "java.sql.Types.DECIMAL"
}
AttributeFillerIntegerType: {
className = "BigDecimal.class"
typeName = "java.sql.Types.DECIMAL"
}
AttributeFillerTextType: {
}
}
append(
'''
rs.addColumn("«data.attributeRef.name»", «className», null, «typeName»);
''')
}
append(
'''
return rs;''')
]
])
list +=
definition.toMethod("generateFillerTextRow",
_typeReferenceBuilder.typeRef(Map, _typeReferenceBuilder.typeRef(String),
_typeReferenceBuilder.typeRef(Object)), [
parameters += definition.toParameter("provider",
_typeReferenceBuilder.typeRef(FillerTextProvider))
body = [
append(
'''
Map<String,Object> rowData = new HashMap<>();
''')
for (data : entity.fillerDatas) {
var fillerTextMethod = "TO_BE_IMPLEMENTED"
var type = data.fillerType
switch type {
AttributeFillerDateFuture:
fillerTextMethod = '''new Timestamp(provider.date(0,«type.dateFutureYears»).getTime())'''
AttributeFillerDatePast:
fillerTextMethod = '''new Timestamp(provider.date(-«type.datePastYears»,0).getTime())'''
AttributeFillerDateRange:
fillerTextMethod = '''new Timestamp(provider.date(«type.dateBeginYears»,«type.dateEndYears»).getTime())'''
AttributeFillerSignedDoubleRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''((BigDecimal)rowData.get("«type.beginRangeRef.name»")).doubleValue()'''
}
if (type.endRangeRef !== null) {
endRange = '''((BigDecimal)rowData.get("«type.endRangeRef.name»")).doubleValue()'''
}
fillerTextMethod = '''new BigDecimal(provider.signeddouble(«type.decimals»,«beginRange»,«endRange»,«type.rounded»))'''
}
AttributeFillerSignedDoubleRandom: {
var List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
append('''double[] «data.attributeRef.name»_items = {«StringUtils.join(items, ",")»};
''')
fillerTextMethod = '''new BigDecimal(«data.attributeRef.name»_items[provider.unsignedinteger(«type.items.size-1»)])'''
}
AttributeFillerSignedIntegerRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''((BigDecimal)rowData.get("«type.beginRangeRef.name»")).intValue()'''
}
if (type.endRangeRef !== null) {
endRange = '''((BigDecimal)rowData.get("«type.endRangeRef.name»")).intValue()'''
}
fillerTextMethod = '''new BigDecimal(provider.signedinteger(«beginRange»,«endRange»,«type.rounded»))'''
}
AttributeFillerSignedIntegerRandom: {
var List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
append('''int[] «data.attributeRef.name»_items = {«StringUtils.join(items, ",")»};
''')
fillerTextMethod = '''new BigDecimal(«data.attributeRef.name»_items[provider.unsignedinteger(«type.items.size-1»)])'''
}
AttributeFillerTextRandom: {
var List<String> items = new ArrayList
for (item : type.items) {
items.add('''"«item»"''')
}
append('''Object[] «data.attributeRef.name»_items = {«StringUtils.join(items, ",")»};
''')
fillerTextMethod = '''«data.attributeRef.name»_items[provider.unsignedinteger(«type.items.size-1»)]'''
}
AttributeFillerTextParagraphs:
fillerTextMethod = '''provider.paragraphs(«type.count»)'''
AttributeFillerTextSentences:
fillerTextMethod = '''provider.sentences(«type.count»)'''
AttributeFillerTextWords:
fillerTextMethod = '''provider.words(«type.count»)'''
AttributeFillerUnsignedDoubleRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''((BigDecimal)rowData.get("«type.beginRangeRef.name»")).doubleValue()'''
}
if (type.endRangeRef !== null) {
endRange = '''((BigDecimal)rowData.get("«type.endRangeRef.name»")).doubleValue()'''
}
fillerTextMethod = '''new BigDecimal(provider.unsigneddouble(«type.decimals»,«beginRange»,«endRange»,«type.rounded»))'''
}
AttributeFillerUnsignedDoubleRandom: {
var List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
append('''double[] «data.attributeRef.name»_items = {«StringUtils.join(items, ",")»};
''')
fillerTextMethod = '''new BigDecimal(«data.attributeRef.name»_items[provider.unsignedinteger(«type.items.size-1»)])'''
}
AttributeFillerUnsignedIntegerRange: {
var beginRange = '''«type.beginRange»'''
var endRange = '''«type.endRange»'''
if (type.beginRangeRef !== null) {
beginRange = '''((BigDecimal)rowData.get("«type.beginRangeRef.name»")).intValue()'''
}
if (type.endRangeRef !== null) {
endRange = '''((BigDecimal)rowData.get("«type.endRangeRef.name»")).intValue()'''
}
fillerTextMethod = '''new BigDecimal(provider.unsignedinteger(«beginRange»,«endRange»,«type.rounded»))'''
}
AttributeFillerUnsignedIntegerRandom: {
var List<String> items = new ArrayList
for (item : type.items) {
items.add('''«item»''')
}
append('''int[] «data.attributeRef.name»_items = {«StringUtils.join(items, ",")»};
''')
fillerTextMethod = '''new BigDecimal(«data.attributeRef.name»_items[provider.unsignedinteger(«type.items.size-1»)])'''
}
}
append(
'''
rowData.put("«data.attributeRef.name»", «fillerTextMethod»);
''')
}
append(
'''
return rowData;''')
]
])
}
}
/**
* <p>build the id map as lookup for primary key oriented applications.</p>
*
*/
def String createIdMap(DatamartDefinition definition) {
var listTxt = ""
for (idColumn : idMap.keySet) {
listTxt = '''
«listTxt»
put("«idColumn»", EType.«dtType.getBasicType(idMap.get(idColumn).primaryKeyAttribute as LEntityAttribute)»);'''
}
listTxt = '''
{{
«listTxt»
}}'''
return listTxt
}
def String createPrimaryList(DatamartDefinition definition) {
var listTxt = ""
for (idColumn : idMap.keySet) {
var typeName = ""
if (idMap.get(idColumn).idAttributeType instanceof LDataType) {
if ((idMap.get(idColumn).idAttributeType as LDataType).jvmTypeReference !== null) {
typeName = (idMap.get(idColumn).idAttributeType as LDataType).jvmTypeReference.type.simpleName
} else {
typeName = (idMap.get(idColumn).idAttributeType as LDataType).name
}
listTxt = '''
«listTxt»
add(new DatamartPrimary<«typeName»>("«idColumn»", "«idMap.get(idColumn).primaryKeyAttribute.name»", "«idMap.get(idColumn).name»"));'''
}
}
listTxt = '''
{{
«listTxt»
}}'''
return listTxt
}
def String addPrimaryFilters(DatamartDefinition definition) {
var listTxt = ""
for (idColumn : idMap.keySet) {
listTxt = '''
«listTxt»
add(new DatamartFilter(DatamartFilter.FilterType.BY_ID, "«idMap.get(idColumn).name».«idMap.get(idColumn).primaryKeyAttribute.name»",""));'''
}
return listTxt
}
/**
* <p>build the types map as lookup for datatypes.</p>
*
*/
def String createTypesMaps(
DatamartDefinition definition,
HashMap<String, LEntityAttribute> typesMap
) {
var listTxt = '''
put("«IUserAccessService.ADMINISTRATOR»", new HashMap<String,EType>()«definition.createTypesMap(null, typesMap)»);'''
for (role : definition.roles) {
listTxt = '''
«listTxt»
put("«role.assignedRole.name»", new HashMap<String,EType>()«definition.createTypesMap(role, typesMap)»);'''
}
listTxt = '''
{{
«listTxt»
}}'''
return listTxt
}
/**
* <p>build the types map as lookup for datatypes according to authorization roles.</p>
*
*/
def String createTypesMap(DatamartDefinition definition, DatamartRole role,
HashMap<String, LEntityAttribute> typesMap) {
var listTxt = ""
if (role === null) { // grant all
for (attribute : typesMap.keySet) {
val type = dtType.getBasicType(typesMap.get(attribute))
listTxt = '''
«listTxt»
put("«attribute»", EType.«type.toString»);'''
}
} else {
for (attribute : typesMap.keySet) {
if (role.isAuthorized(attribute)) {
val type = dtType.getBasicType(typesMap.get(attribute))
listTxt = '''
«listTxt»
put("«attribute»", EType.«type.toString»);'''
}
}
}
listTxt = '''
{{
«listTxt»
}}'''
return listTxt
}
/**
* <p>build the axis map.</p>
*
*/
def String createAxisMap(DatamartDefinition definition) {
var text = ""
var map = <Integer, Map<String, Integer>>newHashMap
if (definition.source !== null) {
if (definition.source instanceof DatamartEntity) {
(definition.source as DatamartEntity).createAxisMap(map)
}
if (definition.source instanceof DatamartTask) {
(definition.source as DatamartTask).createAxisMap(map)
}
}
for (axisNumber : map.keySet()) {
if (definition.source instanceof DatamartEntity && axisNumber == AxisEnum.COLUMNS_VALUE) {
if (!ignoreEntityGrouping) {
for (LEntity entityRef : entityGrouping.values) {
var idColumn = DatamartDefinitionUtil.getEntityIdAliasName(entityRef)
if (idColumn !== null) {
map.get(axisNumber).put(idColumn, 0)
}
}
}
}
// sort according weight reverse and format map
var listTxt = map.get(axisNumber).entrySet.stream.sorted(Map.Entry.comparingByValue.reversed).map [
"add(\"" + it.key + "\");"
].collect(Collectors.joining("\n", "{{\n", "\n}}"))
text = '''
«text»
put(«axisNumber»,new ArrayList<String>() «listTxt»);'''
}
text = '''
{{
«text»
}}'''
return text
}
/**
* <p>creates an axis map for tasks.</p>
*
*/
def void createAxisMap(DatamartTask task, Map<Integer, Map<String, Integer>> map) {
this.idMap.clear()
for (column : task.columns) {
var axisNumber = 0
var name = column.columnRef.literal
var found = false
for (axNum : map.keySet()) {
if (axNum == axisNumber) {
map.get(axNum).put(name, defaultColumnWeight)
found = true
}
}
if (!found) {
var columns = <String, Integer>newHashMap
columns.put(name, defaultColumnWeight)
map.put(axisNumber, columns)
}
}
}
def void recursAxisMap(LScalarType type, DatamartAttribute attribute, Map<Integer, Map<String, Integer>> map,
int axisNumber) {
if (type instanceof LBean) {
var bean = type as LBean
for (attr : bean.allAttributes) {
if (attr.type instanceof LBean) {
recursAxisMap(attr.type, attribute, map, axisNumber)
} else {
addAxisAttribute(attr.name, defaultColumnWeight, map, axisNumber)
}
}
} else {
var weight = defaultColumnWeight
if (attribute.hasColumnWeight) {
weight = attribute.columnWeight
}
addAxisAttribute(DatamartAttributeUtil.getAliasedAttributeName(attribute), weight, map, axisNumber)
}
}
/**
* <p>recursively create an axis map for entities.</p>
*
*/
def void createAxisMap(DatamartEntity entity, Map<Integer, Map<String, Integer>> map) {
for (attribute : entity.attributes) {
var axisNumber = -1
if (attribute.axis.name.value == -1) {
axisNumber = 0
} else {
axisNumber = attribute.axis.name.value
}
var type = attribute.attributeRef.type as LScalarType
recursAxisMap(type, attribute, map, axisNumber)
}
for (navigation : entity.navigations) {
navigation.datamartEntity.createAxisMap(map)
}
}
def addAxisAttribute(String name, Integer weight, Map<Integer, Map<String, Integer>> map, int axisNumber) {
var found = false
for (axNum : map.keySet()) {
if (axNum == axisNumber) {
map.get(axNum).put(name, weight)
found = true
}
}
if (!found) {
var columns = <String, Integer>newHashMap
columns.put(name, weight)
map.put(axisNumber, columns)
}
}
def getAttributeType(DatamartAttribute prop) {
return prop.attributeRef.type
}
/**
* <p>build a map for the filters contained in a datamart depending on a cube.</p>
*
*/
def createFilterMap(DatamartDefinition definition) {
var text = ""
if (definition.source !== null) {
if (definition.source instanceof DatamartCube) {
var cube = (definition.source as DatamartCube)
for (axisslicer : cube.axisslicer) {
if (axisslicer instanceof DatamartCubeAxis && (axisslicer as DatamartCubeAxis).elements !== null) {
for (element : (axisslicer as DatamartCubeAxis).elements) {
if (element instanceof DatamartHierarchy) {
var hierarchy = (element as DatamartHierarchy)
if (hierarchy.filtered) {
text = '''
«text»
add(new DatamartFilter(DatamartFilter.FilterType.SINGLEHIERARCHY, "«(element as DatamartHierarchy).getLevelName(true, false, false, false)»","«(element as DatamartHierarchy).createMDXFilter(definition.source)»"));'''
}
if (hierarchy.selected) {
text = '''
«text»
add(new DatamartFilter(DatamartFilter.FilterType.MULTIPLEHIERARCHY, "«(element as DatamartHierarchy).getLevelName(true, false, false, false)»","«(element as DatamartHierarchy).createMDXFilter(definition.source)»"));'''
}
if (hierarchy.except) {
text = '''
«text»
add(new DatamartFilter(DatamartFilter.FilterType.EXCEPT, "«hierarchy.getDimensionName(true)+".["+hierarchy.exceptRef.name+"]"»","«hierarchy.createMDXFilter(definition.source)»"));'''
}
}
}
}
if (axisslicer instanceof DatamartSlicer && (axisslicer as DatamartSlicer).element !== null) {
var element = (axisslicer as DatamartSlicer).element
if (element instanceof DatamartHierarchy) {
var hierarchy = (element as DatamartHierarchy)
if (hierarchy.filtered) {
text = '''
«text»
add(new DatamartFilter(DatamartFilter.FilterType.SINGLESLICER, "«(element as DatamartHierarchy).getLevelName(true, false, false, false)»","«(element as DatamartHierarchy).createMDXFilter(definition.source)»"));'''
}
if (hierarchy.selected) {
text = '''
«text»
add(new DatamartFilter(DatamartFilter.FilterType.MULTIPLESLICER, "«(element as DatamartHierarchy).getLevelName(true, false, false, false)»","«(element as DatamartHierarchy).createMDXFilter(definition.source)»"));'''
}
}
}
}
}
if (definition.source instanceof DatamartEntity) {
var entity = (definition.source as DatamartEntity)
text = entity.createFiltermapCondition(definition)
text = text + definition.addPrimaryFilters
}
if (definition.source instanceof DatamartTask) {
var task = (definition.source as DatamartTask)
text = task.createFiltermapCondition(definition)
}
if (text.length > 0) {
text = '''
{{
«text»
}}'''
}
}
return text
}
/**
* <p>build a map for the filters contained in a datamart depending on a task.</p>
*
*/
def String createFiltermapCondition(DatamartTask task, DatamartDefinition definition) {
var text = ""
for (condition : task.conditions) {
text = '''
«text»
«condition.createSQLFilter(task, definition)»'''
}
return text
}
/**
* <p>build the sql filter condition depending on an entity.</p>
*
*/
def createSQLFilter(DatamartCondition condition, DatamartTask task, DatamartDefinition definition) {
var text = ""
if (condition.condition !== null) {
if (condition.condition instanceof ConditionalExpression) {
var element = (condition.condition as ConditionalExpression).right
if ((condition.condition as ConditionalExpression).left instanceof DatamartTaskFilter) {
var taskFilter = (condition.condition as ConditionalExpression).left as DatamartTaskFilter
if (element.filtered || element.selected) {
var filter = '''«taskFilter.filterRef.literal»'''
text = '''
«text»
add(new DatamartFilter(«IF element.filtered»DatamartFilter.FilterType.SINGLE«ELSEIF element.selected»DatamartFilter.FilterType.MULTIPLE«ENDIF», "«taskFilter.filterRef.literal»","«filter»"));'''
}
}
}
}
return text
}
/**
* <p>build a map for the filters contained in a datamart depending on an entity.</p>
*
*/
def String createFiltermapCondition(DatamartEntity entity, DatamartDefinition definition) {
var text = ""
for (condition : entity.conditions) {
text = '''
«text»
«condition.createSQLFilter(entity, definition)»'''
}
for (navigation : entity.navigations) {
if (navigation instanceof DatamartMember) {
text = '''
«text»
«(navigation as DatamartMember).datamartEntity.createFiltermapCondition(definition)»'''
}
if (navigation instanceof DatamartOwner) {
text = '''
«text»
«(navigation as DatamartOwner).datamartEntity.createFiltermapCondition(definition)»'''
}
}
return text
}
/**
* <p>build the sql filter condition depending on an entity.</p>
*
*/
def createSQLFilter(DatamartCondition condition, DatamartEntity entity, DatamartDefinition definition) {
var text = ""
if (condition.condition !== null) {
if (condition.condition instanceof ConditionalExpression) {
var element = (condition.condition as ConditionalExpression).right
var attribute = (condition.condition as ConditionalExpression).left as DatamartAttributeBase
var filter = element.createSQLFilter(entity, attribute)
if (element.filtered) {
text = '''«text»add(new DatamartFilter(DatamartFilter.FilterType.SINGLE, "«attribute.getAttributeName(entity)»","«filter»"));'''
}
if (element.selected) {
text = '''«text»add(new DatamartFilter(DatamartFilter.FilterType.MULTIPLE, "«attribute.getAttributeName(entity)»","«filter»"));'''
}
if (element.ranged) {
if (attribute.attributeRef.datatype.isDate) {
if (attribute.attributeRef.properties !== null) {
text = '''«text»add(new DatamartFilter(DatamartFilter.FilterType.BETWEEN_DATE, dateFilterAttributeProperties.get("«attribute.getAttributeName(entity)»"), "«attribute.getAttributeName(entity)»",""));'''
} else {
text = '''«text»add(new DatamartFilter(DatamartFilter.FilterType.BETWEEN_DATE, "«attribute.getAttributeName(entity)»",""));'''
}
} else {
text = '''«text»add(new DatamartFilter(DatamartFilter.FilterType.BETWEEN, "«attribute.getAttributeName(entity)»",""));'''
}
}
}
}
return text
}
def createSQLFilter(Expression element, DatamartEntity entity, DatamartAttributeBase attribute) {
var tableName = entity.entityRef.toTableName
if (entity.hasSuperType) {
tableName = entity.entityRef.superType.toTableName
}
var type = attribute.attributeRef.type as LDataType
var filter = ""
if (element.optional && !type.date) {
filter = '''select «IDataMart.SQLFILTERNOTHING» from «EnumDatabaseVendor.ONE_ROW_ONE_COLUMN_TABLE» union '''
}
filter = '''«filter»select distinct «attribute.attributeRef.toColumnName» as \"«DatamartAttributeUtil.getAliasedAttributeName(attribute)»\" from «entity.entityRef.persistenceInfo.schemaName.provideSchemaName»«tableName» order by 1'''
return filter
}
/**
* <p>build the mdx filter slice depending on a cube.</p>
*
*/
def createMDXFilter(DatamartHierarchy level, DatamartSource source) {
var filter = "select {} on columns,"
if (level.levelRef !== null) {
filter = '''«filter»«level.getLevelName(true, false, false, false)».members on rows'''
}
if (source instanceof DatamartCube) {
filter = '''«filter» from «(source as DatamartCube).cubeRef.name»'''
}
return filter
}
/**
* <p>helper to get a level name.</p>
*
*/
def getFilterAlias(DatamartHierarchy level) {
var text = ""
if (level.levelRef !== null) {
text = '''«level.getDimensionName(false)»«level.levelRef.name.toFirstUpper»'''
}
return text
}
/**
* <p>mdx syntax part for aggregations on sets.</p>
*
*/
def createSetAggregation(List<DatamartSetAggregation> usedSetAggregation, Boolean nonEmpty) {
var set = ""
var firstTuple = true
for (element : usedSetAggregation) {
if (firstTuple) {
firstTuple = false
} else {
set = '''«set»,'''
}
set = '''«set»«element.evaluateExpression(null)»'''
}
if (usedSetAggregation.size > 1) {
set = '''«IF nonEmpty»Non Empty«ENDIF»{«set»}'''
} else if (usedSetAggregation.size > 0) {
set = '''«IF nonEmpty»Non Empty «ENDIF»«set»'''
}
return set
}
/**
* <p>mdx syntax part for hierarchies.</p>
*
*/
def createHierarchies(List<DatamartHierarchy> usedHierarchies, Boolean nonEmpty) {
var set = ""
var firstTuple = true
for (element : usedHierarchies) {
if (firstTuple) {
firstTuple = false
} else {
set = '''«set»,'''
}
set = '''«set»«element.getLevelName(true, true, true, false)»'''
}
if (usedHierarchies.size > 1) {
set = '''«IF nonEmpty»Non Empty«ENDIF»{«set»}'''
} else if (usedHierarchies.size > 0) {
set = '''«IF nonEmpty»Non Empty «ENDIF»«set»'''
}
return set
}
/**
* <p>mdx syntax part for measures.</p>
*
*/
def createMeasures(List<DatamartMeasure> usedMeasures, List<DatamartDerivedMeasure> usedDerived, Boolean nonEmpty) {
var set = ""
var firstTuple = true
for (element : usedMeasures) {
if (firstTuple) {
firstTuple = false
} else {
set = '''«set»,'''
}
set = '''«set»«element.getMeasureName»'''
}
for (element : usedDerived) {
if (firstTuple) {
firstTuple = false
} else {
set = '''«set»,'''
}
set = '''«set»«element.getDerivedMeasureName»'''
}
if (usedMeasures.size + usedDerived.size > 1) {
set = '''«IF nonEmpty»Non Empty«ENDIF»{«set»}'''
} else if (usedMeasures.size + usedDerived.size > 0) {
set = '''«IF nonEmpty»Non Empty «ENDIF»«set»'''
}
return set
}
/**
* <p>the main function to build a mdx statement.</p>
*
*/
def createMDXStatement(DatamartDefinition definition) {
this.sqlAliasCounter.clear()
this.sqlFilterMap.clear()
this.sqlGrouping.clear()
this.entityGrouping.clear()
this.ignoreEntityGrouping = false
this.sqlHasAggregate = false
this.sqlHasOrder = false
this.idMap.clear()
var cube = (definition.source as DatamartCube)
var body = ""
var slice = ""
var derived = ""
var firstAxis = true
var firstSlice = true
var firstderived = true
for (axisslicer : cube.axisslicer) {
if (axisslicer instanceof DatamartCubeAxis) {
var crossJoinMeasure = false
var crossJoinHierarchy = false
var crossJoinSetAggregation = false
var axis = (axisslicer as DatamartCubeAxis)
if (firstAxis) {
firstAxis = false
} else {
body = '''«body»,'''
}
if (axis.elements !== null) {
var set = ""
val usedHierarchies = <DatamartHierarchy>newArrayList
val usedMeasures = <DatamartMeasure>newArrayList
val usedDerivedMeasure = <DatamartDerivedMeasure>newArrayList
val usedSetAggregation = <DatamartSetAggregation>newArrayList
for (element : axis.elements) {
if (element instanceof DatamartSetAggregation) {
// if a set aggregation comes along, all is cross joined
if (usedMeasures.size > 0 || usedDerivedMeasure.size > 0) {
if (crossJoinMeasure) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createMeasures(
usedMeasures, usedDerivedMeasure, false)»'''
if (crossJoinMeasure) {
set = '''«set»)'''
}
usedMeasures.clear
usedDerivedMeasure.clear
crossJoinSetAggregation = true
}
if (usedHierarchies.size > 0) {
if (crossJoinHierarchy) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createHierarchies(
usedHierarchies, false)»'''
if (crossJoinHierarchy) {
set = '''«set»)'''
}
usedHierarchies.clear
crossJoinSetAggregation = true
}
var setAggregation = (element as DatamartSetAggregation)
usedSetAggregation.add(setAggregation)
}
if (element instanceof DatamartHierarchy) {
// if hierarchy changes to measure, a crossjoin is generated
if (usedMeasures.size > 0 || usedDerivedMeasure.size > 0) {
if (crossJoinMeasure) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createMeasures(
usedMeasures, usedDerivedMeasure, false)»'''
if (crossJoinMeasure) {
set = '''«set»)'''
}
usedMeasures.clear
usedDerivedMeasure.clear
crossJoinMeasure = true
}
if (usedSetAggregation.size > 0) {
if (crossJoinSetAggregation) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createSetAggregation(
usedSetAggregation, false)»'''
if (crossJoinSetAggregation) {
set = '''«set»)'''
}
usedSetAggregation.clear
crossJoinSetAggregation = true
}
var hierarchyLevel = (element as DatamartHierarchy)
// if hierarchies are mixed, a crossjoin is generated
var lastHierarchy = usedHierarchies.last
if (!crossJoinHierarchy && (lastHierarchy === null ||
hierarchyLevel.getHierarchyName.equals(lastHierarchy.getHierarchyName))) {
usedHierarchies.add(hierarchyLevel)
} else {
if (crossJoinHierarchy) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createHierarchies(
usedHierarchies, false)»'''
if (crossJoinHierarchy) {
set = '''«set»)'''
}
usedHierarchies.clear
usedHierarchies.add(hierarchyLevel)
crossJoinHierarchy = true
}
}
if (element instanceof DatamartMeasure) {
// if measure changes to hierarchy, a crossjoin is generated
if (usedHierarchies.size > 0) {
if (crossJoinMeasure) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createHierarchies(
usedHierarchies, false)»'''
if (crossJoinMeasure) {
set = '''«set»)'''
}
usedHierarchies.clear
crossJoinMeasure = true
}
if (usedSetAggregation.size > 0) {
if (crossJoinSetAggregation) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createSetAggregation(
usedSetAggregation, false)»'''
if (crossJoinSetAggregation) {
set = '''«set»)'''
}
usedSetAggregation.clear
crossJoinSetAggregation = true
}
var measure = (element as DatamartMeasure)
usedMeasures.add(measure)
}
if (element instanceof DatamartDerivedMeasure) {
// if measure changes to hierarchy, a crossjoin is generated
if (usedHierarchies.size > 0) {
if (crossJoinMeasure) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createHierarchies(
usedHierarchies, false)»'''
if (crossJoinMeasure) {
set = '''«set»)'''
}
usedHierarchies.clear
crossJoinMeasure = true
}
if (usedSetAggregation.size > 0) {
if (crossJoinSetAggregation) {
set = '''«set»,'''
}
set = '''«IF cube.nonEmpty»NonEmptyCrossjoin«ELSE»CrossJoin«ENDIF»(«set»«createSetAggregation(
usedSetAggregation, false)»'''
if (crossJoinSetAggregation) {
set = '''«set»)'''
}
usedSetAggregation.clear
crossJoinSetAggregation = true
}
var measure = (element as DatamartDerivedMeasure)
usedDerivedMeasure.add(measure)
}
}
if (crossJoinMeasure || crossJoinHierarchy || crossJoinSetAggregation) {
set = '''«set»,'''
}
set = '''«set»«createHierarchies(usedHierarchies,
cube.nonEmpty && !(crossJoinMeasure || crossJoinHierarchy || crossJoinSetAggregation))»'''
usedHierarchies.clear
set = '''«set»«createMeasures(usedMeasures, usedDerivedMeasure,
cube.nonEmpty && !(crossJoinMeasure || crossJoinHierarchy || crossJoinSetAggregation))»'''
usedMeasures.clear
usedDerivedMeasure.clear
set = '''«set»«createSetAggregation(usedSetAggregation,
cube.nonEmpty && !(crossJoinMeasure || crossJoinHierarchy || crossJoinSetAggregation))»'''
usedMeasures.clear
if (crossJoinMeasure || crossJoinHierarchy || crossJoinSetAggregation) {
set = '''«set»)'''
}
body = '''«body»«set» on «axis.axis.name»'''
}
}
if (axisslicer instanceof DatamartSlicer) {
if (firstSlice) {
firstSlice = false
} else {
slice = '''«slice»,'''
}
var element = (axisslicer as DatamartSlicer).element
if (element instanceof DatamartHierarchy) {
var hierarchyLevel = (element as DatamartHierarchy)
slice = '''«slice»«hierarchyLevel.getLevelName(true, true, true, true)»'''
}
if (element instanceof DatamartMeasure) {
slice = '''«slice»«(element as DatamartMeasure).getMeasureName»'''
}
}
if (axisslicer instanceof DatamartDefineDerivedMeasure) {
if (firstderived) {
firstderived = false
}
var derivedMeasure = (axisslicer as DatamartDefineDerivedMeasure)
derived = '''«derived» member [Measures].[«derivedMeasure.name»] as «derivedMeasure.buildDerivedFormula»'''
}
}
if (!firstSlice) {
slice = ''' where («slice»)'''
}
if (!firstderived) {
derived = '''with«derived» '''
}
return '''«derived»select «body» from «cube.cubeRef.name»«slice»'''
}
def isCrossJoined(DatamartDefinition definition) {
if (!(definition.source instanceof DatamartCube)) {
return false;
}
var cube = (definition.source as DatamartCube)
var firstAxis = true
for (axisslicer : cube.axisslicer) {
if (axisslicer instanceof DatamartCubeAxis) {
var crossJoinMeasure = false
var crossJoinHierarchy = false
var crossJoinSetAggregation = false
var axis = (axisslicer as DatamartCubeAxis)
if (firstAxis) {
firstAxis = false
}
if (axis.elements !== null) {
val usedHierarchies = <DatamartHierarchy>newArrayList
val usedMeasures = <DatamartMeasure>newArrayList
val usedDerivedMeasure = <DatamartDerivedMeasure>newArrayList
val usedSetAggregation = <DatamartSetAggregation>newArrayList
for (element : axis.elements) {
if (element instanceof DatamartSetAggregation) {
// if a set aggregation comes along, all is cross joined
if (usedMeasures.size > 0 || usedDerivedMeasure.size > 0) {
usedMeasures.clear
usedDerivedMeasure.clear
crossJoinSetAggregation = true
}
if (usedHierarchies.size > 0) {
usedHierarchies.clear
crossJoinSetAggregation = true
}
var setAggregation = (element as DatamartSetAggregation)
usedSetAggregation.add(setAggregation)
}
if (element instanceof DatamartHierarchy) {
// if hierarchy changes to measure, a crossjoin is generated
if (usedMeasures.size > 0 || usedDerivedMeasure.size > 0) {
usedMeasures.clear
usedDerivedMeasure.clear
crossJoinMeasure = true
}
if (usedSetAggregation.size > 0) {
usedSetAggregation.clear
crossJoinSetAggregation = true
}
var hierarchyLevel = (element as DatamartHierarchy)
// if hierarchies are mixed, a crossjoin is generated
var lastHierarchy = usedHierarchies.last
if (!crossJoinHierarchy && (lastHierarchy === null ||
hierarchyLevel.getHierarchyName.equals(lastHierarchy.getHierarchyName))) {
usedHierarchies.add(hierarchyLevel)
} else {
usedHierarchies.clear
usedHierarchies.add(hierarchyLevel)
crossJoinHierarchy = true
}
}
if (element instanceof DatamartMeasure) {
// if measure changes to hierarchy, a crossjoin is generated
if (usedHierarchies.size > 0) {
usedHierarchies.clear
crossJoinMeasure = true
}
if (usedSetAggregation.size > 0) {
usedSetAggregation.clear
crossJoinSetAggregation = true
}
var measure = (element as DatamartMeasure)
usedMeasures.add(measure)
}
if (element instanceof DatamartDerivedMeasure) {
// if measure changes to hierarchy, a crossjoin is generated
if (usedHierarchies.size > 0) {
usedHierarchies.clear
crossJoinMeasure = true
}
if (usedSetAggregation.size > 0) {
usedSetAggregation.clear
crossJoinSetAggregation = true
}
var measure = (element as DatamartDerivedMeasure)
usedDerivedMeasure.add(measure)
}
}
usedMeasures.clear
usedDerivedMeasure.clear
usedMeasures.clear
}
return (crossJoinMeasure || crossJoinHierarchy || crossJoinSetAggregation);
}
}
return false;
}
/**
* <p>mdx syntax part for hierarchy names. If a hierarchy itself has no name in the cube definition, the dimension name is used instead</p>
*
*/
def String getHierarchyName(DatamartHierarchy hierarchy) {
if (hierarchy.hierarchyRef.name === null) {
return (hierarchy.hierarchyRef.eContainer as CubeDimension).name
} else {
hierarchy.hierarchyRef.name
}
}
/**
* <p>mdx syntax part for derived measure expressions.</p>
*
*/
def buildDerivedFormula(DatamartDefineDerivedMeasure derivedMeasure) {
var formula = ""
for (element : derivedMeasure.derivedElement) {
formula = '''«formula»«element.evaluateExpression(null)»'''
}
return "'".concat(formula).concat("'")
}
/**
* <p>as the grammar makes use of expressions along an abstract syntax tree, we need this recursive dispatcher to synthesize resulting code.</p>
*
*/
// due to a possible bug in xtext 2.4.2 we must supply the extra entity as the model will find a wrong one from the attribute
def String evaluateExpression(Expression element, DatamartEntity entity) {
var evaluation = ""
if (element.value !== null) {
evaluation = element.value
}
if (element.numberValue !== null) {
evaluation = element.numberValue
}
if (element.stringValue !== null) {
evaluation = "'".concat(element.stringValue).concat("'")
}
if (element.filtered || element.selected || element.ranged) {
evaluation = '''«DatamartFilter.decorate(((element.eContainer() as ConditionalExpression).left as DatamartAttributeBase).getAttributeName(entity))»'''
}
if (element.function !== null) {
if (element.function instanceof DatamartFunction) {
evaluation = '''«evaluation»«element.hierarchy.getLevelName(true, true, true, false)».«(element.function as DatamartFunction).
function.name()»'''
}
if (element.function instanceof DatamartParameterFunction) {
evaluation = '''«evaluation»«element.hierarchy.getLevelName(true, true, true, false)».«(element.function as DatamartParameterFunction).
function.name()»(«(element.function as DatamartParameterFunction).parameter.value»)'''
}
}
// derived functionless hierarchized measure
if (element.hierarchy !== null && element.function === null) {
evaluation = '''«evaluation»«element.hierarchy.getLevelName(true, true, true, false)»'''
}
if (element instanceof DatamartSetTuple) {
if ((element as DatamartSetTuple).left.setFunction !== null) {
if ((element as DatamartSetTuple).left.setFunction instanceof DatamartSetFunction) {
evaluation = '''«evaluation»«((element as DatamartSetTuple).left.setFunction as DatamartSetFunction).
setFunction.name()»(«(element as DatamartSetTuple).right.getLevelName(true, true, true, false)»)'''
}
if ((element as DatamartSetTuple).left.setFunction instanceof DatamartSetParameterFunction) {
evaluation = '''«evaluation»«((element as DatamartSetTuple).left.setFunction as DatamartSetParameterFunction).
setFunction.name()»(«(element as DatamartSetTuple).right.getLevelName(true, true, true, false)»,«(((element as DatamartSetTuple).
left.setFunction as DatamartSetParameterFunction).parameter as DatamartFunctionIntParameter).
value»)'''
}
}
}
if (element instanceof DatamartMeasure) {
evaluation = '''«(element as DatamartMeasure).getMeasureName»'''
}
if (element instanceof DatamartDerivedMeasure) {
evaluation = '''«(element as DatamartDerivedMeasure).getDerivedMeasureName»'''
}
if (element instanceof DatamartHierarchy) {
evaluation = '''«(element as DatamartHierarchy).getLevelName(true, true, true, false)»'''
}
if (element instanceof DatamartAttributeBase) {
evaluation = '''«(element as DatamartAttributeBase).getAttributeName(entity)»'''
}
if (element instanceof Multiplication) {
evaluation = '''«(element as Multiplication).left.evaluateExpression(entity)»'''
evaluation = '''«evaluation»*'''
evaluation = '''«evaluation»«(element as Multiplication).right.evaluateExpression(entity)»'''
}
if (element instanceof Division) {
evaluation = '''«(element as Division).left.evaluateExpression(entity)»'''
evaluation = '''«evaluation»/'''
evaluation = '''«evaluation»«(element as Division).right.evaluateExpression(entity)»'''
}
if (element instanceof Addition) {
evaluation = '''(«(element as Addition).left.evaluateExpression(entity)»'''
evaluation = '''«evaluation»+'''
evaluation = '''«evaluation»«(element as Addition).right.evaluateExpression(entity)»)'''
}
if (element instanceof Subtraction) {
evaluation = '''(«(element as Subtraction).left.evaluateExpression(entity)»'''
evaluation = '''«evaluation»-'''
evaluation = '''«evaluation»«(element as Subtraction).right.evaluateExpression(entity)»)'''
}
if (element instanceof Conjunction) {
evaluation = '''«(element as Conjunction).left.evaluateExpression(entity)»'''
evaluation = '''«evaluation» and '''
evaluation = '''«evaluation»«(element as Conjunction).right.evaluateExpression(entity)»'''
}
if (element instanceof Disjunction) {
evaluation = '''(«(element as Disjunction).left.evaluateExpression(entity)»'''
evaluation = '''«evaluation» or '''
evaluation = '''«evaluation»«(element as Disjunction).right.evaluateExpression(entity)»)'''
}
if (element instanceof ConditionalExpression) {
evaluation = '''«(element as ConditionalExpression).left.evaluateExpression(entity)»'''
var optionalAllowed = true
if ((element as ConditionalExpression).left instanceof DatamartAttributeBase) {
// we cannot allow optional with date as we cannot mix * with date types
var type = ((element as ConditionalExpression).left as DatamartAttributeBase).attributeRef.
type as LDataType
optionalAllowed = !type.date
}
if ((element as ConditionalExpression).right.selected) {
evaluation = '''«evaluation» in '''
evaluation = '''«evaluation»(«(element as ConditionalExpression).right.evaluateExpression(entity)»)'''
} else if ((element as ConditionalExpression).right.ranged) {
evaluation = '''«(element as ConditionalExpression).right.evaluateExpression(entity)»'''
} else {
evaluation = '''«evaluation» «(element as ConditionalExpression).operator.literal» '''
evaluation = '''«evaluation»«(element as ConditionalExpression).right.evaluateExpression(entity)»'''
}
if ((element as ConditionalExpression).right.optional && optionalAllowed) {
evaluation = '''(«(element as ConditionalExpression).right.evaluateExpression(entity)»=«IDataMart.SQLFILTERNOTHING» or «evaluation»)'''
}
}
if (element instanceof DatamartMemberTuple) {
evaluation = '''(«(element as DatamartMemberTuple).right.evaluateExpression(entity)»'''
evaluation = '''«evaluation»,'''
evaluation = '''«evaluation»«(element as DatamartMemberTuple).left.evaluateExpression(entity)»)'''
}
if (element instanceof DatamartAggregation) {
if ((element as DatamartAggregation).left.aggregation !== null) {
if ((element as DatamartAggregation).left.aggregation instanceof DatamartAggregationFunction) {
evaluation = '''«((element as DatamartAggregation).left.aggregation as DatamartAggregationFunction).
aggregation.name()»('''
if ((element as DatamartAggregation).left.set instanceof DatamartHierarchy) {
evaluation = '''«evaluation»«((element as DatamartAggregation).left.set as DatamartHierarchy).
getLevelName(true, true, true, false)»'''
}
if ((element as DatamartAggregation).left.set instanceof DatamartSetTuple) {
evaluation = '''«evaluation»«((element as DatamartAggregation).left.set as DatamartSetTuple).
evaluateExpression(entity)»'''
}
}
}
evaluation = '''«evaluation»,'''
evaluation = '''«evaluation»«(element as DatamartAggregation).right.evaluateExpression(entity)»)'''
}
if (element instanceof DatamartSetAggregation) {
if ((element as DatamartSetAggregation).left.aggregation !== null) {
if ((element as DatamartSetAggregation).left.aggregation instanceof DatamartSetAggregationFunction) {
evaluation = '''«((element as DatamartSetAggregation).left.aggregation as DatamartSetAggregationFunction).
aggregation.name()»('''
if ((element as DatamartSetAggregation).left.set instanceof DatamartHierarchy) {
evaluation = '''«evaluation»«((element as DatamartSetAggregation).left.set as DatamartHierarchy).
getLevelName(true, true, true, false)»'''
}
if ((element as DatamartSetAggregation).left.set instanceof DatamartSetTuple) {
evaluation = '''«evaluation»«((element as DatamartSetAggregation).left.set as DatamartSetTuple).
evaluateExpression(entity)»'''
}
}
}
evaluation = '''«evaluation»,«(((element as DatamartSetAggregation).left.aggregation as DatamartSetAggregationFunction).
parameter as DatamartFunctionIntParameter).value»,'''
evaluation = '''«evaluation»«(element as DatamartSetAggregation).right.evaluateExpression(entity)»)'''
}
return evaluation
}
/**
* <p>mdx syntax part for attribute names, full qualified and aliased>
*
*/
def getAttributeName(DatamartAttributeBase attribute, DatamartEntity entity) {
if (entity !== null) {
return '''«entity.entityAlias».«attribute.attributeRef.toColumnName»'''
} else {
return '''«(attribute.attributeRef.eContainer as LEntity).name».«attribute.attributeRef.toColumnName»'''
}
}
/**
* <p>mdx syntax part for measure names.</p>
*
*/
def getMeasureName(DatamartMeasure measure) {
return '''[Measures].[«measure.measureRef.name»]'''
}
/**
* <p>mdx syntax part for derived measure names.</p>
*
*/
def getDerivedMeasureName(DatamartDerivedMeasure measure) {
return '''[Measures].[«measure.derivedRef.name»]'''
}
/**
* <p>mdx syntax part for dimension names.</p>
*
*/
def getDimensionName(DatamartHierarchy hierarchy, Boolean withBrackets) {
var dim = ""
if (hierarchy.hierarchyRef.eContainer !== null) {
if (hierarchy.hierarchyRef.name === null) {
dim = '''«IF withBrackets»[«ENDIF»«(hierarchy.hierarchyRef.eContainer as CubeDimension).name»«IF withBrackets»]«ENDIF»'''
} else {
dim = '''«IF withBrackets»[«ENDIF»«hierarchy.hierarchyRef.name»«IF withBrackets»]«ENDIF»'''
}
}
return dim
}
/**
* <p>mdx syntax part for level names.</p>
*
*/
def getLevelName(DatamartHierarchy hierarchy, Boolean withBrackets, Boolean withFiltermask, Boolean withFunctions,
Boolean isSlicer) {
var text = '''«hierarchy.getDimensionName(withBrackets)»'''
if (hierarchy.levelRef !== null) {
text = '''«text».'''
if (hierarchy.filtered && withFiltermask) {
if (isSlicer) {
text = '''«DatamartFilter.FILTER_PLACEHOLDER»«text»'''
} else {
text = '''«DatamartFilter.FILTER_PLACEHOLDER»«text»'''
}
}
if (hierarchy.selected && withFiltermask) {
if (isSlicer) {
text = '''«DatamartFilter.FILTER_PLACEHOLDER»«text»'''
} else {
text = '''«DatamartFilter.FILTER_PLACEHOLDER»«text»'''
}
}
if (withBrackets) {
text = '''«text»['''
}
text = '''«text»«hierarchy.levelRef.name»'''
if (withBrackets) {
text = '''«text»]'''
}
if (hierarchy.filtered && withFiltermask) {
if (isSlicer) {
text = '''«text»«DatamartFilter.FILTER_PLACEHOLDER»'''
} else {
text = '''«text»«DatamartFilter.FILTER_PLACEHOLDER»'''
}
}
if (hierarchy.selected && withFiltermask) {
if (isSlicer) {
text = '''«text»«DatamartFilter.FILTER_PLACEHOLDER»'''
} else {
text = '''«text»«DatamartFilter.FILTER_PLACEHOLDER»'''
}
}
if (hierarchy.filtered || hierarchy.selected) {
if (hierarchy.all && withFunctions) {
text = '''«text».Children'''
}
} else if (withFunctions) {
text = '''«text».Members'''
}
if (hierarchy.except && withFunctions) {
text = '''Except(«text»,{«DatamartFilter.FILTER_PLACEHOLDER»«hierarchy.getDimensionName(true)».«IF withBrackets»[«ENDIF»«hierarchy.exceptRef.name»«IF withBrackets»]«ENDIF»«DatamartFilter.FILTER_PLACEHOLDER»})'''
}
if (hierarchy.ordered && withFunctions) {
if (hierarchy.orderRef instanceof DatamartMeasure) {
text = '''Order(«text»,«(hierarchy.orderRef as DatamartMeasure).getMeasureName»,«IF hierarchy.
descending»Desc«ELSE»Asc«ENDIF»)'''
} else {
text = '''Order(«text»,«(hierarchy.orderRef as DatamartDerivedMeasure).getDerivedMeasureName»,«IF hierarchy.
descending»Desc«ELSE»Asc«ENDIF»)'''
}
}
}
if (hierarchy.levelRef === null && hierarchy.exceptRef === null && withFunctions) {
if (hierarchy.hierarchyRef.eContainer !== null &&
!(hierarchy.hierarchyRef.eContainer as CubeDimension).typeTime) {
if (hierarchy.all) {
text = '''«text».Members'''
} else if (hierarchy.allMember && hierarchy.hierarchyRef.allMemberName) {
text = '''«text».[«hierarchy.hierarchyRef.allMemberNameValue.replaceAll("\"","")»]'''
} else if (hierarchy.allLevels) {
text = '''«text».AllMembers'''
} else if (hierarchy.defaultMember && hierarchy.hierarchyRef.defaultMember) {
text = '''«text».Defaultmember'''
} else {
if (hierarchy.hierarchyRef.defaultMember) {
text = '''«text».Defaultmember'''
} else {
text = '''«text».Members'''
}
}
}
}
return '''«text»'''
}
/**
* <p>helper for entity names.</p>
*
*/
def getEntityAlias(DatamartEntity entity) {
return getEntityAlias(entity.entityRef)
}
/**
* <p>helper for entity names including aliases when used in recursive join relations.</p>
*
*/
def String getEntityAlias(LEntity entityRef) {
var name = ""
if (entityRef.hasSuperType) {
name = entityRef.superType.getName()
} else {
name = entityRef.getName()
}
var alias = name
if (sqlAliasCounter.containsKey(name)) {
var newId = sqlAliasCounter.get(name)
alias = '''«alias»«IF newId > 0»«newId»«ENDIF»'''
}
return alias
}
/**
* <p>helper for entity names including aliases when used in recursive join relations.</p>
*
*/
def entityAlias2(DatamartEntity entity) {
return entity.entityRef.entityAlias2
}
def entityAlias2(LEntity entityRef) {
var name = ""
if (entityRef.hasSuperType) {
name = entityRef.superType.getName()
} else {
name = entityRef.getName()
}
var alias = name
if (sqlAliasCounter.containsKey(name)) {
var newId = sqlAliasCounter.get(name)
sqlAliasCounter.put(name, newId + 1)
alias = '''«alias»«newId + 1»'''
} else {
sqlAliasCounter.put(name, 0)
}
return alias
}
/**
* <p>main method to build sql statements bases on entities and roles.</p>
*
*/
def createSQLStatements(DatamartDefinition definition, DatamartEntity entity,
HashMap<String, LEntityAttribute> typesMap) {
var listTxt = '''
put("«IUserAccessService.ADMINISTRATOR»", "«definition.createSQLStatement(null, typesMap)»");'''
for (role : definition.roles) {
if (role.isAuthorized(entity)) {
var stmt = definition.createSQLStatement(role, typesMap);
if (!stmt.empty) {
listTxt = '''
«listTxt»
put("«role.assignedRole.name»", "«stmt»");'''
}
}
}
listTxt = '''
{{
«listTxt»
}}'''
return listTxt
}
/**
* <p>main method to build sql statements bases on entities and a role.</p>
*
*/
def createSQLStatement(DatamartDefinition definition, DatamartRole role,
HashMap<String, LEntityAttribute> typesMap) {
this.sqlAliasCounter.clear()
this.sqlFilterMap.clear()
this.sqlGrouping.clear()
this.sqlHasAggregate = false
this.sqlHasOrder = false
if (role === null) {
this.entityGrouping.clear()
this.idMap.clear()
this.ignoreEntityGrouping = false
}
var attributes = <String, Pair<String, Integer>>newHashMap
var conditions = <String>newArrayList
var orderings = <String, Integer>newLinkedHashMap
var entity = (definition.source as DatamartEntity)
var used = entity.createEntity(null, null, attributes, conditions, orderings, role, typesMap)
var select = attributes.createSelect(definition)
var condition = conditions.createCondition
var ordering = orderings.createOrdering
var grouping = this.sqlGrouping.createGrouping
if (select.empty) {
return ""
}
return '''select «select» from «used»«IF conditions.size > 0» where «condition»«ENDIF»«IF this.
sqlHasAggregate» group by «grouping»«ENDIF»«IF this.sqlHasOrder» order by «ordering»«ENDIF»'''
}
/**
* <p>sql syntax part for group by.</p>
*
*/
def createGrouping(ArrayList<String> grouping) {
var groupingString = ""
for (String groupBy : grouping) {
groupingString = '''«IF !groupingString.empty»«groupingString»,«ENDIF»«groupBy»'''
}
return groupingString
}
/**
* <p>sql syntax part for where.</p>
*
*/
def createCondition(ArrayList<String> conditions) {
var conditionString = ""
for (String condition : conditions) {
conditionString = '''«IF !conditionString.empty»«conditionString» and «ENDIF»(«condition»)'''
}
return conditionString
}
/**
* <p>sql syntax part for order.</p>
*
*/
def createOrdering(Map<String, Integer> orderings) {
sqlHasOrder = orderings.size > 0
return orderings.entrySet.stream.sorted(Map.Entry.comparingByValue.reversed).map[it.key].collect(
Collectors.joining(","))
}
/**
* <p>sql syntax part for select.</p>
*
*/
def createSelect(Map<String, Pair<String, Integer>> attributes, DatamartDefinition definition) {
var selectString = ""
selectString = attributes.entrySet.sortWith[e1, e2|return (e2.value.value - e1.value.value)].map [
it.key + " as \\\"" + it.value.key + "\\\""
].join(",")
datamartDtoMapper = "new DatamartDtoMapper()"
if (definition !== null) {
if (!ignoreEntityGrouping) {
for (LEntity entityRef : entityGrouping.values) {
var entityName = ""
if (entityRef.hasSuperType) {
entityName = entityRef.superType.getName()
} else {
entityName = entityRef.getName()
}
var dtoFqn = EntityUtils.getDtoFQNForLEntity(entityRef)
var idColumn = DatamartDefinitionUtil.getEntityIdAliasName(entityRef)
if (entityRef.primaryKeyAttribute !== null) {
selectString = '''«selectString»,«entityName».«entityRef.primaryKeyAttribute.name» as \"«idColumn»\"'''
if (entityRef.hasSuperType) {
idMap.put(idColumn, entityRef.superType)
} else {
idMap.put(idColumn, entityRef)
}
datamartDtoMapper = '''
«datamartDtoMapper»
.add("«dtoFqn»", "«entityRef.primaryKeyAttribute.name»", EType.«dtType.getBasicType(idMap.get(idColumn).primaryKeyAttribute as LEntityAttribute)», "«idColumn»")'''
}
}
}
}
return selectString
}
def hasSuperType(DatamartEntity entity) {
return entity.entityRef.hasSuperType
}
def hasSuperType(LEntity entityRef) {
return entityRef.superType !== null && !entityRef.superType.mappedSuperclass &&
!entityRef.superType.equals(entityRef)
}
/**
* <p>recursive entity relation builder.</p>
*
*/
def String createEntity(DatamartEntity entity, DatamartEntity parent, DatamartNavigation parentNavigation,
Map<String, Pair<String, Integer>> attributes, List<String> conditions,
LinkedHashMap<String, Integer> orderings, DatamartRole role, HashMap<String, LEntityAttribute> typesMap) {
var body = ""
var tableName = entity.entityRef.toTableName
if (entity.hasSuperType) {
conditions.add('''«entity.entityAlias».disc='«entity.entityRef.toTableName»' ''')
tableName = entity.entityRef.superType.toTableName
}
if (role.isAuthorized(entity)) {
body = '''«body»«entity.entityRef.persistenceInfo.schemaName.provideSchemaName»«tableName» «entity.entityAlias2»'''
if (parent !== null && parentNavigation !== null) {
body = ''' left join «body»«entity.createJoin(parent, parentNavigation)»'''
}
if (entity.hasSuperType) {
body = '''«body» left join «entity.createSupertypeJoin»'''
}
for (DatamartNavigation navigation : entity.navigations) {
if (navigation instanceof DatamartMember) {
if (role.isAuthorized((navigation as DatamartMember).datamartEntity,
(navigation as DatamartMember).joinRef as DatamartReference)) {
body = '''«body»«(navigation as DatamartMember).datamartEntity.createEntity(entity, navigation,
attributes, conditions, orderings, role, typesMap)»'''
}
}
if (navigation instanceof DatamartOwner) {
if (role.isAuthorized((navigation as DatamartOwner).datamartEntity,
(navigation as DatamartOwner).joinRef as DatamartReference)) {
body = '''«body»«(navigation as DatamartOwner).datamartEntity.createEntity(entity, navigation,
attributes, conditions, orderings, role, typesMap)»'''
}
}
}
if (entity.attributes.empty) {
for (attr : entity.entityRef.allAttributes) {
if (!attr.isId && !attr.isUuid && !attr.isVersion) {
var datamartAttr = DatamartDSLFactory.eINSTANCE.createDatamartAttribute
datamartAttr.attributeRef = attr
entity.recurAttribute(datamartAttr, false, "", defaultColumnWeight, attributes, role, typesMap)
}
}
} else {
for (DatamartAttribute attribute : entity.attributes) {
var columnWeight = defaultColumnWeight
if (attribute.hasColumnWeight) {
columnWeight = attribute.columnWeight
}
entity.recurAttribute(attribute, attribute.aggregated, attribute.aggregate.getName(), columnWeight,
attributes, role, typesMap)
}
}
for (DatamartCondition condition : entity.conditions) {
conditions.add(condition.condition.evaluateExpression(entity))
}
for (DatamartOrder order : entity.ordering) {
var Integer columnWeight
if (order.hasColumnWeight) {
columnWeight = order.columnWeight
} else {
columnWeight = defaultColumnWeight
}
orderings.put(entity.entityAlias + "." + order.orderBy.toColumnName + " " + order.orderHow.getName(),
columnWeight)
}
}
return body
}
def void recurAttribute(DatamartEntity entity, DatamartAttribute datamartAttr, boolean aggregated,
String aggregateName, Integer columnWeight, Map<String, Pair<String, Integer>> attributes, DatamartRole role,
HashMap<String, LEntityAttribute> typesMap) {
var attr = datamartAttr.attributeRef
var LScalarType type = attr.type
if (type instanceof LBean) {
var bean = type as LBean
for (battr : bean.allAttributes) {
if (battr.type instanceof LBean) {
entity.recurAttribute(datamartAttr, aggregated, aggregateName, columnWeight, attributes, role,
typesMap)
} else {
entity.addAttribute(datamartAttr, aggregated, aggregateName, columnWeight, attributes, role,
typesMap)
}
}
} else {
entity.addAttribute(datamartAttr, aggregated, aggregateName, columnWeight, attributes, role, typesMap)
}
}
def aliasedColumnName(LEntity entityRef, LAttribute attr) {
var name = ""
if (entityRef.hasSuperType) {
if (entityRef.superType.allAttributes.contains(attr)) {
name = entityRef.superType.getName()
} else {
name = entityRef.getName()
}
} else {
name = entityRef.getName()
}
var alias = name
if (sqlAliasCounter.containsKey(name)) {
var newId = sqlAliasCounter.get(name)
alias = '''«alias»«IF newId > 0»«newId»«ENDIF»'''
}
return alias + "." + attr.toColumnName
}
def void addAttribute(DatamartEntity datamartEntity, DatamartAttribute datamartAttr, boolean aggregated,
String aggregateName, Integer columnWeight, Map<String, Pair<String, Integer>> attributes, DatamartRole role,
HashMap<String, LEntityAttribute> typesMap) {
var entity = datamartEntity.entityRef
var attr = datamartAttr.attributeRef
var key = entity.aliasedColumnName(attr)
var attrName = "" // TODO (JCD): Already required??? Is not used!!
var typesAttr = ""
if (entity.hasSuperType) {
if (entity.superType.allAttributes.contains(attr)) {
// attrName = entity.superType.name+"."+attr.toColumnName.toLowerCase
attrName = entity.superType.name + "." + DatamartAttributeUtil.getAliasedAttributeName(datamartAttr)
typesAttr = entity.superType.name + "." + DatamartAttributeUtil.getAliasedAttributeName(datamartAttr)
} else {
// attrName = entity.name+"."+attr.toColumnName.toLowerCase
attrName = entity.name + "." + DatamartAttributeUtil.getAliasedAttributeName(datamartAttr)
typesAttr = entity.name + "." + DatamartAttributeUtil.getAliasedAttributeName(datamartAttr)
}
} else {
// attrName = entity.name+"."+attr.toColumnName.toLowerCase
attrName = entity.name + "." + DatamartAttributeUtil.getAliasedAttributeName(datamartAttr)
typesAttr = entity.name + "." + DatamartAttributeUtil.getAliasedAttributeName(datamartAttr)
}
typesMap.put(typesAttr, attr as LEntityAttribute);
if (role.isAuthorized(entity, attr.name)) {
if (aggregated) {
key = '''«aggregateName»(«key»)'''
this.sqlHasAggregate = true;
// attributes.put(key.toString, new Pair(attr.name, columnWeight))
attributes.put(key.toString,
new Pair(DatamartAttributeUtil.getAliasedAttributeName(datamartAttr), columnWeight))
this.ignoreEntityGrouping = true
} else {
this.entityGrouping.put(entity.entityAlias, entity)
this.sqlGrouping.add(key.toString)
// attributes.put(key.toString, new Pair(attr.name, columnWeight))
attributes.put(key.toString,
new Pair(DatamartAttributeUtil.getAliasedAttributeName(datamartAttr), columnWeight))
}
}
}
def boolean isAuthorized(DatamartRole role, DatamartEntity entity) {
// no role - all granted
if (role === null) {
return true
}
// all role entities
for (roleElement : role.assignedRole.roleElements) {
if (roleElement instanceof RoleEntity) {
if (entity.entityRef.name.equals(((roleElement as RoleEntity).entityRef as LEntity).name)) {
return true
}
}
}
return false
}
def boolean isAuthorized(DatamartRole role, LEntity entity, String attributeName) {
// no role - all granted
if (role === null) {
return true
}
// all role entities
for (roleElement : role.assignedRole.roleElements) {
if (roleElement instanceof RoleEntity) {
if (entity.name.equals(((roleElement as RoleEntity).entityRef as LEntity).name)) {
for (feature : (roleElement as RoleEntity).entityFeatures) {
if (attributeName.equals((feature.entityAttriCol as LEntityFeature).name)) {
if (feature instanceof RoleEntityAttribute) {
if ("INVISIBLE".equals(feature.entityAttriUnauthorized.literal)) {
return false
}
}
}
}
}
}
}
return true
}
def boolean isAuthorized(DatamartRole role, String entityAttribute) {
// no role - all granted
if (role === null) {
return true
}
// all role entities
for (roleElement : role.assignedRole.roleElements) {
if (roleElement instanceof RoleEntity) {
var parts = entityAttribute.split("\\.");
if (parts.get(0).equals(((roleElement as RoleEntity).entityRef as LEntity).name)) {
for (feature : (roleElement as RoleEntity).entityFeatures) {
if (parts.get(1).equals((feature.entityAttriCol as LEntityFeature).name)) {
if (feature instanceof RoleEntityAttribute) {
if ("INVISIBLE".equals(feature.entityAttriUnauthorized.literal)) {
return false
}
}
}
}
return true
}
}
}
return false
}
def boolean isAuthorized(DatamartRole role, DatamartEntity entity, DatamartReference link) {
// no role - all granted
if (role === null) {
return true
}
// all role entities
for (roleElement : role.assignedRole.roleElements) {
if (roleElement instanceof RoleEntity) {
if (entity.entityRef.name.equals(((roleElement as RoleEntity).entityRef as LEntity).name)) {
// all role entity features
for (feature : (roleElement as RoleEntity).entityFeatures) {
if (feature instanceof RoleEntityReference) {
if (link.ref.name.toLowerCase.equals((feature.entityAttriCol as LEntityFeature).name)) {
if ("INVISIBLE".equals(feature.entityAttriUnauthorized.literal)) {
return false
}
}
}
}
return true;
}
}
}
return false
}
def getProvideSchemaName(
String schemaName) '''«IF schemaName !== null && schemaName.length > 0»«schemaName».«ENDIF»'''
/**
* <p>sql syntax part for joined relations.</p>
*
*/
def createJoin(DatamartEntity entity, DatamartEntity parent, DatamartNavigation navigation) {
var join = ""
var joinRef = navigation.joinRef
if (joinRef instanceof DatamartReference) {
var name = joinRef.ref.toColumnName
if (navigation instanceof DatamartMember) {
// determination of the right column name of the foreign key id required for the join
// using the name of the reference instead of the name joinref.
var refs = navigation.datamartEntity.entityRef.allReferences
for (ref : refs) {
if (ref.type !== null && ref.type.equals(parent.entityRef)) {
name = ref.toColumnName
}
}
join = '''«entity.getEntityAlias».«name»=«parent.getEntityAlias».«parent.entityRef.idAttributeName»'''
} else if (navigation instanceof DatamartOwner) {
join = '''«entity.getEntityAlias».«entity.entityRef.idAttributeName»=«parent.getEntityAlias».«name»'''
}
join = ''' on(«join»)'''
}
}
def createSupertypeJoin(DatamartEntity entity) {
var subTypeAlias = entity.entityRef.name
if (sqlAliasCounter.containsKey(entity.entityRef.name)) {
var newId = sqlAliasCounter.get(entity.entityRef.name)
subTypeAlias = '''«subTypeAlias»«IF newId > 0»«newId»«ENDIF»'''
}
var join = '''«subTypeAlias».«entity.entityRef.idAttributeName»=«entity.entityRef.superType.getEntityAlias».«entity.entityRef.superType.idAttributeName»'''
join = '''«entity.entityRef.persistenceInfo.schemaName.provideSchemaName»«entity.entityRef.toTableName» «subTypeAlias» on(«join»)'''
}
/**
* get a set of entities used by the datamart
*/
def Set<LEntity> findAllEntities(DatamartDefinition datamart) {
var entities = new HashSet<LEntity>()
switch (datamart.source) {
DatamartEntity: findAllEntites(datamart.source as DatamartEntity, entities)
DatamartCube: findAllEntites(datamart.source as DatamartCube, entities)
}
return entities
}
/**
* add all entities used by the datamart entity into the given set of entities
*/
def void findAllEntites(DatamartEntity datamartEntity, Set<LEntity> entities) {
entities.add(datamartEntity.entityRef)
for (navigation : datamartEntity.navigations) {
findAllEntites(navigation.datamartEntity, entities)
}
}
/**
* add all entities used by the datamart cube into the given set of entities
*/
def void findAllEntites(DatamartCube datamartCube, Set<LEntity> entities) {
entities.add(datamartCube.cubeRef.cubeTypeEntity.entityRef.entityValue)
for (dimensionUsage : datamartCube.cubeRef.cubeTypeEntity.dimensionUsages) {
for (hierarchy : dimensionUsage.sourceValue.hierarchies) {
entities.add(hierarchy.cubeDimEntity.entityRef.entityValue)
}
}
}
def List<DatamartAttribute> allEntityAttributes(DatamartDefinition datamart) {
var attributes = <DatamartAttribute>newArrayList
if (datamart.source instanceof DatamartEntity) {
allEntityAttributes(datamart.source as DatamartEntity, attributes, "")
}
return attributes
}
/**
* add all entities used by the datamart entity into the given set of entities
*/
def void allEntityAttributes(DatamartEntity datamartEntity, List<DatamartAttribute> attributes, String refPrefix) {
if (datamartEntity.attributes.empty && attributes.empty) { // only at root level
var eAttrs = datamartEntity.entityRef.allAttributes
for (eAttr : eAttrs) {
if (!eAttr.id && !eAttr.uuid && !eAttr.version) {
var attribute = DatamartDSLFactory.eINSTANCE.createDatamartAttribute
attribute.attributeRef = eAttr
var axis = DatamartDSLFactory.eINSTANCE.createDatamartAxis
axis.name = AxisEnum.COLUMNS
attribute.axis = axis
attributes.add(attribute);
}
}
} else {
for (DatamartAttribute attribute : datamartEntity.attributes) {
attributes.add(attribute)
}
for (navigation : datamartEntity.navigations) {
allEntityAttributes(navigation.datamartEntity, attributes, navigation.joinRef.ref.name)
}
}
var primary = datamartEntity.entityRef.primaryKeyAttribute
var attribute = DatamartDSLFactory.eINSTANCE.createDatamartAttribute
attribute.attributeRef = primary
attribute.aliased = true
attribute.aliasName = '''«refPrefix»«IF refPrefix.empty»«primary.name.toFirstLower»«ELSE»«primary.name.toFirstUpper»«ENDIF»'''
attributes.add(attribute);
}
}